From ec49fedc45e18148484e798aea649fbec3183fdd Mon Sep 17 00:00:00 2001 From: Luis Fernando Molina Date: Wed, 7 Feb 2018 21:05:26 +0100 Subject: [PATCH] Initial commit --- .gitattributes | 2 + .vs/AACharly/v15/.suo | Bin 0 -> 28160 bytes AACharly.njsproj | 84 + AACharly.sln | 25 + Azure File Storage.js | 247 + Azure Web Job Shutdown.js | 41 + Carol.azure.storage.connstring | 7 + Charly.azure.storage.connstring | 7 + Debug Log.js | 144 + Markets.js | 252 + Poloniex API Client.js | 406 + Poloniex-Historic-Trades/Interval.js | 1116 ++ .../Poloniex Historic Trades.js | 169 + Poloniex-Historic-Trades/run.js | 97 + Poloniex-Hole-Fixing/Interval.js | 1748 +++ Poloniex-Hole-Fixing/Poloniex Hole Fixing.js | 169 + Poloniex-Hole-Fixing/run.js | 97 + Poloniex-Live-Trades/Interval.js | 675 ++ Poloniex-Live-Trades/Poloniex Live Trades.js | 106 + Poloniex-Live-Trades/run.js | 57 + README.md | 1 + Utilities.js | 81 + azure.app.config | 7 + bin/Microsoft.NodejsTools.WebRole.dll | Bin 0 -> 33056 bytes logs/Dummy File.txt | 0 node_modules/.bin/sshpk-conv | 15 + node_modules/.bin/sshpk-conv.cmd | 7 + node_modules/.bin/sshpk-sign | 15 + node_modules/.bin/sshpk-sign.cmd | 7 + node_modules/.bin/sshpk-verify | 15 + node_modules/.bin/sshpk-verify.cmd | 7 + node_modules/.bin/uuid | 15 + node_modules/.bin/uuid.cmd | 7 + node_modules/ajv/.tonic_example.js | 20 + node_modules/ajv/LICENSE | 22 + node_modules/ajv/README.md | 1213 +++ node_modules/ajv/dist/ajv.bundle.js | 8023 ++++++++++++++ node_modules/ajv/dist/ajv.min.js | 6 + node_modules/ajv/dist/ajv.min.js.map | 1 + node_modules/ajv/dist/nodent.min.js | 8 + node_modules/ajv/dist/regenerator.min.js | 32 + node_modules/ajv/lib/ajv.d.ts | 284 + node_modules/ajv/lib/ajv.js | 420 + node_modules/ajv/lib/async.js | 218 + node_modules/ajv/lib/cache.js | 26 + node_modules/ajv/lib/compile/_rules.js | 28 + node_modules/ajv/lib/compile/equal.js | 45 + node_modules/ajv/lib/compile/formats.js | 164 + node_modules/ajv/lib/compile/index.js | 390 + node_modules/ajv/lib/compile/resolve.js | 267 + node_modules/ajv/lib/compile/rules.js | 40 + node_modules/ajv/lib/compile/schema_obj.js | 9 + node_modules/ajv/lib/compile/ucs2length.js | 20 + node_modules/ajv/lib/compile/util.js | 257 + .../ajv/lib/compile/validation_error.js | 14 + node_modules/ajv/lib/dot/_limit.jst | 49 + node_modules/ajv/lib/dot/_limitItems.jst | 10 + node_modules/ajv/lib/dot/_limitLength.jst | 10 + node_modules/ajv/lib/dot/_limitProperties.jst | 10 + node_modules/ajv/lib/dot/allOf.jst | 34 + node_modules/ajv/lib/dot/anyOf.jst | 48 + node_modules/ajv/lib/dot/coerce.def | 61 + node_modules/ajv/lib/dot/custom.jst | 184 + node_modules/ajv/lib/dot/defaults.def | 32 + node_modules/ajv/lib/dot/definitions.def | 182 + node_modules/ajv/lib/dot/dependencies.jst | 69 + node_modules/ajv/lib/dot/enum.jst | 30 + node_modules/ajv/lib/dot/errors.def | 185 + node_modules/ajv/lib/dot/format.jst | 100 + node_modules/ajv/lib/dot/items.jst | 101 + node_modules/ajv/lib/dot/missing.def | 34 + node_modules/ajv/lib/dot/multipleOf.jst | 20 + node_modules/ajv/lib/dot/not.jst | 43 + node_modules/ajv/lib/dot/oneOf.jst | 44 + node_modules/ajv/lib/dot/pattern.jst | 14 + node_modules/ajv/lib/dot/properties.jst | 319 + node_modules/ajv/lib/dot/ref.jst | 86 + node_modules/ajv/lib/dot/required.jst | 96 + node_modules/ajv/lib/dot/uniqueItems.jst | 38 + node_modules/ajv/lib/dot/v5/_formatLimit.jst | 116 + node_modules/ajv/lib/dot/v5/constant.jst | 10 + .../ajv/lib/dot/v5/patternRequired.jst | 28 + node_modules/ajv/lib/dot/v5/switch.jst | 73 + node_modules/ajv/lib/dot/validate.jst | 210 + node_modules/ajv/lib/dotjs/README.md | 3 + node_modules/ajv/lib/dotjs/_formatLimit.js | 176 + node_modules/ajv/lib/dotjs/_limit.js | 124 + node_modules/ajv/lib/dotjs/_limitItems.js | 76 + node_modules/ajv/lib/dotjs/_limitLength.js | 81 + .../ajv/lib/dotjs/_limitProperties.js | 76 + node_modules/ajv/lib/dotjs/allOf.js | 43 + node_modules/ajv/lib/dotjs/anyOf.js | 65 + node_modules/ajv/lib/dotjs/constant.js | 52 + node_modules/ajv/lib/dotjs/custom.js | 220 + node_modules/ajv/lib/dotjs/dependencies.js | 147 + node_modules/ajv/lib/dotjs/enum.js | 65 + node_modules/ajv/lib/dotjs/format.js | 138 + node_modules/ajv/lib/dotjs/items.js | 144 + node_modules/ajv/lib/dotjs/multipleOf.js | 76 + node_modules/ajv/lib/dotjs/not.js | 83 + node_modules/ajv/lib/dotjs/oneOf.js | 76 + node_modules/ajv/lib/dotjs/pattern.js | 74 + node_modules/ajv/lib/dotjs/patternRequired.js | 51 + node_modules/ajv/lib/dotjs/properties.js | 445 + node_modules/ajv/lib/dotjs/ref.js | 119 + node_modules/ajv/lib/dotjs/required.js | 249 + node_modules/ajv/lib/dotjs/switch.js | 128 + node_modules/ajv/lib/dotjs/uniqueItems.js | 71 + node_modules/ajv/lib/dotjs/validate.js | 375 + node_modules/ajv/lib/keyword.js | 129 + .../ajv/lib/refs/json-schema-draft-04.json | 150 + node_modules/ajv/lib/refs/json-schema-v5.json | 328 + node_modules/ajv/lib/v5.js | 52 + node_modules/ajv/package.json | 161 + node_modules/ajv/scripts/.eslintrc.yml | 3 + node_modules/ajv/scripts/bundle.js | 54 + node_modules/ajv/scripts/compile-dots.js | 73 + node_modules/ajv/scripts/info | 10 + node_modules/ajv/scripts/prepare-tests | 9 + node_modules/ajv/scripts/travis-gh-pages | 23 + node_modules/asn1/.npmignore | 2 + node_modules/asn1/.travis.yml | 4 + node_modules/asn1/LICENSE | 19 + node_modules/asn1/README.md | 50 + node_modules/asn1/lib/ber/errors.js | 13 + node_modules/asn1/lib/ber/index.js | 27 + node_modules/asn1/lib/ber/reader.js | 261 + node_modules/asn1/lib/ber/types.js | 36 + node_modules/asn1/lib/ber/writer.js | 316 + node_modules/asn1/lib/index.js | 20 + node_modules/asn1/package.json | 89 + node_modules/asn1/tst/ber/reader.test.js | 208 + node_modules/asn1/tst/ber/writer.test.js | 370 + node_modules/assert-plus/AUTHORS | 6 + node_modules/assert-plus/CHANGES.md | 8 + node_modules/assert-plus/README.md | 155 + node_modules/assert-plus/assert.js | 206 + node_modules/assert-plus/package.json | 106 + node_modules/asynckit/LICENSE | 21 + node_modules/asynckit/README.md | 233 + node_modules/asynckit/bench.js | 76 + node_modules/asynckit/index.js | 6 + node_modules/asynckit/lib/abort.js | 29 + node_modules/asynckit/lib/async.js | 34 + node_modules/asynckit/lib/defer.js | 26 + node_modules/asynckit/lib/iterate.js | 75 + .../asynckit/lib/readable_asynckit.js | 91 + .../asynckit/lib/readable_parallel.js | 25 + node_modules/asynckit/lib/readable_serial.js | 25 + .../asynckit/lib/readable_serial_ordered.js | 29 + node_modules/asynckit/lib/state.js | 37 + node_modules/asynckit/lib/streamify.js | 141 + node_modules/asynckit/lib/terminator.js | 29 + node_modules/asynckit/package.json | 118 + node_modules/asynckit/parallel.js | 43 + node_modules/asynckit/serial.js | 17 + node_modules/asynckit/serialOrdered.js | 75 + node_modules/asynckit/stream.js | 21 + node_modules/aws-sign2/LICENSE | 55 + node_modules/aws-sign2/README.md | 4 + node_modules/aws-sign2/index.js | 212 + node_modules/aws-sign2/package.json | 72 + node_modules/aws4/.npmignore | 4 + node_modules/aws4/.tern-port | 1 + node_modules/aws4/.travis.yml | 5 + node_modules/aws4/LICENSE | 19 + node_modules/aws4/README.md | 523 + node_modules/aws4/aws4.js | 332 + node_modules/aws4/lru.js | 96 + node_modules/aws4/package.json | 132 + node_modules/azure-storage/.jshintignore | 3 + node_modules/azure-storage/.jshintrc | 32 + node_modules/azure-storage/.npmignore | 11 + node_modules/azure-storage/.travis.yml | 19 + node_modules/azure-storage/BreakingChanges.md | 104 + node_modules/azure-storage/CONTRIBUTING.md | 81 + node_modules/azure-storage/CONTRIBUTORS.txt | 7 + node_modules/azure-storage/ChangeLog.md | 761 ++ node_modules/azure-storage/LICENSE.txt | 176 + node_modules/azure-storage/README.md | 535 + .../azure-storage/browser/ChangeLog.md | 69 + node_modules/azure-storage/browser/README.md | 106 + .../browser/azure-storage.blob.export.js | 73 + .../browser/azure-storage.file.export.js | 69 + .../browser/azure-storage.queue.export.js | 70 + .../browser/azure-storage.table.export.js | 70 + node_modules/azure-storage/browser/bundle.js | 49 + .../azure-storage/browser/samples/cors.PNG | Bin 0 -> 13072 bytes .../browser/samples/sample-blob.html | 511 + .../browser/samples/sample-file.html | 588 + .../browser/samples/sample-queue.html | 465 + .../browser/samples/sample-table.html | 440 + .../samples/blobuploaddownloadsample.js | 246 + .../examples/samples/continuationsample.js | 159 + .../samples/requestresponseeventssample.js | 96 + .../examples/samples/retrypolicysample.js | 230 + .../examples/samples/sassample.js | 218 + .../examples/samples/snapshotsample.js | 219 + .../examples/samples/tablequerysample.js | 165 + node_modules/azure-storage/gruntfile.js | 106 + node_modules/azure-storage/jsdoc/jsdoc.json | 27 + .../azure-storage/lib/azure-storage.js | 369 + .../lib/common/common.browser.js | 21 + .../azure-storage/lib/common/common.core.js | 67 + .../azure-storage/lib/common/common.node.js | 22 + .../lib/common/diagnostics/logger.js | 148 + .../azure-storage/lib/common/errors/errors.js | 68 + .../filters/exponentialretrypolicyfilter.js | 95 + .../common/filters/linearretrypolicyfilter.js | 75 + .../lib/common/filters/retrypolicyfilter.js | 233 + .../lib/common/http/webresource.js | 324 + .../lib/common/md5-wrapper/md5.browser.js | 26 + .../lib/common/md5-wrapper/md5.node.js | 26 + .../lib/common/md5-wrapper/package.json | 7 + .../lib/common/models/aclresult.js | 122 + .../common/models/servicepropertiesresult.js | 427 + .../lib/common/models/servicestatsparser.js | 34 + .../lib/common/request-wrapper/package.json | 7 + .../common/request-wrapper/request.browser.js | 258 + .../common/request-wrapper/request.node.js | 17 + .../lib/common/services/servicesettings.js | 262 + .../common/services/storageserviceclient.js | 1355 +++ .../common/services/storageservicesettings.js | 420 + .../lib/common/signing/hmacsha256sign.js | 43 + .../common/signing/sharedaccesssignature.js | 56 + .../lib/common/signing/sharedkey.js | 500 + .../lib/common/streams/batchoperation.js | 425 + .../common/streams/browserfilereadstream.js | 61 + .../lib/common/streams/bufferstream.js | 50 + .../lib/common/streams/chunkallocator.js | 128 + .../lib/common/streams/chunkstream.js | 321 + .../common/streams/chunkstreamwithstream.js | 103 + .../lib/common/streams/filereadstream.js | 261 + .../lib/common/streams/rangestream.js | 293 + .../lib/common/streams/readablefs.js | 32 + .../lib/common/streams/speedsummary.js | 205 + .../lib/common/util/accesscondition.js | 166 + .../lib/common/util/constants.js | 2536 +++++ .../azure-storage/lib/common/util/date.js | 69 + .../lib/common/util/iso8061date.js | 66 + .../lib/common/util/patch-xmlbuilder.js | 31 + .../azure-storage/lib/common/util/sr.js | 76 + .../lib/common/util/storageutilities.js | 42 + .../azure-storage/lib/common/util/util.js | 618 ++ .../azure-storage/lib/common/util/validate.js | 560 + .../lib/services/blob/blobservice.browser.js | 319 + .../lib/services/blob/blobservice.core.js | 5733 ++++++++++ .../lib/services/blob/blobservice.node.js | 461 + .../lib/services/blob/blobutilities.js | 136 + .../blob/internal/blockrangestream.js | 203 + .../services/blob/internal/pagerangestream.js | 43 + .../lib/services/blob/models/blobresult.js | 304 + .../services/blob/models/blocklistresult.js | 85 + .../services/blob/models/containerresult.js | 116 + .../lib/services/blob/models/leaseresult.js | 73 + .../lib/services/file/fileservice.browser.js | 95 + .../lib/services/file/fileservice.core.js | 3937 +++++++ .../lib/services/file/fileservice.node.js | 182 + .../lib/services/file/fileutilities.js | 72 + .../services/file/internal/filerangestream.js | 46 + .../services/file/models/directoryresult.js | 58 + .../lib/services/file/models/fileresult.js | 207 + .../lib/services/file/models/shareresult.js | 84 + .../queue/models/queuemessageresult.js | 131 + .../lib/services/queue/models/queueresult.js | 72 + .../lib/services/queue/queuemessageencoder.js | 182 + .../lib/services/queue/queueservice.js | 1468 +++ .../lib/services/queue/queueutilities.js | 39 + .../lib/services/table/internal/edmhandler.js | 197 + .../services/table/internal/odatahandler.js | 217 + .../services/table/internal/requesthandler.js | 135 + .../services/table/internal/sharedkeytable.js | 92 + .../lib/services/table/models/batchresult.js | 232 + .../lib/services/table/models/entityresult.js | 62 + .../lib/services/table/models/tableresult.js | 37 + .../lib/services/table/tablebatch.js | 209 + .../lib/services/table/tablequery.js | 419 + .../lib/services/table/tableservice.js | 1391 +++ .../lib/services/table/tableutilities.js | 154 + .../azure-storage/node_modules/.bin/uuid | 15 + .../azure-storage/node_modules/.bin/uuid.cmd | 7 + .../node_modules/request/CHANGELOG.md | 674 ++ .../node_modules/request/LICENSE | 55 + .../node_modules/request/README.md | 1115 ++ .../node_modules/request/index.js | 156 + .../node_modules/request/lib/auth.js | 168 + .../node_modules/request/lib/cookies.js | 39 + .../request/lib/getProxyFromURI.js | 79 + .../node_modules/request/lib/har.js | 215 + .../node_modules/request/lib/helpers.js | 66 + .../node_modules/request/lib/multipart.js | 113 + .../node_modules/request/lib/oauth.js | 148 + .../node_modules/request/lib/querystring.js | 51 + .../node_modules/request/lib/redirect.js | 157 + .../node_modules/request/lib/tunnel.js | 176 + .../request/node_modules/extend/.eslintrc | 17 + .../request/node_modules/extend/.jscs.json | 175 + .../request/node_modules/extend/.npmignore | 1 + .../request/node_modules/extend/.travis.yml | 179 + .../request/node_modules/extend/CHANGELOG.md | 77 + .../request/node_modules/extend/LICENSE | 23 + .../request/node_modules/extend/README.md | 81 + .../node_modules/extend/component.json | 32 + .../request/node_modules/extend/index.js | 86 + .../request/node_modules/extend/package.json | 105 + .../node_modules/request/package.json | 156 + .../node_modules/request/request.js | 1565 +++ .../node_modules/uuid/.eslintrc.json | 47 + .../azure-storage/node_modules/uuid/AUTHORS | 5 + .../node_modules/uuid/CHANGELOG.md | 57 + .../node_modules/uuid/LICENSE.md | 21 + .../azure-storage/node_modules/uuid/README.md | 293 + .../node_modules/uuid/README_js.md | 280 + .../azure-storage/node_modules/uuid/bin/uuid | 65 + .../azure-storage/node_modules/uuid/index.js | 8 + .../node_modules/uuid/lib/bytesToUuid.js | 23 + .../node_modules/uuid/lib/md5-browser.js | 216 + .../node_modules/uuid/lib/md5.js | 25 + .../node_modules/uuid/lib/rng-browser.js | 32 + .../node_modules/uuid/lib/rng.js | 8 + .../node_modules/uuid/lib/sha1-browser.js | 89 + .../node_modules/uuid/lib/sha1.js | 25 + .../node_modules/uuid/lib/v35.js | 53 + .../node_modules/uuid/package.json | 123 + .../azure-storage/node_modules/uuid/v1.js | 109 + .../azure-storage/node_modules/uuid/v3.js | 4 + .../azure-storage/node_modules/uuid/v4.js | 29 + .../azure-storage/node_modules/uuid/v5.js | 3 + node_modules/azure-storage/package.json | 145 + node_modules/azure-storage/tsconfig.json | 14 + node_modules/azure-storage/typings.json | 6 + .../typings/azure-storage/azure-storage.d.ts | 9520 +++++++++++++++++ .../typings/globals/node/index.d.ts | 1440 +++ .../typings/globals/node/typings.json | 13 + node_modules/azure-storage/typings/index.d.ts | 1 + node_modules/bcrypt-pbkdf/README.md | 39 + node_modules/bcrypt-pbkdf/index.js | 556 + node_modules/bcrypt-pbkdf/package.json | 75 + node_modules/boom/.npmignore | 18 + node_modules/boom/.travis.yml | 8 + node_modules/boom/CONTRIBUTING.md | 1 + node_modules/boom/LICENSE | 28 + node_modules/boom/README.md | 652 ++ node_modules/boom/images/boom.png | Bin 0 -> 29479 bytes node_modules/boom/lib/index.js | 318 + node_modules/boom/package.json | 89 + node_modules/boom/test/index.js | 654 ++ node_modules/browserify-mime/.npmignore | 3 + node_modules/browserify-mime/LICENSE | 19 + node_modules/browserify-mime/README.md | 63 + .../browserify-mime/browserify-mime.js | 1813 ++++ node_modules/browserify-mime/mime.js | 114 + node_modules/browserify-mime/package.json | 76 + node_modules/browserify-mime/test.js | 62 + node_modules/caseless/LICENSE | 28 + node_modules/caseless/README.md | 45 + node_modules/caseless/index.js | 67 + node_modules/caseless/package.json | 92 + node_modules/caseless/test.js | 67 + node_modules/co/History.md | 172 + node_modules/co/LICENSE | 22 + node_modules/co/Readme.md | 212 + node_modules/co/index.js | 237 + node_modules/co/package.json | 98 + node_modules/combined-stream/License | 19 + node_modules/combined-stream/Readme.md | 138 + .../combined-stream/lib/combined_stream.js | 188 + node_modules/combined-stream/package.json | 94 + node_modules/core-util-is/LICENSE | 19 + node_modules/core-util-is/README.md | 3 + node_modules/core-util-is/float.patch | 604 ++ node_modules/core-util-is/lib/util.js | 107 + node_modules/core-util-is/package.json | 86 + node_modules/core-util-is/test.js | 68 + node_modules/cryptiles/.npmignore | 18 + node_modules/cryptiles/.travis.yml | 8 + node_modules/cryptiles/LICENSE | 28 + node_modules/cryptiles/README.md | 16 + node_modules/cryptiles/lib/index.js | 68 + node_modules/cryptiles/package.json | 85 + node_modules/cryptiles/test/index.js | 102 + node_modules/dashdash/CHANGES.md | 364 + node_modules/dashdash/LICENSE.txt | 24 + node_modules/dashdash/README.md | 574 + .../dashdash/etc/dashdash.bash_completion.in | 389 + node_modules/dashdash/lib/dashdash.js | 1055 ++ .../dashdash/node_modules/assert-plus/AUTHORS | 6 + .../node_modules/assert-plus/CHANGES.md | 14 + .../node_modules/assert-plus/README.md | 162 + .../node_modules/assert-plus/assert.js | 211 + .../node_modules/assert-plus/package.json | 106 + node_modules/dashdash/package.json | 116 + node_modules/delayed-stream/.npmignore | 1 + node_modules/delayed-stream/License | 19 + node_modules/delayed-stream/Makefile | 7 + node_modules/delayed-stream/Readme.md | 141 + .../delayed-stream/lib/delayed_stream.js | 107 + node_modules/delayed-stream/package.json | 88 + node_modules/ecc-jsbn/.npmignore | 15 + node_modules/ecc-jsbn/LICENSE | 21 + node_modules/ecc-jsbn/README.md | 8 + node_modules/ecc-jsbn/index.js | 57 + node_modules/ecc-jsbn/lib/LICENSE-jsbn | 40 + node_modules/ecc-jsbn/lib/ec.js | 561 + node_modules/ecc-jsbn/lib/sec.js | 170 + node_modules/ecc-jsbn/package.json | 81 + node_modules/ecc-jsbn/test.js | 14 + node_modules/extend/.npmignore | 1 + node_modules/extend/.travis.yml | 5 + node_modules/extend/README.md | 59 + node_modules/extend/index.js | 78 + node_modules/extend/package.json | 85 + node_modules/extsprintf/.gitmodules | 0 node_modules/extsprintf/.npmignore | 2 + node_modules/extsprintf/LICENSE | 19 + node_modules/extsprintf/Makefile | 24 + node_modules/extsprintf/Makefile.targ | 285 + node_modules/extsprintf/README.md | 46 + node_modules/extsprintf/jsl.node.conf | 137 + node_modules/extsprintf/lib/extsprintf.js | 183 + node_modules/extsprintf/package.json | 69 + node_modules/fast-deep-equal/.eslintrc.yml | 25 + node_modules/fast-deep-equal/.npmignore | 60 + node_modules/fast-deep-equal/.travis.yml | 8 + node_modules/fast-deep-equal/LICENSE | 21 + node_modules/fast-deep-equal/README.md | 55 + .../fast-deep-equal/benchmark/.eslintrc.yml | 5 + .../fast-deep-equal/benchmark/index.js | 56 + node_modules/fast-deep-equal/index.js | 43 + node_modules/fast-deep-equal/package.json | 105 + .../fast-deep-equal/spec/.eslintrc.yml | 5 + .../fast-deep-equal/spec/index.spec.js | 18 + node_modules/fast-deep-equal/spec/tests.js | 320 + .../fast-json-stable-stringify/.eslintrc.yml | 26 + .../fast-json-stable-stringify/.npmignore | 4 + .../fast-json-stable-stringify/.travis.yml | 8 + .../fast-json-stable-stringify/LICENSE | 18 + .../fast-json-stable-stringify/README.md | 119 + .../benchmark/index.js | 31 + .../benchmark/test.json | 137 + .../example/key_cmp.js | 7 + .../example/nested.js | 3 + .../fast-json-stable-stringify/example/str.js | 3 + .../example/value_cmp.js | 7 + .../fast-json-stable-stringify/index.js | 59 + .../fast-json-stable-stringify/package.json | 105 + .../fast-json-stable-stringify/test/cmp.js | 13 + .../fast-json-stable-stringify/test/nested.js | 44 + .../fast-json-stable-stringify/test/str.js | 46 + .../test/to-json.js | 22 + node_modules/forever-agent/LICENSE | 55 + node_modules/forever-agent/README.md | 4 + node_modules/forever-agent/index.js | 138 + node_modules/forever-agent/package.json | 80 + node_modules/form-data/License | 19 + node_modules/form-data/README.md | 217 + node_modules/form-data/lib/browser.js | 2 + node_modules/form-data/lib/form_data.js | 444 + node_modules/form-data/lib/populate.js | 10 + node_modules/form-data/package.json | 136 + node_modules/getpass/.npmignore | 8 + node_modules/getpass/.travis.yml | 9 + node_modules/getpass/LICENSE | 18 + node_modules/getpass/README.md | 32 + node_modules/getpass/lib/index.js | 123 + .../getpass/node_modules/assert-plus/AUTHORS | 6 + .../node_modules/assert-plus/CHANGES.md | 14 + .../node_modules/assert-plus/README.md | 162 + .../node_modules/assert-plus/assert.js | 211 + .../node_modules/assert-plus/package.json | 106 + node_modules/getpass/package.json | 77 + node_modules/har-schema/LICENSE | 13 + node_modules/har-schema/README.md | 49 + node_modules/har-schema/lib/afterRequest.json | 29 + .../har-schema/lib/beforeRequest.json | 29 + node_modules/har-schema/lib/browser.json | 19 + node_modules/har-schema/lib/cache.json | 20 + node_modules/har-schema/lib/content.json | 28 + node_modules/har-schema/lib/cookie.json | 35 + node_modules/har-schema/lib/creator.json | 19 + node_modules/har-schema/lib/entry.json | 52 + node_modules/har-schema/lib/har.json | 12 + node_modules/har-schema/lib/header.json | 19 + node_modules/har-schema/lib/index.js | 22 + node_modules/har-schema/lib/log.json | 35 + node_modules/har-schema/lib/page.json | 31 + node_modules/har-schema/lib/pageTimings.json | 17 + node_modules/har-schema/lib/postData.json | 42 + node_modules/har-schema/lib/query.json | 19 + node_modules/har-schema/lib/request.json | 56 + node_modules/har-schema/lib/response.json | 53 + node_modules/har-schema/lib/timings.json | 41 + node_modules/har-schema/package.json | 113 + node_modules/har-validator/LICENSE | 13 + node_modules/har-validator/README.md | 75 + .../har-validator/lib/browser/async.js | 96 + .../har-validator/lib/browser/error.js | 15 + .../har-validator/lib/browser/promise.js | 93 + node_modules/har-validator/lib/node4/async.js | 136 + node_modules/har-validator/lib/node4/error.js | 22 + .../har-validator/lib/node4/promise.js | 132 + node_modules/har-validator/lib/node6/async.js | 133 + node_modules/har-validator/lib/node6/error.js | 22 + .../har-validator/lib/node6/promise.js | 130 + node_modules/har-validator/lib/node7/async.js | 133 + node_modules/har-validator/lib/node7/error.js | 22 + .../har-validator/lib/node7/promise.js | 130 + node_modules/har-validator/package.json | 127 + node_modules/har-validator/src/async.js | 96 + node_modules/har-validator/src/error.js | 15 + node_modules/har-validator/src/promise.js | 93 + node_modules/hash-base/LICENSE | 21 + node_modules/hash-base/README.md | 48 + node_modules/hash-base/index.js | 95 + node_modules/hash-base/package.json | 104 + node_modules/hawk/.npmignore | 20 + node_modules/hawk/.travis.yml | 5 + node_modules/hawk/LICENSE | 28 + node_modules/hawk/README.md | 634 ++ node_modules/hawk/bower.json | 24 + node_modules/hawk/component.json | 19 + node_modules/hawk/dist/client.js | 343 + node_modules/hawk/example/usage.js | 78 + node_modules/hawk/images/hawk.png | Bin 0 -> 6945 bytes node_modules/hawk/images/logo.png | Bin 0 -> 71732 bytes node_modules/hawk/lib/browser.js | 637 ++ node_modules/hawk/lib/client.js | 369 + node_modules/hawk/lib/crypto.js | 126 + node_modules/hawk/lib/index.js | 15 + node_modules/hawk/lib/server.js | 548 + node_modules/hawk/lib/utils.js | 184 + node_modules/hawk/package.json | 92 + node_modules/hawk/test/browser.js | 1492 +++ node_modules/hawk/test/client.js | 440 + node_modules/hawk/test/crypto.js | 70 + node_modules/hawk/test/index.js | 378 + node_modules/hawk/test/readme.js | 95 + node_modules/hawk/test/server.js | 1329 +++ node_modules/hawk/test/uri.js | 838 ++ node_modules/hawk/test/utils.js | 149 + node_modules/hoek/.npmignore | 18 + node_modules/hoek/.travis.yml | 7 + node_modules/hoek/CONTRIBUTING.md | 1 + node_modules/hoek/LICENSE | 31 + node_modules/hoek/README.md | 584 + node_modules/hoek/images/hoek.png | Bin 0 -> 37939 bytes node_modules/hoek/lib/escape.js | 132 + node_modules/hoek/lib/index.js | 993 ++ node_modules/hoek/package.json | 87 + node_modules/hoek/test/escaper.js | 88 + node_modules/hoek/test/index.js | 2513 +++++ node_modules/hoek/test/modules/ignore.txt | 0 node_modules/hoek/test/modules/test1.js | 1 + node_modules/hoek/test/modules/test2.js | 1 + node_modules/hoek/test/modules/test3.js | 1 + node_modules/http-signature/.dir-locals.el | 6 + node_modules/http-signature/.npmignore | 7 + node_modules/http-signature/CHANGES.md | 46 + node_modules/http-signature/LICENSE | 18 + node_modules/http-signature/README.md | 79 + node_modules/http-signature/http_signing.md | 363 + node_modules/http-signature/lib/index.js | 29 + node_modules/http-signature/lib/parser.js | 318 + node_modules/http-signature/lib/signer.js | 399 + node_modules/http-signature/lib/utils.js | 112 + node_modules/http-signature/lib/verify.js | 88 + node_modules/http-signature/package.json | 107 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 7 + node_modules/inherits/inherits_browser.js | 23 + node_modules/inherits/package.json | 90 + node_modules/is-typedarray/LICENSE.md | 18 + node_modules/is-typedarray/README.md | 16 + node_modules/is-typedarray/index.js | 41 + node_modules/is-typedarray/package.json | 82 + node_modules/is-typedarray/test.js | 34 + node_modules/isarray/.npmignore | 1 + node_modules/isarray/.travis.yml | 4 + node_modules/isarray/Makefile | 6 + node_modules/isarray/README.md | 60 + node_modules/isarray/component.json | 19 + node_modules/isarray/index.js | 5 + node_modules/isarray/package.json | 95 + node_modules/isarray/test.js | 20 + node_modules/isstream/.jshintrc | 59 + node_modules/isstream/.npmignore | 1 + node_modules/isstream/.travis.yml | 12 + node_modules/isstream/LICENSE.md | 11 + node_modules/isstream/README.md | 66 + node_modules/isstream/isstream.js | 27 + node_modules/isstream/package.json | 85 + node_modules/isstream/test.js | 168 + node_modules/jsbn/.npmignore | 2 + node_modules/jsbn/LICENSE | 40 + node_modules/jsbn/README.md | 175 + node_modules/jsbn/example.html | 12 + node_modules/jsbn/example.js | 3 + node_modules/jsbn/index.js | 1357 +++ node_modules/jsbn/package.json | 81 + node_modules/json-edm-parser/.npmignore | 33 + node_modules/json-edm-parser/.travis.yml | 17 + node_modules/json-edm-parser/LICENSE | 22 + node_modules/json-edm-parser/README.md | 40 + node_modules/json-edm-parser/package.json | 86 + node_modules/json-edm-parser/parser.js | 85 + node_modules/json-edm-parser/test/boundary.js | 102 + node_modules/json-edm-parser/test/edm.js | 106 + node_modules/json-edm-parser/test/invalid.js | 15 + node_modules/json-edm-parser/test/offset.js | 67 + .../json-edm-parser/test/primitives.js | 61 + node_modules/json-edm-parser/test/utf8.js | 38 + .../json-schema-traverse/.eslintrc.yml | 27 + node_modules/json-schema-traverse/.npmignore | 60 + node_modules/json-schema-traverse/.travis.yml | 8 + node_modules/json-schema-traverse/LICENSE | 21 + node_modules/json-schema-traverse/README.md | 69 + node_modules/json-schema-traverse/index.js | 81 + .../json-schema-traverse/package.json | 97 + .../json-schema-traverse/spec/.eslintrc.yml | 6 + .../spec/fixtures/schema.js | 125 + .../json-schema-traverse/spec/index.spec.js | 102 + node_modules/json-schema/README.md | 5 + .../json-schema/draft-00/hyper-schema | 68 + node_modules/json-schema/draft-00/json-ref | 26 + node_modules/json-schema/draft-00/links | 33 + node_modules/json-schema/draft-00/schema | 155 + .../json-schema/draft-01/hyper-schema | 68 + node_modules/json-schema/draft-01/json-ref | 26 + node_modules/json-schema/draft-01/links | 33 + node_modules/json-schema/draft-01/schema | 155 + .../json-schema/draft-02/hyper-schema | 68 + node_modules/json-schema/draft-02/json-ref | 26 + node_modules/json-schema/draft-02/links | 35 + node_modules/json-schema/draft-02/schema | 166 + .../json-schema/draft-03/examples/address | 20 + .../json-schema/draft-03/examples/calendar | 53 + .../json-schema/draft-03/examples/card | 105 + .../json-schema/draft-03/examples/geo | 8 + .../json-schema/draft-03/examples/interfaces | 23 + .../json-schema/draft-03/hyper-schema | 60 + node_modules/json-schema/draft-03/json-ref | 26 + node_modules/json-schema/draft-03/links | 35 + node_modules/json-schema/draft-03/schema | 174 + .../json-schema/draft-04/hyper-schema | 60 + node_modules/json-schema/draft-04/links | 41 + node_modules/json-schema/draft-04/schema | 189 + .../json-schema/draft-zyp-json-schema-03.xml | 1120 ++ .../json-schema/draft-zyp-json-schema-04.xml | 1072 ++ node_modules/json-schema/lib/links.js | 66 + node_modules/json-schema/lib/validate.js | 273 + node_modules/json-schema/package.json | 91 + node_modules/json-schema/test/tests.js | 95 + node_modules/json-stable-stringify/.npmignore | 1 + .../json-stable-stringify/.travis.yml | 4 + node_modules/json-stable-stringify/LICENSE | 18 + .../json-stable-stringify/example/key_cmp.js | 7 + .../json-stable-stringify/example/nested.js | 3 + .../json-stable-stringify/example/str.js | 3 + .../example/value_cmp.js | 7 + node_modules/json-stable-stringify/index.js | 84 + .../json-stable-stringify/package.json | 100 + .../json-stable-stringify/readme.markdown | 130 + .../json-stable-stringify/test/cmp.js | 11 + .../json-stable-stringify/test/nested.js | 35 + .../json-stable-stringify/test/replacer.js | 74 + .../json-stable-stringify/test/space.js | 59 + .../json-stable-stringify/test/str.js | 32 + .../json-stable-stringify/test/to-json.js | 20 + node_modules/json-stringify-safe/.npmignore | 1 + node_modules/json-stringify-safe/CHANGELOG.md | 14 + node_modules/json-stringify-safe/LICENSE | 15 + node_modules/json-stringify-safe/Makefile | 35 + node_modules/json-stringify-safe/README.md | 52 + node_modules/json-stringify-safe/package.json | 94 + node_modules/json-stringify-safe/stringify.js | 27 + .../json-stringify-safe/test/mocha.opts | 2 + .../test/stringify_test.js | 246 + node_modules/jsonify/README.markdown | 34 + node_modules/jsonify/index.js | 2 + node_modules/jsonify/lib/parse.js | 273 + node_modules/jsonify/lib/stringify.js | 154 + node_modules/jsonify/package.json | 77 + node_modules/jsonify/test/parse.js | 16 + node_modules/jsonify/test/stringify.js | 15 + node_modules/jsonparse/.npmignore | 1 + node_modules/jsonparse/LICENSE | 24 + node_modules/jsonparse/README.markdown | 11 + node_modules/jsonparse/bench.js | 26 + .../jsonparse/examples/twitterfeed.js | 30 + node_modules/jsonparse/jsonparse.js | 341 + node_modules/jsonparse/package.json | 84 + node_modules/jsonparse/samplejson/basic.json | 167 + node_modules/jsonparse/samplejson/basic2.json | 180 + node_modules/jsonparse/test/boundary.js | 110 + node_modules/jsonparse/test/offset.js | 67 + node_modules/jsonparse/test/primitives.js | 57 + node_modules/jsonparse/test/unvalid.js | 15 + node_modules/jsonparse/test/utf8.js | 38 + node_modules/jsprim/CHANGES.md | 49 + node_modules/jsprim/CONTRIBUTING.md | 19 + node_modules/jsprim/LICENSE | 19 + node_modules/jsprim/README.md | 287 + node_modules/jsprim/lib/jsprim.js | 735 ++ .../jsprim/node_modules/assert-plus/AUTHORS | 6 + .../node_modules/assert-plus/CHANGES.md | 14 + .../jsprim/node_modules/assert-plus/README.md | 162 + .../jsprim/node_modules/assert-plus/assert.js | 211 + .../node_modules/assert-plus/package.json | 106 + node_modules/jsprim/package.json | 78 + node_modules/md5.js/LICENSE | 21 + node_modules/md5.js/README.md | 31 + node_modules/md5.js/index.js | 145 + node_modules/md5.js/package.json | 104 + node_modules/mime-db/HISTORY.md | 343 + node_modules/mime-db/LICENSE | 22 + node_modules/mime-db/README.md | 94 + node_modules/mime-db/db.json | 6966 ++++++++++++ node_modules/mime-db/index.js | 11 + node_modules/mime-db/package.json | 131 + node_modules/mime-types/HISTORY.md | 247 + node_modules/mime-types/LICENSE | 23 + node_modules/mime-types/README.md | 108 + node_modules/mime-types/index.js | 188 + node_modules/mime-types/package.json | 123 + node_modules/node-uuid/.npmignore | 4 + node_modules/node-uuid/LICENSE.md | 21 + node_modules/node-uuid/README.md | 8 + node_modules/node-uuid/benchmark/README.md | 53 + node_modules/node-uuid/benchmark/bench.gnu | 174 + node_modules/node-uuid/benchmark/bench.sh | 34 + .../node-uuid/benchmark/benchmark-native.c | 34 + node_modules/node-uuid/benchmark/benchmark.js | 84 + node_modules/node-uuid/bin/uuid | 26 + node_modules/node-uuid/bower.json | 23 + node_modules/node-uuid/component.json | 25 + node_modules/node-uuid/lib/sha1-browser.js | 120 + node_modules/node-uuid/package.json | 108 + node_modules/node-uuid/test/compare_v1.js | 63 + node_modules/node-uuid/test/test.html | 17 + node_modules/node-uuid/test/test.js | 231 + node_modules/node-uuid/uuid.js | 272 + node_modules/node-uuid/v3.js | 54 + node_modules/nonce/.npmignore | 4 + node_modules/nonce/.travis.yml | 6 + node_modules/nonce/LICENSE | 15 + node_modules/nonce/README.markdown | 12 + node_modules/nonce/index.js | 20 + node_modules/nonce/package.json | 86 + node_modules/oauth-sign/LICENSE | 55 + node_modules/oauth-sign/README.md | 4 + node_modules/oauth-sign/index.js | 136 + node_modules/oauth-sign/package.json | 90 + node_modules/performance-now/.npmignore | 1 + node_modules/performance-now/.tm_properties | 7 + node_modules/performance-now/.travis.yml | 4 + node_modules/performance-now/Makefile | 25 + node_modules/performance-now/README.md | 30 + .../performance-now/lib/performance-now.js | 32 + node_modules/performance-now/license.txt | 7 + node_modules/performance-now/package.json | 76 + .../src/performance-now.coffee | 15 + node_modules/performance-now/test/mocha.opts | 3 + .../test/performance-now.coffee | 38 + node_modules/process-nextick-args/.travis.yml | 12 + node_modules/process-nextick-args/index.js | 43 + node_modules/process-nextick-args/license.md | 19 + .../process-nextick-args/package.json | 74 + node_modules/process-nextick-args/readme.md | 18 + node_modules/process-nextick-args/test.js | 24 + node_modules/punycode/LICENSE-MIT.txt | 20 + node_modules/punycode/README.md | 176 + node_modules/punycode/package.json | 118 + node_modules/punycode/punycode.js | 533 + node_modules/qs/.eslintignore | 1 + node_modules/qs/.eslintrc | 18 + node_modules/qs/.jscs.json | 176 + node_modules/qs/CHANGELOG.md | 175 + node_modules/qs/LICENSE | 28 + node_modules/qs/README.md | 440 + node_modules/qs/dist/qs.js | 597 ++ node_modules/qs/lib/formats.js | 18 + node_modules/qs/lib/index.js | 11 + node_modules/qs/lib/parse.js | 167 + node_modules/qs/lib/stringify.js | 207 + node_modules/qs/lib/utils.js | 182 + node_modules/qs/package.json | 112 + node_modules/qs/test/.eslintrc | 11 + node_modules/qs/test/index.js | 7 + node_modules/qs/test/parse.js | 519 + node_modules/qs/test/stringify.js | 567 + node_modules/qs/test/utils.js | 22 + node_modules/readable-stream/.npmignore | 5 + node_modules/readable-stream/.travis.yml | 52 + node_modules/readable-stream/.zuul.yml | 1 + node_modules/readable-stream/LICENSE | 18 + node_modules/readable-stream/README.md | 36 + .../readable-stream/doc/stream.markdown | 1760 +++ .../doc/wg-meetings/2015-01-30.md | 60 + 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 | 880 ++ .../readable-stream/lib/_stream_transform.js | 180 + .../readable-stream/lib/_stream_writable.js | 516 + node_modules/readable-stream/package.json | 104 + node_modules/readable-stream/passthrough.js | 1 + node_modules/readable-stream/readable.js | 12 + node_modules/readable-stream/transform.js | 1 + node_modules/readable-stream/writable.js | 1 + node_modules/request/CHANGELOG.md | 674 ++ node_modules/request/LICENSE | 55 + node_modules/request/README.md | 1097 ++ node_modules/request/index.js | 155 + node_modules/request/lib/auth.js | 167 + node_modules/request/lib/cookies.js | 38 + node_modules/request/lib/getProxyFromURI.js | 79 + node_modules/request/lib/har.js | 205 + node_modules/request/lib/helpers.js | 66 + node_modules/request/lib/multipart.js | 112 + node_modules/request/lib/oauth.js | 148 + node_modules/request/lib/querystring.js | 50 + node_modules/request/lib/redirect.js | 154 + node_modules/request/lib/tunnel.js | 175 + node_modules/request/node_modules/.bin/uuid | 15 + .../request/node_modules/.bin/uuid.cmd | 7 + .../node_modules/ajv/.tonic_example.js | 20 + node_modules/request/node_modules/ajv/LICENSE | 22 + .../request/node_modules/ajv/README.md | 1327 +++ .../node_modules/ajv/dist/ajv.bundle.js | 7345 +++++++++++++ .../request/node_modules/ajv/dist/ajv.min.js | 3 + .../node_modules/ajv/dist/ajv.min.js.map | 1 + .../node_modules/ajv/dist/nodent.min.js | 2 + .../node_modules/ajv/dist/regenerator.min.js | 2 + .../request/node_modules/ajv/lib/$data.js | 49 + .../request/node_modules/ajv/lib/ajv.d.ts | 358 + .../request/node_modules/ajv/lib/ajv.js | 502 + .../request/node_modules/ajv/lib/cache.js | 26 + .../node_modules/ajv/lib/compile/_rules.js | 31 + .../node_modules/ajv/lib/compile/async.js | 90 + .../node_modules/ajv/lib/compile/equal.js | 3 + .../ajv/lib/compile/error_classes.js | 34 + .../node_modules/ajv/lib/compile/formats.js | 135 + .../node_modules/ajv/lib/compile/index.js | 380 + .../node_modules/ajv/lib/compile/resolve.js | 271 + .../node_modules/ajv/lib/compile/rules.js | 58 + .../ajv/lib/compile/schema_obj.js | 9 + .../ajv/lib/compile/ucs2length.js | 20 + .../node_modules/ajv/lib/compile/util.js | 267 + .../node_modules/ajv/lib/dot/_limit.jst | 96 + .../node_modules/ajv/lib/dot/_limitItems.jst | 10 + .../node_modules/ajv/lib/dot/_limitLength.jst | 10 + .../ajv/lib/dot/_limitProperties.jst | 10 + .../node_modules/ajv/lib/dot/allOf.jst | 34 + .../node_modules/ajv/lib/dot/anyOf.jst | 48 + .../node_modules/ajv/lib/dot/coerce.def | 61 + .../node_modules/ajv/lib/dot/const.jst | 11 + .../node_modules/ajv/lib/dot/contains.jst | 57 + .../node_modules/ajv/lib/dot/custom.jst | 191 + .../node_modules/ajv/lib/dot/defaults.def | 32 + .../node_modules/ajv/lib/dot/definitions.def | 199 + .../node_modules/ajv/lib/dot/dependencies.jst | 80 + .../request/node_modules/ajv/lib/dot/enum.jst | 30 + .../node_modules/ajv/lib/dot/errors.def | 194 + .../node_modules/ajv/lib/dot/format.jst | 106 + .../node_modules/ajv/lib/dot/items.jst | 100 + .../node_modules/ajv/lib/dot/missing.def | 39 + .../node_modules/ajv/lib/dot/multipleOf.jst | 20 + .../request/node_modules/ajv/lib/dot/not.jst | 43 + .../node_modules/ajv/lib/dot/oneOf.jst | 44 + .../node_modules/ajv/lib/dot/pattern.jst | 14 + .../node_modules/ajv/lib/dot/properties.jst | 327 + .../ajv/lib/dot/propertyNames.jst | 54 + .../request/node_modules/ajv/lib/dot/ref.jst | 85 + .../node_modules/ajv/lib/dot/required.jst | 108 + .../node_modules/ajv/lib/dot/uniqueItems.jst | 38 + .../node_modules/ajv/lib/dot/validate.jst | 272 + .../node_modules/ajv/lib/dotjs/README.md | 3 + .../node_modules/ajv/lib/dotjs/_limit.js | 149 + .../node_modules/ajv/lib/dotjs/_limitItems.js | 76 + .../ajv/lib/dotjs/_limitLength.js | 81 + .../ajv/lib/dotjs/_limitProperties.js | 76 + .../node_modules/ajv/lib/dotjs/allOf.js | 43 + .../node_modules/ajv/lib/dotjs/anyOf.js | 73 + .../node_modules/ajv/lib/dotjs/const.js | 55 + .../node_modules/ajv/lib/dotjs/contains.js | 81 + .../node_modules/ajv/lib/dotjs/custom.js | 226 + .../ajv/lib/dotjs/dependencies.js | 167 + .../node_modules/ajv/lib/dotjs/enum.js | 65 + .../node_modules/ajv/lib/dotjs/format.js | 149 + .../node_modules/ajv/lib/dotjs/items.js | 140 + .../node_modules/ajv/lib/dotjs/multipleOf.js | 76 + .../request/node_modules/ajv/lib/dotjs/not.js | 83 + .../node_modules/ajv/lib/dotjs/oneOf.js | 70 + .../node_modules/ajv/lib/dotjs/pattern.js | 74 + .../node_modules/ajv/lib/dotjs/properties.js | 468 + .../ajv/lib/dotjs/propertyNames.js | 81 + .../request/node_modules/ajv/lib/dotjs/ref.js | 123 + .../node_modules/ajv/lib/dotjs/required.js | 268 + .../node_modules/ajv/lib/dotjs/uniqueItems.js | 71 + .../node_modules/ajv/lib/dotjs/validate.js | 458 + .../request/node_modules/ajv/lib/keyword.js | 135 + .../node_modules/ajv/lib/patternGroups.js | 36 + .../node_modules/ajv/lib/refs/$data.json | 17 + .../ajv/lib/refs/json-schema-draft-04.json | 150 + .../ajv/lib/refs/json-schema-draft-06.json | 154 + .../ajv/lib/refs/json-schema-v5.json | 250 + .../request/node_modules/ajv/package.json | 160 + .../node_modules/ajv/scripts/.eslintrc.yml | 3 + .../node_modules/ajv/scripts/bundle.js | 61 + .../node_modules/ajv/scripts/compile-dots.js | 73 + .../request/node_modules/ajv/scripts/info | 10 + .../node_modules/ajv/scripts/prepare-tests | 9 + .../node_modules/ajv/scripts/travis-gh-pages | 23 + .../request/node_modules/assert-plus/AUTHORS | 6 + .../node_modules/assert-plus/CHANGES.md | 14 + .../node_modules/assert-plus/README.md | 162 + .../node_modules/assert-plus/assert.js | 211 + .../node_modules/assert-plus/package.json | 106 + .../request/node_modules/aws-sign2/LICENSE | 55 + .../request/node_modules/aws-sign2/README.md | 4 + .../request/node_modules/aws-sign2/index.js | 212 + .../node_modules/aws-sign2/package.json | 76 + .../request/node_modules/boom/LICENSE | 29 + .../request/node_modules/boom/README.md | 760 ++ .../request/node_modules/boom/lib/index.js | 433 + .../request/node_modules/boom/package.json | 95 + .../request/node_modules/cryptiles/.npmignore | 3 + .../request/node_modules/cryptiles/LICENSE | 28 + .../request/node_modules/cryptiles/README.md | 19 + .../node_modules/cryptiles/lib/index.js | 88 + .../cryptiles/node_modules/boom/LICENSE | 29 + .../cryptiles/node_modules/boom/README.md | 784 ++ .../cryptiles/node_modules/boom/lib/index.js | 457 + .../cryptiles/node_modules/boom/package.json | 104 + .../node_modules/cryptiles/package.json | 103 + .../request/node_modules/extend/.eslintrc | 17 + .../request/node_modules/extend/.jscs.json | 175 + .../request/node_modules/extend/.npmignore | 1 + .../request/node_modules/extend/.travis.yml | 179 + .../request/node_modules/extend/CHANGELOG.md | 77 + .../request/node_modules/extend/LICENSE | 23 + .../request/node_modules/extend/README.md | 81 + .../node_modules/extend/component.json | 32 + .../request/node_modules/extend/index.js | 86 + .../request/node_modules/extend/package.json | 105 + .../request/node_modules/form-data/License | 19 + .../request/node_modules/form-data/README.md | 234 + .../node_modules/form-data/README.md.bak | 234 + .../node_modules/form-data/lib/browser.js | 2 + .../node_modules/form-data/lib/form_data.js | 457 + .../node_modules/form-data/lib/populate.js | 10 + .../node_modules/form-data/package.json | 136 + .../request/node_modules/har-schema/LICENSE | 13 + .../request/node_modules/har-schema/README.md | 49 + .../har-schema/lib/afterRequest.json | 30 + .../har-schema/lib/beforeRequest.json | 30 + .../node_modules/har-schema/lib/browser.json | 20 + .../node_modules/har-schema/lib/cache.json | 21 + .../node_modules/har-schema/lib/content.json | 29 + .../node_modules/har-schema/lib/cookie.json | 36 + .../node_modules/har-schema/lib/creator.json | 20 + .../node_modules/har-schema/lib/entry.json | 53 + .../node_modules/har-schema/lib/har.json | 13 + .../node_modules/har-schema/lib/header.json | 20 + .../node_modules/har-schema/lib/index.js | 22 + .../node_modules/har-schema/lib/log.json | 36 + .../node_modules/har-schema/lib/page.json | 32 + .../har-schema/lib/pageTimings.json | 18 + .../node_modules/har-schema/lib/postData.json | 43 + .../node_modules/har-schema/lib/query.json | 20 + .../node_modules/har-schema/lib/request.json | 57 + .../node_modules/har-schema/lib/response.json | 54 + .../node_modules/har-schema/lib/timings.json | 42 + .../node_modules/har-schema/package.json | 113 + .../node_modules/har-validator/LICENSE | 13 + .../node_modules/har-validator/README.md | 54 + .../node_modules/har-validator/lib/async.js | 98 + .../node_modules/har-validator/lib/error.js | 17 + .../node_modules/har-validator/lib/promise.js | 95 + .../node_modules/har-validator/package.json | 101 + .../request/node_modules/hawk/.npmignore | 5 + .../request/node_modules/hawk/LICENSE | 28 + .../request/node_modules/hawk/README.md | 637 ++ .../request/node_modules/hawk/client.js | 3 + .../request/node_modules/hawk/dist/browser.js | 793 ++ .../request/node_modules/hawk/lib/browser.js | 653 ++ .../request/node_modules/hawk/lib/client.js | 394 + .../request/node_modules/hawk/lib/crypto.js | 128 + .../request/node_modules/hawk/lib/index.js | 17 + .../request/node_modules/hawk/lib/server.js | 550 + .../request/node_modules/hawk/lib/utils.js | 186 + .../request/node_modules/hawk/package.json | 105 + .../request/node_modules/hoek/.npmignore | 3 + .../request/node_modules/hoek/LICENSE | 32 + .../request/node_modules/hoek/README.md | 30 + .../request/node_modules/hoek/lib/escape.js | 168 + .../request/node_modules/hoek/lib/index.js | 974 ++ .../request/node_modules/hoek/package.json | 97 + .../http-signature/.dir-locals.el | 6 + .../node_modules/http-signature/.npmignore | 7 + .../node_modules/http-signature/CHANGES.md | 46 + .../node_modules/http-signature/LICENSE | 18 + .../node_modules/http-signature/README.md | 79 + .../http-signature/http_signing.md | 363 + .../node_modules/http-signature/lib/index.js | 29 + .../node_modules/http-signature/lib/parser.js | 315 + .../node_modules/http-signature/lib/signer.js | 401 + .../node_modules/http-signature/lib/utils.js | 112 + .../node_modules/http-signature/lib/verify.js | 88 + .../node_modules/http-signature/package.json | 111 + .../node_modules/performance-now/.npmignore | 1 + .../performance-now/.tm_properties | 7 + .../node_modules/performance-now/.travis.yml | 6 + .../node_modules/performance-now/README.md | 30 + .../performance-now/lib/performance-now.js | 36 + .../lib/performance-now.js.map | 10 + .../node_modules/performance-now/license.txt | 7 + .../node_modules/performance-now/package.json | 90 + .../performance-now/src/index.d.ts | 8 + .../src/performance-now.coffee | 17 + .../performance-now/test/mocha.opts | 3 + .../test/performance-now.coffee | 43 + .../performance-now/test/scripts.coffee | 27 + .../test/scripts/delayed-call.coffee | 11 + .../test/scripts/delayed-require.coffee | 12 + .../test/scripts/difference.coffee | 6 + .../test/scripts/initial-value.coffee | 10 + .../request/node_modules/qs/.editorconfig | 30 + .../request/node_modules/qs/.eslintignore | 1 + .../request/node_modules/qs/.eslintrc | 19 + .../request/node_modules/qs/CHANGELOG.md | 221 + node_modules/request/node_modules/qs/LICENSE | 28 + .../request/node_modules/qs/README.md | 475 + .../request/node_modules/qs/dist/qs.js | 627 ++ .../request/node_modules/qs/lib/formats.js | 18 + .../request/node_modules/qs/lib/index.js | 11 + .../request/node_modules/qs/lib/parse.js | 174 + .../request/node_modules/qs/lib/stringify.js | 210 + .../request/node_modules/qs/lib/utils.js | 202 + .../request/node_modules/qs/package.json | 114 + .../request/node_modules/qs/test/.eslintrc | 15 + .../request/node_modules/qs/test/index.js | 7 + .../request/node_modules/qs/test/parse.js | 573 + .../request/node_modules/qs/test/stringify.js | 596 ++ .../request/node_modules/qs/test/utils.js | 34 + .../request/node_modules/sntp/.npmignore | 3 + .../request/node_modules/sntp/LICENSE | 28 + .../request/node_modules/sntp/README.md | 68 + .../request/node_modules/sntp/lib/index.js | 412 + .../request/node_modules/sntp/package.json | 91 + .../request/node_modules/uuid/.eslintrc.json | 47 + .../request/node_modules/uuid/AUTHORS | 5 + .../request/node_modules/uuid/CHANGELOG.md | 57 + .../request/node_modules/uuid/LICENSE.md | 21 + .../request/node_modules/uuid/README.md | 293 + .../request/node_modules/uuid/README_js.md | 280 + .../request/node_modules/uuid/bin/uuid | 65 + .../request/node_modules/uuid/index.js | 8 + .../node_modules/uuid/lib/bytesToUuid.js | 23 + .../node_modules/uuid/lib/md5-browser.js | 216 + .../request/node_modules/uuid/lib/md5.js | 25 + .../node_modules/uuid/lib/rng-browser.js | 32 + .../request/node_modules/uuid/lib/rng.js | 8 + .../node_modules/uuid/lib/sha1-browser.js | 89 + .../request/node_modules/uuid/lib/sha1.js | 25 + .../request/node_modules/uuid/lib/v35.js | 53 + .../request/node_modules/uuid/package.json | 124 + node_modules/request/node_modules/uuid/v1.js | 109 + node_modules/request/node_modules/uuid/v3.js | 4 + node_modules/request/node_modules/uuid/v4.js | 29 + node_modules/request/node_modules/uuid/v5.js | 3 + node_modules/request/package.json | 166 + node_modules/request/request.js | 1552 +++ node_modules/safe-buffer/.travis.yml | 7 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 + node_modules/safe-buffer/index.js | 62 + node_modules/safe-buffer/package.json | 97 + node_modules/safe-buffer/test.js | 101 + node_modules/sax/AUTHORS | 10 + node_modules/sax/LICENSE | 32 + node_modules/sax/LICENSE-W3C.html | 188 + node_modules/sax/README.md | 216 + node_modules/sax/component.json | 12 + node_modules/sax/examples/big-not-pretty.xml | 8002 ++++++++++++++ node_modules/sax/examples/example.js | 29 + node_modules/sax/examples/get-products.js | 58 + node_modules/sax/examples/hello-world.js | 4 + node_modules/sax/examples/not-pretty.xml | 8 + node_modules/sax/examples/pretty-print.js | 74 + node_modules/sax/examples/shopping.xml | 2 + node_modules/sax/examples/strict.dtd | 870 ++ node_modules/sax/examples/test.html | 15 + node_modules/sax/examples/test.xml | 1254 +++ node_modules/sax/lib/sax.js | 1355 +++ node_modules/sax/package.json | 108 + node_modules/sax/test/attribute-name.js | 33 + node_modules/sax/test/attribute-no-space.js | 75 + node_modules/sax/test/buffer-overrun.js | 26 + node_modules/sax/test/case.js | 50 + node_modules/sax/test/cdata-chunked.js | 11 + node_modules/sax/test/cdata-end-split.js | 15 + node_modules/sax/test/cdata-fake-end.js | 28 + node_modules/sax/test/cdata-multiple.js | 15 + node_modules/sax/test/cdata.js | 10 + node_modules/sax/test/cyrillic.js | 8 + node_modules/sax/test/duplicate-attribute.js | 13 + node_modules/sax/test/end_empty_stream.js | 5 + node_modules/sax/test/entities.js | 10 + node_modules/sax/test/entity-mega.js | 16 + node_modules/sax/test/flush.js | 13 + node_modules/sax/test/index.js | 86 + node_modules/sax/test/issue-23.js | 43 + node_modules/sax/test/issue-30.js | 24 + node_modules/sax/test/issue-35.js | 15 + node_modules/sax/test/issue-47.js | 12 + node_modules/sax/test/issue-49.js | 31 + node_modules/sax/test/issue-84.js | 13 + node_modules/sax/test/parser-position.js | 28 + node_modules/sax/test/script-close-better.js | 12 + node_modules/sax/test/script.js | 12 + .../sax/test/self-closing-child-strict.js | 44 + node_modules/sax/test/self-closing-child.js | 44 + node_modules/sax/test/self-closing-tag.js | 25 + node_modules/sax/test/stray-ending.js | 17 + .../sax/test/trailing-attribute-no-value.js | 10 + .../sax/test/trailing-non-whitespace.js | 18 + node_modules/sax/test/unclosed-root.js | 11 + node_modules/sax/test/unquoted.js | 18 + node_modules/sax/test/utf8-split.js | 32 + node_modules/sax/test/xmlns-as-tag-name.js | 15 + node_modules/sax/test/xmlns-issue-41.js | 68 + node_modules/sax/test/xmlns-rebinding.js | 63 + node_modules/sax/test/xmlns-strict.js | 74 + .../sax/test/xmlns-unbound-element.js | 33 + node_modules/sax/test/xmlns-unbound.js | 15 + node_modules/sax/test/xmlns-xml-default-ns.js | 31 + .../xmlns-xml-default-prefix-attribute.js | 36 + .../sax/test/xmlns-xml-default-prefix.js | 21 + .../sax/test/xmlns-xml-default-redefine.js | 41 + node_modules/sntp/.npmignore | 18 + node_modules/sntp/.travis.yml | 5 + node_modules/sntp/LICENSE | 28 + node_modules/sntp/Makefile | 9 + node_modules/sntp/README.md | 68 + node_modules/sntp/examples/offset.js | 16 + node_modules/sntp/examples/time.js | 25 + node_modules/sntp/index.js | 1 + node_modules/sntp/lib/index.js | 412 + node_modules/sntp/package.json | 89 + node_modules/sntp/test/index.js | 435 + node_modules/sshpk/.npmignore | 9 + node_modules/sshpk/.travis.yml | 11 + node_modules/sshpk/LICENSE | 18 + node_modules/sshpk/README.md | 698 ++ node_modules/sshpk/bin/sshpk-conv | 201 + node_modules/sshpk/bin/sshpk-sign | 191 + node_modules/sshpk/bin/sshpk-verify | 166 + node_modules/sshpk/lib/algs.js | 168 + node_modules/sshpk/lib/certificate.js | 377 + node_modules/sshpk/lib/dhe.js | 411 + node_modules/sshpk/lib/ed-compat.js | 96 + node_modules/sshpk/lib/errors.js | 84 + node_modules/sshpk/lib/fingerprint.js | 161 + node_modules/sshpk/lib/formats/auto.js | 73 + .../sshpk/lib/formats/openssh-cert.js | 322 + node_modules/sshpk/lib/formats/pem.js | 186 + node_modules/sshpk/lib/formats/pkcs1.js | 320 + node_modules/sshpk/lib/formats/pkcs8.js | 505 + node_modules/sshpk/lib/formats/rfc4253.js | 146 + node_modules/sshpk/lib/formats/ssh-private.js | 261 + node_modules/sshpk/lib/formats/ssh.js | 114 + node_modules/sshpk/lib/formats/x509-pem.js | 77 + node_modules/sshpk/lib/formats/x509.js | 726 ++ node_modules/sshpk/lib/identity.js | 277 + node_modules/sshpk/lib/index.js | 39 + node_modules/sshpk/lib/key.js | 274 + node_modules/sshpk/lib/private-key.js | 254 + node_modules/sshpk/lib/signature.js | 313 + node_modules/sshpk/lib/ssh-buffer.js | 148 + node_modules/sshpk/lib/utils.js | 288 + node_modules/sshpk/man/man1/sshpk-conv.1 | 135 + node_modules/sshpk/man/man1/sshpk-sign.1 | 81 + node_modules/sshpk/man/man1/sshpk-verify.1 | 68 + .../sshpk/node_modules/assert-plus/AUTHORS | 6 + .../sshpk/node_modules/assert-plus/CHANGES.md | 14 + .../sshpk/node_modules/assert-plus/README.md | 162 + .../sshpk/node_modules/assert-plus/assert.js | 211 + .../node_modules/assert-plus/package.json | 106 + node_modules/sshpk/package.json | 125 + node_modules/string_decoder/.npmignore | 2 + node_modules/string_decoder/LICENSE | 20 + node_modules/string_decoder/README.md | 7 + node_modules/string_decoder/index.js | 221 + node_modules/string_decoder/package.json | 78 + node_modules/stringstream/.npmignore | 15 + node_modules/stringstream/.travis.yml | 4 + node_modules/stringstream/LICENSE.txt | 22 + node_modules/stringstream/README.md | 38 + node_modules/stringstream/example.js | 27 + node_modules/stringstream/package.json | 77 + node_modules/stringstream/stringstream.js | 102 + node_modules/tough-cookie/LICENSE | 27 + node_modules/tough-cookie/README.md | 509 + node_modules/tough-cookie/lib/cookie.js | 1341 +++ node_modules/tough-cookie/lib/memstore.js | 170 + node_modules/tough-cookie/lib/pathMatch.js | 61 + .../tough-cookie/lib/permuteDomain.js | 56 + node_modules/tough-cookie/lib/pubsuffix.js | 98 + node_modules/tough-cookie/lib/store.js | 71 + node_modules/tough-cookie/package.json | 127 + node_modules/tunnel-agent/LICENSE | 55 + node_modules/tunnel-agent/README.md | 4 + node_modules/tunnel-agent/index.js | 244 + node_modules/tunnel-agent/package.json | 94 + node_modules/tweetnacl/.npmignore | 4 + node_modules/tweetnacl/AUTHORS.md | 28 + node_modules/tweetnacl/CHANGELOG.md | 221 + node_modules/tweetnacl/LICENSE | 24 + .../tweetnacl/PULL_REQUEST_TEMPLATE.md | 20 + node_modules/tweetnacl/README.md | 459 + node_modules/tweetnacl/nacl-fast.js | 2388 +++++ node_modules/tweetnacl/nacl-fast.min.js | 2 + node_modules/tweetnacl/nacl.d.ts | 98 + node_modules/tweetnacl/nacl.js | 1175 ++ node_modules/tweetnacl/nacl.min.js | 1 + node_modules/tweetnacl/package.json | 112 + node_modules/underscore/LICENSE | 23 + node_modules/underscore/README.md | 22 + node_modules/underscore/package.json | 95 + node_modules/underscore/underscore-min.js | 6 + node_modules/underscore/underscore-min.map | 1 + node_modules/underscore/underscore.js | 1548 +++ node_modules/util-deprecate/History.md | 16 + node_modules/util-deprecate/LICENSE | 24 + node_modules/util-deprecate/README.md | 53 + node_modules/util-deprecate/browser.js | 67 + node_modules/util-deprecate/node.js | 6 + node_modules/util-deprecate/package.json | 80 + node_modules/validator/.jshintrc | 3 + node_modules/validator/.npmignore | 3 + node_modules/validator/.travis.yml | 7 + node_modules/validator/LICENSE | 20 + node_modules/validator/Makefile | 35 + node_modules/validator/README.md | 174 + node_modules/validator/bower.json | 18 + node_modules/validator/package.json | 97 + node_modules/validator/test/client-side.js | 26 + node_modules/validator/test/exports.js | 21 + node_modules/validator/test/sanitizers.js | 223 + node_modules/validator/test/validators.js | 1947 ++++ node_modules/validator/validator.js | 727 ++ node_modules/validator/validator.min.js | 23 + node_modules/verror/.npmignore | 9 + node_modules/verror/CHANGES.md | 28 + node_modules/verror/CONTRIBUTING.md | 19 + node_modules/verror/LICENSE | 19 + node_modules/verror/README.md | 528 + node_modules/verror/lib/verror.js | 451 + .../verror/node_modules/assert-plus/AUTHORS | 6 + .../node_modules/assert-plus/CHANGES.md | 14 + .../verror/node_modules/assert-plus/README.md | 162 + .../verror/node_modules/assert-plus/assert.js | 211 + .../node_modules/assert-plus/package.json | 106 + node_modules/verror/package.json | 76 + node_modules/xml2js/.npmignore | 6 + node_modules/xml2js/.travis.yml | 5 + node_modules/xml2js/83.coffee | 6 + node_modules/xml2js/LICENSE | 19 + node_modules/xml2js/README.md | 248 + node_modules/xml2js/canon.xml | 482 + node_modules/xml2js/lib/xml2js.js | 299 + node_modules/xml2js/package.json | 165 + node_modules/xml2js/text.coffee | 11 + node_modules/xml2js/text.xml | 485 + node_modules/xmlbuilder/.npmignore | 7 + node_modules/xmlbuilder/Makefile | 15 + node_modules/xmlbuilder/README.md | 73 + node_modules/xmlbuilder/lib/XMLBuilder.js | 136 + node_modules/xmlbuilder/lib/XMLFragment.js | 415 + node_modules/xmlbuilder/lib/index.js | 15 + node_modules/xmlbuilder/package.json | 88 + .../AACharly.njsproj.CoreCompileInputs.cache | 1 + .../AACharly.njsproj.FileListAbsolute.txt | 3 + ...arly.njsprojResolveAssemblyReference.cache | Bin 0 -> 2592 bytes package-lock.json | 670 ++ package.json | 17 + 1288 files changed, 226749 insertions(+) create mode 100644 .gitattributes create mode 100644 .vs/AACharly/v15/.suo create mode 100644 AACharly.njsproj create mode 100644 AACharly.sln create mode 100644 Azure File Storage.js create mode 100644 Azure Web Job Shutdown.js create mode 100644 Carol.azure.storage.connstring create mode 100644 Charly.azure.storage.connstring create mode 100644 Debug Log.js create mode 100644 Markets.js create mode 100644 Poloniex API Client.js create mode 100644 Poloniex-Historic-Trades/Interval.js create mode 100644 Poloniex-Historic-Trades/Poloniex Historic Trades.js create mode 100644 Poloniex-Historic-Trades/run.js create mode 100644 Poloniex-Hole-Fixing/Interval.js create mode 100644 Poloniex-Hole-Fixing/Poloniex Hole Fixing.js create mode 100644 Poloniex-Hole-Fixing/run.js create mode 100644 Poloniex-Live-Trades/Interval.js create mode 100644 Poloniex-Live-Trades/Poloniex Live Trades.js create mode 100644 Poloniex-Live-Trades/run.js create mode 100644 README.md create mode 100644 Utilities.js create mode 100644 azure.app.config create mode 100644 bin/Microsoft.NodejsTools.WebRole.dll create mode 100644 logs/Dummy File.txt create mode 100644 node_modules/.bin/sshpk-conv create mode 100644 node_modules/.bin/sshpk-conv.cmd create mode 100644 node_modules/.bin/sshpk-sign create mode 100644 node_modules/.bin/sshpk-sign.cmd create mode 100644 node_modules/.bin/sshpk-verify create mode 100644 node_modules/.bin/sshpk-verify.cmd create mode 100644 node_modules/.bin/uuid create mode 100644 node_modules/.bin/uuid.cmd create mode 100644 node_modules/ajv/.tonic_example.js create mode 100644 node_modules/ajv/LICENSE create mode 100644 node_modules/ajv/README.md create mode 100644 node_modules/ajv/dist/ajv.bundle.js create mode 100644 node_modules/ajv/dist/ajv.min.js create mode 100644 node_modules/ajv/dist/ajv.min.js.map create mode 100644 node_modules/ajv/dist/nodent.min.js create mode 100644 node_modules/ajv/dist/regenerator.min.js create mode 100644 node_modules/ajv/lib/ajv.d.ts create mode 100644 node_modules/ajv/lib/ajv.js create mode 100644 node_modules/ajv/lib/async.js create mode 100644 node_modules/ajv/lib/cache.js create mode 100644 node_modules/ajv/lib/compile/_rules.js create mode 100644 node_modules/ajv/lib/compile/equal.js create mode 100644 node_modules/ajv/lib/compile/formats.js create mode 100644 node_modules/ajv/lib/compile/index.js create mode 100644 node_modules/ajv/lib/compile/resolve.js create mode 100644 node_modules/ajv/lib/compile/rules.js create mode 100644 node_modules/ajv/lib/compile/schema_obj.js create mode 100644 node_modules/ajv/lib/compile/ucs2length.js create mode 100644 node_modules/ajv/lib/compile/util.js create mode 100644 node_modules/ajv/lib/compile/validation_error.js create mode 100644 node_modules/ajv/lib/dot/_limit.jst create mode 100644 node_modules/ajv/lib/dot/_limitItems.jst create mode 100644 node_modules/ajv/lib/dot/_limitLength.jst create mode 100644 node_modules/ajv/lib/dot/_limitProperties.jst create mode 100644 node_modules/ajv/lib/dot/allOf.jst create mode 100644 node_modules/ajv/lib/dot/anyOf.jst create mode 100644 node_modules/ajv/lib/dot/coerce.def create mode 100644 node_modules/ajv/lib/dot/custom.jst create mode 100644 node_modules/ajv/lib/dot/defaults.def create mode 100644 node_modules/ajv/lib/dot/definitions.def create mode 100644 node_modules/ajv/lib/dot/dependencies.jst create mode 100644 node_modules/ajv/lib/dot/enum.jst create mode 100644 node_modules/ajv/lib/dot/errors.def create mode 100644 node_modules/ajv/lib/dot/format.jst create mode 100644 node_modules/ajv/lib/dot/items.jst create mode 100644 node_modules/ajv/lib/dot/missing.def create mode 100644 node_modules/ajv/lib/dot/multipleOf.jst create mode 100644 node_modules/ajv/lib/dot/not.jst create mode 100644 node_modules/ajv/lib/dot/oneOf.jst create mode 100644 node_modules/ajv/lib/dot/pattern.jst create mode 100644 node_modules/ajv/lib/dot/properties.jst create mode 100644 node_modules/ajv/lib/dot/ref.jst create mode 100644 node_modules/ajv/lib/dot/required.jst create mode 100644 node_modules/ajv/lib/dot/uniqueItems.jst create mode 100644 node_modules/ajv/lib/dot/v5/_formatLimit.jst create mode 100644 node_modules/ajv/lib/dot/v5/constant.jst create mode 100644 node_modules/ajv/lib/dot/v5/patternRequired.jst create mode 100644 node_modules/ajv/lib/dot/v5/switch.jst create mode 100644 node_modules/ajv/lib/dot/validate.jst create mode 100644 node_modules/ajv/lib/dotjs/README.md create mode 100644 node_modules/ajv/lib/dotjs/_formatLimit.js create mode 100644 node_modules/ajv/lib/dotjs/_limit.js create mode 100644 node_modules/ajv/lib/dotjs/_limitItems.js create mode 100644 node_modules/ajv/lib/dotjs/_limitLength.js create mode 100644 node_modules/ajv/lib/dotjs/_limitProperties.js create mode 100644 node_modules/ajv/lib/dotjs/allOf.js create mode 100644 node_modules/ajv/lib/dotjs/anyOf.js create mode 100644 node_modules/ajv/lib/dotjs/constant.js create mode 100644 node_modules/ajv/lib/dotjs/custom.js create mode 100644 node_modules/ajv/lib/dotjs/dependencies.js create mode 100644 node_modules/ajv/lib/dotjs/enum.js create mode 100644 node_modules/ajv/lib/dotjs/format.js create mode 100644 node_modules/ajv/lib/dotjs/items.js create mode 100644 node_modules/ajv/lib/dotjs/multipleOf.js create mode 100644 node_modules/ajv/lib/dotjs/not.js create mode 100644 node_modules/ajv/lib/dotjs/oneOf.js create mode 100644 node_modules/ajv/lib/dotjs/pattern.js create mode 100644 node_modules/ajv/lib/dotjs/patternRequired.js create mode 100644 node_modules/ajv/lib/dotjs/properties.js create mode 100644 node_modules/ajv/lib/dotjs/ref.js create mode 100644 node_modules/ajv/lib/dotjs/required.js create mode 100644 node_modules/ajv/lib/dotjs/switch.js create mode 100644 node_modules/ajv/lib/dotjs/uniqueItems.js create mode 100644 node_modules/ajv/lib/dotjs/validate.js create mode 100644 node_modules/ajv/lib/keyword.js create mode 100644 node_modules/ajv/lib/refs/json-schema-draft-04.json create mode 100644 node_modules/ajv/lib/refs/json-schema-v5.json create mode 100644 node_modules/ajv/lib/v5.js create mode 100644 node_modules/ajv/package.json create mode 100644 node_modules/ajv/scripts/.eslintrc.yml create mode 100644 node_modules/ajv/scripts/bundle.js create mode 100644 node_modules/ajv/scripts/compile-dots.js create mode 100644 node_modules/ajv/scripts/info create mode 100644 node_modules/ajv/scripts/prepare-tests create mode 100644 node_modules/ajv/scripts/travis-gh-pages create mode 100644 node_modules/asn1/.npmignore create mode 100644 node_modules/asn1/.travis.yml create mode 100644 node_modules/asn1/LICENSE create mode 100644 node_modules/asn1/README.md create mode 100644 node_modules/asn1/lib/ber/errors.js create mode 100644 node_modules/asn1/lib/ber/index.js create mode 100644 node_modules/asn1/lib/ber/reader.js create mode 100644 node_modules/asn1/lib/ber/types.js create mode 100644 node_modules/asn1/lib/ber/writer.js create mode 100644 node_modules/asn1/lib/index.js create mode 100644 node_modules/asn1/package.json create mode 100644 node_modules/asn1/tst/ber/reader.test.js create mode 100644 node_modules/asn1/tst/ber/writer.test.js create mode 100644 node_modules/assert-plus/AUTHORS create mode 100644 node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/assert-plus/README.md create mode 100644 node_modules/assert-plus/assert.js create mode 100644 node_modules/assert-plus/package.json create mode 100644 node_modules/asynckit/LICENSE create mode 100644 node_modules/asynckit/README.md create mode 100644 node_modules/asynckit/bench.js create mode 100644 node_modules/asynckit/index.js create mode 100644 node_modules/asynckit/lib/abort.js create mode 100644 node_modules/asynckit/lib/async.js create mode 100644 node_modules/asynckit/lib/defer.js create mode 100644 node_modules/asynckit/lib/iterate.js create mode 100644 node_modules/asynckit/lib/readable_asynckit.js create mode 100644 node_modules/asynckit/lib/readable_parallel.js create mode 100644 node_modules/asynckit/lib/readable_serial.js create mode 100644 node_modules/asynckit/lib/readable_serial_ordered.js create mode 100644 node_modules/asynckit/lib/state.js create mode 100644 node_modules/asynckit/lib/streamify.js create mode 100644 node_modules/asynckit/lib/terminator.js create mode 100644 node_modules/asynckit/package.json create mode 100644 node_modules/asynckit/parallel.js create mode 100644 node_modules/asynckit/serial.js create mode 100644 node_modules/asynckit/serialOrdered.js create mode 100644 node_modules/asynckit/stream.js create mode 100644 node_modules/aws-sign2/LICENSE create mode 100644 node_modules/aws-sign2/README.md create mode 100644 node_modules/aws-sign2/index.js create mode 100644 node_modules/aws-sign2/package.json create mode 100644 node_modules/aws4/.npmignore create mode 100644 node_modules/aws4/.tern-port create mode 100644 node_modules/aws4/.travis.yml create mode 100644 node_modules/aws4/LICENSE create mode 100644 node_modules/aws4/README.md create mode 100644 node_modules/aws4/aws4.js create mode 100644 node_modules/aws4/lru.js create mode 100644 node_modules/aws4/package.json create mode 100644 node_modules/azure-storage/.jshintignore create mode 100644 node_modules/azure-storage/.jshintrc create mode 100644 node_modules/azure-storage/.npmignore create mode 100644 node_modules/azure-storage/.travis.yml create mode 100644 node_modules/azure-storage/BreakingChanges.md create mode 100644 node_modules/azure-storage/CONTRIBUTING.md create mode 100644 node_modules/azure-storage/CONTRIBUTORS.txt create mode 100644 node_modules/azure-storage/ChangeLog.md create mode 100644 node_modules/azure-storage/LICENSE.txt create mode 100644 node_modules/azure-storage/README.md create mode 100644 node_modules/azure-storage/browser/ChangeLog.md create mode 100644 node_modules/azure-storage/browser/README.md create mode 100644 node_modules/azure-storage/browser/azure-storage.blob.export.js create mode 100644 node_modules/azure-storage/browser/azure-storage.file.export.js create mode 100644 node_modules/azure-storage/browser/azure-storage.queue.export.js create mode 100644 node_modules/azure-storage/browser/azure-storage.table.export.js create mode 100644 node_modules/azure-storage/browser/bundle.js create mode 100644 node_modules/azure-storage/browser/samples/cors.PNG create mode 100644 node_modules/azure-storage/browser/samples/sample-blob.html create mode 100644 node_modules/azure-storage/browser/samples/sample-file.html create mode 100644 node_modules/azure-storage/browser/samples/sample-queue.html create mode 100644 node_modules/azure-storage/browser/samples/sample-table.html create mode 100644 node_modules/azure-storage/examples/samples/blobuploaddownloadsample.js create mode 100644 node_modules/azure-storage/examples/samples/continuationsample.js create mode 100644 node_modules/azure-storage/examples/samples/requestresponseeventssample.js create mode 100644 node_modules/azure-storage/examples/samples/retrypolicysample.js create mode 100644 node_modules/azure-storage/examples/samples/sassample.js create mode 100644 node_modules/azure-storage/examples/samples/snapshotsample.js create mode 100644 node_modules/azure-storage/examples/samples/tablequerysample.js create mode 100644 node_modules/azure-storage/gruntfile.js create mode 100644 node_modules/azure-storage/jsdoc/jsdoc.json create mode 100644 node_modules/azure-storage/lib/azure-storage.js create mode 100644 node_modules/azure-storage/lib/common/common.browser.js create mode 100644 node_modules/azure-storage/lib/common/common.core.js create mode 100644 node_modules/azure-storage/lib/common/common.node.js create mode 100644 node_modules/azure-storage/lib/common/diagnostics/logger.js create mode 100644 node_modules/azure-storage/lib/common/errors/errors.js create mode 100644 node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js create mode 100644 node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js create mode 100644 node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js create mode 100644 node_modules/azure-storage/lib/common/http/webresource.js create mode 100644 node_modules/azure-storage/lib/common/md5-wrapper/md5.browser.js create mode 100644 node_modules/azure-storage/lib/common/md5-wrapper/md5.node.js create mode 100644 node_modules/azure-storage/lib/common/md5-wrapper/package.json create mode 100644 node_modules/azure-storage/lib/common/models/aclresult.js create mode 100644 node_modules/azure-storage/lib/common/models/servicepropertiesresult.js create mode 100644 node_modules/azure-storage/lib/common/models/servicestatsparser.js create mode 100644 node_modules/azure-storage/lib/common/request-wrapper/package.json create mode 100644 node_modules/azure-storage/lib/common/request-wrapper/request.browser.js create mode 100644 node_modules/azure-storage/lib/common/request-wrapper/request.node.js create mode 100644 node_modules/azure-storage/lib/common/services/servicesettings.js create mode 100644 node_modules/azure-storage/lib/common/services/storageserviceclient.js create mode 100644 node_modules/azure-storage/lib/common/services/storageservicesettings.js create mode 100644 node_modules/azure-storage/lib/common/signing/hmacsha256sign.js create mode 100644 node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js create mode 100644 node_modules/azure-storage/lib/common/signing/sharedkey.js create mode 100644 node_modules/azure-storage/lib/common/streams/batchoperation.js create mode 100644 node_modules/azure-storage/lib/common/streams/browserfilereadstream.js create mode 100644 node_modules/azure-storage/lib/common/streams/bufferstream.js create mode 100644 node_modules/azure-storage/lib/common/streams/chunkallocator.js create mode 100644 node_modules/azure-storage/lib/common/streams/chunkstream.js create mode 100644 node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js create mode 100644 node_modules/azure-storage/lib/common/streams/filereadstream.js create mode 100644 node_modules/azure-storage/lib/common/streams/rangestream.js create mode 100644 node_modules/azure-storage/lib/common/streams/readablefs.js create mode 100644 node_modules/azure-storage/lib/common/streams/speedsummary.js create mode 100644 node_modules/azure-storage/lib/common/util/accesscondition.js create mode 100644 node_modules/azure-storage/lib/common/util/constants.js create mode 100644 node_modules/azure-storage/lib/common/util/date.js create mode 100644 node_modules/azure-storage/lib/common/util/iso8061date.js create mode 100644 node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js create mode 100644 node_modules/azure-storage/lib/common/util/sr.js create mode 100644 node_modules/azure-storage/lib/common/util/storageutilities.js create mode 100644 node_modules/azure-storage/lib/common/util/util.js create mode 100644 node_modules/azure-storage/lib/common/util/validate.js create mode 100644 node_modules/azure-storage/lib/services/blob/blobservice.browser.js create mode 100644 node_modules/azure-storage/lib/services/blob/blobservice.core.js create mode 100644 node_modules/azure-storage/lib/services/blob/blobservice.node.js create mode 100644 node_modules/azure-storage/lib/services/blob/blobutilities.js create mode 100644 node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js create mode 100644 node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js create mode 100644 node_modules/azure-storage/lib/services/blob/models/blobresult.js create mode 100644 node_modules/azure-storage/lib/services/blob/models/blocklistresult.js create mode 100644 node_modules/azure-storage/lib/services/blob/models/containerresult.js create mode 100644 node_modules/azure-storage/lib/services/blob/models/leaseresult.js create mode 100644 node_modules/azure-storage/lib/services/file/fileservice.browser.js create mode 100644 node_modules/azure-storage/lib/services/file/fileservice.core.js create mode 100644 node_modules/azure-storage/lib/services/file/fileservice.node.js create mode 100644 node_modules/azure-storage/lib/services/file/fileutilities.js create mode 100644 node_modules/azure-storage/lib/services/file/internal/filerangestream.js create mode 100644 node_modules/azure-storage/lib/services/file/models/directoryresult.js create mode 100644 node_modules/azure-storage/lib/services/file/models/fileresult.js create mode 100644 node_modules/azure-storage/lib/services/file/models/shareresult.js create mode 100644 node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js create mode 100644 node_modules/azure-storage/lib/services/queue/models/queueresult.js create mode 100644 node_modules/azure-storage/lib/services/queue/queuemessageencoder.js create mode 100644 node_modules/azure-storage/lib/services/queue/queueservice.js create mode 100644 node_modules/azure-storage/lib/services/queue/queueutilities.js create mode 100644 node_modules/azure-storage/lib/services/table/internal/edmhandler.js create mode 100644 node_modules/azure-storage/lib/services/table/internal/odatahandler.js create mode 100644 node_modules/azure-storage/lib/services/table/internal/requesthandler.js create mode 100644 node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js create mode 100644 node_modules/azure-storage/lib/services/table/models/batchresult.js create mode 100644 node_modules/azure-storage/lib/services/table/models/entityresult.js create mode 100644 node_modules/azure-storage/lib/services/table/models/tableresult.js create mode 100644 node_modules/azure-storage/lib/services/table/tablebatch.js create mode 100644 node_modules/azure-storage/lib/services/table/tablequery.js create mode 100644 node_modules/azure-storage/lib/services/table/tableservice.js create mode 100644 node_modules/azure-storage/lib/services/table/tableutilities.js create mode 100644 node_modules/azure-storage/node_modules/.bin/uuid create mode 100644 node_modules/azure-storage/node_modules/.bin/uuid.cmd create mode 100644 node_modules/azure-storage/node_modules/request/CHANGELOG.md create mode 100644 node_modules/azure-storage/node_modules/request/LICENSE create mode 100644 node_modules/azure-storage/node_modules/request/README.md create mode 100644 node_modules/azure-storage/node_modules/request/index.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/auth.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/cookies.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/getProxyFromURI.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/har.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/helpers.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/multipart.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/oauth.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/querystring.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/redirect.js create mode 100644 node_modules/azure-storage/node_modules/request/lib/tunnel.js create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/.eslintrc create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/.jscs.json create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/.npmignore create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/.travis.yml create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/CHANGELOG.md create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/LICENSE create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/README.md create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/component.json create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/index.js create mode 100644 node_modules/azure-storage/node_modules/request/node_modules/extend/package.json create mode 100644 node_modules/azure-storage/node_modules/request/package.json create mode 100644 node_modules/azure-storage/node_modules/request/request.js create mode 100644 node_modules/azure-storage/node_modules/uuid/.eslintrc.json create mode 100644 node_modules/azure-storage/node_modules/uuid/AUTHORS create mode 100644 node_modules/azure-storage/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/azure-storage/node_modules/uuid/LICENSE.md create mode 100644 node_modules/azure-storage/node_modules/uuid/README.md create mode 100644 node_modules/azure-storage/node_modules/uuid/README_js.md create mode 100644 node_modules/azure-storage/node_modules/uuid/bin/uuid create mode 100644 node_modules/azure-storage/node_modules/uuid/index.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/bytesToUuid.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/md5-browser.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/md5.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/rng-browser.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/rng.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/sha1-browser.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/sha1.js create mode 100644 node_modules/azure-storage/node_modules/uuid/lib/v35.js create mode 100644 node_modules/azure-storage/node_modules/uuid/package.json create mode 100644 node_modules/azure-storage/node_modules/uuid/v1.js create mode 100644 node_modules/azure-storage/node_modules/uuid/v3.js create mode 100644 node_modules/azure-storage/node_modules/uuid/v4.js create mode 100644 node_modules/azure-storage/node_modules/uuid/v5.js create mode 100644 node_modules/azure-storage/package.json create mode 100644 node_modules/azure-storage/tsconfig.json create mode 100644 node_modules/azure-storage/typings.json create mode 100644 node_modules/azure-storage/typings/azure-storage/azure-storage.d.ts create mode 100644 node_modules/azure-storage/typings/globals/node/index.d.ts create mode 100644 node_modules/azure-storage/typings/globals/node/typings.json create mode 100644 node_modules/azure-storage/typings/index.d.ts create mode 100644 node_modules/bcrypt-pbkdf/README.md create mode 100644 node_modules/bcrypt-pbkdf/index.js create mode 100644 node_modules/bcrypt-pbkdf/package.json create mode 100644 node_modules/boom/.npmignore create mode 100644 node_modules/boom/.travis.yml create mode 100644 node_modules/boom/CONTRIBUTING.md create mode 100644 node_modules/boom/LICENSE create mode 100644 node_modules/boom/README.md create mode 100644 node_modules/boom/images/boom.png create mode 100644 node_modules/boom/lib/index.js create mode 100644 node_modules/boom/package.json create mode 100644 node_modules/boom/test/index.js create mode 100644 node_modules/browserify-mime/.npmignore create mode 100644 node_modules/browserify-mime/LICENSE create mode 100644 node_modules/browserify-mime/README.md create mode 100644 node_modules/browserify-mime/browserify-mime.js create mode 100644 node_modules/browserify-mime/mime.js create mode 100644 node_modules/browserify-mime/package.json create mode 100644 node_modules/browserify-mime/test.js create mode 100644 node_modules/caseless/LICENSE create mode 100644 node_modules/caseless/README.md create mode 100644 node_modules/caseless/index.js create mode 100644 node_modules/caseless/package.json create mode 100644 node_modules/caseless/test.js create mode 100644 node_modules/co/History.md create mode 100644 node_modules/co/LICENSE create mode 100644 node_modules/co/Readme.md create mode 100644 node_modules/co/index.js create mode 100644 node_modules/co/package.json create mode 100644 node_modules/combined-stream/License create mode 100644 node_modules/combined-stream/Readme.md create mode 100644 node_modules/combined-stream/lib/combined_stream.js create mode 100644 node_modules/combined-stream/package.json create mode 100644 node_modules/core-util-is/LICENSE create mode 100644 node_modules/core-util-is/README.md create mode 100644 node_modules/core-util-is/float.patch create mode 100644 node_modules/core-util-is/lib/util.js create mode 100644 node_modules/core-util-is/package.json create mode 100644 node_modules/core-util-is/test.js create mode 100644 node_modules/cryptiles/.npmignore create mode 100644 node_modules/cryptiles/.travis.yml create mode 100644 node_modules/cryptiles/LICENSE create mode 100644 node_modules/cryptiles/README.md create mode 100644 node_modules/cryptiles/lib/index.js create mode 100644 node_modules/cryptiles/package.json create mode 100644 node_modules/cryptiles/test/index.js create mode 100644 node_modules/dashdash/CHANGES.md create mode 100644 node_modules/dashdash/LICENSE.txt create mode 100644 node_modules/dashdash/README.md create mode 100644 node_modules/dashdash/etc/dashdash.bash_completion.in create mode 100644 node_modules/dashdash/lib/dashdash.js create mode 100644 node_modules/dashdash/node_modules/assert-plus/AUTHORS create mode 100644 node_modules/dashdash/node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/dashdash/node_modules/assert-plus/README.md create mode 100644 node_modules/dashdash/node_modules/assert-plus/assert.js create mode 100644 node_modules/dashdash/node_modules/assert-plus/package.json create mode 100644 node_modules/dashdash/package.json create mode 100644 node_modules/delayed-stream/.npmignore create mode 100644 node_modules/delayed-stream/License create mode 100644 node_modules/delayed-stream/Makefile create mode 100644 node_modules/delayed-stream/Readme.md create mode 100644 node_modules/delayed-stream/lib/delayed_stream.js create mode 100644 node_modules/delayed-stream/package.json create mode 100644 node_modules/ecc-jsbn/.npmignore create mode 100644 node_modules/ecc-jsbn/LICENSE create mode 100644 node_modules/ecc-jsbn/README.md create mode 100644 node_modules/ecc-jsbn/index.js create mode 100644 node_modules/ecc-jsbn/lib/LICENSE-jsbn create mode 100644 node_modules/ecc-jsbn/lib/ec.js create mode 100644 node_modules/ecc-jsbn/lib/sec.js create mode 100644 node_modules/ecc-jsbn/package.json create mode 100644 node_modules/ecc-jsbn/test.js create mode 100644 node_modules/extend/.npmignore create mode 100644 node_modules/extend/.travis.yml create mode 100644 node_modules/extend/README.md create mode 100644 node_modules/extend/index.js create mode 100644 node_modules/extend/package.json create mode 100644 node_modules/extsprintf/.gitmodules create mode 100644 node_modules/extsprintf/.npmignore create mode 100644 node_modules/extsprintf/LICENSE create mode 100644 node_modules/extsprintf/Makefile create mode 100644 node_modules/extsprintf/Makefile.targ create mode 100644 node_modules/extsprintf/README.md create mode 100644 node_modules/extsprintf/jsl.node.conf create mode 100644 node_modules/extsprintf/lib/extsprintf.js create mode 100644 node_modules/extsprintf/package.json create mode 100644 node_modules/fast-deep-equal/.eslintrc.yml create mode 100644 node_modules/fast-deep-equal/.npmignore create mode 100644 node_modules/fast-deep-equal/.travis.yml create mode 100644 node_modules/fast-deep-equal/LICENSE create mode 100644 node_modules/fast-deep-equal/README.md create mode 100644 node_modules/fast-deep-equal/benchmark/.eslintrc.yml create mode 100644 node_modules/fast-deep-equal/benchmark/index.js create mode 100644 node_modules/fast-deep-equal/index.js create mode 100644 node_modules/fast-deep-equal/package.json create mode 100644 node_modules/fast-deep-equal/spec/.eslintrc.yml create mode 100644 node_modules/fast-deep-equal/spec/index.spec.js create mode 100644 node_modules/fast-deep-equal/spec/tests.js create mode 100644 node_modules/fast-json-stable-stringify/.eslintrc.yml create mode 100644 node_modules/fast-json-stable-stringify/.npmignore create mode 100644 node_modules/fast-json-stable-stringify/.travis.yml create mode 100644 node_modules/fast-json-stable-stringify/LICENSE create mode 100644 node_modules/fast-json-stable-stringify/README.md create mode 100644 node_modules/fast-json-stable-stringify/benchmark/index.js create mode 100644 node_modules/fast-json-stable-stringify/benchmark/test.json create mode 100644 node_modules/fast-json-stable-stringify/example/key_cmp.js create mode 100644 node_modules/fast-json-stable-stringify/example/nested.js create mode 100644 node_modules/fast-json-stable-stringify/example/str.js create mode 100644 node_modules/fast-json-stable-stringify/example/value_cmp.js create mode 100644 node_modules/fast-json-stable-stringify/index.js create mode 100644 node_modules/fast-json-stable-stringify/package.json create mode 100644 node_modules/fast-json-stable-stringify/test/cmp.js create mode 100644 node_modules/fast-json-stable-stringify/test/nested.js create mode 100644 node_modules/fast-json-stable-stringify/test/str.js create mode 100644 node_modules/fast-json-stable-stringify/test/to-json.js create mode 100644 node_modules/forever-agent/LICENSE create mode 100644 node_modules/forever-agent/README.md create mode 100644 node_modules/forever-agent/index.js create mode 100644 node_modules/forever-agent/package.json create mode 100644 node_modules/form-data/License create mode 100644 node_modules/form-data/README.md create mode 100644 node_modules/form-data/lib/browser.js create mode 100644 node_modules/form-data/lib/form_data.js create mode 100644 node_modules/form-data/lib/populate.js create mode 100644 node_modules/form-data/package.json create mode 100644 node_modules/getpass/.npmignore create mode 100644 node_modules/getpass/.travis.yml create mode 100644 node_modules/getpass/LICENSE create mode 100644 node_modules/getpass/README.md create mode 100644 node_modules/getpass/lib/index.js create mode 100644 node_modules/getpass/node_modules/assert-plus/AUTHORS create mode 100644 node_modules/getpass/node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/getpass/node_modules/assert-plus/README.md create mode 100644 node_modules/getpass/node_modules/assert-plus/assert.js create mode 100644 node_modules/getpass/node_modules/assert-plus/package.json create mode 100644 node_modules/getpass/package.json create mode 100644 node_modules/har-schema/LICENSE create mode 100644 node_modules/har-schema/README.md create mode 100644 node_modules/har-schema/lib/afterRequest.json create mode 100644 node_modules/har-schema/lib/beforeRequest.json create mode 100644 node_modules/har-schema/lib/browser.json create mode 100644 node_modules/har-schema/lib/cache.json create mode 100644 node_modules/har-schema/lib/content.json create mode 100644 node_modules/har-schema/lib/cookie.json create mode 100644 node_modules/har-schema/lib/creator.json create mode 100644 node_modules/har-schema/lib/entry.json create mode 100644 node_modules/har-schema/lib/har.json create mode 100644 node_modules/har-schema/lib/header.json create mode 100644 node_modules/har-schema/lib/index.js create mode 100644 node_modules/har-schema/lib/log.json create mode 100644 node_modules/har-schema/lib/page.json create mode 100644 node_modules/har-schema/lib/pageTimings.json create mode 100644 node_modules/har-schema/lib/postData.json create mode 100644 node_modules/har-schema/lib/query.json create mode 100644 node_modules/har-schema/lib/request.json create mode 100644 node_modules/har-schema/lib/response.json create mode 100644 node_modules/har-schema/lib/timings.json create mode 100644 node_modules/har-schema/package.json create mode 100644 node_modules/har-validator/LICENSE create mode 100644 node_modules/har-validator/README.md create mode 100644 node_modules/har-validator/lib/browser/async.js create mode 100644 node_modules/har-validator/lib/browser/error.js create mode 100644 node_modules/har-validator/lib/browser/promise.js create mode 100644 node_modules/har-validator/lib/node4/async.js create mode 100644 node_modules/har-validator/lib/node4/error.js create mode 100644 node_modules/har-validator/lib/node4/promise.js create mode 100644 node_modules/har-validator/lib/node6/async.js create mode 100644 node_modules/har-validator/lib/node6/error.js create mode 100644 node_modules/har-validator/lib/node6/promise.js create mode 100644 node_modules/har-validator/lib/node7/async.js create mode 100644 node_modules/har-validator/lib/node7/error.js create mode 100644 node_modules/har-validator/lib/node7/promise.js create mode 100644 node_modules/har-validator/package.json create mode 100644 node_modules/har-validator/src/async.js create mode 100644 node_modules/har-validator/src/error.js create mode 100644 node_modules/har-validator/src/promise.js create mode 100644 node_modules/hash-base/LICENSE create mode 100644 node_modules/hash-base/README.md create mode 100644 node_modules/hash-base/index.js create mode 100644 node_modules/hash-base/package.json create mode 100644 node_modules/hawk/.npmignore create mode 100644 node_modules/hawk/.travis.yml create mode 100644 node_modules/hawk/LICENSE create mode 100644 node_modules/hawk/README.md create mode 100644 node_modules/hawk/bower.json create mode 100644 node_modules/hawk/component.json create mode 100644 node_modules/hawk/dist/client.js create mode 100644 node_modules/hawk/example/usage.js create mode 100644 node_modules/hawk/images/hawk.png create mode 100644 node_modules/hawk/images/logo.png create mode 100644 node_modules/hawk/lib/browser.js create mode 100644 node_modules/hawk/lib/client.js create mode 100644 node_modules/hawk/lib/crypto.js create mode 100644 node_modules/hawk/lib/index.js create mode 100644 node_modules/hawk/lib/server.js create mode 100644 node_modules/hawk/lib/utils.js create mode 100644 node_modules/hawk/package.json create mode 100644 node_modules/hawk/test/browser.js create mode 100644 node_modules/hawk/test/client.js create mode 100644 node_modules/hawk/test/crypto.js create mode 100644 node_modules/hawk/test/index.js create mode 100644 node_modules/hawk/test/readme.js create mode 100644 node_modules/hawk/test/server.js create mode 100644 node_modules/hawk/test/uri.js create mode 100644 node_modules/hawk/test/utils.js create mode 100644 node_modules/hoek/.npmignore create mode 100644 node_modules/hoek/.travis.yml create mode 100644 node_modules/hoek/CONTRIBUTING.md create mode 100644 node_modules/hoek/LICENSE create mode 100644 node_modules/hoek/README.md create mode 100644 node_modules/hoek/images/hoek.png create mode 100644 node_modules/hoek/lib/escape.js create mode 100644 node_modules/hoek/lib/index.js create mode 100644 node_modules/hoek/package.json create mode 100644 node_modules/hoek/test/escaper.js create mode 100644 node_modules/hoek/test/index.js create mode 100644 node_modules/hoek/test/modules/ignore.txt create mode 100644 node_modules/hoek/test/modules/test1.js create mode 100644 node_modules/hoek/test/modules/test2.js create mode 100644 node_modules/hoek/test/modules/test3.js create mode 100644 node_modules/http-signature/.dir-locals.el create mode 100644 node_modules/http-signature/.npmignore create mode 100644 node_modules/http-signature/CHANGES.md create mode 100644 node_modules/http-signature/LICENSE create mode 100644 node_modules/http-signature/README.md create mode 100644 node_modules/http-signature/http_signing.md create mode 100644 node_modules/http-signature/lib/index.js create mode 100644 node_modules/http-signature/lib/parser.js create mode 100644 node_modules/http-signature/lib/signer.js create mode 100644 node_modules/http-signature/lib/utils.js create mode 100644 node_modules/http-signature/lib/verify.js create mode 100644 node_modules/http-signature/package.json create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/is-typedarray/LICENSE.md create mode 100644 node_modules/is-typedarray/README.md create mode 100644 node_modules/is-typedarray/index.js create mode 100644 node_modules/is-typedarray/package.json create mode 100644 node_modules/is-typedarray/test.js create mode 100644 node_modules/isarray/.npmignore create mode 100644 node_modules/isarray/.travis.yml create mode 100644 node_modules/isarray/Makefile create mode 100644 node_modules/isarray/README.md create mode 100644 node_modules/isarray/component.json create mode 100644 node_modules/isarray/index.js create mode 100644 node_modules/isarray/package.json create mode 100644 node_modules/isarray/test.js create mode 100644 node_modules/isstream/.jshintrc create mode 100644 node_modules/isstream/.npmignore create mode 100644 node_modules/isstream/.travis.yml create mode 100644 node_modules/isstream/LICENSE.md create mode 100644 node_modules/isstream/README.md create mode 100644 node_modules/isstream/isstream.js create mode 100644 node_modules/isstream/package.json create mode 100644 node_modules/isstream/test.js create mode 100644 node_modules/jsbn/.npmignore create mode 100644 node_modules/jsbn/LICENSE create mode 100644 node_modules/jsbn/README.md create mode 100644 node_modules/jsbn/example.html create mode 100644 node_modules/jsbn/example.js create mode 100644 node_modules/jsbn/index.js create mode 100644 node_modules/jsbn/package.json create mode 100644 node_modules/json-edm-parser/.npmignore create mode 100644 node_modules/json-edm-parser/.travis.yml create mode 100644 node_modules/json-edm-parser/LICENSE create mode 100644 node_modules/json-edm-parser/README.md create mode 100644 node_modules/json-edm-parser/package.json create mode 100644 node_modules/json-edm-parser/parser.js create mode 100644 node_modules/json-edm-parser/test/boundary.js create mode 100644 node_modules/json-edm-parser/test/edm.js create mode 100644 node_modules/json-edm-parser/test/invalid.js create mode 100644 node_modules/json-edm-parser/test/offset.js create mode 100644 node_modules/json-edm-parser/test/primitives.js create mode 100644 node_modules/json-edm-parser/test/utf8.js create mode 100644 node_modules/json-schema-traverse/.eslintrc.yml create mode 100644 node_modules/json-schema-traverse/.npmignore create mode 100644 node_modules/json-schema-traverse/.travis.yml create mode 100644 node_modules/json-schema-traverse/LICENSE create mode 100644 node_modules/json-schema-traverse/README.md create mode 100644 node_modules/json-schema-traverse/index.js create mode 100644 node_modules/json-schema-traverse/package.json create mode 100644 node_modules/json-schema-traverse/spec/.eslintrc.yml create mode 100644 node_modules/json-schema-traverse/spec/fixtures/schema.js create mode 100644 node_modules/json-schema-traverse/spec/index.spec.js create mode 100644 node_modules/json-schema/README.md create mode 100644 node_modules/json-schema/draft-00/hyper-schema create mode 100644 node_modules/json-schema/draft-00/json-ref create mode 100644 node_modules/json-schema/draft-00/links create mode 100644 node_modules/json-schema/draft-00/schema create mode 100644 node_modules/json-schema/draft-01/hyper-schema create mode 100644 node_modules/json-schema/draft-01/json-ref create mode 100644 node_modules/json-schema/draft-01/links create mode 100644 node_modules/json-schema/draft-01/schema create mode 100644 node_modules/json-schema/draft-02/hyper-schema create mode 100644 node_modules/json-schema/draft-02/json-ref create mode 100644 node_modules/json-schema/draft-02/links create mode 100644 node_modules/json-schema/draft-02/schema create mode 100644 node_modules/json-schema/draft-03/examples/address create mode 100644 node_modules/json-schema/draft-03/examples/calendar create mode 100644 node_modules/json-schema/draft-03/examples/card create mode 100644 node_modules/json-schema/draft-03/examples/geo create mode 100644 node_modules/json-schema/draft-03/examples/interfaces create mode 100644 node_modules/json-schema/draft-03/hyper-schema create mode 100644 node_modules/json-schema/draft-03/json-ref create mode 100644 node_modules/json-schema/draft-03/links create mode 100644 node_modules/json-schema/draft-03/schema create mode 100644 node_modules/json-schema/draft-04/hyper-schema create mode 100644 node_modules/json-schema/draft-04/links create mode 100644 node_modules/json-schema/draft-04/schema create mode 100644 node_modules/json-schema/draft-zyp-json-schema-03.xml create mode 100644 node_modules/json-schema/draft-zyp-json-schema-04.xml create mode 100644 node_modules/json-schema/lib/links.js create mode 100644 node_modules/json-schema/lib/validate.js create mode 100644 node_modules/json-schema/package.json create mode 100644 node_modules/json-schema/test/tests.js create mode 100644 node_modules/json-stable-stringify/.npmignore create mode 100644 node_modules/json-stable-stringify/.travis.yml create mode 100644 node_modules/json-stable-stringify/LICENSE create mode 100644 node_modules/json-stable-stringify/example/key_cmp.js create mode 100644 node_modules/json-stable-stringify/example/nested.js create mode 100644 node_modules/json-stable-stringify/example/str.js create mode 100644 node_modules/json-stable-stringify/example/value_cmp.js create mode 100644 node_modules/json-stable-stringify/index.js create mode 100644 node_modules/json-stable-stringify/package.json create mode 100644 node_modules/json-stable-stringify/readme.markdown create mode 100644 node_modules/json-stable-stringify/test/cmp.js create mode 100644 node_modules/json-stable-stringify/test/nested.js create mode 100644 node_modules/json-stable-stringify/test/replacer.js create mode 100644 node_modules/json-stable-stringify/test/space.js create mode 100644 node_modules/json-stable-stringify/test/str.js create mode 100644 node_modules/json-stable-stringify/test/to-json.js create mode 100644 node_modules/json-stringify-safe/.npmignore create mode 100644 node_modules/json-stringify-safe/CHANGELOG.md create mode 100644 node_modules/json-stringify-safe/LICENSE create mode 100644 node_modules/json-stringify-safe/Makefile create mode 100644 node_modules/json-stringify-safe/README.md create mode 100644 node_modules/json-stringify-safe/package.json create mode 100644 node_modules/json-stringify-safe/stringify.js create mode 100644 node_modules/json-stringify-safe/test/mocha.opts create mode 100644 node_modules/json-stringify-safe/test/stringify_test.js create mode 100644 node_modules/jsonify/README.markdown create mode 100644 node_modules/jsonify/index.js create mode 100644 node_modules/jsonify/lib/parse.js create mode 100644 node_modules/jsonify/lib/stringify.js create mode 100644 node_modules/jsonify/package.json create mode 100644 node_modules/jsonify/test/parse.js create mode 100644 node_modules/jsonify/test/stringify.js create mode 100644 node_modules/jsonparse/.npmignore create mode 100644 node_modules/jsonparse/LICENSE create mode 100644 node_modules/jsonparse/README.markdown create mode 100644 node_modules/jsonparse/bench.js create mode 100644 node_modules/jsonparse/examples/twitterfeed.js create mode 100644 node_modules/jsonparse/jsonparse.js create mode 100644 node_modules/jsonparse/package.json create mode 100644 node_modules/jsonparse/samplejson/basic.json create mode 100644 node_modules/jsonparse/samplejson/basic2.json create mode 100644 node_modules/jsonparse/test/boundary.js create mode 100644 node_modules/jsonparse/test/offset.js create mode 100644 node_modules/jsonparse/test/primitives.js create mode 100644 node_modules/jsonparse/test/unvalid.js create mode 100644 node_modules/jsonparse/test/utf8.js create mode 100644 node_modules/jsprim/CHANGES.md create mode 100644 node_modules/jsprim/CONTRIBUTING.md create mode 100644 node_modules/jsprim/LICENSE create mode 100644 node_modules/jsprim/README.md create mode 100644 node_modules/jsprim/lib/jsprim.js create mode 100644 node_modules/jsprim/node_modules/assert-plus/AUTHORS create mode 100644 node_modules/jsprim/node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/jsprim/node_modules/assert-plus/README.md create mode 100644 node_modules/jsprim/node_modules/assert-plus/assert.js create mode 100644 node_modules/jsprim/node_modules/assert-plus/package.json create mode 100644 node_modules/jsprim/package.json create mode 100644 node_modules/md5.js/LICENSE create mode 100644 node_modules/md5.js/README.md create mode 100644 node_modules/md5.js/index.js create mode 100644 node_modules/md5.js/package.json create mode 100644 node_modules/mime-db/HISTORY.md create mode 100644 node_modules/mime-db/LICENSE create mode 100644 node_modules/mime-db/README.md create mode 100644 node_modules/mime-db/db.json create mode 100644 node_modules/mime-db/index.js create mode 100644 node_modules/mime-db/package.json create mode 100644 node_modules/mime-types/HISTORY.md create mode 100644 node_modules/mime-types/LICENSE create mode 100644 node_modules/mime-types/README.md create mode 100644 node_modules/mime-types/index.js create mode 100644 node_modules/mime-types/package.json create mode 100644 node_modules/node-uuid/.npmignore create mode 100644 node_modules/node-uuid/LICENSE.md create mode 100644 node_modules/node-uuid/README.md create mode 100644 node_modules/node-uuid/benchmark/README.md create mode 100644 node_modules/node-uuid/benchmark/bench.gnu create mode 100644 node_modules/node-uuid/benchmark/bench.sh create mode 100644 node_modules/node-uuid/benchmark/benchmark-native.c create mode 100644 node_modules/node-uuid/benchmark/benchmark.js create mode 100644 node_modules/node-uuid/bin/uuid create mode 100644 node_modules/node-uuid/bower.json create mode 100644 node_modules/node-uuid/component.json create mode 100644 node_modules/node-uuid/lib/sha1-browser.js create mode 100644 node_modules/node-uuid/package.json create mode 100644 node_modules/node-uuid/test/compare_v1.js create mode 100644 node_modules/node-uuid/test/test.html create mode 100644 node_modules/node-uuid/test/test.js create mode 100644 node_modules/node-uuid/uuid.js create mode 100644 node_modules/node-uuid/v3.js create mode 100644 node_modules/nonce/.npmignore create mode 100644 node_modules/nonce/.travis.yml create mode 100644 node_modules/nonce/LICENSE create mode 100644 node_modules/nonce/README.markdown create mode 100644 node_modules/nonce/index.js create mode 100644 node_modules/nonce/package.json create mode 100644 node_modules/oauth-sign/LICENSE create mode 100644 node_modules/oauth-sign/README.md create mode 100644 node_modules/oauth-sign/index.js create mode 100644 node_modules/oauth-sign/package.json create mode 100644 node_modules/performance-now/.npmignore create mode 100644 node_modules/performance-now/.tm_properties create mode 100644 node_modules/performance-now/.travis.yml create mode 100644 node_modules/performance-now/Makefile create mode 100644 node_modules/performance-now/README.md create mode 100644 node_modules/performance-now/lib/performance-now.js create mode 100644 node_modules/performance-now/license.txt create mode 100644 node_modules/performance-now/package.json create mode 100644 node_modules/performance-now/src/performance-now.coffee create mode 100644 node_modules/performance-now/test/mocha.opts create mode 100644 node_modules/performance-now/test/performance-now.coffee create mode 100644 node_modules/process-nextick-args/.travis.yml create mode 100644 node_modules/process-nextick-args/index.js create mode 100644 node_modules/process-nextick-args/license.md create mode 100644 node_modules/process-nextick-args/package.json create mode 100644 node_modules/process-nextick-args/readme.md create mode 100644 node_modules/process-nextick-args/test.js create mode 100644 node_modules/punycode/LICENSE-MIT.txt create mode 100644 node_modules/punycode/README.md create mode 100644 node_modules/punycode/package.json create mode 100644 node_modules/punycode/punycode.js create mode 100644 node_modules/qs/.eslintignore create mode 100644 node_modules/qs/.eslintrc create mode 100644 node_modules/qs/.jscs.json create mode 100644 node_modules/qs/CHANGELOG.md create mode 100644 node_modules/qs/LICENSE create mode 100644 node_modules/qs/README.md create mode 100644 node_modules/qs/dist/qs.js create mode 100644 node_modules/qs/lib/formats.js create mode 100644 node_modules/qs/lib/index.js create mode 100644 node_modules/qs/lib/parse.js create mode 100644 node_modules/qs/lib/stringify.js create mode 100644 node_modules/qs/lib/utils.js create mode 100644 node_modules/qs/package.json create mode 100644 node_modules/qs/test/.eslintrc create mode 100644 node_modules/qs/test/index.js create mode 100644 node_modules/qs/test/parse.js create mode 100644 node_modules/qs/test/stringify.js create mode 100644 node_modules/qs/test/utils.js create mode 100644 node_modules/readable-stream/.npmignore create mode 100644 node_modules/readable-stream/.travis.yml create mode 100644 node_modules/readable-stream/.zuul.yml create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/doc/stream.markdown create mode 100644 node_modules/readable-stream/doc/wg-meetings/2015-01-30.md create mode 100644 node_modules/readable-stream/duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/passthrough.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/readable-stream/transform.js create mode 100644 node_modules/readable-stream/writable.js create mode 100644 node_modules/request/CHANGELOG.md create mode 100644 node_modules/request/LICENSE create mode 100644 node_modules/request/README.md create mode 100644 node_modules/request/index.js create mode 100644 node_modules/request/lib/auth.js create mode 100644 node_modules/request/lib/cookies.js create mode 100644 node_modules/request/lib/getProxyFromURI.js create mode 100644 node_modules/request/lib/har.js create mode 100644 node_modules/request/lib/helpers.js create mode 100644 node_modules/request/lib/multipart.js create mode 100644 node_modules/request/lib/oauth.js create mode 100644 node_modules/request/lib/querystring.js create mode 100644 node_modules/request/lib/redirect.js create mode 100644 node_modules/request/lib/tunnel.js create mode 100644 node_modules/request/node_modules/.bin/uuid create mode 100644 node_modules/request/node_modules/.bin/uuid.cmd create mode 100644 node_modules/request/node_modules/ajv/.tonic_example.js create mode 100644 node_modules/request/node_modules/ajv/LICENSE create mode 100644 node_modules/request/node_modules/ajv/README.md create mode 100644 node_modules/request/node_modules/ajv/dist/ajv.bundle.js create mode 100644 node_modules/request/node_modules/ajv/dist/ajv.min.js create mode 100644 node_modules/request/node_modules/ajv/dist/ajv.min.js.map create mode 100644 node_modules/request/node_modules/ajv/dist/nodent.min.js create mode 100644 node_modules/request/node_modules/ajv/dist/regenerator.min.js create mode 100644 node_modules/request/node_modules/ajv/lib/$data.js create mode 100644 node_modules/request/node_modules/ajv/lib/ajv.d.ts create mode 100644 node_modules/request/node_modules/ajv/lib/ajv.js create mode 100644 node_modules/request/node_modules/ajv/lib/cache.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/_rules.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/async.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/equal.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/error_classes.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/formats.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/index.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/resolve.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/rules.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/schema_obj.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/ucs2length.js create mode 100644 node_modules/request/node_modules/ajv/lib/compile/util.js create mode 100644 node_modules/request/node_modules/ajv/lib/dot/_limit.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/_limitItems.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/_limitLength.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/_limitProperties.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/allOf.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/anyOf.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/coerce.def create mode 100644 node_modules/request/node_modules/ajv/lib/dot/const.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/contains.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/custom.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/defaults.def create mode 100644 node_modules/request/node_modules/ajv/lib/dot/definitions.def create mode 100644 node_modules/request/node_modules/ajv/lib/dot/dependencies.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/enum.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/errors.def create mode 100644 node_modules/request/node_modules/ajv/lib/dot/format.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/items.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/missing.def create mode 100644 node_modules/request/node_modules/ajv/lib/dot/multipleOf.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/not.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/oneOf.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/pattern.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/properties.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/propertyNames.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/ref.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/required.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/uniqueItems.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dot/validate.jst create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/README.md create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/_limit.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/_limitItems.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/_limitLength.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/_limitProperties.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/allOf.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/anyOf.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/const.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/contains.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/custom.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/dependencies.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/enum.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/format.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/items.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/multipleOf.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/not.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/oneOf.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/pattern.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/properties.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/propertyNames.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/ref.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/required.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/uniqueItems.js create mode 100644 node_modules/request/node_modules/ajv/lib/dotjs/validate.js create mode 100644 node_modules/request/node_modules/ajv/lib/keyword.js create mode 100644 node_modules/request/node_modules/ajv/lib/patternGroups.js create mode 100644 node_modules/request/node_modules/ajv/lib/refs/$data.json create mode 100644 node_modules/request/node_modules/ajv/lib/refs/json-schema-draft-04.json create mode 100644 node_modules/request/node_modules/ajv/lib/refs/json-schema-draft-06.json create mode 100644 node_modules/request/node_modules/ajv/lib/refs/json-schema-v5.json create mode 100644 node_modules/request/node_modules/ajv/package.json create mode 100644 node_modules/request/node_modules/ajv/scripts/.eslintrc.yml create mode 100644 node_modules/request/node_modules/ajv/scripts/bundle.js create mode 100644 node_modules/request/node_modules/ajv/scripts/compile-dots.js create mode 100644 node_modules/request/node_modules/ajv/scripts/info create mode 100644 node_modules/request/node_modules/ajv/scripts/prepare-tests create mode 100644 node_modules/request/node_modules/ajv/scripts/travis-gh-pages create mode 100644 node_modules/request/node_modules/assert-plus/AUTHORS create mode 100644 node_modules/request/node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/request/node_modules/assert-plus/README.md create mode 100644 node_modules/request/node_modules/assert-plus/assert.js create mode 100644 node_modules/request/node_modules/assert-plus/package.json create mode 100644 node_modules/request/node_modules/aws-sign2/LICENSE create mode 100644 node_modules/request/node_modules/aws-sign2/README.md create mode 100644 node_modules/request/node_modules/aws-sign2/index.js create mode 100644 node_modules/request/node_modules/aws-sign2/package.json create mode 100644 node_modules/request/node_modules/boom/LICENSE create mode 100644 node_modules/request/node_modules/boom/README.md create mode 100644 node_modules/request/node_modules/boom/lib/index.js create mode 100644 node_modules/request/node_modules/boom/package.json create mode 100644 node_modules/request/node_modules/cryptiles/.npmignore create mode 100644 node_modules/request/node_modules/cryptiles/LICENSE create mode 100644 node_modules/request/node_modules/cryptiles/README.md create mode 100644 node_modules/request/node_modules/cryptiles/lib/index.js create mode 100644 node_modules/request/node_modules/cryptiles/node_modules/boom/LICENSE create mode 100644 node_modules/request/node_modules/cryptiles/node_modules/boom/README.md create mode 100644 node_modules/request/node_modules/cryptiles/node_modules/boom/lib/index.js create mode 100644 node_modules/request/node_modules/cryptiles/node_modules/boom/package.json create mode 100644 node_modules/request/node_modules/cryptiles/package.json create mode 100644 node_modules/request/node_modules/extend/.eslintrc create mode 100644 node_modules/request/node_modules/extend/.jscs.json create mode 100644 node_modules/request/node_modules/extend/.npmignore create mode 100644 node_modules/request/node_modules/extend/.travis.yml create mode 100644 node_modules/request/node_modules/extend/CHANGELOG.md create mode 100644 node_modules/request/node_modules/extend/LICENSE create mode 100644 node_modules/request/node_modules/extend/README.md create mode 100644 node_modules/request/node_modules/extend/component.json create mode 100644 node_modules/request/node_modules/extend/index.js create mode 100644 node_modules/request/node_modules/extend/package.json create mode 100644 node_modules/request/node_modules/form-data/License create mode 100644 node_modules/request/node_modules/form-data/README.md create mode 100644 node_modules/request/node_modules/form-data/README.md.bak create mode 100644 node_modules/request/node_modules/form-data/lib/browser.js create mode 100644 node_modules/request/node_modules/form-data/lib/form_data.js create mode 100644 node_modules/request/node_modules/form-data/lib/populate.js create mode 100644 node_modules/request/node_modules/form-data/package.json create mode 100644 node_modules/request/node_modules/har-schema/LICENSE create mode 100644 node_modules/request/node_modules/har-schema/README.md create mode 100644 node_modules/request/node_modules/har-schema/lib/afterRequest.json create mode 100644 node_modules/request/node_modules/har-schema/lib/beforeRequest.json create mode 100644 node_modules/request/node_modules/har-schema/lib/browser.json create mode 100644 node_modules/request/node_modules/har-schema/lib/cache.json create mode 100644 node_modules/request/node_modules/har-schema/lib/content.json create mode 100644 node_modules/request/node_modules/har-schema/lib/cookie.json create mode 100644 node_modules/request/node_modules/har-schema/lib/creator.json create mode 100644 node_modules/request/node_modules/har-schema/lib/entry.json create mode 100644 node_modules/request/node_modules/har-schema/lib/har.json create mode 100644 node_modules/request/node_modules/har-schema/lib/header.json create mode 100644 node_modules/request/node_modules/har-schema/lib/index.js create mode 100644 node_modules/request/node_modules/har-schema/lib/log.json create mode 100644 node_modules/request/node_modules/har-schema/lib/page.json create mode 100644 node_modules/request/node_modules/har-schema/lib/pageTimings.json create mode 100644 node_modules/request/node_modules/har-schema/lib/postData.json create mode 100644 node_modules/request/node_modules/har-schema/lib/query.json create mode 100644 node_modules/request/node_modules/har-schema/lib/request.json create mode 100644 node_modules/request/node_modules/har-schema/lib/response.json create mode 100644 node_modules/request/node_modules/har-schema/lib/timings.json create mode 100644 node_modules/request/node_modules/har-schema/package.json create mode 100644 node_modules/request/node_modules/har-validator/LICENSE create mode 100644 node_modules/request/node_modules/har-validator/README.md create mode 100644 node_modules/request/node_modules/har-validator/lib/async.js create mode 100644 node_modules/request/node_modules/har-validator/lib/error.js create mode 100644 node_modules/request/node_modules/har-validator/lib/promise.js create mode 100644 node_modules/request/node_modules/har-validator/package.json create mode 100644 node_modules/request/node_modules/hawk/.npmignore create mode 100644 node_modules/request/node_modules/hawk/LICENSE create mode 100644 node_modules/request/node_modules/hawk/README.md create mode 100644 node_modules/request/node_modules/hawk/client.js create mode 100644 node_modules/request/node_modules/hawk/dist/browser.js create mode 100644 node_modules/request/node_modules/hawk/lib/browser.js create mode 100644 node_modules/request/node_modules/hawk/lib/client.js create mode 100644 node_modules/request/node_modules/hawk/lib/crypto.js create mode 100644 node_modules/request/node_modules/hawk/lib/index.js create mode 100644 node_modules/request/node_modules/hawk/lib/server.js create mode 100644 node_modules/request/node_modules/hawk/lib/utils.js create mode 100644 node_modules/request/node_modules/hawk/package.json create mode 100644 node_modules/request/node_modules/hoek/.npmignore create mode 100644 node_modules/request/node_modules/hoek/LICENSE create mode 100644 node_modules/request/node_modules/hoek/README.md create mode 100644 node_modules/request/node_modules/hoek/lib/escape.js create mode 100644 node_modules/request/node_modules/hoek/lib/index.js create mode 100644 node_modules/request/node_modules/hoek/package.json create mode 100644 node_modules/request/node_modules/http-signature/.dir-locals.el create mode 100644 node_modules/request/node_modules/http-signature/.npmignore create mode 100644 node_modules/request/node_modules/http-signature/CHANGES.md create mode 100644 node_modules/request/node_modules/http-signature/LICENSE create mode 100644 node_modules/request/node_modules/http-signature/README.md create mode 100644 node_modules/request/node_modules/http-signature/http_signing.md create mode 100644 node_modules/request/node_modules/http-signature/lib/index.js create mode 100644 node_modules/request/node_modules/http-signature/lib/parser.js create mode 100644 node_modules/request/node_modules/http-signature/lib/signer.js create mode 100644 node_modules/request/node_modules/http-signature/lib/utils.js create mode 100644 node_modules/request/node_modules/http-signature/lib/verify.js create mode 100644 node_modules/request/node_modules/http-signature/package.json create mode 100644 node_modules/request/node_modules/performance-now/.npmignore create mode 100644 node_modules/request/node_modules/performance-now/.tm_properties create mode 100644 node_modules/request/node_modules/performance-now/.travis.yml create mode 100644 node_modules/request/node_modules/performance-now/README.md create mode 100644 node_modules/request/node_modules/performance-now/lib/performance-now.js create mode 100644 node_modules/request/node_modules/performance-now/lib/performance-now.js.map create mode 100644 node_modules/request/node_modules/performance-now/license.txt create mode 100644 node_modules/request/node_modules/performance-now/package.json create mode 100644 node_modules/request/node_modules/performance-now/src/index.d.ts create mode 100644 node_modules/request/node_modules/performance-now/src/performance-now.coffee create mode 100644 node_modules/request/node_modules/performance-now/test/mocha.opts create mode 100644 node_modules/request/node_modules/performance-now/test/performance-now.coffee create mode 100644 node_modules/request/node_modules/performance-now/test/scripts.coffee create mode 100644 node_modules/request/node_modules/performance-now/test/scripts/delayed-call.coffee create mode 100644 node_modules/request/node_modules/performance-now/test/scripts/delayed-require.coffee create mode 100644 node_modules/request/node_modules/performance-now/test/scripts/difference.coffee create mode 100644 node_modules/request/node_modules/performance-now/test/scripts/initial-value.coffee create mode 100644 node_modules/request/node_modules/qs/.editorconfig create mode 100644 node_modules/request/node_modules/qs/.eslintignore create mode 100644 node_modules/request/node_modules/qs/.eslintrc create mode 100644 node_modules/request/node_modules/qs/CHANGELOG.md create mode 100644 node_modules/request/node_modules/qs/LICENSE create mode 100644 node_modules/request/node_modules/qs/README.md create mode 100644 node_modules/request/node_modules/qs/dist/qs.js create mode 100644 node_modules/request/node_modules/qs/lib/formats.js create mode 100644 node_modules/request/node_modules/qs/lib/index.js create mode 100644 node_modules/request/node_modules/qs/lib/parse.js create mode 100644 node_modules/request/node_modules/qs/lib/stringify.js create mode 100644 node_modules/request/node_modules/qs/lib/utils.js create mode 100644 node_modules/request/node_modules/qs/package.json create mode 100644 node_modules/request/node_modules/qs/test/.eslintrc create mode 100644 node_modules/request/node_modules/qs/test/index.js create mode 100644 node_modules/request/node_modules/qs/test/parse.js create mode 100644 node_modules/request/node_modules/qs/test/stringify.js create mode 100644 node_modules/request/node_modules/qs/test/utils.js create mode 100644 node_modules/request/node_modules/sntp/.npmignore create mode 100644 node_modules/request/node_modules/sntp/LICENSE create mode 100644 node_modules/request/node_modules/sntp/README.md create mode 100644 node_modules/request/node_modules/sntp/lib/index.js create mode 100644 node_modules/request/node_modules/sntp/package.json create mode 100644 node_modules/request/node_modules/uuid/.eslintrc.json create mode 100644 node_modules/request/node_modules/uuid/AUTHORS create mode 100644 node_modules/request/node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/request/node_modules/uuid/LICENSE.md create mode 100644 node_modules/request/node_modules/uuid/README.md create mode 100644 node_modules/request/node_modules/uuid/README_js.md create mode 100644 node_modules/request/node_modules/uuid/bin/uuid create mode 100644 node_modules/request/node_modules/uuid/index.js create mode 100644 node_modules/request/node_modules/uuid/lib/bytesToUuid.js create mode 100644 node_modules/request/node_modules/uuid/lib/md5-browser.js create mode 100644 node_modules/request/node_modules/uuid/lib/md5.js create mode 100644 node_modules/request/node_modules/uuid/lib/rng-browser.js create mode 100644 node_modules/request/node_modules/uuid/lib/rng.js create mode 100644 node_modules/request/node_modules/uuid/lib/sha1-browser.js create mode 100644 node_modules/request/node_modules/uuid/lib/sha1.js create mode 100644 node_modules/request/node_modules/uuid/lib/v35.js create mode 100644 node_modules/request/node_modules/uuid/package.json create mode 100644 node_modules/request/node_modules/uuid/v1.js create mode 100644 node_modules/request/node_modules/uuid/v3.js create mode 100644 node_modules/request/node_modules/uuid/v4.js create mode 100644 node_modules/request/node_modules/uuid/v5.js create mode 100644 node_modules/request/package.json create mode 100644 node_modules/request/request.js create mode 100644 node_modules/safe-buffer/.travis.yml create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/safe-buffer/test.js create mode 100644 node_modules/sax/AUTHORS create mode 100644 node_modules/sax/LICENSE create mode 100644 node_modules/sax/LICENSE-W3C.html create mode 100644 node_modules/sax/README.md create mode 100644 node_modules/sax/component.json create mode 100644 node_modules/sax/examples/big-not-pretty.xml create mode 100644 node_modules/sax/examples/example.js create mode 100644 node_modules/sax/examples/get-products.js create mode 100644 node_modules/sax/examples/hello-world.js create mode 100644 node_modules/sax/examples/not-pretty.xml create mode 100644 node_modules/sax/examples/pretty-print.js create mode 100644 node_modules/sax/examples/shopping.xml create mode 100644 node_modules/sax/examples/strict.dtd create mode 100644 node_modules/sax/examples/test.html create mode 100644 node_modules/sax/examples/test.xml create mode 100644 node_modules/sax/lib/sax.js create mode 100644 node_modules/sax/package.json create mode 100644 node_modules/sax/test/attribute-name.js create mode 100644 node_modules/sax/test/attribute-no-space.js create mode 100644 node_modules/sax/test/buffer-overrun.js create mode 100644 node_modules/sax/test/case.js create mode 100644 node_modules/sax/test/cdata-chunked.js create mode 100644 node_modules/sax/test/cdata-end-split.js create mode 100644 node_modules/sax/test/cdata-fake-end.js create mode 100644 node_modules/sax/test/cdata-multiple.js create mode 100644 node_modules/sax/test/cdata.js create mode 100644 node_modules/sax/test/cyrillic.js create mode 100644 node_modules/sax/test/duplicate-attribute.js create mode 100644 node_modules/sax/test/end_empty_stream.js create mode 100644 node_modules/sax/test/entities.js create mode 100644 node_modules/sax/test/entity-mega.js create mode 100644 node_modules/sax/test/flush.js create mode 100644 node_modules/sax/test/index.js create mode 100644 node_modules/sax/test/issue-23.js create mode 100644 node_modules/sax/test/issue-30.js create mode 100644 node_modules/sax/test/issue-35.js create mode 100644 node_modules/sax/test/issue-47.js create mode 100644 node_modules/sax/test/issue-49.js create mode 100644 node_modules/sax/test/issue-84.js create mode 100644 node_modules/sax/test/parser-position.js create mode 100644 node_modules/sax/test/script-close-better.js create mode 100644 node_modules/sax/test/script.js create mode 100644 node_modules/sax/test/self-closing-child-strict.js create mode 100644 node_modules/sax/test/self-closing-child.js create mode 100644 node_modules/sax/test/self-closing-tag.js create mode 100644 node_modules/sax/test/stray-ending.js create mode 100644 node_modules/sax/test/trailing-attribute-no-value.js create mode 100644 node_modules/sax/test/trailing-non-whitespace.js create mode 100644 node_modules/sax/test/unclosed-root.js create mode 100644 node_modules/sax/test/unquoted.js create mode 100644 node_modules/sax/test/utf8-split.js create mode 100644 node_modules/sax/test/xmlns-as-tag-name.js create mode 100644 node_modules/sax/test/xmlns-issue-41.js create mode 100644 node_modules/sax/test/xmlns-rebinding.js create mode 100644 node_modules/sax/test/xmlns-strict.js create mode 100644 node_modules/sax/test/xmlns-unbound-element.js create mode 100644 node_modules/sax/test/xmlns-unbound.js create mode 100644 node_modules/sax/test/xmlns-xml-default-ns.js create mode 100644 node_modules/sax/test/xmlns-xml-default-prefix-attribute.js create mode 100644 node_modules/sax/test/xmlns-xml-default-prefix.js create mode 100644 node_modules/sax/test/xmlns-xml-default-redefine.js create mode 100644 node_modules/sntp/.npmignore create mode 100644 node_modules/sntp/.travis.yml create mode 100644 node_modules/sntp/LICENSE create mode 100644 node_modules/sntp/Makefile create mode 100644 node_modules/sntp/README.md create mode 100644 node_modules/sntp/examples/offset.js create mode 100644 node_modules/sntp/examples/time.js create mode 100644 node_modules/sntp/index.js create mode 100644 node_modules/sntp/lib/index.js create mode 100644 node_modules/sntp/package.json create mode 100644 node_modules/sntp/test/index.js create mode 100644 node_modules/sshpk/.npmignore create mode 100644 node_modules/sshpk/.travis.yml create mode 100644 node_modules/sshpk/LICENSE create mode 100644 node_modules/sshpk/README.md create mode 100644 node_modules/sshpk/bin/sshpk-conv create mode 100644 node_modules/sshpk/bin/sshpk-sign create mode 100644 node_modules/sshpk/bin/sshpk-verify create mode 100644 node_modules/sshpk/lib/algs.js create mode 100644 node_modules/sshpk/lib/certificate.js create mode 100644 node_modules/sshpk/lib/dhe.js create mode 100644 node_modules/sshpk/lib/ed-compat.js create mode 100644 node_modules/sshpk/lib/errors.js create mode 100644 node_modules/sshpk/lib/fingerprint.js create mode 100644 node_modules/sshpk/lib/formats/auto.js create mode 100644 node_modules/sshpk/lib/formats/openssh-cert.js create mode 100644 node_modules/sshpk/lib/formats/pem.js create mode 100644 node_modules/sshpk/lib/formats/pkcs1.js create mode 100644 node_modules/sshpk/lib/formats/pkcs8.js create mode 100644 node_modules/sshpk/lib/formats/rfc4253.js create mode 100644 node_modules/sshpk/lib/formats/ssh-private.js create mode 100644 node_modules/sshpk/lib/formats/ssh.js create mode 100644 node_modules/sshpk/lib/formats/x509-pem.js create mode 100644 node_modules/sshpk/lib/formats/x509.js create mode 100644 node_modules/sshpk/lib/identity.js create mode 100644 node_modules/sshpk/lib/index.js create mode 100644 node_modules/sshpk/lib/key.js create mode 100644 node_modules/sshpk/lib/private-key.js create mode 100644 node_modules/sshpk/lib/signature.js create mode 100644 node_modules/sshpk/lib/ssh-buffer.js create mode 100644 node_modules/sshpk/lib/utils.js create mode 100644 node_modules/sshpk/man/man1/sshpk-conv.1 create mode 100644 node_modules/sshpk/man/man1/sshpk-sign.1 create mode 100644 node_modules/sshpk/man/man1/sshpk-verify.1 create mode 100644 node_modules/sshpk/node_modules/assert-plus/AUTHORS create mode 100644 node_modules/sshpk/node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/sshpk/node_modules/assert-plus/README.md create mode 100644 node_modules/sshpk/node_modules/assert-plus/assert.js create mode 100644 node_modules/sshpk/node_modules/assert-plus/package.json create mode 100644 node_modules/sshpk/package.json create mode 100644 node_modules/string_decoder/.npmignore create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/index.js create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/stringstream/.npmignore create mode 100644 node_modules/stringstream/.travis.yml create mode 100644 node_modules/stringstream/LICENSE.txt create mode 100644 node_modules/stringstream/README.md create mode 100644 node_modules/stringstream/example.js create mode 100644 node_modules/stringstream/package.json create mode 100644 node_modules/stringstream/stringstream.js create mode 100644 node_modules/tough-cookie/LICENSE create mode 100644 node_modules/tough-cookie/README.md create mode 100644 node_modules/tough-cookie/lib/cookie.js create mode 100644 node_modules/tough-cookie/lib/memstore.js create mode 100644 node_modules/tough-cookie/lib/pathMatch.js create mode 100644 node_modules/tough-cookie/lib/permuteDomain.js create mode 100644 node_modules/tough-cookie/lib/pubsuffix.js create mode 100644 node_modules/tough-cookie/lib/store.js create mode 100644 node_modules/tough-cookie/package.json create mode 100644 node_modules/tunnel-agent/LICENSE create mode 100644 node_modules/tunnel-agent/README.md create mode 100644 node_modules/tunnel-agent/index.js create mode 100644 node_modules/tunnel-agent/package.json create mode 100644 node_modules/tweetnacl/.npmignore create mode 100644 node_modules/tweetnacl/AUTHORS.md create mode 100644 node_modules/tweetnacl/CHANGELOG.md create mode 100644 node_modules/tweetnacl/LICENSE create mode 100644 node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md create mode 100644 node_modules/tweetnacl/README.md create mode 100644 node_modules/tweetnacl/nacl-fast.js create mode 100644 node_modules/tweetnacl/nacl-fast.min.js create mode 100644 node_modules/tweetnacl/nacl.d.ts create mode 100644 node_modules/tweetnacl/nacl.js create mode 100644 node_modules/tweetnacl/nacl.min.js create mode 100644 node_modules/tweetnacl/package.json create mode 100644 node_modules/underscore/LICENSE create mode 100644 node_modules/underscore/README.md create mode 100644 node_modules/underscore/package.json create mode 100644 node_modules/underscore/underscore-min.js create mode 100644 node_modules/underscore/underscore-min.map create mode 100644 node_modules/underscore/underscore.js create mode 100644 node_modules/util-deprecate/History.md create mode 100644 node_modules/util-deprecate/LICENSE create mode 100644 node_modules/util-deprecate/README.md create mode 100644 node_modules/util-deprecate/browser.js create mode 100644 node_modules/util-deprecate/node.js create mode 100644 node_modules/util-deprecate/package.json create mode 100644 node_modules/validator/.jshintrc create mode 100644 node_modules/validator/.npmignore create mode 100644 node_modules/validator/.travis.yml create mode 100644 node_modules/validator/LICENSE create mode 100644 node_modules/validator/Makefile create mode 100644 node_modules/validator/README.md create mode 100644 node_modules/validator/bower.json create mode 100644 node_modules/validator/package.json create mode 100644 node_modules/validator/test/client-side.js create mode 100644 node_modules/validator/test/exports.js create mode 100644 node_modules/validator/test/sanitizers.js create mode 100644 node_modules/validator/test/validators.js create mode 100644 node_modules/validator/validator.js create mode 100644 node_modules/validator/validator.min.js create mode 100644 node_modules/verror/.npmignore create mode 100644 node_modules/verror/CHANGES.md create mode 100644 node_modules/verror/CONTRIBUTING.md create mode 100644 node_modules/verror/LICENSE create mode 100644 node_modules/verror/README.md create mode 100644 node_modules/verror/lib/verror.js create mode 100644 node_modules/verror/node_modules/assert-plus/AUTHORS create mode 100644 node_modules/verror/node_modules/assert-plus/CHANGES.md create mode 100644 node_modules/verror/node_modules/assert-plus/README.md create mode 100644 node_modules/verror/node_modules/assert-plus/assert.js create mode 100644 node_modules/verror/node_modules/assert-plus/package.json create mode 100644 node_modules/verror/package.json create mode 100644 node_modules/xml2js/.npmignore create mode 100644 node_modules/xml2js/.travis.yml create mode 100644 node_modules/xml2js/83.coffee create mode 100644 node_modules/xml2js/LICENSE create mode 100644 node_modules/xml2js/README.md create mode 100644 node_modules/xml2js/canon.xml create mode 100644 node_modules/xml2js/lib/xml2js.js create mode 100644 node_modules/xml2js/package.json create mode 100644 node_modules/xml2js/text.coffee create mode 100644 node_modules/xml2js/text.xml create mode 100644 node_modules/xmlbuilder/.npmignore create mode 100644 node_modules/xmlbuilder/Makefile create mode 100644 node_modules/xmlbuilder/README.md create mode 100644 node_modules/xmlbuilder/lib/XMLBuilder.js create mode 100644 node_modules/xmlbuilder/lib/XMLFragment.js create mode 100644 node_modules/xmlbuilder/lib/index.js create mode 100644 node_modules/xmlbuilder/package.json create mode 100644 obj/Debug/AACharly.njsproj.CoreCompileInputs.cache create mode 100644 obj/Debug/AACharly.njsproj.FileListAbsolute.txt create mode 100644 obj/Debug/AACharly.njsprojResolveAssemblyReference.cache create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..dfe077042 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.vs/AACharly/v15/.suo b/.vs/AACharly/v15/.suo new file mode 100644 index 0000000000000000000000000000000000000000..3e6ec083c251110065a74adc9008fe5c4726f4c2 GIT binary patch literal 28160 zcmeHP3vgUj8NN$_TC}ZzEmA?!P$(+9$tG#ils?$zK?@CyO?5% z-*fJ{XU~8B^Z3vIIA?$H^P^w5=WC1ppqRpHWtQ^Bo93m>=%)s~7%z;@xN8{Y&3Mlsofu zQMeNrQ_6s{9@u-4YE#BsYRP}S5Hr%)-T7~=pY|ae(^m@;Kk*JJ3A7-ssDLi?MFgPg zA}1}1*?tp$vGiYu+Sbhx zRnA8Ay0HR1%{BcYyyN3(db|MfdjRAK%K*m$Y5@9ACId(x58!W)L%ay^K>$&`4{!qD zM8Nw2Re+NLivb*qlK@KqrvTWWO98cjcLG@dJjC<$^t%xI0qjTOGKXrtoH>8yxv&Qg z>iVDm`l566^{)*e#!0TfgSq}62Hu(Vk4`|4GvWxO$p?(1z>x){+ZA9&)6Jh*1x$&?4Ng_4=)E?0r(`~ zO2AbB_OlT_g}mzlp9b6j*a^51unTY#;4^@m0iOkY4zL?=3*c73ZGhVWcK|*QxD#*} z;BLS@fO`RZ0AB#y2e=>bMZlK;4*u*TD+!A!O#u78Q|RjStkQYs7vYBWU#Cf z)g+^gC}#T&`NwCZ*tVeI#WhHir!Z^*)^4p25=sx^F|>g4-w4_hb(Q`UrCOK2Bu^5x zI)7h{*W{rLlshS9rXl-9AP2SsZvxMmshv?pJF-d(+D7?Y)xLARvZ4g}kLyHWSCm72 z{m-m<*tFn0lsz->v^C=R1W`><iU7gUx{^|e(3^cO9EZ$(Ah^~yFW9gx3CrLew^ zBb|U1v_sjXY_>vZ%Bw1Ye%d^#pE7I$<_zZFF!n$0d1oQ!(@aoeqj0zfc`ni zqdwtv{!#Xq_{}?S44M$vV;0nBv=!lOmj`|gFL5)NnrHj?7yS);z6Z4R;X@hVJaB=e zhF@61L+FVij0UxjI9kPAV`wY^KXoOk{|J0B)H@0+5nzevEeU`Zuq{cg7utb00xgxJ zWemXYqg|O}>XrU?qAc6MAn2q0J&O9Xh)F4}k(7q|pp9lt7{%}8_h}`}f7-EVyJB!( zf1;e-H~H^eyrhKYm45D(wDT}fcRvh3{!PAc1Y+`1ra7lMx0yD>e2aYA2F>MY52PQ! zZ2vzAc~yYL0NU$L1}p)b0+4l(Chlw8-z~SOr)OSOYi{5CW_Pv;bNGZGd*b1YjLtJ%II|gLs3UJ{R#uJ^f+CoAh)y zV)87OKM(QwfRE_UA4MG2(-$HB7~o?4xd(AnPpgP~0e$*&9PxmjP9PrC(<#J5dYUVe ztAcpRrAGAh7~*j~eW@OAL;MNAcEDv!N6|fDFaRs-k*Lb zz2I9){}r?h=CLzSG|4>MaHFr11PGfHc^>(LA3GJf5G56M54nV}-HaeNp_6p+506Yf zvUuy_KmFi=i{3cvB~DfclCG&}`>hAS*zOtm&sqNTApiNuix%jk%+YoWT&J>(oBUg8 z`EP3da`UADSk*Q>u{s|<@~Ip8=dS(opHF@5Ki~h=jZd@DT#?40?U^I^Squ0Uxz;Mk zLfnyZlEnm=MG{P+3S~OMA<2tnxVT))H;1kYj5>v;2pVR;_@2GH{GYn~p5H$8v#mdk z(O*zVgKSOl@z!#+Kcs90UnGyMf)GZbtV%f>bTFn-oW}%&m?U}Uh2MK-*F)Qu`qB^m z{?%_@I5OXoGSLZQpSPmUP5$6s>J%t{oP+|00XQw3%F1_1B=+hLZuowu71EuIcS>WF389yZ%`#}8MVkirFrGFGBQU z{Oi!iF-@XLg3TmAZ@VV85j({}w?O*~$C5ggSNz8PZ!NZ+C`P*v*ixEcNDWxngIe*9 zr?8v?`~L_Opg!dl|8XeG`O46xQA_43G(YKQV`~zS^4;bE^?%}(LDcH}y%4YE{Fmon zgqM%8D;yn}S#RJ5hGG zUfrAR|IwQsLkETQ7w?Hh)n*H}}u+G604wK9}WN5(hy zo}-R$i6n;AjlG#{I-cx{B*(kQhg6$>7@Q(Eni^y$)Yk-SYr0glClTKo$;MO38m;0? zNkrDzG}eNIw`%*t*u}k=kt9jfA9O9nClgwh%h$V#DQr`hra6^Z4;#y{ck$5U8*Z)s z($!Cfe>WjBX-M@D1nv0+r;}HVNr|R9D$H?M4XJt>EnGr(eDK+^U9au@;pG2TfBX9D zvnSBln789;TsI6AKc~OSLrm0Mh08z~^+kn${Z8i@J^#G&;g|N*{OFZR+P@@K-t2ad zE$mp4KBjF|_q{vUU48!Hdo1b9A0#~8T})?ddd2h&sAf}Z)s(5VD$mp^y8H4bb?z&_ z`}WnBZCv$8^(npk^67GyKd4#Shf?I9E>x#=FJd?RwBI`g>3^1cuv1z2j=J9y`hy#O z`VgD~@h?SzQvhD&j|))NtNo+N2|3=CLjQ&MouuEg`XX%lKFx!KTFf4S08~j@_=hyb zZa{esWylu^{W+tV^aGaWbO>qHQJ!zn+!(@VD%=>}_8+qw1647QpP656)|5oL3aO6K zJc0#Aa?GI?));>LdhC?q-ZP#32m8cP${*JpRqFn8A}SF0L5WYPGLvl{#>3r<+)+`M z=%7T-rQE%ZG-NuI)KS(v1X^|D0G`)L|8$uq+M?qy^?g|vKi~- zN|v#g6)npeW7LIkhURs?6jQVfoFN3CbvttFz$cpUTnC$!Uugg*YtizW;k&NWQXzP< zm!nJzezOeUt@!Y18yFC6c^#0n6B<*ZxJ5Tk7CAiCNh=n;$E!5|K3hO*jvbwh8T)p+ZQ}whZ;b)%yc3=BJY%HdltaE}E&v}MEwaJ`uokl_h8E;z&ziEgCujdI zwk@=Hg(+_tMfP2)&>0yEiHBa=H|LO ze`xvgrk2pMme$s$mTeQEP)mO#ofr=!2QowH)WAe^MR+&^V@fzN9M6P>#Uq?nhfU@+)! zX$Z9kgRM=i&CQ{0Wp1YMT(>@OFo|CWds8YMkCxT}M~ePxDXPD%QI?~Q(<5qKQ>3w{ z*00t#Eb}+iEnn_$ZjAN%m#LB7`sM~zt#51&)Yb+Y8yb12C@;KM@tG8T`Z6dJ)2=Z~ zFWcuZJy^szJ@ynikeXr6cABnBB~*WVd<+J$BB$vgG@-E5YggFVmGLvnyuO_Kw{$iz zOKCksTB@(tHASu0!j75l?<=rQ>Bl~}qfodW!#P!YdSZE@Q7Hrga=pSsJJfl_#Y16I znzuAM(frid2bS*`NId?X#m{o(NCS+FJ)R%Dpj_?W1VJza!MFo)08Z1G(!41=d*y3$ z&wR&@=Pw(3?uve^Rw`b%-I8W;;cyi9mmGac5l}%ji(LH5r zcTNhk zrfe;+8Y$;2zlMd06xvfBX+GxvXm+Ad@}6>96jz5grJbtewv zeE#PuU%8|%GvA|b;$7mM|LS>99r*q?f(LF-clJHGNONgRQ-qAgj1%`HWqRM6*nTs` zl&|tBw&M7={;TOnuiWa64AkS)#5t(sIdtlg~UT?^xV zY_^ZLpylavtJ?rPf6n_1)Z>ZW8e@JgeUS9KFgW3tr#YPN0r31i2fH5N6~FQPyY>11 zUQpc!A1ZHqO6u9#!hru@@bOMEPlBk2KedqPe{Gs{v$DSKo@H8)e7tHG( z*p~7y!;S75dui~yLk}KkyL0!Nm)k!5*5F1$|E{F0EIGEhPxEDE+V-6F;+*A4-2bA! zo5U`}bs_%~gCk)VD1Y!i%kcoO^PgIqy#Hd4e;jjz|H#K%@AiTBABcAeig?9uT>obL z9on3v?QcAf7h3T?wu^lmiEJOBOIE3{PRO<`>q z`F}88_Ww8eq*(QyH@1ItfB2@pCrKSkl5wW8hsyx&K%4{J7m7VU#<~`={HU zZD*I_S%n$IRENK$hE>Q{#LUgOW9ON4U$t>>6?d! z{=a$u>mS}W=(}$A{=uuZ{e9WBxUH^Bt|GD1(@tuY~r@bzvW5w@fT9}qsjng9PP;<6Srd;S5NwG20M;Ke6=&;MrUXP&M9+qScRO{1QNp}4qQ`a{0E zH|OMSJ3c!3#p-`go^Vv-V>^0Y?6hi@oGFMMCyV})x}UuNHc*-NTe+)yE*SN#x%{HL hdVl + + + Debug + 2.0 + {ae0a3fe2-7021-4cc2-9922-a887ca5cdd7c} + + ShowAllFiles + Poloniex-Hole-Fixing\run.js + c:\users\luis\source\repos\AACharly\Poloniex-Hole-Fixing + . + {3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD} + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + True + 0 + / + http://localhost:48022/ + False + True + http://localhost:1337 + False + + + + + + + CurrentPage + True + False + False + False + + + + + + + + + False + False + + + + + \ No newline at end of file diff --git a/AACharly.sln b/AACharly.sln new file mode 100644 index 000000000..9ebd7e1df --- /dev/null +++ b/AACharly.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.10 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}") = "AACharly", "AACharly.njsproj", "{AE0A3FE2-7021-4CC2-9922-A887CA5CDD7C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AE0A3FE2-7021-4CC2-9922-A887CA5CDD7C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AE0A3FE2-7021-4CC2-9922-A887CA5CDD7C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AE0A3FE2-7021-4CC2-9922-A887CA5CDD7C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AE0A3FE2-7021-4CC2-9922-A887CA5CDD7C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9128DF06-8CA5-497C-8BF7-B924571C5394} + EndGlobalSection +EndGlobal diff --git a/Azure File Storage.js b/Azure File Storage.js new file mode 100644 index 000000000..dcb2f6c89 --- /dev/null +++ b/Azure File Storage.js @@ -0,0 +1,247 @@ + +exports.newAzureFileStorage = function newAzureFileStorage(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const MODULE_NAME = "Azure File Storage"; + + var fs = require('fs'); + var util = require('util'); + var guid = require('node-uuid'); + var crypto = require('crypto'); + var storage = require('azure-storage'); + + const DEBUG_MODULE = require('./Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + const shareName = 'data'; + let dataOwner; + + let azureFileStorage = { + initialize: initialize, + createFolder: createFolder, + createTextFile: createTextFile, + getTextFile: getTextFile, + listFilesAndFolders: listFilesAndFolders + }; + + let fileService; + + return azureFileStorage; + + + function initialize(dataOwnerBotName) { + + try { + + if (dataOwnerBotName === undefined) { + + dataOwner = bot.name; + + } else { + + dataOwner = dataOwnerBotName; + + } + + fileService = storage.createFileService(readConfig().connectionString); + + } + catch (err) { + const logText = "[ERROR] 'initialize' - ERROR : " + err.message; + logger.write(logText); + } + } + + function readConfig() { + + try { + + return JSON.parse(fs.readFileSync(ROOT_DIR + dataOwner + '.azure.storage.connstring', 'utf8')); + + } + catch (err) { + const logText = "[ERROR] 'readConfig' - ERROR : " + err.message; + logger.write(logText); + } + + } + + function createFolder(folderPath, callBackFunction) { + + try { + + fileService.createDirectoryIfNotExists(shareName, folderPath, onFolderCreated); + + function onFolderCreated(err) { + + if (err) { + + const logText = "[ERROR] createFolder - onFolderCreated ' ERROR = " + err.message + " SHARE NAME = " + shareName + " FOLDER PATH = " + folderPath; + console.log(logText); + logger.write(logText); + + } + + callBackFunction(); + + } + + } + catch (err) { + const logText = "[ERROR] 'createFolder' - ERROR : " + err.message; + logger.write(logText); + } + + } + + function createTextFile(folderPath, fileName, fileContent, callBackFunction) { + + try { + + fileService.createFileFromText(shareName, folderPath, fileName, fileContent, onFileCreated); + + function onFileCreated(err, result, response) { + + if (err) { + + const logText = "[WARN] createTextFile - onFileCreated ' ERROR = " + err.message + " SHARE NAME = " + shareName + " FOLDER PATH = " + folderPath + " FILE NAME = " + fileName; + console.log(logText); + logger.write(logText); + + if (err.message.indexOf("The server is busy") > 0) { + + fileService.createFileFromText(shareName, folderPath, fileName, fileContent, onFileCreatedSecondTry); + + function onFileCreatedSecondTry(err) { + + if (err) { + + const logText = "[ERROR] createTextFile - onFileCreated - onFileCreatedSecondTry : File not created. Giving Up.' ERROR = " + err.message + " SHARE NAME = " + shareName + " FOLDER PATH = " + folderPath + " FILE NAME = " + fileName; + console.log(logText); + logger.write(logText); + + } else { + + const logText = "[INFO] createTextFile - onFileCreated - onFileCreatedSecondTry ' : File succesfully created on second try. SHARE NAME = " + shareName + " FOLDER PATH = " + folderPath + " FILE NAME = " + fileName; + console.log(logText); + logger.write(logText); + + } + } + } + } + + callBackFunction(); + } + + } + catch (err) { + const logText = "[ERROR] 'createTextFile' - ERROR : " + err.message; + logger.write(logText); + } + + } + + function getTextFile(folderPath, fileName, callBackFunction, ignoreNotFound) { + + try { + + fileService.getFileToText(shareName, folderPath, fileName, undefined, onFileReceived); + + function onFileReceived(err, text, response) { + + if (err) { + + if (ignoreNotFound === undefined) { + + const logText = "[ERROR] getTextFile - onFileReceived ' ERROR = " + err.message + " SHARE NAME = " + shareName + " FOLDER PATH = " + folderPath + " FILE NAME = " + fileName; + console.log(logText); + logger.write(logText); + + } + + text = undefined; + + } + + callBackFunction(text); + } + + } + catch (err) { + const logText = "[ERROR] 'getTextFile' - ERROR : " + err.message; + logger.write(logText); + } + + } + + function listFilesAndFolders(folderPath, callBackFunction) { + + try { + + let items = { + files: [], + folders: [] + }; + + /* + * @param { object } [options] The request options. + * @param { int } [options.maxResults] Specifies the maximum number of folders to return per call to Azure ServiceClient. + * This does NOT affect list size returned by this function. (maximum: 5000) + * @param { LocationMode } [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param { int } [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param { int } [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request.The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param { string } [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param { bool } [options.useNagleAlgorithm] Determines whether the Nagle al + */ + + let options = { + maxResults: 500 + }; + + fileService.listFilesAndDirectoriesSegmented(shareName, folderPath, null, options, onFilesAndFoldersReceived); + + + function onFilesAndFoldersReceived(error, result) { + + try { + + if (error) { + + const logText = "[ERROR] 'listFilesAndFolders - onFilesAndFoldersReceived' - ERROR RECEIVED : " + error; + logger.write(logText); + + callBackFunction(items); + + } else { + + items.files.push.apply(items.files, result.entries.files); + items.folders.push.apply(items.folders, result.entries.directories); + + callBackFunction(items); + + } + + } + catch (err) { + const logText = "[ERROR] 'listFilesAndFolders - onFilesAndFoldersReceived' - ERROR : " + err.message; + logger.write(logText); + } + + } + + } + catch (err) { + const logText = "[ERROR] 'listFilesAndFolders' - ERROR : " + err.message; + logger.write(logText); + } + } + +}; \ No newline at end of file diff --git a/Azure Web Job Shutdown.js b/Azure Web Job Shutdown.js new file mode 100644 index 000000000..22ed305de --- /dev/null +++ b/Azure Web Job Shutdown.js @@ -0,0 +1,41 @@ + +exports.newShutdownEvent = function newShutdownEvent(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const MODULE_NAME = "Azure Web Job Shutdown"; + + + const DEBUG_MODULE = require('./Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + let shutdownEvent = { + isShuttingDown: isShuttingDown + }; + + return shutdownEvent; + + + function isShuttingDown() { + + let filePath = process.env.WEBJOBS_SHUTDOWN_FILE; + + let fs = require('fs'); + + if (fs.existsSync(filePath)) { + return true; + } + else + { + return false; + } + + } + + + + +} \ No newline at end of file diff --git a/Carol.azure.storage.connstring b/Carol.azure.storage.connstring new file mode 100644 index 000000000..9f6ac1b4c --- /dev/null +++ b/Carol.azure.storage.connstring @@ -0,0 +1,7 @@ +{ +"useDevelopmentStorage": false, +"connectionString": "DefaultEndpointsProtocol=https;AccountName=aadata;AccountKey=YOu76OjlJX9T1QTWbj5cvqyYXTdufW1jISNyrtr8RlUK++kVIdm/TnYuyLJzp8kptAEhbQnN4PP3c6SoPLvR+A==;EndpointSuffix=core.windows.net", +"accountName": "", +"accountKey": "", +"sas": "" +} \ No newline at end of file diff --git a/Charly.azure.storage.connstring b/Charly.azure.storage.connstring new file mode 100644 index 000000000..382fe98bd --- /dev/null +++ b/Charly.azure.storage.connstring @@ -0,0 +1,7 @@ +{ +"useDevelopmentStorage": false, +"connectionString": "DefaultEndpointsProtocol=https;AccountName=aacharly;AccountKey=pqBgOyo3bRWeBYHBB4MsSogPJ2tBIuPdLWeok+VCr2T7NkipAz+i003J9OqjJC4ylNKg22PM7MuhUiYFaYrzpw==;EndpointSuffix=core.windows.net", +"accountName": "", +"accountKey": "", +"sas": "" +} \ No newline at end of file diff --git a/Debug Log.js b/Debug Log.js new file mode 100644 index 000000000..fc543e5d7 --- /dev/null +++ b/Debug Log.js @@ -0,0 +1,144 @@ + + + +exports.newDebugLog = function newDebugLog() { + + + const MODULE_NAME = "Debug Log"; + const fileSystem = require('fs'); + + const currentDate = new Date(); + const dateString = currentDate.getUTCFullYear() + '-' + pad(currentDate.getUTCMonth() + 1, 2) + '-' + pad(currentDate.getUTCDate(), 2) + '-' + pad(currentDate.getUTCHours(), 2) + '-' + pad(currentDate.getUTCMinutes(), 2); + const randomId = parseInt(Math.random() * 1000000); + + let fileNumber = 1; + let messageId = 0; + let firstCall = true; + let folderPath; + + debugLog = { + bot: undefined, + fileName: undefined, + write: write + }; + + + + return debugLog; + + + function createFolders() { + + try { + + folderPath = debugLog.bot.devTeam; + + createFolderSync(folderPath); + + folderPath = debugLog.bot.devTeam + "/" + debugLog.bot.type; + + createFolderSync(folderPath); + + folderPath = debugLog.bot.devTeam + "/" + debugLog.bot.type + "/" + debugLog.bot.name; + + createFolderSync(folderPath); + + folderPath = debugLog.bot.devTeam + "/" + debugLog.bot.type + "/" + debugLog.bot.name + "/" + debugLog.bot.version; + + createFolderSync(folderPath); + + folderPath = debugLog.bot.devTeam + "/" + debugLog.bot.type + "/" + debugLog.bot.name + "/" + debugLog.bot.version + "/" + debugLog.bot.process; + + createFolderSync(folderPath); + + firstCall = false; + + } + catch (err) { + console.log("Error trying to create the folders needed. Error: " + err); + } + + + } + + + function write(Message) { + + if (firstCall === true) { + + createFolders(); + + } + + let filePath = getCurrentLogFile(folderPath + "/" + dateString + "---" + randomId + "---", this.fileName); + + let newDate = new Date(); + newDate = newDate.toISOString(); + + messageId++; + + try { + + fileSystem.appendFileSync(filePath, '\r\n' + newDate + " " + messageId + " " + Message); + + } + catch (err) { + console.log("Error trying to log info into a file. File: " + filePath + " Error:" + err); + } + } + + + function createFolderSync(name) { + try { + fileSystem.mkdirSync( '../logs/' + name) + } catch (err) { + if (err.code !== 'EEXIST') throw err + } + } + + function getCurrentLogFile(relativePath, fileName) { + + let filePath; + let stats; + let i; + + try { + for (i = 1; i < 1000000; i++) { + + filePath = '../logs/' + relativePath + i + "." + fileName + '.log'; + stats = fileSystem.statSync(filePath); + } + } + catch (err) { + + if (i > 1) { + + filePath = '../logs/' + relativePath + (i - 1) + "." + fileName + '.log'; + + stats = fileSystem.statSync(filePath); + const fileSizeInBytes = stats.size; + + if (fileSizeInBytes > 10240000) { + + filePath = '../logs/' + relativePath + i + "." + fileName + '.log'; + } + + return filePath; + + } else { + + return filePath; + + } + + } + + } + + function pad(str, max) { + str = str.toString(); + return str.length < max ? pad("0" + str, max) : str; + } + +}; + diff --git a/Markets.js b/Markets.js new file mode 100644 index 000000000..54ba5512d --- /dev/null +++ b/Markets.js @@ -0,0 +1,252 @@ +/* This business logic module is responsible for Markets and Assets. */ + + +exports.newMarkets = function newMarkets(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const MODULE_NAME = "Markets"; + + const FOLDER_PATHS = 'data'; + const MARKETS_FOLDER_NAME = "other-files"; + + const DEBUG_MODULE = require('./Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + const EXCHANGE_ID = 1; + const fileName = "Markets_" + EXCHANGE_ID + ".json"; + + const DATA_OWNER_BOT_NAME = "Carol" + + const markets = { + DISABLED: 0, + ENABLED: 1, + getMarketsByExchange: getMarketsByExchange, + getExistingOrNewMarketId: getExistingOrNewMarketId, + createNewAsset: createNewAsset, + createNewMarket: createNewMarket, + disableMarket: disableMarket, + initialize: initialize + }; + + //const dataLayer = DATA_LAYER_MODULE.newDataLayer(); + + let marketsArray; + + const AZURE_FILE_STORAGE = require('./Azure File Storage'); + let azureFileStorage = AZURE_FILE_STORAGE.newAzureFileStorage(bot); + + return markets; + + + function initialize(callBackFunction) { + + azureFileStorage.initialize(DATA_OWNER_BOT_NAME); + + try { + + azureFileStorage.getTextFile(MARKETS_FOLDER_NAME, fileName, onFileRead); + + function onFileRead(text) { + + try { + + var fileString = text; + let cleanString = fileString; + + /* Dont know why but sometimes files comes with a first characater that is not supposed to be there and you can not see it at the file opened with notepad */ + + if (fileString[0] !== "[") { + + cleanString = ''; + + for (let i = 1; i < fileString.length; i++) { + cleanString = cleanString + fileString[i]; + } + } + + marketsArray = JSON.parse(cleanString); + callBackFunction(); + + } + catch (err) { + const logText = "[ERROR] initialize - onFileRead ' ERROR : " + err.message + " File: " + fileName; + console.log(logText); + logger.write(logText); + } + + } + } + catch (err) { + const logText = "[ERROR] initialize - ' ERROR : " + err.message + " File Not Found: " + fileName; + console.log(logText); + logger.write(logText); + } + + + } + + + + function getMarketsByExchange(exchangeId, callBackFunction) { + + try { + + // TODO: Currently the exchange Id is ignored as the class is still working with only one exchange. We must fix this. + + callBackFunction(JSON.stringify(marketsArray)); + + + } catch (err) { + + const logText = "[ERROR] getMarketsByExchange - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + + } + + + function getExistingOrNewMarketId(marketName, market, exchangeId, callBackFunction) { + + // TODO: At this function is missing the following: If a market does not exists, it must be greated, and Id generated and returned. We automatically discover new markets when this function is called with a market that didn-t previuously existed. + + try { + + for (let i = 0; i < marketsArray.length; i++) { + + if (marketsArray[i][1] + "_" + marketsArray[i][2] === marketName) { + + callBackFunction(marketName, market, marketsArray[i][0]); + return; + + } + } + + + } catch (err) { + + const logText = "[ERROR] getExistingOrNewMarketId - ' ERROR : " + err.message + " marketId = " + marketId + " idAssetA = " + idAssetA + " idAssetB = " + idAssetB; + console.log(logText); + logger.write(logText); + + } + + } + + + function createNewAsset(assetCode, callBackFunction) { + + // TODO: Upgrade this function in order to update the file containing all assets, not the database that will be deprecated. + + try { + + dataLayer.newAsset(assetCode, onIdReady); + + function onIdReady(resultSet) { + + try { + + callBackFunction(resultSet); + resultSet = []; + + } catch (err) { + + const logText = "[ERROR] createNewAsset - onIdReady ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + + } catch (err) { + + const logText = "[ERROR] createNewAsset - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + + } + + + + function createNewMarket(exchangeId, idAssetA, idAssetB, callBackFunction) { + + // TODO: Upgrade this function in order to update the file containing all markets, not the database that will be deprecated. + + try { + + dataLayer.newMarket(exchangeId, idAssetA, idAssetB, onIdReady); + + function onIdReady(resultSet) { + + try { + + callBackFunction(resultSet); + + } catch (err) { + + const logText = "[ERROR] createNewMarket - onIdReady ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + } + } + + } catch (err) { + + const logText = "[ERROR] createNewMarket - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + } + } + + + function disableMarket(exchangeId, marketId, callBackFunction) { + + // This function puts the requested market in a DISABLED status. + + // TODO: Currently the exchangeId is ignored. + + try { + + for (let i = 0; i < marketsArray.length; i++) { + + if (marketsArray[i][0] === marketId) { + + marketsArray[i][3] = markets.DISABLED; + break; + + } + + } + + azureFileStorage.createTextFile(MARKETS_FOLDER_NAME, fileName, JSON.stringify(marketsArray), onFileReplaced); + + function onFileReplaced() { + + try { + + callBackFunction(); + + } catch (err) { + + const logText = "[ERROR] disableMarket - onFileReplaced ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + } + } + + } catch (err) { + + const logText = "[ERROR] disableMarket - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + } + } + +}; \ No newline at end of file diff --git a/Poloniex API Client.js b/Poloniex API Client.js new file mode 100644 index 000000000..d7e74a657 --- /dev/null +++ b/Poloniex API Client.js @@ -0,0 +1,406 @@ +module.exports = (function () { + 'use strict'; + + // Module dependencies + var crypto = require('crypto'), + request = require('request'), + nonce = require('nonce')(); + + // Constants + var version = '0.0.8', + PUBLIC_API_URL = 'https://poloniex.com/public', + PRIVATE_API_URL = 'https://poloniex.com/tradingApi', + USER_AGENT = 'poloniex.js ' + version; + //USER_AGENT = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0' + + // Helper methods + function joinCurrencies(currencyA, currencyB) { + // If only one arg, then return the first + if (typeof currencyB !== 'string') { + return currencyA; + } + + return currencyA + '_' + currencyB; + } + + // Constructor + function Poloniex(key, secret) { + // Generate headers signed by this user's key and secret. + // The secret is encapsulated and never exposed + this._getPrivateHeaders = function (parameters) { + var paramString, signature; + + if (!key || !secret) { + throw 'Poloniex: Error. API key and secret required'; + } + + // Convert to `arg1=foo&arg2=bar` + paramString = Object.keys(parameters).map(function (param) { + return encodeURIComponent(param) + '=' + encodeURIComponent(parameters[param]); + }).join('&'); + + signature = crypto.createHmac('sha512', secret).update(paramString).digest('hex'); + + return { + Key: key, + Sign: signature + }; + }; + } + + // Currently, this fails with `Error: CERT_UNTRUSTED` + // Poloniex.STRICT_SSL can be set to `false` to avoid this. Use with caution. + // Will be removed in future, once this is resolved. + Poloniex.STRICT_SSL = true; + + // Customisable user agent string + Poloniex.USER_AGENT = USER_AGENT; + + // Prototype + Poloniex.prototype = { + constructor: Poloniex, + + // Make an API request + _request: function (options, callback) { + if (!('headers' in options)) { + options.headers = {}; + } + + options.json = true; + options.headers['User-Agent'] = Poloniex.USER_AGENT; + options.strictSSL = Poloniex.STRICT_SSL; + + request(options, function (err, response, body) { + // Empty response + if (!err && (typeof body === 'undefined' || body === null)) { + err = 'Empty response'; + } + + callback(err, body); + }); + + return this; + }, + + // Make a public API request + _public: function (command, parameters, callback) { + var options; + + if (typeof parameters === 'function') { + callback = parameters; + parameters = {}; + } + + parameters || (parameters = {}); + parameters.command = command; + options = { + method: 'GET', + url: PUBLIC_API_URL, + qs: parameters + }; + + options.qs.command = command; + return this._request(options, callback); + }, + + // Make a private API request + _private: function (command, parameters, callback) { + var options; + + if (typeof parameters === 'function') { + callback = parameters; + parameters = {}; + } + + parameters || (parameters = {}); + parameters.command = command; + parameters.nonce = nonce(); + + options = { + method: 'POST', + url: PRIVATE_API_URL, + form: parameters, + headers: this._getPrivateHeaders(parameters) + }; + + return this._request(options, callback); + }, + + ///// + // PUBLIC METHODS + + returnTicker: function (callback) { + return this._public('returnTicker', callback); + }, + + return24hVolume: function (callback) { + return this._public('return24hVolume', callback); + }, + + returnOrderBook: function (currencyA, currencyB, depth, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + depth: depth + }; + + return this._public('returnOrderBook', parameters, callback); + }, + + returnOrderBooks: function (depth, callback) { + var parameters = { + currencyPair: 'all', + depth: depth + }; + + return this._public('returnOrderBook', parameters, callback); + }, + + returnPublicTradeHistory: function (currencyA, currencyB, start, end, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + start: start, + end: end + }; + + return this._public('returnTradeHistory', parameters, callback); + }, + + returnChartData: function (currencyA, currencyB, period, start, end, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + period: period, + start: start, + end: end + }; + + return this._public('returnChartData', parameters, callback); + }, + + returnCurrencies: function (callback) { + return this._public('returnCurrencies', callback); + }, + + returnLoanOrders: function (currency, callback) { + return this._public('returnLoanOrders', { currency: currency }, callback); + }, + + ///// + // PRIVATE METHODS + + returnBalances: function (callback) { + return this._private('returnBalances', {}, callback); + }, + + returnCompleteBalances: function (callback) { + return this._private('returnCompleteBalances', {}, callback); + }, + + returnDepositAddresses: function (callback) { + return this._private('returnDepositAddresses', {}, callback); + }, + + generateNewAddress: function (currency, callback) { + return this._private('returnDepositsWithdrawals', { currency: currency }, callback); + }, + + returnDepositsWithdrawals: function (start, end, callback) { + return this._private('returnDepositsWithdrawals', { start: start, end: end }, callback); + }, + + returnOpenOrders: function (currencyA, currencyB, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB) + }; + + return this._private('returnOpenOrders', parameters, callback); + }, + + returnTradeHistory: function (currencyA, currencyB, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB) + }; + + return this._private('returnTradeHistory', parameters, callback); + }, + + returnOrderTrades: function (orderNumber, callback) { + var parameters = { + orderNumber: orderNumber + }; + + return this._private('returnOrderTrades', parameters, callback); + }, + + buy: function (currencyA, currencyB, rate, amount, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + rate: rate, + amount: amount + }; + + return this._private('buy', parameters, callback); + }, + + sell: function (currencyA, currencyB, rate, amount, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + rate: rate, + amount: amount + }; + + return this._private('sell', parameters, callback); + }, + + cancelOrder: function (currencyA, currencyB, orderNumber, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + orderNumber: orderNumber + }; + + return this._private('cancelOrder', parameters, callback); + }, + + moveOrder: function (orderNumber, rate, amount, callback) { + var parameters = { + orderNumber: orderNumber, + rate: rate, + amount: amount ? amount : null + }; + + return this._private('moveOrder', parameters, callback); + }, + + withdraw: function (currency, amount, address, callback) { + var parameters = { + currency: currency, + amount: amount, + address: address + }; + + return this._private('withdraw', parameters, callback); + }, + + returnFeeInfo: function (callback) { + return this._private('returnFeeInfo', {}, callback); + }, + + returnAvailableAccountBalances: function (account, callback) { + var options = {}; + if (account) { + options.account = account; + } + return this._private('returnAvailableAccountBalances', options, callback); + }, + + returnTradableBalances: function (callback) { + return this._private('returnTradableBalances', {}, callback); + }, + + transferBalance: function (currency, amount, fromAccount, toAccount, callback) { + var parameters = { + currency: currency, + amount: amount, + fromAccount: fromAccount, + toAccount: toAccount + }; + + return this._private('transferBalance', parameters, callback); + }, + + returnMarginAccountSummary: function (callback) { + return this._private('returnMarginAccountSummary', {}, callback); + }, + + marginBuy: function (currencyA, currencyB, rate, amount, lendingRate, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + rate: rate, + amount: amount, + lendingRate: lendingRate ? lendingRate : null + }; + + return this._private('marginBuy', parameters, callback); + }, + + marginSell: function (currencyA, currencyB, rate, amount, lendingRate, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB), + rate: rate, + amount: amount, + lendingRate: lendingRate ? lendingRate : null + }; + + return this._private('marginSell', parameters, callback); + }, + + getMarginPosition: function (currencyA, currencyB, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB) + }; + + return this._private('getMarginPosition', parameters, callback); + }, + + closeMarginPosition: function (currencyA, currencyB, callback) { + var parameters = { + currencyPair: joinCurrencies(currencyA, currencyB) + }; + + return this._private('closeMarginPosition', parameters, callback); + }, + + createLoanOffer: function (currency, amount, duration, autoRenew, lendingRate, callback) { + var parameters = { + currency: currency, + amount: amount, + duration: duration, + autoRenew: autoRenew, + lendingRate: lendingRate + }; + + return this._private('createLoanOffer', parameters, callback); + }, + + cancelLoanOffer: function (orderNumber, callback) { + var parameters = { + orderNumber: orderNumber + }; + + return this._private('cancelLoanOffer', parameters, callback); + }, + + returnOpenLoanOffers: function (callback) { + return this._private('returnOpenLoanOffers', {}, callback); + }, + + returnActiveLoans: function (callback) { + return this._private('returnActiveLoans', {}, callback); + }, + + returnLendingHistory: function (start, end, limit, callback) { + var parameters = { + start: start, + end: end, + limit: limit + }; + + return this._private('returnLendingHistory', parameters, callback); + }, + + toggleAutoRenew: function (orderNumber, callback) { + return this._private('toggleAutoRenew', { orderNumber: orderNumber }, callback); + } + + }; + + // Backwards Compatibility + Poloniex.prototype.getTicker = Poloniex.prototype.returnTicker; + Poloniex.prototype.get24hVolume = Poloniex.prototype.return24hVolume; + Poloniex.prototype.getOrderBook = Poloniex.prototype.returnOrderBook; + Poloniex.prototype.getTradeHistory = Poloniex.prototype.returnChartData; + Poloniex.prototype.myBalances = Poloniex.prototype.returnBalances; + Poloniex.prototype.myOpenOrders = Poloniex.prototype.returnOpenOrders; + Poloniex.prototype.myTradeHistory = Poloniex.prototype.returnTradeHistory; + + return Poloniex; +})(); \ No newline at end of file diff --git a/Poloniex-Historic-Trades/Interval.js b/Poloniex-Historic-Trades/Interval.js new file mode 100644 index 000000000..f3b236951 --- /dev/null +++ b/Poloniex-Historic-Trades/Interval.js @@ -0,0 +1,1116 @@ +exports.newInterval = function newInterval(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + const GMT_SECONDS = ':00.000 GMT+0000'; + const GMT_MILI_SECONDS = '.000 GMT+0000'; + + const MODULE_NAME = "Interval"; + const LOG_INFO = true; + + const EXCHANGE_NAME = "Poloniex"; + const EXCHANGE_ID = 1; + + const TRADES_FOLDER_NAME = "Trades"; + + const GO_RANDOM = false; + const FORCE_MARKET = 2; // This allows to debug the execution of an specific market. Not intended for production. + + const MARKETS_MODULE = require(ROOT_DIR + 'Markets'); + + const POLONIEX_CLIENT_MODULE = require(ROOT_DIR + 'Poloniex API Client'); + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + interval = { + initialize: initialize, + start: start + }; + + let markets; + + const AZURE_FILE_STORAGE = require(ROOT_DIR + 'Azure File Storage'); + let azureFileStorage = AZURE_FILE_STORAGE.newAzureFileStorage(bot); + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + let utilities = UTILITIES.newUtilities(bot); + + let year; + let month; + + return interval; + + function initialize(yearAssigend, monthAssigned, callBackFunction) { + + try { + + year = yearAssigend; + month = monthAssigned; + + month = utilities.pad(month, 2); // Adding a left zero when needed. + + logger.fileName = MODULE_NAME + "-" + year + "-" + month; + + const logText = "[INFO] initialize - Entering function 'initialize' " + " @ " + year + "-" + month; + console.log(logText); + logger.write(logText); + + azureFileStorage.initialize(); + + markets = MARKETS_MODULE.newMarkets(bot); + markets.initialize(callBackFunction); + + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + +/* + +This process is going to do the following: + +It will look for the oldest file for each market and it will request to the exchange the max amount of transactions from that moment, backwards. +Then it will iterate through those transactions to create the files for each minute with the trades it got from the exchange. Finally when it reaches the +begining of the history of the market, it will move to the next market and repead the process. + +This process complements the Live Trades process and write historical trades files exactly in the same format. + +*/ + + function start(callBackFunction) { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'start', with year = " + year + " and month = " + month); + } + + let processDate = new Date(year + "-" + month + "-1 00:00:00.000 GMT+0000"); + + processDate.setUTCMonth(processDate.getUTCMonth() + 1); // First we go 1 month into the future. + processDate.setUTCSeconds(processDate.getUTCSeconds() - 30); // Then we go back 30 seconds, or to the last minute of the original month. + + let thisDatetime = new Date(); + + if ((year === thisDatetime.getUTCFullYear() && month > thisDatetime.getUTCMonth() + 1) || year > thisDatetime.getUTCFullYear()) { + + logger.write("[INFO] We are too far in the future. Interval will not execute. Sorry."); + return; + + } + + let moreIntervalCallsNeeded = false; // Here we control if some processing has been done. If none, that means that it is not necesary to call this Interval again. + + let currentDate; // This will hold the current datetime of each execution. + let cursorDatetime; // This holds the datetime we are using to request records from, backwards. + + let marketQueue; // This is the queue of all markets to be procesesd at each interval. + let market = { // This is the current market being processed after removing it from the queue. + id: 0, + assetA: "", + assetB: "" + }; + + let dateForPath; + + let filePath; + + let exchangeCallTime; + + const FIRST_RECORD_ID = 100; // This should be around 100. + + marketsLoop(); + + /* + + At every run, the process needs to loop through all the markets at this exchange. + The problem is that we can not fire all the requests at once to the exchange or we would get banned. + For that reason we create a queue with the markets to process and we do one at the time. + The following functions marketsLoop(), openMarket(), closeMarket() and closeAndOpenMarket() controls the serialization of this processing. + + */ + + function marketsLoop() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'marketsLoop'"); + } + + currentDate = new Date(); + markets.getMarketsByExchange(EXCHANGE_ID, onMarketsReady); + + function onMarketsReady(marketsArray) { + + marketQueue = JSON.parse(marketsArray); + + openMarket(); // First execution and entering into the real loop. + + } + } + catch (err) { + const logText = "[ERROR] 'marketsLoop' - ERROR : " + err.message; + logger.write(logText); + } + } + + function openMarket() { + + // To open a Market means picking a new market from the queue. + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'openMarket'"); + } + + + if (marketQueue.length === 0) { + + if (LOG_INFO === true) { + logger.write("[INFO] 'openMarket' - marketQueue.length === 0"); + } + + const logText = "[WARN] We processed all the markets."; + logger.write(logText); + + callBackFunction(moreIntervalCallsNeeded); + + return; + } + + + if (GO_RANDOM === true) { + const index = parseInt(Math.random() * (marketQueue.length - 1)); + + market.id = marketQueue[index][0]; + market.assetA = marketQueue[index][1]; + market.assetB = marketQueue[index][2]; + market.status = marketQueue[index][3]; + + marketQueue.splice(index, 1); + } else { + let marketRecord = marketQueue.shift(); + + market.id = marketRecord[0]; + market.assetA = marketRecord[1]; + market.assetB = marketRecord[2]; + market.status = marketRecord[3]; + + if (FORCE_MARKET > 0) { + if (FORCE_MARKET !== market.id) { + closeAndOpenMarket(); + return; + } + } + } + + if (LOG_INFO === true) { + logger.write("[INFO] 'openMarket' - marketQueue.length = " + marketQueue.length); + logger.write("[INFO] 'openMarket' - market sucessfully opened : " + market.assetA + "_" + market.assetB); + } + + if (market.status === markets.ENABLED) { + + getMarketStatusReport(); + + } else { + + logger.write("[INFO] 'openMarket' - market " + market.assetA + "_" + market.assetB + " skipped because its status is not valid. Status = " + market.status); + closeAndOpenMarket(); + return; + + } + + + } + catch (err) { + const logText = "[ERROR] 'openMarket' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function closeMarket() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'closeMarket'"); + } + + } + + function closeAndOpenMarket() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'closeAndOpenMarket'"); + } + + openMarket(); + + } + + + /* + + The following code executes for each market, getting the trades from the exchange and saving them in files at the cloud storage. + + */ + + + function getMarketStatusReport() { + + /* + + The market status report is independent from the year and month this current interval is working on. We will read the report to + check if the whole market is already completed. If it is, there is no need to do anything else. + + */ + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'getMarketStatusReport'"); + } + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + if (text === undefined) { + + getMonthStatusReport(); + + } else { + + let statusReport = JSON.parse(text); + + if (statusReport.completeHistory === true) { + + const logText = "[INFO] 'getMarketStatusReport' - Market " + market.assetA + '_' + market.assetB + " is already complete. Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } else { + + getMonthStatusReport(); + + } + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'getMarketStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + + function getMonthStatusReport() { + + /* + + In order to know where to start the process (which datetime) we need to read the StatusReport of the process. This file will tell + us where we left after the last execution or if the process has finished for this market. + + */ + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'getMarketStatusReport'"); + } + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process + "/" + year + "/" + month; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + if (text === undefined) { + + if (processDate.valueOf() > thisDatetime.valueOf()) { + + currentDate = thisDatetime; + getTheTrades(); + + } else { + + currentDate = processDate; + getTheTrades(); + + } + + } else { + + let statusReport = JSON.parse(text); + + if (statusReport.completeHistory === true) { + + const logText = "[INFO] 'getMonthStatusReport' - Market " + market.assetA + '_' + market.assetB + " is already complete. Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } else { + + /* We get from the file the datetime of the last file created. */ + + currentDate = new Date(statusReport.lastFile.year + "-" + statusReport.lastFile.month + "-" + statusReport.lastFile.days + " " + statusReport.lastFile.hours + ":" + statusReport.lastFile.minutes + GMT_SECONDS); + + getTheTrades(); + + } + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'getMonthStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function getTheTrades() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'getTheTrades'"); + } + + const firstTradeDate = parseInt(currentDate.valueOf() / 1000); + + const firstMomentOfMonth = new Date(year + "-" + month + "-1 00:00:00.000 GMT+0000"); + + /* We request to the Exchange API some more records than needed, anyway we will discard records out of the range we need. To do this we substract some seconds and add some + seconds to the already calculated UNIX timestamps. */ + + let startTime = parseInt(firstMomentOfMonth.valueOf() / 1000) - 5; + let endTime = firstTradeDate + 60; + + if (endTime - startTime > 60 * 60 * 24 * 30) { + + /* + + We can not ask this exchange for more than 30 days in a single request. So we substract in this case a few days so as not + to violate this policy on 31 days months. + + */ + + startTime = startTime + 60 * 60 * 25 * 7; // we add one week to be confortable. + + } + + exchangeCallTime = new Date(); + + let poloniexApiClient = new POLONIEX_CLIENT_MODULE(); + + poloniexApiClient.returnPublicTradeHistory(market.assetA, market.assetB, startTime, endTime, onExchangeCallReturned); + + } + catch (err) { + const logText = "[ERROR] 'getTheTrades' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function onExchangeCallReturned(err, tradesRequested) { + + try { + + if (LOG_INFO === true) { + + let exchangeResponseTime = new Date(); + let timeDifference = (exchangeResponseTime.valueOf() - exchangeCallTime.valueOf()) / 1000; + logger.write("[INFO] Entering function 'onExchangeCallReturned' - Call time recorded = " + timeDifference + " seconds."); + } + + if (err || tradesRequested.error !== undefined) { + try { + + if (err.message.indexOf("ETIMEDOUT") > 0) { + + const logText = "[WARN] onExchangeCallReturned - Timeout reached while trying to access the Exchange API. Trying again. : ERROR = " + err.message; + logger.write(logText); + + /* We try to reconnect to the exchange and fetch the data again. */ + + getTheTrades(); + return; + + } else { + + if (err.message.indexOf("ECONNRESET") > 0) { + + const logText = "[WARN] onExchangeCallReturned - The exchange reseted the connection. Trying again. : ERROR = " + err.message; + logger.write(logText); + + /* We try to reconnect to the exchange and fetch the data again. */ + + getTheTrades(); + return; + + } else { + + + const logText = "[ERROR] onExchangeCallReturned - Unexpected error trying to contact the Exchange. Giving up. : ERROR = " + err.message; + logger.write(logText); + closeMarket(); + return; + } + } + + } catch (err) { + const logText = "[ERROR] onExchangeCallReturned : ERROR : tradesRequested.error = " + tradesRequested.error; + logger.write(logText); + + if (tradesRequested.error === "Invalid currency pair.") { + + markets.disableMarket(EXCHANGE_ID, market.id, onMarketDeactivated); + + function onMarketDeactivated() { + + logger.write("[INFO] Market " + market.assetA + "_" + market.assetB + " deactivated. Id = " + market.id); + + closeAndOpenMarket(); + return; + + } + + } + + closeMarket(); + return; + } + + closeMarket(); + return; + + } else { + + if (tradesRequested.length === 0) { + + const logText = "[WARN] 'onExchangeCallReturned' - The exchange didn't return any records. We assume this means the date requested is before the begining of this market. "; + logger.write(logText); + closeAndOpenMarket(); + + } else { + + tradesReadyToBeSaved(tradesRequested); + + } + } + } + catch (err) { + const logText = "[ERROR] 'onExchangeCallReturned' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + function tradesReadyToBeSaved(tradesRequested) { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'tradesReadyToBeSaved'"); + } + + moreIntervalCallsNeeded = true; // If we are requesting trades from the exchange, that means that something is being done. + + let filesWrittenCounter = 0; // We count each file written to the cloud so when we reach some number we partially update the status report + let fileRecordCounter = 0; + + let needSeparator; + let separator; + + let lastProcessMinute; // Stores the previous record minute during each iteration + let filesToSave = []; // Array where we will store all the content to be written to files + + needSeparator = false; + + let fileContent = ""; + + let beginingOfMarket = false; // This flag is turned on when we detect the conditions that makes us assume we are at the begining of the hitory of the market. + + let currentProcessMinute = Math.trunc(currentDate.valueOf() / 1000 / 60); + let firstProcessMinute = currentProcessMinute; + + /* We will iterate through all the records received from the exchange. We know Poloniex sends the older records first, so this is going to be going back in time as we advance. */ + + for (let i = 0; i < tradesRequested.length; i++) { + + let record = tradesRequested[i]; + + const trade = { + tradeIdAtExchange: record.tradeID, + marketIdAtExchange: record.globalTradeID, + type: record.type, + rate: record.rate, + amountA: record.total, + amountB: record.amount, + datetime: new Date(record.date + GMT_MILI_SECONDS) + }; + + trade.seconds = trade.datetime.getUTCSeconds(); + + if (trade.tradeIdAtExchange < FIRST_RECORD_ID) { // Experience has shown us that the first trade records of any market are out of range, because they are teststing the market with any value. So no worries if they are not recorded in our history. + + beginingOfMarket = true; + + } + + let currentRecordMinute = Math.trunc(trade.datetime.valueOf() / 1000 / 60); // This are the number of minutes since the begining of time of this trade. + + if (currentRecordMinute > currentProcessMinute) { + + /* We discard this trade, since it happened after the minute we want to record in the current file. */ + + continue; + } + + if (currentRecordMinute < currentProcessMinute) { + + /* + + The information is older that the current time. + We must store the current info and reset the pointer to the current time to match the one on the information currently being processd. + We know this can lead to a 'hole' or some empty files being skipped, but we solve that problem with the next loop. + + */ + + let blackMinutes = currentProcessMinute - currentRecordMinute; + + for (let j = 1; j <= blackMinutes; j++) { + + storeFileContent(); + currentProcessMinute--; + + } + } + + if (currentRecordMinute === currentProcessMinute) { + + if (needSeparator === false) { + + needSeparator = true; + separator = ''; + + } else { + separator = ','; + } + + fileContent = '[' + trade.tradeIdAtExchange + ',"' + trade.type + '",' + trade.rate + ',' + trade.amountA + ',' + trade.amountB + ',' + trade.seconds + ']' + separator + fileContent; + + fileRecordCounter++; + + } + + } + + if (fileContent !== "") { + + /* + + Normally, we would not save the content of the last file, since it usually contains some of the records of that minute. + There are a few exceptions: + + If it is the last file of the month (the one at the very begining of the month) we must save it. + + */ + + let date = new Date(currentProcessMinute * 60 * 1000); + + if ((date.getUTCFullYear() === year) && + (date.getUTCMonth() + 1 === parseInt(month)) && // remember we added left zeros to look cool. + (date.getUTCDate() === 1) && + (date.getUTCHours() === 0) && + (date.getUTCMinutes() === 0)) { + + storeFileContent(); + + } else { + + /* + + The second exception happens when we approach the begining of the month. + In markets with few volume, there might be a lot of minutes or even hours, close to the begining of the month with no records. Naturally the process + would stop with the last record received from the exchange. So we must fix that an to do it, we check if we processed only one minute, + in that case, we interpret that all the minutes below until the begining of the month, are with empty records. If this condition is not met, then we must + ignore the records as they might be some missing for the current minute. + + */ + + if (firstProcessMinute - currentProcessMinute === 1) { + + /* We will artificially generate all the minutes upto the begining of the month. The first will contain some records, all the rest will be empty. */ + + const firstMomentOfMonth = new Date(year + "-" + month + "-1 00:00:00.000 GMT+0000"); + + let firstMinute = Math.trunc(firstMomentOfMonth.valueOf() / 1000 / 60); // This are the number of minutes since the begining of time to the begining of the month. + + let blackMinutes = currentProcessMinute - firstMinute + 1; + + for (let j = 1; j <= blackMinutes; j++) { + + storeFileContent(); + currentProcessMinute--; + + } + + } else { + + /* We dont store the last processed file since it might be incomplete. */ + + } + } + } + + function storeFileContent() { + + fileContent = '[' + fileContent + ']'; + + let fileRecord = { + datetime: currentProcessMinute, + content: fileContent, + records: fileRecordCounter + }; + + filesToSave.push(fileRecord); + + fileRecordCounter = 0; + needSeparator = false; + fileContent = ""; + } + + /* + + Now it is time to process all the information we stored at filesToSave. + + */ + + if (LOG_INFO === true) { + logger.write("[INFO] About to save " + (filesToSave.length + 1) + " files. "); + } + + let i = 0; + let date; + + nextRecord(); + + function nextRecord() { + + let fileName = '' + market.assetA + '_' + market.assetB + '.json'; + + date = new Date(filesToSave[i].datetime * 60 * 1000); + fileRecordCounter = filesToSave[i].records; + fileContent = filesToSave[i].content; + + dateForPath = date.getUTCFullYear() + '/' + utilities.pad(date.getUTCMonth() + 1, 2) + '/' + utilities.pad(date.getUTCDate(), 2) + '/' + utilities.pad(date.getUTCHours(), 2) + '/' + utilities.pad(date.getUTCMinutes(), 2); + + filePath = EXCHANGE_NAME + "/Output/" + TRADES_FOLDER_NAME + '/' + dateForPath; + + utilities.createFolderIfNeeded(filePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + azureFileStorage.createTextFile(filePath, fileName, fileContent + '\n', onFileCreated); + + function onFileCreated() { + + let paddedCounter = utilities.pad(fileRecordCounter, 4); + let paddedFile = utilities.pad(i + 1, 5); + + const logText = "[WARN] Finished with File # " + paddedFile + " @ " + market.assetA + "_" + market.assetB + ", " + paddedCounter + " records inserted into " + filePath + "/" + fileName + ""; + console.log(logText); + logger.write(logText); + + controlLoop(); + } + } + } + + + function controlLoop() { + + i++; + + if (i < filesToSave.length) { + + filesWrittenCounter++; + + if (filesWrittenCounter === 30) { // Every now and then we write a Status Report so that if the process is terminated, it can resume later from there. + + writeStatusReport(date, false, false, onReportWritten); + + function onReportWritten() { + + filesWrittenCounter = 0; + nextRecord(); + + } + + } else { + + nextRecord(); + + } + + } else { + + if (LOG_INFO === true) { + logger.write("[INFO] Leaving function 'tradesReadyToBeSaved'"); + } + + let monthCompleteHistory = false; + + if ((date.getUTCFullYear() === year) && + (date.getUTCMonth() + 1 === parseInt(month)) && // remember we added left zeros to look cool. + (date.getUTCDate() === 1) && + (date.getUTCHours() === 0) && + (date.getUTCMinutes() === 0)) { + + /* + + When we get to the first minute of the month, that menas we completed the whole month and this should later be recorded + at the Status Report. + + */ + + monthCompleteHistory = true; + + } + + if (beginingOfMarket === true) { + + /* + + If we already detected that we completed the whole market (by reaching a very low trade Id) then we can also say that + we completed the current month. + + */ + + monthCompleteHistory = true; + } + + writeStatusReport(date, monthCompleteHistory, beginingOfMarket, onReportWritten); + + function onReportWritten() { + + closeAndOpenMarket(); + + } + + } + } + } + catch (err) { + const logText = "[ERROR] 'tradesReadyToBeSaved' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + + function writeStatusReport(lastFileDate, isMonthComplete, isBeginingOfMarket, callBack) { + + /* + + The report is a file that records important information to be used by a) another instance of the same process, b) another process or by c) another bot. + + The first thing to do is to read the current report file content, if it exists. + + In this particular process, we will record the last file processed. + + */ + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'writeStatusReport'"); + } + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process + "/" + year + "/" + month; + + utilities.createFolderIfNeeded(reportFilePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + let report = { + lastFile: { + year: lastFileDate.getUTCFullYear(), + month: (lastFileDate.getUTCMonth() + 1), + days: lastFileDate.getUTCDate(), + hours: lastFileDate.getUTCHours(), + minutes: lastFileDate.getUTCMinutes() + }, + completeHistory: isMonthComplete + }; + + let fileContent = JSON.stringify(report); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onFileCreated); + + function onFileCreated() { + + if (LOG_INFO === true) { + logger.write("[INFO] 'writeStatusReport' - Content written: " + fileContent); + } + + if (isBeginingOfMarket === true) { + + reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + + utilities.createFolderIfNeeded(reportFilePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + let report = { + lastFile: { + year: lastFileDate.getUTCFullYear(), + month: (lastFileDate.getUTCMonth() + 1), + days: lastFileDate.getUTCDate(), + hours: lastFileDate.getUTCHours(), + minutes: lastFileDate.getUTCMinutes() + }, + completeHistory: false // This will be true only when all months are completed. + }; + + let fileContent = JSON.stringify(report); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onMasterFileCreated); + + function onMasterFileCreated() { + + if (LOG_INFO === true) { + logger.write("[INFO] 'writeStatusReport' - Begining of market reached !!! - Content written: " + fileContent); + } + + verifyMarketComplete(isMonthComplete, callBack); + + } + + } + + } + + else { + + verifyMarketComplete(isMonthComplete, callBack); + + } + + } + } + + + } + catch (err) { + const logText = "[ERROR] 'writeStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + function verifyMarketComplete(isMonthComplete, callBack) { + + if (isMonthComplete === true) { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Month Completed !!! "); + + /* + + To know if the whole market is complete, we need to ready all the status reports, one by one, since the first + month / year to the current month / year. + + To know which is the first month / year we will read the main Status Report. Only if it exists (that is after the first + month of the market reached a very low trade), we will know from it which is the initial month / year. + + Obtaining the current month / year is trivial, since it is current time. We will scan all the files and we need all of + them to report that the month has been completed in order to declare the whole market as completed. + + All of the above is what we call the last step. + + */ + + let initialYear; + let initialMonth; + + let finalYear = (new Date()).getUTCFullYear(); + let finalMonth = (new Date()).getUTCMonth() + 1; + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + /* Lets read the main status report */ + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + if (text === undefined) { + + /* The first month of the market didnt create this file yet. Aborting verification. */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED since the main status report did not exist. "); + + callBack(); + + } else { + + let statusReport = JSON.parse(text); + + initialYear = statusReport.lastFile.year; + initialMonth = statusReport.lastFile.month; + + loopCycle(); + } + + } + + function loopCycle() { + + /* + + Here we read the status report file of each month / year to verify if it is complete or not. + + */ + let paddedInitialMonth = utilities.pad(initialMonth, 2); + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process + "/" + initialYear + "/" + paddedInitialMonth; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onStatusReportFileReceived, true); + + function onStatusReportFileReceived(text) { + + if (text === undefined) { + + /* If any of the files do not exist, it is enough to know the market is not complete. */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " did not exist. "); + + callBack(); + + } else { + + let statusReport = JSON.parse(text); + + if (statusReport.completeHistory === true) { + + loop(); // Lets see the next month. + + } else { + + /* If any of the files says that month is not complete then it is enough to know the market is not complete. */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " did not have a complete history. "); + + callBack(); + + } + } + + } + + } + + function loop() { + + initialMonth++; + + if (initialMonth > 12) { + + initialMonth = 1; + initialYear++; + + } + + if ((initialYear === finalYear && initialMonth > finalMonth) || (initialYear > finalYear)) { + + /* We arrived to the point where we have checked all the status reports of every month and they are all complete. */ + + readAndWriteNewReport(); + + return; + } + + loopCycle(); + + } + + function readAndWriteNewReport() { + + /* We will read the current file to preserve its data, and save it again with market complete = true */ + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + let statusReport = JSON.parse(text); + + statusReport.completeHistory = true; + + let fileContent = JSON.stringify(statusReport); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onMasterFileCreated); + + function onMasterFileCreated() { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification SUCESSFULL . Market Completed !!! - Content written: " + fileContent); + + callBack(); + + } + } + } + + } else { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED: Month is not complete. "); + callBack(); + + } + + } + + + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; diff --git a/Poloniex-Historic-Trades/Poloniex Historic Trades.js b/Poloniex-Historic-Trades/Poloniex Historic Trades.js new file mode 100644 index 000000000..af8431a81 --- /dev/null +++ b/Poloniex-Historic-Trades/Poloniex Historic Trades.js @@ -0,0 +1,169 @@ +exports.newPloniexHistoricTrades = function newPloniexHistoricTrades(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const INTERVAL_LAPSE = 24 * 60 * 60 * 1000; + + const MODULE_NAME = "Poloniex Exchange Historic Trades"; + const LOG_INFO = true; + + const INTERVAL_MODULE = require('./Interval'); + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + const INTERVAL_MAX_LOOPS = -1; // -1 for infinite loop. + + poloniexHistoricTrades = { + initialize: initialize, + start: start + }; + + const SHUTDOWN_EVENT = require(ROOT_DIR + 'Azure Web Job Shutdown'); + let shutdownEvent = SHUTDOWN_EVENT.newShutdownEvent(bot); + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + let utilities = UTILITIES.newUtilities(bot); + + let year; + let month; + + return poloniexHistoricTrades; + + function initialize(yearAssigend, monthAssigned, callBackFunction) { + + try { + + year = yearAssigend; + month = monthAssigned; + + month = utilities.pad(month, 2); // Adding a left zero when needed. + + logger.fileName = MODULE_NAME + "-" + year + "-" + month; + + const logText = "[INFO] initialize - Entering function 'initialize' " + " @ " + year + "-" + month; + console.log(logText); + logger.write(logText); + + callBackFunction(); + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + + + function start() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'start', with year = " + year + " and month = " + month); + } + + let intervalId; + + if (INTERVAL_MAX_LOOPS === 0) { + + intervalId = setInterval(startNewInterval, INTERVAL_LAPSE); + + } + + let intervalLoopCounter = 0; + + startNewInterval(); // First, inmadiate run. + + function startNewInterval() { + + try { + + if (LOG_INFO === true) { + + if (INTERVAL_MAX_LOOPS !== 0) { + + logger.write("[INFO] Entering function 'startNewInterval', next execution inmediately after the current Interval finishes."); + + } else { + + logger.write("[INFO] Entering function 'startNewInterval', next execution in " + INTERVAL_LAPSE / 1000 / 60 + " minutes."); + + } + + } + + + if (shutdownEvent.isShuttingDown() === false) { + + let fileProcessingInterval = INTERVAL_MODULE.newInterval(bot); + + fileProcessingInterval.initialize(year, month, onReadyToStart); + + function onReadyToStart() { + + fileProcessingInterval.start(loopControl); + + } + + } + else { + + clearInterval(intervalId); + + const logText = "[INFO] requestNewData - Terminating Set Interval - About to exit gracefully the process. "; + console.log(logText); + logger.write(logText); + + } + + } + catch (err) { + const logText = "[ERROR] 'startNewInterval' - ERROR : " + err.message; + logger.write(logText); + } + } + + function loopControl(moreIntervalExecutionsNeeded) { + + if (moreIntervalExecutionsNeeded === true) { + + intervalLoopCounter++; + + if (intervalLoopCounter === INTERVAL_MAX_LOOPS) { + + const logText = "[WARN] 'INTERVAL_MAX_LOOPS' reached. Stopping execution. "; + logger.write(logText); + + } else { + + const logText = "[WARN] 'loopControl'. Staring new Interval. "; + logger.write(logText); + + startNewInterval(); // Looped Execution. + + } + + } else { + + logger.write("[WARN] Received the signal from last Interval execution to not call it anymore. Stopping execution. "); + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; + + + diff --git a/Poloniex-Historic-Trades/run.js b/Poloniex-Historic-Trades/run.js new file mode 100644 index 000000000..b04555958 --- /dev/null +++ b/Poloniex-Historic-Trades/run.js @@ -0,0 +1,97 @@ + +let bot = { + name: "Charly", + process: "Historic-Trades", + type: "Connectivity", + version: "1.0.0", + devTeam: "AA Masters" +}; + +const ROOT_DIR = '../'; + +const MODULE_NAME = "run"; + +const START_POLONIEX_HISTORIC_TRADES = true; +const START_POLONIEX_HISTORIC_TRADES_AT_ONE_MONTH = false; + +const POLONIEX_HISTORIC_TRADES_MODULE = require('./Poloniex Historic Trades'); + +const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); +const logger = DEBUG_MODULE.newDebugLog(); +logger.fileName = MODULE_NAME; +logger.bot = bot; + +process.on('uncaughtException', function (err) { + logger.write('uncaughtException - ' + err.message); +}); + + +process.on('unhandledRejection', (reason, p) => { + logger.write("Unhandled Rejection at: Promise " + JSON.stringify(p) + " reason: " + reason); +}); + + +process.on('exit', function (code) { + logger.write('About to exit with code:' + code); +}); + + +try { + if (START_POLONIEX_HISTORIC_TRADES === true) { + + for (let year = 2018; year > 2014; year--) { + + for (let month = 12; month > 0; month--) { + + let timeDelay = Math.random() * 100 * 1000; // We need a delay so as not to get banned from the exchange for requesting to many things at the same time. + + setTimeout(startProcess, timeDelay); + + function startProcess() { + + const newPloniexHistoricTrades = POLONIEX_HISTORIC_TRADES_MODULE.newPloniexHistoricTrades(bot); + + newPloniexHistoricTrades.initialize(year, month, onInitializeReady); + + function onInitializeReady() { + + newPloniexHistoricTrades.start(); + + } + + } + + } + + } + + } + + + if (START_POLONIEX_HISTORIC_TRADES_AT_ONE_MONTH === true) { + + startProcess(); + + function startProcess() { + + const newPloniexHistoricTrades = POLONIEX_HISTORIC_TRADES_MODULE.newPloniexHistoricTrades(bot); + + let month = 12; + let year = 2017; + + newPloniexHistoricTrades.initialize(year, month, onInitializeReady); + + function onInitializeReady() { + + newPloniexHistoricTrades.start(); + + } + } + } + + +} catch (err) { + console.log(err.message); + logger.write(err.message); +} + diff --git a/Poloniex-Hole-Fixing/Interval.js b/Poloniex-Hole-Fixing/Interval.js new file mode 100644 index 000000000..744a74635 --- /dev/null +++ b/Poloniex-Hole-Fixing/Interval.js @@ -0,0 +1,1748 @@ +exports.newInterval = function newInterval(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + const GMT_SECONDS = ':00.000 GMT+0000'; + const GMT_MILI_SECONDS = '.000 GMT+0000'; + + const MODULE_NAME = "Interval"; + const LOG_INFO = true; + + const EXCHANGE_NAME = "Poloniex"; + const EXCHANGE_ID = 1; + + const TRADES_FOLDER_NAME = "Trades"; + + const GO_RANDOM = false; + const FORCE_MARKET = 2; // This allows to debug the execution of an specific market. Not intended for production. + + const MARKETS_MODULE = require(ROOT_DIR + 'Markets'); + + const POLONIEX_CLIENT_MODULE = require(ROOT_DIR + 'Poloniex API Client'); + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + interval = { + initialize: initialize, + start: start + }; + + let markets; + + const AZURE_FILE_STORAGE = require(ROOT_DIR + 'Azure File Storage'); + let azureFileStorage = AZURE_FILE_STORAGE.newAzureFileStorage(bot); + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + let utilities = UTILITIES.newUtilities(bot); + + let year; + let month; + + return interval; + + function initialize(yearAssigend, monthAssigned, callBackFunction) { + + try { + + year = yearAssigend; + month = monthAssigned; + + month = utilities.pad(month, 2); // Adding a left zero when needed. + + logger.fileName = MODULE_NAME + "-" + year + "-" + month; + + const logText = "[INFO] initialize - Entering function 'initialize' " + " @ " + year + "-" + month; + console.log(logText); + logger.write(logText); + + azureFileStorage.initialize(); + + markets = MARKETS_MODULE.newMarkets(bot); + markets.initialize(callBackFunction); + + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + +/* + +This process is going to do the following: + +It will iterate through all the markets and will try to find "holes" on the transaction history and fix them by retrieving the missing transactions from the exchange. + +What are holes? + + Holes are missing transactions in the history of the market and the reason there can be holes are the following: + + 1) The "Lives Trades" process can be stopped and later started again. The process will only retrieve live trades, leaving a "hole" between it was stopped and restarted. + 2) The "Historic Trades" process might have received a "hole" of transactions directly from the exchange. + 3) The "Historic Trades" process failed to write some files to the storage and now they are missing, together with the transaction in them. + 4) The "Historic Trades" process wrote some files to the storage with corrupted content. + 5) The "Historic Trades" process wrote files with transaction not properly ordered by Trade Id (sometimes the exchange sent this wrong). + +How does the process work? + + Transactions have a unique id generated by the exchange. It is a secuencial number. This process scans the transaction history looking for missing ids. When it finds + some group of missing ids, it request the exchange the missing records and it writes the necesary files to fix the hole. But some things might happen: + + 1) The exchange responds, but does not provides the missing records. In this case the process will flag this hole for retry later, up to 3 times. After that it will flag + the hole as "permanent". + 2) The exchange call timeouts: the process will continue retrying later. + 3) The exchange returns an unexpected error: The process will retry up to 3 times later under this condition. + 4) The exchange returns neighboring transactions but not the missing ones. The process will retry 3 more times and mark the hole as permanent if the exchange refuses to send the missing trades. + +Since the process is run in an infinite loop but can be restarted any time, the status of is running is recorded in the Process.Status file. + +What is the lastFile pointer? + + It is the Datetime since the begining of the hitory of a market that is considered without holes (or only with permanent ones, unfixables). In other words, the process + starts from the begining of the history of a market, and only when its history is signaled as "Complete" by the "Historic Trades" process. From there, the process is advancing + in time, validating the history and fixing holes, and moving the lastFile pointer forward as it gets sure that all the previous trades files are with no holes or unfixable ones. + This pointer will later be used by Indicators bots that depends of these trades, to calculate their final version of indicators up to the lastFile pointer datetime. + + +*/ + + function start(callBackFunction) { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'start', with year = " + year + " and month = " + month); + } + + let processDate = new Date(year + "-" + month + "-1 00:00:00.000 GMT+0000"); + + let lastMinuteOfMonth = new Date(year + "-" + month + "-1 00:00:00.000 GMT+0000"); + + lastMinuteOfMonth.setUTCMonth(lastMinuteOfMonth.getUTCMonth() + 1); // First we go 1 month into the future. + lastMinuteOfMonth.setUTCSeconds(lastMinuteOfMonth.getUTCSeconds() - 30); // Then we go back 30 seconds, or to the last minute of the original month. + + let thisDatetime = new Date(); + + if ((year === thisDatetime.getUTCFullYear() && month > thisDatetime.getUTCMonth() + 1) || year > thisDatetime.getUTCFullYear()) { + + logger.write("[INFO] We are too far in the future. Interval will not execute. Sorry."); + return; + + } + + let nextIntervalExecution = false; // This tell weather the Interval module will be executed again or not. By default it will not unless some hole have been found in the current execution. + + let currentDate; // This will hold the current datetime of each execution. + let cursorDatetime; // This holds the datetime we are using to request records from, backwards. + + let marketQueue; // This is the queue of all markets to be procesesd at each interval. + let market = { // This is the current market being processed after removing it from the queue. + id: 0, + assetA: "", + assetB: "" + }; + + let dateForPath; + + let filePath; + + let exchangeCallTime; + + const MAX_EXCHANGE_CALL_RETRIES = 3; + let exchangeCallRetries = 0; + + const MAX_HOLE_FIXING_RETRIES = 3; + + const FIRST_TRADE_RECORD_ID = -1; + const UNKNOWN_TRADE_RECORD_ID = -2; + + let tradesWithHole = []; // File content of the file where a hole was discovered. + + let currentTradeId; // This points to the last Trade Id that is ok. + let currentDatetime; // This points to the last Trade datetime that is ok. + + /* The next 3 variables hold the information read from varios Status Reports. */ + + let lastLiveTradeFile; // Datetime of the last complete trades file written by the Live Trades process. + let lastHistoricTradeFile; // Datatime of the last trades file written by the Historic Trades process. + let lastHoleFixingFile; // Datetime of the last file certified by the Hole Fixing process as without permanent holes. + + /* The next 4 variables hold the results of the search of the next hole. */ + + let holeInitialId; // This is the Id just before the hole. + let holeInitialDatetime; // This is the Datetime just before the hole. + + let holeFinalId; // This is the Id just after the hole. + let holeFinalDatetime; // This is the Datetime just after the hole. + + let holeFixingStatusReport; // Current hole Fixing Status Report. + + marketsLoop(); + + /* + + At every run, the process needs to loop through all the markets at this exchange. + The problem is that we can not fire all the requests at once to the exchange or we would get banned. + For that reason we create a queue with the markets to process and we do one at the time. + The following functions marketsLoop(), openMarket(), closeMarket() and closeAndOpenMarket() controls the serialization of this processing. + + */ + + function marketsLoop() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'marketsLoop'"); + } + + currentDate = new Date(); + markets.getMarketsByExchange(EXCHANGE_ID, onMarketsReady); + + function onMarketsReady(marketsArray) { + + marketQueue = JSON.parse(marketsArray); + + openMarket(); // First execution and entering into the real loop. + + } + } + catch (err) { + const logText = "[ERROR] 'marketsLoop' - ERROR : " + err.message; + logger.write(logText); + } + } + + function openMarket() { + + // To open a Market means picking a new market from the queue. + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'openMarket'"); + } + + + if (marketQueue.length === 0) { + + if (LOG_INFO === true) { + logger.write("[INFO] 'openMarket' - marketQueue.length === 0"); + } + + const logText = "[WARN] We processed all the markets."; + logger.write(logText); + + callBackFunction(nextIntervalExecution); + + return; + } + + if (GO_RANDOM === true) { + const index = parseInt(Math.random() * (marketQueue.length - 1)); + + market.id = marketQueue[index][0]; + market.assetA = marketQueue[index][1]; + market.assetB = marketQueue[index][2]; + market.status = marketQueue[index][3]; + + marketQueue.splice(index, 1); + } else { + let marketRecord = marketQueue.shift(); + + market.id = marketRecord[0]; + market.assetA = marketRecord[1]; + market.assetB = marketRecord[2]; + market.status = marketRecord[3]; + + if (FORCE_MARKET > 0) { + if (FORCE_MARKET !== market.id) { + closeAndOpenMarket(); + return; + } + } + } + + if (LOG_INFO === true) { + logger.write("[INFO] 'openMarket' - marketQueue.length = " + marketQueue.length); + logger.write("[INFO] 'openMarket' - market sucessfully opened : " + market.assetA + "_" + market.assetB); + } + + if (market.status === markets.ENABLED) { + + exchangeCallRetries = 0; // For each market we will count the retries, so we need to reset this here. + + getStatusReport(); + + } else { + + logger.write("[INFO] 'openMarket' - market " + market.assetA + "_" + market.assetB + " skipped because its status is not valid. Status = " + market.status); + closeAndOpenMarket(); + return; + + } + + + } + catch (err) { + const logText = "[ERROR] 'openMarket' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function closeMarket() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'closeMarket'"); + } + + } + + function closeAndOpenMarket() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'closeAndOpenMarket'"); + } + + openMarket(); + } + + + /* + + The following code executes for each market, trying to fix the hole in trades history. + + */ + + + function getStatusReport() { + + /* + + In order to know where to start the process (which datetime) we need to read the StatusReport of the process. This file will tell + us where we left after the last execution. If this file does not exist, this could mean that this process was never sucessfuly ran + for this market. This is normal when the market does not have the "complete" flag at the Trades History status report. + + We will also get the status report from the Live Trade process, to know which is highest possible datetime the process can work on. + + */ + + try { + + let reportFilePath; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json" + + getLivesTrades(); + + function getLivesTrades() { + + reportFilePath = EXCHANGE_NAME + "/Processes/" + "Live-Trades"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onStatusReportReceived, true); + + function onStatusReportReceived(text) { + + if (text === undefined) { + + /* The file does not exist, so this means it is too early to run this process. */ + + const logText = "[INFO] 'getStatusReport' - Market " + market.assetA + '_' + market.assetB + " is too early too prcess it, since there are no Live Trades reports about it yet. Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } else { + + let statusReport; + + try { + + statusReport = JSON.parse(text); + + lastLiveTradeFile = new Date(statusReport.lastFile.year + "-" + statusReport.lastFile.month + "-" + statusReport.lastFile.days + " " + statusReport.lastFile.hours + ":" + statusReport.lastFile.minutes + GMT_SECONDS); + + } catch (err) { + + /* + + It might happen the the file contect is corrupt if it is read exactly at the moment the other process is writting it. + In this situation we just assume the current datetime is a good engough value. + + */ + + lastLiveTradeFile = new Date(); + + } + + /* We get from the file the datetime of the last file created. */ + + getHistoricTrades(); + + } + } + } + + function getHistoricTrades() { + + reportFilePath = EXCHANGE_NAME + "/Processes/" + "Historic-Trades"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onStatusReportReceived, true); + + function onStatusReportReceived(text) { + + if (text === undefined) { + + /* The file does not exist, so this means it is too early to run this process. */ + + const logText = "[INFO] 'getStatusReport' - Market " + market.assetA + '_' + market.assetB + " is too early too prcess it, since there are no Historic Trades reports about it yet. Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } else { + + let statusReport = JSON.parse(text); + + /* We get from the file to know if this markets history is complete or not. */ + + if (statusReport.completeHistory === true) { + + lastHistoricTradeFile = new Date(statusReport.lastFile.year + "-" + statusReport.lastFile.month + "-" + statusReport.lastFile.days + " " + statusReport.lastFile.hours + ":" + statusReport.lastFile.minutes + GMT_SECONDS); + + /* + + Before processing this month we need to check if it is not too far in the past. + + */ + + if ( + processDate.getUTCFullYear() < lastHistoricTradeFile.getUTCFullYear() + || + (processDate.getUTCFullYear() === lastHistoricTradeFile.getUTCFullYear() && processDate.getUTCMonth() < lastHistoricTradeFile.getUTCMonth()) + ) { + + const logText = "[INFO] 'getStatusReport' - The current year / month is before the start of the market history for market " + market.assetA + '_' + market.assetB + " . Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } else { + + getHoleFixing(); + + } + + } else { + + const logText = "[INFO] 'getStatusReport' - Market " + market.assetA + '_' + market.assetB + " is history is not complete. Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } + + } + } + } + + function getHoleFixing() { + + reportFilePath = EXCHANGE_NAME + "/Processes/" + "Hole-Fixing" + "/" + year + "/" + month; + + azureFileStorage.getTextFile(reportFilePath, fileName, onStatusReportReceived, true); + + function onStatusReportReceived(text) { + + try { + holeFixingStatusReport = JSON.parse(text); + } + catch (err) { + text = undefined; // If the content of the file is corrupt, this equals as if the file did not exist. + } + + if (text === undefined) { + + /* + + The file does not exist, so this means this is the first time we are running this process. + Then, we might me under two different possible situations: + + 1. We are at the first month of the market. In this case, the starting date is not the begining of the month but the first date of + the history of the market. + + 2. We are at some other month different than the first one. In this case, the starting date is the first minute of the market. + + */ + + if (processDate.valueOf() < lastHistoricTradeFile.valueOf()) { + + lastHoleFixingFile = new Date(lastHistoricTradeFile.valueOf() - 60 * 1000); // One minute less that the begining of market history. + + currentTradeId = FIRST_TRADE_RECORD_ID; + currentDatetime = new Date(lastHistoricTradeFile.valueOf()); + + } else { + + lastHoleFixingFile = new Date(processDate.valueOf() - 60 * 1000); // One minute less that the begining of the month. + + currentTradeId = UNKNOWN_TRADE_RECORD_ID; + currentDatetime = new Date(processDate.valueOf()); + + } + + findNextHole(); + + } else { + + if (holeFixingStatusReport.monthChecked === true) { + + const logText = "[INFO] 'getStatusReport' - The current year / month was already fully checked for market " + market.assetA + '_' + market.assetB + " . Skipping it. "; + logger.write(logText); + + closeAndOpenMarket(); + + } else { + + /* We get from the file the datetime of the last file without holes. */ + + lastHoleFixingFile = new Date(holeFixingStatusReport.lastFile.year + "-" + holeFixingStatusReport.lastFile.month + "-" + holeFixingStatusReport.lastFile.days + " " + holeFixingStatusReport.lastFile.hours + ":" + holeFixingStatusReport.lastFile.minutes + GMT_SECONDS); + + currentTradeId = holeFixingStatusReport.lastTrade.id; + currentDatetime = new Date(holeFixingStatusReport.lastTrade.year + "-" + holeFixingStatusReport.lastTrade.month + "-" + holeFixingStatusReport.lastTrade.days + " " + holeFixingStatusReport.lastTrade.hours + ":" + holeFixingStatusReport.lastTrade.minutes + ":" + holeFixingStatusReport.lastTrade.seconds + GMT_MILI_SECONDS); + + findNextHole(); + + } + } + } + } + + } + catch (err) { + const logText = "[ERROR] 'getStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function findNextHole() { + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'findNextHole'"); + } + + /* + + To find the next hole, we will read first the current file (which we know if fully ok) and get from it the current Trade Id. + After that, we will continue reading the next files, checking all the ids, until we find a hole. + + */ + + let filePath; + let fileName = '' + market.assetA + '_' + market.assetB + '.json'; + let date; // This is pointing to each Trades File + + let fileCheckedCounter = 0; + + date = new Date(lastHoleFixingFile.valueOf()); + + readNextFile(); + + function readNextFile() { + + date = new Date(date.valueOf() + 60 * 1000); + + if (LOG_INFO === true) { + const logText = "[INFO] Entering function 'readNextFile' with date = " + date.toUTCString(); + logger.write(logText); + } + + if (date.valueOf() > lastLiveTradeFile.valueOf()) { + + /* This mean we reached the forward end of the market */ + + if (LOG_INFO === true) { + logger.write("[INFO] readNextFile - End of the market reached at date = " + date.toUTCString()); + } + + nextIntervalExecution = true; // Even if we didn-t find a hole, we need to continue the execution of this month interval. + + writeStatusReport(currentDatetime, currentTradeId, false, true, onStatusReportWritten); + + function onStatusReportWritten() { + + closeAndOpenMarket(); + + } + + return; + + } + + /* Lets check if we have reached the end of the month. */ + + if (date.valueOf() > lastMinuteOfMonth.valueOf()) { + + /* This mean we reached the forward end of the market */ + + if (LOG_INFO === true) { + logger.write("[INFO] readNextFile - End of the month reached at date = " + date.toUTCString()); + } + + writeStatusReport(currentDatetime, currentTradeId, true, false, onStatusReportWritten); + + function onStatusReportWritten() { + + closeAndOpenMarket(); + + } + + return; + + } + + dateForPath = date.getUTCFullYear() + '/' + utilities.pad(date.getUTCMonth() + 1, 2) + '/' + utilities.pad(date.getUTCDate(), 2) + '/' + utilities.pad(date.getUTCHours(), 2) + '/' + utilities.pad(date.getUTCMinutes(), 2); + + filePath = EXCHANGE_NAME + "/Output/" + TRADES_FOLDER_NAME + '/' + dateForPath; + + azureFileStorage.getTextFile(filePath, fileName, onNextFileReceived, true); + + function onNextFileReceived(text) { + + if (text === undefined) { + + /* The file does not exist, so this means there is a hole!!! */ + + if (LOG_INFO === true) { + logger.write("[INFO] Hole by missing file detected. Date = " + date.toUTCString()); + } + + holeInitialId = currentTradeId; + holeInitialDatetime = new Date(currentDatetime.valueOf()); // Field #5 contains the seconds. + + findEndOfHole(); + + } else { + + try { + + let tradesTest = JSON.parse(text); + + } catch (err) { + + /* + + If the file is corrupt, then we are in a similar situation as if it does not exist. + + */ + + if (LOG_INFO === true) { + logger.write("[INFO] Hole by corrupt file detected. Date = " + date.toUTCString()); + } + + holeInitialId = currentTradeId; + holeInitialDatetime = new Date(currentDatetime.valueOf()); // Field #5 contains the seconds. + + findEndOfHole(); + + return; + } + + checkHolesInFile(text); + + } + } + } + + function checkHolesInFile(text) { + + let trades = JSON.parse(text); + + /* + + tradesWithHole variable: + + Until verified, this trades in this file becomes potentially the last set of trades with hole. If it is not, then this variable will be overwritten later + by the one. + + + We will need these trades at the end of the process. + + */ + + tradesWithHole = trades; + + if (LOG_INFO === true) { + const logText = "[INFO] Entering function 'checkHolesInFile' to check File '" + fileName + "' @ " + filePath + " - " + trades.length + " records in it."; + logger.write(logText); + console.log(logText); + } + + if (currentTradeId === FIRST_TRADE_RECORD_ID || currentTradeId === UNKNOWN_TRADE_RECORD_ID) { + + /* + + Here we dont know the currentTradeId, so we might take it directly from the file. There will be a problem though if the market starts + with some empty files. In those cases, we need to jump to the next file until we find one with some records. + + */ + + if (trades.length > 0) { + + currentTradeId = trades[0][0] - 1; + + } else { + + readNextFile(); + return; + + } + + } + + for (let i = 0; i < trades.length; i++) { + + let fileTradeId = trades[i][0]; // First position in each record. + + if (currentTradeId + 1 > fileTradeId) { + + /* + + This happens when the process resumes execution, reads the first file and the first trades have lowers ids that the ones the process already + checked during the last execution. + + It also happens when we find a non valid id, as the one used in an empty record signaling that the file is incomplete. (zero). + + */ + + continue; // we simply jump to the next trade. + + } + + if (currentTradeId + 1 < fileTradeId) { + + /* + + We should usually try to fix the hole, but there is an exception. If the we tried this 3 times already, we must declare the problem + unsolvable and move forward. + + */ + + let lastRecordedTradeId = 0; + let lastRecordedCounter = 0; + + if (holeFixingStatusReport !== undefined) { // The whole could have benn found before the monthly report was created. + + lastRecordedTradeId = holeFixingStatusReport.lastTrade.id; + lastRecordedCounter = holeFixingStatusReport.lastTrade.counter; + + } + + if (currentTradeId === lastRecordedTradeId && lastRecordedCounter >= MAX_HOLE_FIXING_RETRIES) { + + if (LOG_INFO === true) { + logger.write("[INFO] Hole by non consecutive ID detected. MAX_HOLE_FIXING_RETRIES reched, giving up with this validation. Date = " + date.toUTCString()); + } + + /* We advance anyway to the next Id since there is no other solution. */ + + currentTradeId = fileTradeId; + currentDatetime = new Date(date.valueOf() + trades[i][5] * 1000); + + + } else { + + /* Here we have a hole that needs to be fixed !!! */ + + if (LOG_INFO === true) { + logger.write("[INFO] Hole by non consecutive ID detected. Date = " + date.toUTCString()); + } + + holeInitialId = currentTradeId; + holeInitialDatetime = new Date(currentDatetime.valueOf()); + + holeFinalId = fileTradeId; + holeFinalDatetime = new Date(date.valueOf() + trades[i][5] * 1000); // Field #5 contains the seconds. + + getTheTrades(); + + break; + + } + + + } else { + + /* We keep here the last Trade Id and Datetime that are allright. */ + + currentTradeId = fileTradeId; + currentDatetime = new Date(date.valueOf() + trades[i][5] * 1000); + + } + } + + if (holeInitialId === undefined) { + + fileCheckedCounter++; + + if (fileCheckedCounter === 60) { // Every hour checked we write a Status Report so that if the process is terminated, it can resume later from there. + + writeStatusReport(currentDatetime, currentTradeId, false, false, onStatusReportWritten); + + function onStatusReportWritten() { + + fileCheckedCounter = 0; + readNextFile(); + } + + } else { + + readNextFile(); + + } + } + } + + + function findEndOfHole() { + + /* Here we will enter a loop where will try to find the next available file recorded and extract from it the Id and Datetime from the first record. */ + + date = new Date(date.valueOf() + 60 * 1000); + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'findEndOfHole' with date = " + date.toUTCString()); + } + + if (date.valueOf() > lastLiveTradeFile.valueOf()) { + + /* + + In this case we have an open hole produced by a missing file, and because live trades files contains zero records or are missing, we reached the + forward side of the market. The situation in unsolvable for now, we will leave it of future execution. + + */ + + if (LOG_INFO === true) { + logger.write("[INFO] findEndOfHole - End of the market reached at date = " + date.toUTCString()); + } + + nextIntervalExecution = true; // Even if we didn-t find the end of the hole, we need to continue the execution of this month interval. + + writeStatusReport(currentDatetime, currentTradeId, false, false, onStatusReportWritten); + + function onStatusReportWritten() { + + closeAndOpenMarket(); + + } + + return; + + } + + dateForPath = date.getUTCFullYear() + '/' + utilities.pad(date.getUTCMonth() + 1, 2) + '/' + utilities.pad(date.getUTCDate(), 2) + '/' + utilities.pad(date.getUTCHours(), 2) + '/' + utilities.pad(date.getUTCMinutes(), 2); + + filePath = EXCHANGE_NAME + "/Output/" + TRADES_FOLDER_NAME + '/' + dateForPath; + + azureFileStorage.getTextFile(filePath, fileName, onNextFileReceived, true); + + function onNextFileReceived(text) { + + if (text === undefined) { + + /* The file does not exist, so this means we need to move forward */ + + findEndOfHole(); + + return; + + } else { + + let trades; + + try { + + trades = JSON.parse(text); + + } catch(err) { + /* + + If the file is corrupt, then we are in a similar situation as if it does not exist. + + */ + + if (LOG_INFO === true) { + logger.write("[INFO] findEndOfHole - Corrupt file with no records found at date = " + date.toUTCString()); + } + + findEndOfHole(); + + return; + + } + + if (trades.length === 0) { + + /* This is the same situation that if there is no file, move forward */ + + if (LOG_INFO === true) { + logger.write("[INFO] findEndOfHole - File with no records found at date = " + date.toUTCString()); + } + + findEndOfHole(); + + return; + + } + + if (LOG_INFO === true) { + logger.write("[INFO] findEndOfHole - Next available record found at date = " + date.toUTCString()); + } + + let fileTradeId = trades[0][0]; // First position in each record. + + holeFinalId = fileTradeId; + holeFinalDatetime = new Date(date.valueOf() + trades[0][5] * 1000); // Field #5 contains the seconds. + + getTheTrades(); + + return; + + } + } + } + + } + catch (err) { + const logText = "[ERROR] 'findNextHole' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + function getTheTrades() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'getTheTrades' with input variables: holeInitialDatetime = " + holeInitialDatetime.toUTCString() + ", holeInitialId = " + holeInitialId + ", holeFinalDatetime = " + holeFinalDatetime.toUTCString() + ", holeFinalId = " + holeFinalId ); + } + + /* We request to the Exchange API some more records than needed, anyway we will discard records out of the range we need. To do this we substract some seconds and add some others + seconds to the already calculated UNIX timestamps. */ + + const startTime = parseInt(holeInitialDatetime.valueOf() / 1000 - 65); + const endTime = parseInt(holeFinalDatetime.valueOf() / 1000 + 65); + + exchangeCallTime = new Date(); + + let poloniexApiClient = new POLONIEX_CLIENT_MODULE(); + + poloniexApiClient.returnPublicTradeHistory(market.assetA, market.assetB, startTime, endTime, onExchangeCallReturned); + + } + catch (err) { + const logText = "[ERROR] 'getTheTrades' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function onExchangeCallReturned(err, tradesRequested) { + + try { + + if (LOG_INFO === true) { + + let exchangeResponseTime = new Date(); + let timeDifference = (exchangeResponseTime.valueOf() - exchangeCallTime.valueOf()) / 1000; + logger.write("[INFO] Entering function 'onExchangeCallReturned' - Call time recorded = " + timeDifference + " seconds."); + } + + if (err || tradesRequested.error !== undefined) { + try { + + if (err.message.indexOf("ETIMEDOUT") > 0) { + + exchangeCallRetries++; + + if (exchangeCallRetries > MAX_EXCHANGE_CALL_RETRIES) { + + const logText = "[WARN] onExchangeCallReturned - Timeout reached while trying to access the Exchange API. MAX_EXCHANGE_CALL_RETRIES reached. Giving up. : ERROR = " + err.message; + logger.write(logText); + + closeAndOpenMarket(); + return; + + } else { + + const logText = "[WARN] onExchangeCallReturned - Timeout reached while trying to access the Exchange API. Trying again. : ERROR = " + err.message; + logger.write(logText); + + /* We try to reconnect to the exchange and fetch the data again. */ + + getTheTrades(); + return; + + } + + } else { + + if (err.message.indexOf("ECONNRESET") > 0) { + + exchangeCallRetries++; + + if (exchangeCallRetries > MAX_EXCHANGE_CALL_RETRIES) { + + const logText = "[WARN] onExchangeCallReturned - The exchange reseted the connection. MAX_EXCHANGE_CALL_RETRIES reached. Giving up. : ERROR = " + err.message; + logger.write(logText); + + closeAndOpenMarket(); + return; + + } else { + + const logText = "[WARN] onExchangeCallReturned - The exchange reseted the connection. Trying again. : ERROR = " + err.message; + logger.write(logText); + + /* We try to reconnect to the exchange and fetch the data again. */ + + getTheTrades(); + return; + + } + + } else { + + const logText = "[ERROR] onExchangeCallReturned - Unexpected error trying to contact the Exchange. Giving up. : ERROR = " + err.message; + logger.write(logText); + closeMarket(); + return; + } + } + + } catch (err) { + const logText = "[ERROR] onExchangeCallReturned : ERROR : tradesRequested.error = " + tradesRequested.error; + logger.write(logText); + + if (tradesRequested.error === "Invalid currency pair.") { + + markets.disableMarket(EXCHANGE_ID, market.id, onMarketDeactivated) + + function onMarketDeactivated() { + + logger.write("[INFO] Market " + market.assetA + "_" + market.assetB + " deactivated. Id = " + market.id); + + closeAndOpenMarket(); + return; + + } + + } + + closeMarket(); + return; + } + + closeMarket(); + return; + + } else { + + tradesReadyToBeSaved(tradesRequested); + } + } + catch (err) { + const logText = "[ERROR] 'onExchangeCallReturned' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + function tradesReadyToBeSaved(tradesRequested) { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'tradesReadyToBeSaved'"); + } + + nextIntervalExecution = true; // When there is at least one hole, we activate this flag to get an extra Interval execution when this one ends. + + /* + + We have learnt that the records from the exchange dont always come in the right order, sorted by TradeId. That means the we need to sort them + by ourselves if we want that our verification of holes work. + + */ + + let iterations = tradesRequested.length; + + for (let i = 0; i < iterations; i++) { + + for (let j = 0; j < iterations - 1; j++) { + + if (tradesRequested[j].tradeID < tradesRequested[j + 1].tradeID) { + + let trade = tradesRequested[j + 1]; + + tradesRequested.splice(j + 1, 1); // Remove that trade from the array. + + tradesRequested.splice(j, 0, trade); // Insert the trade removed. + + + } + + } + + } + + /* + + The trades received from the exchange might or might not be enough to fix the hole. We wont worry about that at this point. We will simple record the trades received + in the range where records where missing. + + We only have to take into account that the lowest id we have is already on a file that exist and it is partially verified, so we have to be carefull to overwrite this file + without introducing new holes. + + */ + + let fileRecordCounter = 0; + + let needSeparator; + let separator; + + let lastProcessMinute; // Stores the previous record minute during each iteration + let filesToSave = []; // Array where we will store all the content to be written to files + + needSeparator = false; + + let fileContent = ""; + + let currentProcessMinute = Math.trunc(holeFinalDatetime.valueOf() / 1000 / 60); // Number of minutes since the begining of time, where the process is pointing to. + let holeStartsMinute = Math.trunc(holeInitialDatetime.valueOf() / 1000 / 60); // Number of minutes since the begining of time, where the hole started. + + /* We will iterate through all the records received from the exchange. We know Poloniex sends the older records first, so this is going to be going back in time as we advance. */ + + for (let i = 0; i < tradesRequested.length; i++) { + + let record = tradesRequested[i]; + + const trade = { + tradeIdAtExchange: record.tradeID, + marketIdAtExchange: record.globalTradeID, + type: record.type, + rate: record.rate, + amountA: record.total, + amountB: record.amount, + datetime: new Date(record.date + GMT_MILI_SECONDS) + }; + + trade.seconds = trade.datetime.getUTCSeconds(); + + let currentRecordMinute = Math.trunc(trade.datetime.valueOf() / 1000 / 60); // This are the number of minutes since the begining of time of this trade. + + if (currentRecordMinute > currentProcessMinute) { + + /* We discard this trade, since it happened after the minute we want to record in the current file. */ + + continue; + } + + if (currentRecordMinute < currentProcessMinute) { + + /* + + The information is older that the current time. + We must store the current info and reset the pointer to the current time to match the one on the information currently being processd. + We know this can lead to a 'hole' or some empty files being skipped, but we solve that problem with the next loop. + + */ + + let blackMinutes = currentProcessMinute - currentRecordMinute; + + for (let j = 1; j <= blackMinutes; j++) { + + storeFileContent(); + currentProcessMinute--; + + } + } + + if (currentRecordMinute === currentProcessMinute) { + + if (needSeparator === false) { + + needSeparator = true; + separator = ''; + + } else { + separator = ','; + } + + if (trade.tradeIdAtExchange > holeInitialId) { + + /* We only add trades with ids bigger that the last id verified without holes. */ + + fileContent = '[' + trade.tradeIdAtExchange + ',"' + trade.type + '",' + trade.rate + ',' + trade.amountA + ',' + trade.amountB + ',' + trade.seconds + ']' + separator + fileContent; + + fileRecordCounter++; + + } + } + } + + if (fileContent !== "") { + + /* + + Usually the last file Content must be discarded since it could belong to an incomplete file. But there is one exception: it a hole is found at a file and the previous minute is empty + then this will produce the exception in which the fileContent needs to saved. To figure out if we are in this situation we do the following: + + */ + + if (currentProcessMinute === holeStartsMinute) { + + storeFileContent(); + + } + + + } + + function storeFileContent() { + + let existingFileContent = ""; + let separator = ""; + + if (currentProcessMinute === holeStartsMinute) { + + /* + + Here we are at the situation that the content already generated has to be added to the content already existing on the file where the hole was found. + + */ + + for (let i = 0; i < tradesWithHole.length; i++) { + + if (tradesWithHole[i][0] <= holeInitialId && tradesWithHole[i][0] !== 0) { // 0 because of the empty trade record signaling an incomplete file. + + /* We only add trades with ids smallers that the last id verified without holes. */ + + existingFileContent = existingFileContent + separator + '[' + tradesWithHole[i][0] + ',"' + tradesWithHole[i][1] + '",' + tradesWithHole[i][2] + ',' + tradesWithHole[i][3] + ',' + tradesWithHole[i][4] + ',' + tradesWithHole[i][5] + ']'; + + fileRecordCounter++; + + if (separator === "") { + + separator = ","; + + } + } + } + } + + if (existingFileContent === "") { + + fileContent = '[' + fileContent + ']'; + + } else { + + if (fileContent === "") { + + fileContent = '[' + existingFileContent + ']'; + + } else { + + fileContent = '[' + existingFileContent + "," + fileContent + ']'; + } + } + + let fileRecord = { + datetime: currentProcessMinute, + content: fileContent, + records: fileRecordCounter + }; + + filesToSave.push(fileRecord); + + fileRecordCounter = 0; + needSeparator = false; + fileContent = ""; + } + + /* + + Now it is time to process all the information we stored at filesToSave. + + */ + + let i = 0; + let date; + + nextRecord(); + + function nextRecord() { + + let fileName = '' + market.assetA + '_' + market.assetB + '.json'; + + date = new Date(filesToSave[i].datetime * 60 * 1000); + fileRecordCounter = filesToSave[i].records; + fileContent = filesToSave[i].content; + + dateForPath = date.getUTCFullYear() + '/' + utilities.pad(date.getUTCMonth() + 1, 2) + '/' + utilities.pad(date.getUTCDate(), 2) + '/' + utilities.pad(date.getUTCHours(), 2) + '/' + utilities.pad(date.getUTCMinutes(), 2); + + filePath = EXCHANGE_NAME + "/Output/" + TRADES_FOLDER_NAME + '/' + dateForPath; + + utilities.createFolderIfNeeded(filePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + azureFileStorage.createTextFile(filePath, fileName, fileContent + '\n', onFileCreated); + + function onFileCreated() { + + const logText = "[WARN] Finished with File @ " + market.assetA + "_" + market.assetB + ", " + fileRecordCounter + " records inserted into " + filePath + "/" + fileName + ""; + console.log(logText); + logger.write(logText); + + controlLoop(); + } + } + } + + + function controlLoop() { + + i++; + + if (i < filesToSave.length) { + + nextRecord(); + + } else { + + if (LOG_INFO === true) { + logger.write("[INFO] Leaving function 'tradesReadyToBeSaved'"); + } + + writeStatusReport(undefined, undefined, false, false, onStatusReportWritten); + + function onStatusReportWritten() { + + closeAndOpenMarket(); + + } + + } + } + } + catch (err) { + const logText = "[ERROR] 'tradesReadyToBeSaved' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function writeStatusReport(lastTradeDatetime, lastTradeId, monthChecked, atHeadOfMarket, callBack) { + + /* + + If no parameters are provided, that means that last good information is the begining of the hole. If they are provided is because no hole was detected until the + forward end of the market. + + */ + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'writeStatusReport'"); + } + + if (lastTradeId === undefined) { + + lastTradeId = holeInitialId; + lastTradeDatetime = holeInitialDatetime; + + } + + let lastFileWithoutHoles = new Date(lastTradeDatetime.valueOf() - 60 * 1000); // It is the previous file where the last verified trade is. + + try { + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process + "/" + year + "/" + month; + + utilities.createFolderIfNeeded(reportFilePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + try { + + /* + + Here we will calculate the "counter". The counter keeps track of how many times the process tried to fix the same hole. This allows + the process to know when a hole is not fixable. To do that we need to compre the current status report with the information we ve got + about the hole. If it is the same, we add to the counter. + + */ + + let counter = 0; + + try { + + if (holeFixingStatusReport.lastTrade.id === lastTradeId) { + + counter = holeFixingStatusReport.lastTrade.counter; + + if (counter === undefined) { counter = 0; } + counter++; + + } + + } catch (err) { // we are here when the status report did not exist. + + counter = 0; + + } + + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + let report = { + lastFile: { + year: lastFileWithoutHoles.getUTCFullYear(), + month: (lastFileWithoutHoles.getUTCMonth() + 1), + days: lastFileWithoutHoles.getUTCDate(), + hours: lastFileWithoutHoles.getUTCHours(), + minutes: lastFileWithoutHoles.getUTCMinutes() + }, + lastTrade: { + year: lastTradeDatetime.getUTCFullYear(), + month: (lastTradeDatetime.getUTCMonth() + 1), + days: lastTradeDatetime.getUTCDate(), + hours: lastTradeDatetime.getUTCHours(), + minutes: lastTradeDatetime.getUTCMinutes(), + seconds: lastTradeDatetime.getUTCSeconds(), + id: lastTradeId, + counter: counter + }, + monthChecked: monthChecked, + atHeadOfMarket: atHeadOfMarket + }; + + let fileContent = JSON.stringify(report); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onFileBCreated); + + function onFileBCreated() { + + if (LOG_INFO === true) { + logger.write("[INFO] 'writeStatusReport' - Content written: " + fileContent); + } + + /* + + If we are at the same month of the begining of the market, we need to create the main status report file. + We will re-create it even every time the month status report is created. When this month check finished, other months later + will update it. + + */ + + if (processDate.getUTCMonth() === lastHistoricTradeFile.getUTCMonth() && processDate.getUTCFullYear() === lastHistoricTradeFile.getUTCFullYear()) { + + createMainStatusReport(lastTradeDatetime, lastTradeId, onMainReportCreated); + + function onMainReportCreated () { + + verifyMarketComplete(monthChecked, callBack); + + } + + } else { + + verifyMarketComplete(monthChecked, callBack); + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'writeStatusReport - onFolderCreated' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + } + catch (err) { + const logText = "[ERROR] 'writeStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + function createMainStatusReport(lastTradeDatetime, lastTradeId,callBack) { + try { + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + + utilities.createFolderIfNeeded(reportFilePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + try { + + let lastFileWithoutHoles = new Date(lastTradeDatetime.valueOf() - 60 * 1000); // It is the previous file where the last verified trade is. + + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + let report = { + lastFile: { + year: lastFileWithoutHoles.getUTCFullYear(), + month: (lastFileWithoutHoles.getUTCMonth() + 1), + days: lastFileWithoutHoles.getUTCDate(), + hours: lastFileWithoutHoles.getUTCHours(), + minutes: lastFileWithoutHoles.getUTCMinutes() + }, + lastTrade: { + year: lastTradeDatetime.getUTCFullYear(), + month: (lastTradeDatetime.getUTCMonth() + 1), + days: lastTradeDatetime.getUTCDate(), + hours: lastTradeDatetime.getUTCHours(), + minutes: lastTradeDatetime.getUTCMinutes(), + seconds: lastTradeDatetime.getUTCSeconds(), + id: lastTradeId + } + }; + + let fileContent = JSON.stringify(report); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onFileBCreated); + + function onFileBCreated() { + + if (LOG_INFO === true) { + logger.write("[INFO] 'createMainStatusReport' - Content written: " + fileContent); + } + + callBack(); + + } + + } + catch (err) { + const logText = "[ERROR] 'createMainStatusReport - onFolderCreated' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + } + catch (err) { + const logText = "[ERROR] 'createMainStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + + function verifyMarketComplete(isMonthComplete, callBack) { + + if (isMonthComplete === true) { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Month Completed !!! "); + + /* + + The mission of this function is to update the main status report. This report contains the date of the last file sucessfully checked + but in a consecutive way. + + For example: if the market starts in March, and March, April and June are checked, then the file will be the last of June even if September is also checked. + + */ + + let initialYear; + let initialMonth; + + let finalYear = (new Date()).getUTCFullYear(); + let finalMonth = (new Date()).getUTCMonth() + 1; + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + /* Lets read the main status report */ + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + if (text === undefined) { + + /* The first month of the market didnt create this file yet. Aborting verification. */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED since the main status report does not exist. "); + + callBack(); + + } else { + + let statusReport = JSON.parse(text); + + initialYear = statusReport.lastFile.year; + initialMonth = statusReport.lastFile.month; + + loopCycle(); + } + + } + + function loopCycle() { + + /* + + Here we read the status report file of each month / year to verify if it is complete or not. + + */ + let paddedInitialMonth = utilities.pad(initialMonth, 2); + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process + "/" + initialYear + "/" + paddedInitialMonth; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onStatusReportFileReceived, true); + + function onStatusReportFileReceived(text) { + + if (text === undefined) { + + /* If any of the files do not exist, it means that the continuity has ben broken and this checking procedure must be aborted */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " did not exist. "); + + callBack(); + + } else { + + let statusReport = JSON.parse(text); + + if (statusReport.monthChecked === true) { + + readAndWriteNewReport(statusReport); + + } else { + + /* If any of the files says that month is not checked then it is enough to know the market continuity is broken. */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED since the status report for year " + initialYear + " and month " + initialMonth + " is not hole checked. "); + + callBack(); + + } + } + } + } + + + + function readAndWriteNewReport(monthlyStatusReport) { + + /* We will read the current file to preserve its data, and save it again with the new lastFile */ + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json"; + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + let statusReport = JSON.parse(text); + + /* + + Only if the last trade ID of the month being evaluated is bigger the trade Id at the status report we do replace it, otherwise not. + + */ + + if (monthlyStatusReport.lastTrade.id > statusReport.lastTrade.id) { + + statusReport.lastFile = monthlyStatusReport.lastFile; + statusReport.lastTrade = monthlyStatusReport.lastTrade; + statusReport.lastTrade.counter = undefined; + + let fileContent = JSON.stringify(statusReport); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onMasterFileCreated); + + function onMasterFileCreated() { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Main Status Report Updated - Content written: " + fileContent); + + loop(); // Lets see the next month. + + } + + } else { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Main Status Report Not Updated since current Trade Id (" + monthlyStatusReport.lastTrade.id + ") is <= than Id at main status report file. (" + statusReport.lastTrade.id + ")" ); + + loop(); // Lets see the next month. + + } + } + } + + + function loop() { + + initialMonth++; + + if (initialMonth > 12) { + + initialMonth = 1; + initialYear++; + + } + + if ((initialYear === finalYear && initialMonth > finalMonth) || (initialYear > finalYear)) { + + /* We arrived to the point where we have checked all the status reports of every month and they are all complete. */ + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification Finished. "); + + callBack(); + + return; + } + + loopCycle(); + + } + + } else { + + logger.write("[INFO] 'writeStatusReport' - verifyMarketComplete - Verification ABORTED: Month is not checked. "); + callBack(); + + } + + } + + + + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; diff --git a/Poloniex-Hole-Fixing/Poloniex Hole Fixing.js b/Poloniex-Hole-Fixing/Poloniex Hole Fixing.js new file mode 100644 index 000000000..7f5f61d30 --- /dev/null +++ b/Poloniex-Hole-Fixing/Poloniex Hole Fixing.js @@ -0,0 +1,169 @@ +exports.newPloniexHoleFixing = function newPloniexHoleFixing(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const INTERVAL_LAPSE = 24 * 60 * 60 * 1000; + + const MODULE_NAME = "Poloniex Exchange Hole Fixing"; + const LOG_INFO = true; + + const INTERVAL_MODULE = require('./Interval'); + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + const INTERVAL_MAX_LOOPS = -1; // -1 for infinite loop. + + poloniexHoleFixing = { + initialize: initialize, + start: start + }; + + const SHUTDOWN_EVENT = require(ROOT_DIR + 'Azure Web Job Shutdown'); + let shutdownEvent = SHUTDOWN_EVENT.newShutdownEvent(bot); + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + let utilities = UTILITIES.newUtilities(bot); + + let year; + let month; + + return poloniexHoleFixing; + + function initialize(yearAssigend, monthAssigned, callBackFunction) { + + try { + + year = yearAssigend; + month = monthAssigned; + + month = utilities.pad(month, 2); // Adding a left zero when needed. + + logger.fileName = MODULE_NAME + "-" + year + "-" + month; + + const logText = "[INFO] initialize - Entering function 'initialize' " + " @ " + year + "-" + month; + console.log(logText); + logger.write(logText); + + callBackFunction(); + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + + + function start() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'start', with year = " + year + " and month = " + month); + } + + let intervalId; + + if (INTERVAL_MAX_LOOPS === 0) { + + intervalId = setInterval(startNewInterval, INTERVAL_LAPSE); + + } + + let intervalLoopCounter = 0; + + startNewInterval(); // First, inmadiate run. + + function startNewInterval() { + + try { + + if (LOG_INFO === true) { + + if (INTERVAL_MAX_LOOPS !== 0) { + + logger.write("[INFO] Entering function 'startNewInterval', next execution inmediately after the current Interval finishes."); + + } else { + + logger.write("[INFO] Entering function 'startNewInterval', next execution in " + INTERVAL_LAPSE / 1000 / 60 + " minutes."); + + } + + } + + + if (shutdownEvent.isShuttingDown() === false) { + + let fileProcessingInterval = INTERVAL_MODULE.newInterval(bot); + + fileProcessingInterval.initialize(year, month, onReadyToStart); + + function onReadyToStart() { + + fileProcessingInterval.start(loopControl); + + } + + } + else { + + clearInterval(intervalId); + + const logText = "[INFO] requestNewData - Terminating Set Interval - About to exit gracefully the process. "; + console.log(logText); + logger.write(logText); + + } + + } + catch (err) { + const logText = "[ERROR] 'startNewInterval' - ERROR : " + err.message; + logger.write(logText); + } + } + + function loopControl(moreIntervalExecutionsNeeded) { + + if (moreIntervalExecutionsNeeded === true) { + + intervalLoopCounter++; + + if (intervalLoopCounter === INTERVAL_MAX_LOOPS) { + + const logText = "[WARN] 'INTERVAL_MAX_LOOPS' reached. Stopping execution. "; + logger.write(logText); + + } else { + + const logText = "[WARN] 'loopControl'. Staring new Interval. "; + logger.write(logText); + + startNewInterval(); // Looped Execution. + + } + + } else { + + logger.write("[WARN] Received the signal from last Interval execution to not call it anymore. Stopping execution. "); + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; + + + diff --git a/Poloniex-Hole-Fixing/run.js b/Poloniex-Hole-Fixing/run.js new file mode 100644 index 000000000..1d25ced2e --- /dev/null +++ b/Poloniex-Hole-Fixing/run.js @@ -0,0 +1,97 @@ + +let bot = { + name: "Charly", + process: "Hole-Fixing", + type: "Connectivity", + version: "1.0.0", + devTeam: "AA Masters" +}; + +const ROOT_DIR = '../'; + +const MODULE_NAME = "run"; + +const START_POLONIEX_HOLE_FIXING = true; +const START_POLONIEX_HOLE_FIXING_AT_ONE_MONTH = false; + +const POLONIEX_HOLE_FIXING_MODULE = require('./Poloniex Hole Fixing'); + +const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); +const logger = DEBUG_MODULE.newDebugLog(); +logger.fileName = MODULE_NAME; +logger.bot = bot; + +process.on('uncaughtException', function (err) { + logger.write('uncaughtException - ' + err.message); +}); + + +process.on('unhandledRejection', (reason, p) => { + logger.write("Unhandled Rejection at: Promise " + JSON.stringify(p) + " reason: " + reason); +}); + + +process.on('exit', function (code) { + logger.write('About to exit with code:' + code); +}); + + +try { + if (START_POLONIEX_HOLE_FIXING === true) { + + for (let year = 2018; year > 2014; year--) { + + for (let month = 12; month > 0; month--) { + + let timeDelay = Math.random() * 100 * 1000; // We need a delay so as not to get banned from the exchange for requesting to many things at the same time. + + setTimeout(startProcess, timeDelay); + + function startProcess() { + + const newPloniexHoleFixing = POLONIEX_HOLE_FIXING_MODULE.newPloniexHoleFixing(bot); + + newPloniexHoleFixing.initialize(year, month, onInitializeReady); + + function onInitializeReady() { + + newPloniexHoleFixing.start(); + + } + + } + + } + + } + + } + + + if (START_POLONIEX_HOLE_FIXING_AT_ONE_MONTH === true) { + + startProcess(); + + function startProcess() { + + const newPloniexHoleFixing = POLONIEX_HOLE_FIXING_MODULE.newPloniexHoleFixing(bot); + + let month = 2; + let year = 2015; + + newPloniexHoleFixing.initialize(year, month, onInitializeReady); + + function onInitializeReady() { + + newPloniexHoleFixing.start(); + + } + } + } + + +} catch (err) { + console.log(err.message); + logger.write(err.message); +} + diff --git a/Poloniex-Live-Trades/Interval.js b/Poloniex-Live-Trades/Interval.js new file mode 100644 index 000000000..775727b85 --- /dev/null +++ b/Poloniex-Live-Trades/Interval.js @@ -0,0 +1,675 @@ +exports.newInterval = function newInterval(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + const GMT_SECONDS = ':00.000 GMT+0000'; + const GMT_MILI_SECONDS = '.000 GMT+0000'; + + const MODULE_NAME = "Interval"; + const LOG_INFO = true; + + const EXCHANGE_NAME = "Poloniex"; + const EXCHANGE_ID = 1; + + const TRADES_FOLDER_NAME = "Trades"; + + const GO_RANDOM = false; + const FORCE_MARKET = 2; // This allows to debug the execution of an specific market. Not intended for production. + const FORCED_INITIAL_TIME = undefined; //"2018-01-19 12:15:00.000 GMT+0000" + + const MARKETS_MODULE = require(ROOT_DIR + 'Markets'); + + const POLONIEX_CLIENT_MODULE = require(ROOT_DIR + 'Poloniex API Client'); + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + interval = { + initialize: initialize, + start: start + }; + + let markets; + + const AZURE_FILE_STORAGE = require(ROOT_DIR + 'Azure File Storage'); + let azureFileStorage = AZURE_FILE_STORAGE.newAzureFileStorage(bot); + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + let utilities = UTILITIES.newUtilities(bot); + + return interval; + + function initialize(callBackFunction) { + + try { + + const logText = "[INFO] initialize - Entering function 'initialize' "; + console.log(logText); + logger.write(logText); + + azureFileStorage.initialize(); + + markets = MARKETS_MODULE.newMarkets(bot); + markets.initialize(callBackFunction); + + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + +/* + +We are going to generate 2 files: + +A. The first one will contain all the trades of the current minute and will be store in a folder that we will create for this if it does not exist. +This file will be incomplete, since we are at the current minute and some trades will happen after we retrieve the information from the exchange, +but this is not a problem, since the second file is going to fix this. This file is only usefull for viewing a partial candle as it is being built +at the end of the chart. + +B. The second file will contain all the trades of the previous minute. It will be the definitive file the system will use. + +Besides that, we are going to delete the A file of the previous minute, since it is not needed anymore after the B file is there. + +FILE FORMAT +----------- + +Array of records with this information: + +1. Trade Id provided by the exchange. +2. Trade Type: "buy" or "sell" +3. Trade Rate: the rate of the transaction. +4. Amount Asset A +5. Amount Asset B +6. Time: Seconds and Milliseconds the trade happened. (the rest of the time and date whoever reads the file already know it since it is organized in folders according to this.) + +*/ + + function start() { + + try { + + let currentDate; // This will hold the current datetime of each execution. + let previousMinute; // This hold the current time minus 60 seconds. + let marketQueue; // This is the queue of all markets to be procesesd at each interval. + let market = { // This is the current market being processed after removing it from the queue. + id: 0, + assetA: "", + assetB: "" + }; + + let dateForPathA; + let dateForPathB; + + let filePathA; + let filePathB; + + let reportFilePath = EXCHANGE_NAME + "/Processes/" + bot.process; + + let exchangeCallTime; + + marketsLoop(); + + /* + + At every run, the process needs to loop through all the markets at this exchange. + The problem is that we can not fire all the requests at once to the exchange or we would get banned. + For that reason we create a queue with the markets to process and we do one at the time. + The following functions marketsLoop(), openMarket(), closeMarket() and closeAndOpenMarket() controls the serialization of this processing. + + */ + + function marketsLoop() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'marketsLoop'"); + } + + if (FORCED_INITIAL_TIME !== undefined) { + + currentDate = new Date(FORCED_INITIAL_TIME); + + } else { + + currentDate = new Date(); + + } + + markets.getMarketsByExchange(EXCHANGE_ID, onMarketsReady); + + function onMarketsReady(marketsArray) { + + marketQueue = JSON.parse(marketsArray); + + /* + + First thing to do is to create the folders where all the files are going to be placed. This is done only once per market. + + */ + + previousMinute = new Date(currentDate.valueOf() - 60000); + + dateForPathA = currentDate.getUTCFullYear() + '/' + utilities.pad(currentDate.getUTCMonth() + 1, 2) + '/' + utilities.pad(currentDate.getUTCDate(), 2) + '/' + utilities.pad(currentDate.getUTCHours(), 2) + '/' + utilities.pad(currentDate.getUTCMinutes(), 2); + dateForPathB = previousMinute.getUTCFullYear() + '/' + utilities.pad(previousMinute.getUTCMonth() + 1, 2) + '/' + utilities.pad(previousMinute.getUTCDate(), 2) + '/' + utilities.pad(previousMinute.getUTCHours(), 2) + '/' + utilities.pad(previousMinute.getUTCMinutes(), 2); + + filePathA = EXCHANGE_NAME + "/Output/" + TRADES_FOLDER_NAME + '/' + dateForPathA; + filePathB = EXCHANGE_NAME + "/Output/" + TRADES_FOLDER_NAME + '/' + dateForPathB; + + utilities.createFolderIfNeeded(filePathA, azureFileStorage, onFolderACreated); + + function onFolderACreated() { + + utilities.createFolderIfNeeded(filePathB, azureFileStorage, onFolderBCreated); + + function onFolderBCreated() { + + utilities.createFolderIfNeeded(reportFilePath, azureFileStorage, onFolderCreated); + + function onFolderCreated() { + + openMarket(); // First execution and entering into the real loop. + } + } + } + } + } + catch (err) { + const logText = "[ERROR] 'marketsLoop' - ERROR : " + err.message; + logger.write(logText); + } + } + + function openMarket() { + + // To open a Market means picking a new market from the queue. + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'openMarket'"); + } + + + if (marketQueue.length === 0) { + + if (LOG_INFO === true) { + logger.write("[INFO] 'openMarket' - marketQueue.length === 0"); + } + + const logText = "[WARN] We processed all the markets."; + logger.write(logText); + + closeMarket(); + + return; + } + + if (GO_RANDOM === true) { + const index = parseInt(Math.random() * (marketQueue.length - 1)); + + market.id = marketQueue[index][0]; + market.assetA = marketQueue[index][1]; + market.assetB = marketQueue[index][2]; + market.status = marketQueue[index][3]; + + marketQueue.splice(index, 1); + } else { + let marketRecord = marketQueue.shift(); + + market.id = marketRecord[0]; + market.assetA = marketRecord[1]; + market.assetB = marketRecord[2]; + market.status = marketRecord[3]; + + if (FORCE_MARKET > 0) { + if (FORCE_MARKET !== market.id) { + closeAndOpenMarket(); + return; + } + } + } + + if (LOG_INFO === true) { + logger.write("[INFO] 'openMarket' - marketQueue.length = " + marketQueue.length); + logger.write("[INFO] 'openMarket' - market sucessfully opened : " + market.assetA + "_" + market.assetB); + } + + if (market.status === markets.ENABLED) { + + getTheTrades(); + + } else { + + logger.write("[INFO] 'openMarket' - market " + market.assetA + "_" + market.assetB + " skipped because its status is not valid. Status = " + market.status); + closeAndOpenMarket(); + return; + + } + + + } + catch (err) { + const logText = "[ERROR] 'openMarket' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function closeMarket() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'closeMarket'"); + } + + } + + function closeAndOpenMarket() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'closeAndOpenMarket'"); + } + + openMarket(); + } + + + /* + + The following code executes for each market, getting the trades from the exchange and saving them in files at the cloud storage. + + */ + + function getTheTrades() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'getTheTrades'"); + } + + const datetime = parseInt(currentDate.valueOf() / 1000); + + /* We request to the Exchange API some more records than needed, anyway we will discard records out of the range we need. To do this we substract 120 seconds and add 10 + seconds to the already calculated UNIX timestamps. */ + + const startTime = datetime - 120; + const endTime = datetime + 10; + + exchangeCallTime = new Date(); + + let poloniexApiClient = new POLONIEX_CLIENT_MODULE(); + + poloniexApiClient.returnPublicTradeHistory(market.assetA, market.assetB, startTime, endTime, onExchangeCallReturned); + + } + catch (err) { + const logText = "[ERROR] 'getTheTrades' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function onExchangeCallReturned(err, tradesRequested) { + + try { + + if (LOG_INFO === true) { + + let exchangeResponseTime = new Date(); + let timeDifference = (exchangeResponseTime.valueOf() - exchangeCallTime.valueOf()) / 1000; + logger.write("[INFO] Entering function 'onExchangeCallReturned' - Call time recorded = " + timeDifference + " seconds."); + } + + if (err || tradesRequested.error !== undefined) { + try { + + if (err.message.indexOf("ETIMEDOUT") > 0) { + + const logText = "[WARN] onExchangeCallReturned - Timeout reached while trying to access the Exchange API. Trying again. : ERROR = " + err.message; + logger.write(logText); + + /* We try to reconnect to the exchange and fetch the data again. */ + + getTheTrades(); + return; + + } else { + + if (err.message.indexOf("ECONNRESET") > 0) { + + const logText = "[WARN] onExchangeCallReturned - The exchange reseted the connection. Trying again. : ERROR = " + err.message; + logger.write(logText); + + /* We try to reconnect to the exchange and fetch the data again. */ + + getTheTrades(); + return; + + } else { + + + const logText = "[ERROR] onExchangeCallReturned - Unexpected error trying to contact the Exchange. Giving up. : ERROR = " + err.message; + logger.write(logText); + closeMarket(); + return; + } + } + + } catch (err) { + const logText = "[ERROR] onExchangeCallReturned : ERROR : tradesRequested.error = " + tradesRequested.error; + logger.write(logText); + + if (tradesRequested.error === "Invalid currency pair.") { + + markets.disableMarket(EXCHANGE_ID, market.id, onMarketDeactivated) + + function onMarketDeactivated() { + + logger.write("[INFO] Market " + market.assetA + "_" + market.assetB + " deactivated. Id = " + market.id); + + closeAndOpenMarket(); + return; + + } + + } + + closeMarket(); + return; + } + + closeMarket(); + return; + + } else { + + tradesReadyToBeSaved(tradesRequested); + } + } + catch (err) { + const logText = "[ERROR] 'onExchangeCallReturned' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + function tradesReadyToBeSaved(tradesRequested) { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'tradesReadyToBeSaved'"); + } + + + let fileRecordCounterA = 0; + let fileRecordCounterB = 0; + + let fileNameA = '' + market.assetA + '_' + market.assetB + '.json'; + let fileNameB = '' + market.assetA + '_' + market.assetB + '.json'; + + let needSeparator; + let separator; + + needSeparator = false; + + let fileContent = ""; + + /* First we create the file A */ + + fileContent = fileContent + '['; + + for (i = 0; i < tradesRequested.length; i++) { + + let record = tradesRequested[tradesRequested.length - 1 - i]; // In Poloniex the order of the records is by date DESC so we change it to ASC + + const trade = { + tradeIdAtExchange: record.tradeID, + marketIdAtExchange: record.globalTradeID, + type: record.type, + rate: record.rate, + amountA: record.total, + amountB: record.amount, + datetime: new Date(record.date + GMT_MILI_SECONDS) + }; + + trade.seconds = trade.datetime.getUTCSeconds(); + + if (trade.datetime.getUTCMinutes() === currentDate.getUTCMinutes()) { + + if (needSeparator === false) { + + needSeparator = true; + separator = ''; + + } else { + separator = ','; + } + + fileContent = fileContent + separator + '[' + trade.tradeIdAtExchange + ',"' + trade.type + '",' + trade.rate + ',' + trade.amountA + ',' + trade.amountB + ',' + trade.seconds + ']'; + + fileRecordCounterA++; + + } + + } + + // We add this extra record signaling that this file is still incomplete. + + fileContent = fileContent + separator + '[' + '0' + ',"' + 'inc' + '",' + '0' + ',' + '0' + ',' + '0' + ',' + '0' + ']'; + + fileContent = fileContent + ']'; + + azureFileStorage.createTextFile(filePathA, fileNameA, fileContent + '\n', onFirstFileACreated); + + function onFirstFileACreated() { + + const logText = "[WARN] Finished with File A @ " + market.assetA + "_" + market.assetB + ", " + fileRecordCounterA + " records inserted into " + filePathA + "/" + fileNameA + ""; + console.log(logText); + logger.write(logText); + + generateFileB(); + + } + + function generateFileB() { + + fileContent = ""; + needSeparator = false; + + fileContent = fileContent + '['; + + for (i = 0; i < tradesRequested.length; i++) { + + let record = tradesRequested[tradesRequested.length - 1 - i]; // In Poloniex the order of the records is by date DESC so we change it to ASC + + const trade = { + tradeIdAtExchange: record.tradeID, + marketIdAtExchange: record.globalTradeID, + type: record.type, + rate: record.rate, + amountA: record.total, + amountB: record.amount, + datetime: new Date(record.date + GMT_MILI_SECONDS) + }; + + trade.seconds = trade.datetime.getUTCSeconds(); + + if (trade.datetime.getUTCMinutes() === previousMinute.getUTCMinutes()) { + + if (needSeparator === false) { + + needSeparator = true; + separator = ''; + + } else { + separator = ','; + } + + fileContent = fileContent + separator + '[' + trade.tradeIdAtExchange + ',"' + trade.type + '",' + trade.rate + ',' + trade.amountA + ',' + trade.amountB + ',' + trade.seconds + ']'; + + fileRecordCounterB++; + + } + } + + fileContent = fileContent + ']'; + + azureFileStorage.createTextFile(filePathB, fileNameB, fileContent + '\n', onFileBCreated); + + function onFileBCreated() { + + const logText = "[WARN] Finished with File B @ " + market.assetA + "_" + market.assetB + ", " + fileRecordCounterB + " records inserted into " + filePathB + "/" + fileNameB + ""; + console.log(logText); + logger.write(logText); + + writeStatusReport(); + + } + } + + if (LOG_INFO === true) { + logger.write("[INFO] Leaving function 'tradesReadyToBeSaved'"); + } + + } + catch (err) { + const logText = "[ERROR] 'tradesReadyToBeSaved' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + } + + function writeStatusReport() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'writeStatusReport'"); + } + + /* + + The report is a file that records important information to be used by a) another instance of the same process, b) another process or by c) another bot. + + The first thing to do is to read the current report file content, if it exists. + + There are 2 fields recorded in this file: + + 1) The firstFile: which stores the datetime of the first file ever created by this process. This information is usefull for the Historic Trades process. + 2) The lastFile: which sotres the datetime of the last complete trades file created. + + If the file does not exist, then we created. + + */ + + try { + + let firstFileDatetime; + + let fileName = "Status.Report." + market.assetA + '_' + market.assetB + ".json" + + azureFileStorage.getTextFile(reportFilePath, fileName, onFileReceived, true); + + function onFileReceived(text) { + + if (text === undefined) { + + /* If the file does not exist that means that this is the first time this process run at this market, so we must create the file now. */ + + firstFileDatetime = previousMinute; + + writeReportFile(); + + } else { + + /* Here we just need to confirm that it has the information. */ + + try { + + let statusReport = JSON.parse(text); + + /* We get from the file the datetime of the first file created. */ + + firstFileDatetime = new Date(statusReport.firstFile.year + "-" + statusReport.firstFile.month + "-" + statusReport.firstFile.days + " " + statusReport.firstFile.hours + ":" + statusReport.firstFile.minutes + GMT_SECONDS); + + writeReportFile(); + + } catch (err) { + + /* For some reason the file exists but the content is not there. We will create them well now. */ + + firstFileDatetime = previousMinute; + + writeReportFile(); + + } + + } + + function writeReportFile() { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'writeStatusReport - writeReportFile'"); + } + + + let report = { + firstFile: { + year: firstFileDatetime.getUTCFullYear(), + month: (firstFileDatetime.getUTCMonth() + 1), + days: firstFileDatetime.getUTCDate(), + hours: firstFileDatetime.getUTCHours(), + minutes: firstFileDatetime.getUTCMinutes() + }, + lastFile: { + year: previousMinute.getUTCFullYear(), + month: (previousMinute.getUTCMonth() + 1), + days: previousMinute.getUTCDate(), + hours: previousMinute.getUTCHours(), + minutes: previousMinute.getUTCMinutes() + } + }; + + let fileContent = JSON.stringify(report); + + azureFileStorage.createTextFile(reportFilePath, fileName, fileContent + '\n', onReportFileCreated); + + function onReportFileCreated() { + + if (LOG_INFO === true) { + logger.write("[INFO] 'writeStatusReport' - Content written: " + fileContent); + } + + closeAndOpenMarket(); + + } + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'writeStatusReport' - ERROR : " + err.message; + logger.write(logText); + closeMarket(); + } + + } + + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; diff --git a/Poloniex-Live-Trades/Poloniex Live Trades.js b/Poloniex-Live-Trades/Poloniex Live Trades.js new file mode 100644 index 000000000..b4dc974c2 --- /dev/null +++ b/Poloniex-Live-Trades/Poloniex Live Trades.js @@ -0,0 +1,106 @@ +exports.newPloniexLiveTrades = function newPloniexLiveTrades(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const INTERVAL_LAPSE = 60 * 1000; + + const MODULE_NAME = "Poloniex Exchange Live Trades"; + const LOG_INFO = true; + + const INTERVAL_MODULE = require('./Interval'); + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + poloniexLiveTrades = { + initialize: initialize, + start: start + }; + + const SHUTDOWN_EVENT = require(ROOT_DIR + 'Azure Web Job Shutdown'); + let shutdownEvent = SHUTDOWN_EVENT.newShutdownEvent(bot); + + return poloniexLiveTrades; + + function initialize(callBackFunction) { + + try { + + const logText = "[INFO] initialize - Entering function 'initialize' "; + console.log(logText); + logger.write(logText); + + callBackFunction(); + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + + } + } + + + function start() { + + try { + + let intervalId = setInterval(startNewInterval, INTERVAL_LAPSE); + + startNewInterval(); // First, inmadiate run. + + + + function startNewInterval() { + + try { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'startNewInterval', next execution in " + INTERVAL_LAPSE / 1000 / 60 + " minutes."); + } + + + if (shutdownEvent.isShuttingDown() === false) { + + let fileProcessingInterval = INTERVAL_MODULE.newInterval(bot); + + fileProcessingInterval.initialize(onReadyToStart); + + function onReadyToStart() { + + fileProcessingInterval.start(); + + } + + } + else { + + clearInterval(intervalId); + + const logText = "[INFO] requestNewData - Terminating Set Interval - About to exit gracefully the process. "; + console.log(logText); + logger.write(logText); + + } + + } + catch (err) { + const logText = "[ERROR] 'startNewInterval' - ERROR : " + err.message; + logger.write(logText); + } + } + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; + + + diff --git a/Poloniex-Live-Trades/run.js b/Poloniex-Live-Trades/run.js new file mode 100644 index 000000000..2782c137d --- /dev/null +++ b/Poloniex-Live-Trades/run.js @@ -0,0 +1,57 @@ + +let bot = { + name: "Charly", + process: "Live-Trades", + type: "Connectivity", + version: "1.0.0", + devTeam: "AA Masters" +}; + +const ROOT_DIR = '../'; + +const MODULE_NAME = "run"; + +const START_POLONIEX_LIVE_TRADES = true; + +const POLONIEX_LIVE_TRADES_MODULE = require('./Poloniex Live Trades'); + +const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); +const logger = DEBUG_MODULE.newDebugLog(); +logger.fileName = MODULE_NAME; +logger.bot = bot; + +process.on('uncaughtException', function (err) { + logger.write('uncaughtException - ' + err.message); +}); + + +process.on('unhandledRejection', (reason, p) => { + logger.write("Unhandled Rejection at: Promise " + JSON.stringify(p) + " reason: " + reason); +}); + + +process.on('exit', function (code) { + logger.write('About to exit with code:' + code); +}); + + +try { + if (START_POLONIEX_LIVE_TRADES === true) { + + const newPloniexLiveTrades = POLONIEX_LIVE_TRADES_MODULE.newPloniexLiveTrades(bot); + + newPloniexLiveTrades.initialize(onInitializeReady); + + function onInitializeReady() { + + newPloniexLiveTrades.start(); + + } + + } + +} catch (err) { + console.log(err.message); + logger.write(err.message); +} + diff --git a/README.md b/README.md new file mode 100644 index 000000000..3d8b2ab09 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# AA Charly diff --git a/Utilities.js b/Utilities.js new file mode 100644 index 000000000..b70a5b5f2 --- /dev/null +++ b/Utilities.js @@ -0,0 +1,81 @@ + +exports.newUtilities = function newUtilities(BOT) { + + let bot = BOT; + const ROOT_DIR = '../'; + + const MODULE_NAME = "Utilities"; + + + const DEBUG_MODULE = require('./Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + let utilities = { + pad: pad, + createFolderIfNeeded: createFolderIfNeeded, + calculatePresicion: calculatePresicion + }; + + return utilities; + + + function pad(str, max) { + str = str.toString(); + return str.length < max ? pad("0" + str, max) : str; + } + + function createFolderIfNeeded(path, azureFileStorage, callBackFunction) { + + let splittedPath = path.split("/"); + + let partialPath = ''; + let separator = ""; + + + let i = 0; + loop(); + + function loop() { + + partialPath = partialPath + separator + splittedPath[i]; + separator = "/"; + + i++; + + azureFileStorage.createFolder(partialPath, checkLoop); + + function checkLoop() { + + if (i === splittedPath.length) { + + callBackFunction(); + + } else { + + loop(); + + } + + + } + + } + + } + + + function calculatePresicion(number) { + + for (let i = -10; i <= 10; i++) { + if (number < Math.pow(10, i)) { + return Math.pow(10, i - 3); + } + } + } + + + + +} \ No newline at end of file diff --git a/azure.app.config b/azure.app.config new file mode 100644 index 000000000..9f6ac1b4c --- /dev/null +++ b/azure.app.config @@ -0,0 +1,7 @@ +{ +"useDevelopmentStorage": false, +"connectionString": "DefaultEndpointsProtocol=https;AccountName=aadata;AccountKey=YOu76OjlJX9T1QTWbj5cvqyYXTdufW1jISNyrtr8RlUK++kVIdm/TnYuyLJzp8kptAEhbQnN4PP3c6SoPLvR+A==;EndpointSuffix=core.windows.net", +"accountName": "", +"accountKey": "", +"sas": "" +} \ No newline at end of file diff --git a/bin/Microsoft.NodejsTools.WebRole.dll b/bin/Microsoft.NodejsTools.WebRole.dll new file mode 100644 index 0000000000000000000000000000000000000000..e0d0ccfca361ba6603bd3d811325d2a721bd31c3 GIT binary patch literal 33056 zcmeIb2Ut`|voPG}Ok~Iz5o7=bM8X*|2uc=|B+&rk07DR%!I=R>L;-V77%+m0Ip?g1 zy5^j-m|b&NvwqcQW&p$PyYGMR`|Q2{bB{ZHx~sdZtE;N3yQ}-Kk-a7%211Alzi;0V z+6r&{_|xHE2j!5hWwBigZB#pMxs`}GZW*7QBjXoHC0SBoK0jS37E9#(G!b7~DCXyg z`N7d~{Cr7<$VpR^*H(!-CIq1ff`OLj*lky}b_-eY)d>nAFMx0rP_0CG^WoPQehBH% zaZ*7y2C#8}pBnf9eBXQo{pvd$7sdZIzm-W0f@fO-LeV(V7olO8392U$n(GXSa)dPC zWdP+cIe+`%H<3q14DEhHs&5ZEhdkq*W5w+DbC zZ3h(aBpv89-BkyON@w6gAO>KEbRop;oFMM#z?N=mO8By+2bvOLZ0W_OM7q~5=!MJ~ zs(jTiX8@VXrXN5Nnl1JQ-)Af*R2g6O2jdFr90v`K1co0^B7nd~iNKEhp_~TSQBRpS zL6z6RLkVFrl%*AEE-f277mT!7Hq!Iom!f55PckH0nC-w@5(PkSfGAx(M3!-YI6cHD z1Cs!6J6Awf2Ezg3hGi^xvrBPGU5|iF5J?9;GzbIi+@TXX*2TBNU zW*O)nyjf+Sw(wTq*Q4WxWgt($k5dZ#Aa9Hx1Af8}w9xoLLuve=qBMR!{brSc$~EB! zy@t4987Mj6$0-GV=rhKT0WI(|5oi-O0lG?A@z@S#Y_b%qy4pRa)j^Dw>TK^SjL*2INziVHaHLP6 zNwO3RMdA&$?SP$Z(x4112$LhxgoMv@C`Zb`YVm035MUmYEX4&R9RX-y2Mu-5;5zi@ zNWGb$@E{mASKv%3bIO(lVkoF2 zlP+yzgI^)g9umS&12k<1{K!&VLJ|aJ^_iqB7}o)d!sJLPa~HyIB~O0+W~OL2__?TpD%oVUO(6i`XJ;Ko^c zEW0p>I0lf$DwgT8%3uyu@r*^Ha%-anDt4N5`}_z!`Vb`d!7>t2}r zbuVVo%>O&R(9q{{bh%BGuTxQu*sYwx6uhU2F|dmSY9vuO_(2I`SH)PQ2cfRIT|6d0|9h}q0s!q{hy+}N0G^S+oj|IiScvR(wLAouZmnz|4_XsG8bfH!TL<#{8N=H8! z&I9;Xi0lJ6EI69rm|QJ@J%%5~r+R=@h=c*613#Fq5%i7lP}m`cU8171ttmEI33$OA zg5AWk21p7|G+;M}K^?YnM=QuC`M59RVbl_3u<~Jg`C{N8JoDHk0Va+#RV6;M6wgm& zDJ}-%9=|5!kfpe&qz4q0^n?K0$zJeQ+DY6l*h%OVjCpzr13L*Mb-1pN+bP8vU?=hG zt0C9|#gNCf08ekgqrs8R#RNbXfquGat|S=}v~}k?>TsmjRRnrX#(XIS!=$2;D@%c* z#$cRiD*Hf!9!UC3J*L8(ccN_*O{Olh44A2+lS$gaywKr>m@LImFr|a=yM;BUsbt#u z15%E(H>YWQ;Pxe{05$2j;p?|=pr$OWk8~R}4|G{A)U+9_P}2Z2=mb1i#{Gduc&!Hw zt7MFM_??UwKt2!(GR8AE@CZ-#AmehV12Q(jZ00w~Sk@QlDud-I)5{U(41(5Ff}Y&m zg*E^sOK~x>6qk?)G3U}C!17Ipw^F{iO^~l8e$i_LJP-1)d^IupQk((u#jmf1K&C>z zxEA2a06ZYylek@4zJqX!b|L^9aV44XYL+xv3Y~y9ek`G+FAEpOCh|wg(gcEJt?1f# z6{81|1p`M*7DKUQ@w)#f%y7PCbu*?lb}OSeJy{yWJwgH;BorEIf+KZWpX zAzMsclWYUyx&{&oGeg^!A~z?>$(3>yc!OYJf0PH|DB!5|V1(YldnWYBI!-Rl5ogJ8 ziE%Jk!(gOYC&Zz1pc61JA?q#);lc2}3+cTu+N=Zfuu$oT1RY5-UZAc9c+f|}6}BIA z>tT=t(~E#b2na;bE4*$+z;RrJ-k(8Tph)opv@{I5hS$q94*bSwp*9=CK{Jsd>nfLx za_CTKIbX&VXG$Hnk(tTt+Fw3ft_lyGsGVg|0;m3fuR zLmkv-K<*6ARjwBLthNf`huPzx^+pCR--|A(LC4d$xXdK>Feu}PaIPiYRssjta)cJO zP!A5y?E`T(vOu`qG;$nE3x)D9d@yi83+eE1`ECf8>7$POI1cdeP(4o!l)qzP%I7dJ z0=!-!68r&GEx&*40Ez&RXr$`t9MZNy}TF1pIDg76hkpVUzrojS-J&pSw}qa04ks^*mo+g@ujREwpE0@XCLQj+_bFMm58%0>uWE!GdO(_;( zgiPAvlD7$-IvY6d-(HcjVDKRoqfFtvR;X=<=Db$OO_{=ZV2vD`^RR6q&_ys;BpL$- z>EDkBf|&x{`6*lqW{m{xz&7nIj0S>^lOXwKNHMfapqr3OqFyv5&I}Aug-p~FM!{&X zaid|Jj0P*YkV}BxWBIm%kO%wYg;xhhyCgBGK8jx zATTyvny0!1=4F2xQUbYbkXQyofKH=c>K^ zGJyAh@ExfG;V@XBPDT?Mses`qD-5k8dXXZujJU>tTp|%{%{F2gjDrfgm3ktEmkZ^u z@vv4c_#=aG9=n7P(!3H9d)PyuR+joOaLS3f)kIr_ z>$XL7L7M?*$Jd?hh~45n*E(6u7yTD~YoeJ@!;^nx*7jcSP_q!ZW(C#Dn9N1hP2Mu`ww zqf`hxpehJm>98Xm2BBF1>4x@07>Bf2PN+9(4`Dh=fiM?|Sqo7q%q9(Vc!v)8qztWL z`9nyu`$Cw)zC})jGJFOO`_iE;?35bNZS)lStWJC-3P=Ww4JN%tn9Q?*B}IaoJ%lae zb)-F$gt5Ya5ygeELxMhWAk>7hLn3YH6$?2aO9*j)*ocBS8@WK7gWMp_K^_nbyi6)qHA*154*bJ$ywXuU_et?jux{BqDm_&tQ*8&rZ~h#@Ewek+JNI_^XcfmOf|v;ltSfdb^4R+yP7l6G=WO%)(t zdAdv)>r{vV@j_W{kR-n#PbANgh~p%M(sWT@1z7nCC>G|(MN&uwNTtG(I8j! zP?`k@)8#Zm7vzf(x}eZPae7}!C5h7FBrZBvUG_w zFDDJfii8;fvJ!DRiW7;Iv7kJOOr!uNNrAnJXsjq*lvAWkq~-}_^6(7YKamuUKXOGG zh?YfySSHLAMT?bU12Cp2T-Kb9&z4Gx!!v_~;&f47o)Ak`DFrC3BsNHrmnTZcSu&@% z0#SO7FfV5yWT)mp5s^#=8L1&+XtJOnFDISGL8ozV;w3mIR#cEDOc$Y+&BRM`MM^C~ zVe85Hi zQptdlK%q?0+gK5FUJQvaxxAn$pE+QIMvrxp76(x04_>l_pcsGn%=;E@>B$ zSR{q283A(GvZWOQk}icgEmFavw8E?`%=G3GAeqD*SuM#~jtb$P*5r>&kwn02>TxPFA-3S6QIa;*#c!*g~;9 zCtpOXx;!T>Cof0dA~&!E#GxE|Fg#%p!KNCuP?!)gj1&x07E+>fQuZ6?#AAzwBcN}} z7}n74g(7K*G94kwLaBKWBuI1Uk%i4E>H=GGVV-iJqNHq)L|$Ht;q{9FqRqbQLatB5kC=n2dKNJdWt3TptyRLKTKAFxsR z+03BS^g^i=#+uSx(Zi{QxoYC1C{tVPH06ZaJ;Y5nSv}FVq z=H%fLO_EgsK#r=YZzp+bYMQd345kt&-)tgV%1|}xz%(dk*(Q2v6#{lECcLJ61(hvk zVP$?ewouBMyV(wXKcmx22<0LH)31sGPS91__$qp?jJA+aYKT-Sks_ybIfP2R56%&0 zi6t_5PP$A5QVj)qCX^J!iKIn2>7t*q6@ywNZOT`$0f>Nk8j6P$fvyBd!IkCP$t^Wi z4%azUEi{ctCoB?K3$}uBEEML&$qO@bB=ihJYa|RGNii56r2;}stei^~BR~cg5Bd<0 zks*Z%L)8kXzLP>tnm`~JJfZyn#RXeHo1*lp0nY-3G7y~@W@V(XkSIE>9}s|G4oO$g zLetSy5f!W2XemW{u>r%gFi(yJr;LH3D`Q!BI-?gpC|hS zy#S<1<=?Fs6cB9YVkD4-F{+fa37}Lb1d}94RTd`7D~J(hiBw?4BuTF!RYg=;7+tum zsh28nKsp}JKY=49MWQHtF-2vDaU5d@R?-(%0%Qfi`KEd*FmRO44i@DJOXx1p3t>e} zIaMl*s<;G63Q|M*gT{dIr*S91N(RT9u+mEbyu443gcW=`l7gv_!7mfZVaE{#u?!?a z{QwpZaS8ZjWdKhC7_21ew5TZ^2kCU!KZ&4j42@|3>1H!K|FwGk zeZ|1I3ZNYvVrA`w2u<9QDuvYeaGA{qlo@pkfN`1*WeQ;YV8QW0`SCd8!(eD0!+aV~ ze;9otfXg8_6Ce^8%X}EW6pUFXghT=K;E}@+5kW4-fJ@6j4JDAHQWPPyCkI#&z*9_fOwmIH_w#8!iJMAco??rOM1fEqm;AX!6>dKCSAi4rK@N16 zG~vN^6VrydfF*{pU=3&~e`v)u?l0(!2c3?Anm^Rh4*;xr0LQIkYAq4+QDX+Z(>S~Zh6A)@oIYhx|Pa#d&**5a1+eBf@3LQ9FVU)LW9b+K+Z0=0OIXDRuq zD%}#BLK-bw!#u^>A*TDN&~BV+$yIEA33nB~@B98U_B`ly2~a}U^275ZA85n;QegOZ zIQHw>f16|Ozpno;Xoh8k;TGGkU7Xay0g2Ok zIcyx3k5=O_^&<7UYw0C0`A9E^1wr`%D4`drMVE^N3=jk8aXLJ$sCSx9oM-V#EiEk; zB6vDH4u_$oC(;u^1yapWulydV*IzFMN)Toy8qioX2m!W73OtW!JWqixjD`ekGyv|U z0f5aRbq#b2nXm#Wk zW;PrRuAYuwif;LMz4FP1y5-Xdy%fFjYQ6HgdgZlrSf^LMj13g7B1o{-hI$nQp^r3l z2u2$OjpBdM4(<&CBs_{FF)cc62o8?~fP$hDx-~A{fyqFkE?jbgUIQw<6mz{4jxvhz zV-oZcM@fo0k5tBJM38|LRe-U2DO}wDG9I4+9jH*#(k;UcRA^%U=~n2f=@2w6Z4efh zK2orCnI4A?UFOngxpcpmY4Mpf1zd9$m#bR_y#>m+Y(){Ck_4`<35U2Mxp)9)9WfWa7wAjH0}u5!F-L ztnc_>*5&ip>aWi_@q(W`MdEnx<={SRwD(WuWHx`hDHfnR@)Quml_z4CPcD8Z3UOg8XPDIvWSC|?Fykqovu3(8{^ z;?i&6rkWxRJY?hXrWZnw-Ed$&D0+WdcVLv4DAh=>L@!de4BG-Th8^O=apeYNxO<`Y#Jv(~14!OtLi<1B$e*$%E z0pO=g^7C`#KCa&BA^|1Jq}b$@BEB4a`+in<$M2jjlUXU7!p+(9OBE$? z0zaAH8F0)L=I7*<`0!;yvCI)PB`33EbEz^VYG)cZ?uK)=f_~pLNk)mPAK8NcN++PU zq8Zh|{D~Lv;gU#<9se0LL$K?sh2kqlYcX&|23&FA!$}=KM~**n!rwOu<#ISHftqp& zzfcC8Rdz|p2RC-6pKUgHP<))7vm{RWP3JW*44gBI^K!(w&Yj`pB{w|S&&8Ya_H?oB zq@wXpjEAqYu#*#57G<*z{45DHtZ0(<9Pt}ROyPsq9caQ7DV;_Rd|7dh96<3>5CgV4 zIMYhi*pCdcQgjl$SRyH3o-G2dV2@r?=MrKg@HbsJr#p7$Wai*ErG2Oz}l9#rA# z=J9GB9BW@`6Hna;ykk;4+cG-HA$;r1eXNafeUtlAFe( z6PC{pCwEQ-8ENP?5TtrO;W%HF`u?r@z)Jyzvo~pQUS6ayN31w~6^ZC$3}u~f?EuY> z-TEHi|E2za%mI9-kiH9F{(UF$$_IgW1^ooa<-*|Cqc42K0n16%W5Y!sr{KN}+@pJOOwQtMc2>1<+dNDEf{V_N_>j{)eA2Wzc0P=(pmZ z8~7rC2XOlh(;5V=<-D z9R;lsz$rx!g8_pKcK4WG>?2e7p)gLBN8E|_iQ}EQ$}5h&V+tP@b^y!3yMuj8e2|44 z;@IvCFYH14RJ-EE+qO3igd*E@gqA2-Cj| z`t);Kf5vz08drIXnz3MqJmwDeOG#;uA@+zMpaJ(WTG<}7qt)^wtLDdQFpZAy(npc>`^vK&#CE$T51UO#_hFn@qfw*1WO!t%|1 zq_?{iO{%Fh97mXgiW&wBVQuU5VWDpFodW7YiEbRlCr@0 z41JTPwKqQ=E-N|0`Fwr>KPD)EYGbS^@SwaYPl2bqm%Do}NP4wMQWYEiBa~@U>XEada806+2>KN)B5-4a#Su1*E_RAhA z?|@L1gjGup6D-82B(y;x2p(BU5NKk-Jgt#Ez^w5_{~W!y(mAKJB> zaw4tAfkPE5Kd*0mIB4X1hg&a;ht#;47<-S7%$&pMaGM^|VGq_-&-XTPt)Cba`S8@~%Jc+g-LrG!$8S#F zRkh;yz%^kH>`!+nxH76zEy?QfVdHZwn;kE@dInrT8Al^a;Qy}ukATEKhi|EcKHh7M~R+&5@b z@wmPPGm`2?h1Ybc2^kTjbPl9T^M3FS6y)YO1JoJ3G#Q0(huFDEj94#ewFIqnf+AE8 zHWx-Ei^U-bW(3uh3R9&ias+sVXzxRDaq+Jj5J~?6vz*e$^tNMaP&^e%2DhcUz<>mG zAy8h;x8zeLJ1#z0&Azq6JWY`M$Ly@7&v@B>?dFyTbHk1;I~CD*bA^X~@vGVzT~o7< zrQZGlD^_3R_AWEudGu+kC6gMo@(lOd&GnzKK{m2WR1AN@um1$7giY};lXwGE;el^4%^zX z!{I9r3%)EbE!^%HVS9N;@`MK)t6r^hd$@YxYxjz~d&F9~eWi7`t{-Oax;#ChZ*Ko= z+gS@E(pVo(%Quw00WklK+UYu%;{(gWj}B zTfnEA0iNcZEHU=^H5)Q7ftL#<0Aq#?nWsQNxhRuV#nAr&O2khwXLUws__k+bQX7|GTdb5ju zA3nptidU=uPN*_WLf}-&uLdfkg|(Vnbo=&btM%yB0@hqrBT)=`EO@R%p0UJ0XN-v0&v`pv&u?JQ!i?uv77icgqDPYbGKz`C-ZM8mTVNNS zx3aB^U8kjEGaWvWmxel9PnrBKN%U>e`A6NkRexOgviJO6e#n=g@aU3f8Lfu&jcVL~ zBreM0Q?JRIy^psYI!N~LaA2`ss=(&(+7oeOgz@k8jh9xxJh0h(@bXE+m_9Q~R`sPS zSv$etEm9afp3v0>e+Gz<;0I<=sq_ksr#8iA^wd`l8AK~12Kc@Ot?@n5@9j43|1Z{D4BZ6b#>ml+epEit=(5xVQ+sU0uMMxhRt^ zIQdT++JCjSS}*OH+=|NBV?L`dpC4FV6qnbj^##eXqc0!lew|^YbL*y$e5mOb=NgwM z-)`&+jIus2MOWREc%zT3=7+y|k-ajq+xWU&CEfbZ?!vk9rQOZBg`-X`mjw^GSaJ3B zu2&w54kw3PTeHgVmRj9Ms=Hs@tE4p-ic;GYhYTI=Wpql`o3%YFc6{CX z9Oo;o)W1%Vw{I+Rj=yd|^?ZM3eA<_zhf_lZG23kQ@A^|GrR{a>tbX&1@~d(2n{>R^ zi#FMh=Z)0(C zo$6A&j@HfLJAPD;*`Ija@lMw>I}08x)m*@+OT4vpOt++0(*ozbeEs~{ zoe>spzFQM#y@<0OZojC~Y-(c_$NW`e)cbL@M;_|eO^!O$`piV>H2ePfvrXTdy@jl~$t9kfTE1Diz@kwr{`$SzPxrd$ ztjd`AEyl=c&>oiMz{Y6-wmA(`Cr&#&{?csA)tbq3UMyHWB73MtKgS(KxyXF_s#iv( ze;5sIyKU6TeoMOuoM&CT)8FqR8l2YU^odc2x0-y^l8&!m=(mRS@AoZd_Vh-br8*lu zW4IR@{HRJc2kiHAmHjr##twUg%>D`cO?gso@HaMG++8VeY`+C`68`K4B>%bn{=c%` z^K0|g-Mkt$#ePt(Q>)v%8t)va?rt5k>cn-EsJ7bAPA@qfu}V(yb${oakDq23Ue!8q z%IcZPl+6{C`>=G^lhGXQcUsJuFGe4;IO^JVxWkbS75a3`4eQVy`yJ!wuW2(NKu~;a_RWq%r`8I|P3D^GKEIp2o;YFE zE&kgFR>MBNy2^U50PDTvudMekcf#LUZ=EJ14AvX$Iif0NV%uuXte8Yqj4wC%mHDkr zUnKmGFE1)}N>&-wcCD#f6(Q^KhNJH!`d?%9|JL3ec&#&IOhYmw*yH-6jjM{Uo+#-a zNvv~{_wSvrp}*q9?$U`{ozCek7?+>6HHkbL#n+FizCO^uF=@w|9<$7Dn-e2e?ilcD z?5QUmiD!+wC-PW_#)mb&h%>w%y<*DU2jlylFR#B}^@{C0obhO~eOs%7Pk(&AJD}Q0 z^Bt$LV5dpc+zGin>9no2-gB}X4|LahoR-|#Xy#ac=SGgH%ZFovu0;aB4pQ|)j|=?1 z4d?0K+{Y76cyV#7@$XS%ha7P4&}ZSE-*=X&2bP|TlUhEbj_ep9O72Y<^9;1kTrrsW z)^}TGj}4B_4?YYZajbjd!?^`jc`Lmm&izrcXSvD1wD!*z%x>?-E;da&?AIpWqVk3M zZw@<725q?a;Yr!1JByae-M2;^=x?oOQ>5-2JFb7P&>(}I8#b(s%sMnb@LPF_W%)cq zD)V8WULVs#^QF2nn z=ftgdE$?kwdnA41fOyuq0H>IhRcq@8tk_U9z0maXl#%*{R?aRa* zi=eW-F;&@KADq1u47Y#IF+sb3fAX6&d!K76?%?H`(o3zz5NNdUJu|_<+w7ZG7idu} za}DugP*ssBfW=^|^{o=NXpoujW>qzOJZ}9|s(xcORZ-ajhlW5-No#`31AlRP_-~%x z)!LWa;nkZAUjxdKXBVb9;R`@b`x|F5ea%CTKi_US0fRS|SqXnAZjK!92o+tH=q_%nYskBQoo9mr2TDmJTipB#}8z97vfrd{^$zOLD^Gp`#KaxWh5aXWL~ zv~AY$J<77OdFDwQENl8O+Kz0UHPxn-ca=l%q9wZ`LYADoSyWJ;BABtoa^CCP2^rIu zpX1-|n)TJ_&ZU=$gYqM^4>b(S`4nAr^T@$d>vlFanizG+s@HQ_crz_t+NZJAm6&Yf ziTe!2a}o$tS#*Raec0MCR z{xHz3)|#&K#rx2Qu{-w3wyztxn^U~W^Tqku0d=1QR2L1$AZ>TzXvazSzpa~-Yg7EO zz@cHm1mA02>R0h|FP$LPqFo7#oX$-#AL~QRop}HF;QUA;yvw%26@BJ9+|ez`E6kZ6 zQG2awS@ed(4--pkFZL*2l@oX+bzpSV5?zJ$q=%Cr@AZiPBNlD z9Q9ZiyPt11xYZKd2PyYQd0uYg96o&38l&XGf+15@-`M+}(OdWZAGb6ApeoyjHxFVa zA*gKY4KVj6UgOiPwl)B=0^Jd4V;1%u5k`m@OcI70mE2qzPPniq=}%9%XkSN*x=eoh z0DD2hj-9)gNA-69Dvdj1(!27}p#{|QG*6E&SI>0Osj1YQ3M+42Sb2YFb`_%uBPTCP zGEF_wiC%(FXem{7AZhS_#2sr#*}xJD+$#0XKp^l053#q4KymQp z(v*a@iBhS3Y|5N4nH_%6W6d$wkQ7r zx`(bk>X+q4{b6Lhk*J$CXzaE{4)@1)EcwG)qh#Xi*qi=@*}j8}xxe>3DSLFOzxV7H zC))LNJaf1=@A=>hE?OyaJ?4{n%(%t5WY+u0o@0w|b+EkkeD9(Vy_1Ym#zF6fb5_?9 zl8Xbs%~^jhAuD^kV^O~$nQ>jtci|oLx-q_VMys;QQ#SAGCfuui(I-Ra?uXxP55Bs^ zJ*D|7Ywx93&YwnKG5oMvyA%A0ywmEP3eFX;kPZl#$=ParY{9zJC%az9WG%c{_2SIf zgo$yBr%k=TKJ(;Z&+NPDznxSq*UMqKK1ku)XopX#n)E$_OQ^gJjF!IR6^AZ7U2k}1 z`Gl9pp5}SI3+Z}l%#OeBJ9eeOq;*K6+^KXAk*A}lhnv9B%}tQ$n3nD)1TV6imq6qu zaL=H;zVo+)i8JoSu+CO4H}>?j+LXWaNFh1x&ri>OdAKDhkkJQdpx#ZMU98WkIB=vq z9Vsu`=OR?~8hkDZR2;0Q|oEz6S?!l3~rQtc5yX$5JRQp_-dnSqO-tXg{+0(BswkcCfe0c3?yTXBW zU1FEE>1Gu7`kD5u2IjQ(^_9aGB?>;*jF~)b)1F=@mJt>ip|$sqyu2tc-7|&Tz0V+5 zvQPJpv+rGUN+l!I=9mUu>HqZZay6Us~ z%%cTE$m4s}dw-{ZoR7kO9GUruygFxac8&-K^tPgl{ro=Ag?tl64 zZZTfruRnS9+E(?mT<1P>kscQviw>RXsNKD9n?awxUVX?Z;k>JL z_4=wd>*~bP%|5$^kJx%_XBk0lDK%e~(t6jiNaJ_nF0SYOZ}vOl)P3uwZ6_O;XFJ}z z^GIjh?@PAdSmfl|uf4ND*T-$@t-Rb>!=LYCBF)_TOVbU)4A%^fUAwjK{@6`jE4K`{ zN8$E1Lv4En+}L$KGkmA|oB;)D;7aEV1ebc6${nLM=?py=Fn&-Ls$$fCWHJDkxneSC z-#i)oxzD|MS`dKi296Qk;p#ee+<4GQ0o;lJ$IU-IZB>##-)tc9%?1)~Ho%x$@#3RY z$INNfCGqk~ok+LsuQvCvoFCZQKKD_tnB`m9UZ%|O?L!(g+FbX{J*am{{e{=QYWCVg z-scGeLEzcZnk5+{2UqoNo400O_?$=Cea_sR9k-t6(6Hw6vJR^Us;#*=z2}j>rmRPq zMGswKZStKe$PMM>Cj8ZA~Ml#!9eLPJ)bS%eJ(wH8Z>$6<hOkdSH_q;o)qvLAV9tXB``s#9a1H*6K`ZZI$2A`Q*?(jA$ak8a* zy9RG@#*nz}bF^2rvL1Hy&349!@$XV!oQmBuu4?4Yy_WKJsU~)tkJ;LJwVUbP)#K!# zbyHTGSua_Z`9x^Z@3vj|+|*Hx?NZKKcIy9Ch1{)gkPf^hebDyip3v$8&-a-nT^&09 zNn|*+WW|J=PkPT^^ZEMP%*Of|6{SxvJni-%y!{e=yTwb&vdZs|NgI&5-g(%?q&dlZ zitX%PKFx2io9Hmn-!r=Y_VD1*`_&>2oU03RmQQ;pem{WU!$Ci#@3dK+qFskwSv$)3 z#=NLE)7S0{t;w5t=GKK#YhOm?wU3>BqH!(7N9n2(9)Gb?6L6;)Kl3xIrbpFtn(cRF#L+Rwi4*ShZ9CiCJd@5VN-)_PIU6(=F6;#Jy%tzdQ8J-ifb6JKXr(@zgH&=i+v&@2#R}DvX59#6M z(%;r}$htSS?{7Hx@N;Ia?>RbKELpNe-r&z-FDC5mI>80N$V~OU8zSG{o;buzVptZk zr0AZ%y=Y-WN^IJQ2J>`}86$39dHw#CQSB_-+sEr>oO+g$9&o2OXU@n@>|*w5_PRm~ zgWW>mrWe-^wr1|W8StBy-Lo4a=O;7%s7;=J30{(r6((T)Y4c6I( z_t$*^2a$H*L^MOwF7irEC)Uh;H~TYY3Z>= zDfP9ZW+(Mej0y|c8+dqjQEy&(SnijS`SrW<^ZOl+mFa5^j5#i-Gy-RWk;0iU?Vp~w z6h4Jt>a74tFzQJFWzAE?ltUc zjQ--J!Z)sS>MpGKV)4LnWBqSqs=dRw@|lfi$-vM1+dq2|ad?Y$q*)a&BJxt}b0@DK zvA9}vcj#ft^KGy0)_ZPL4S&7)g`eq0-$~aj?mmgWw<=(@^R6##Jg@9q+V`T#8Pl9$ zRht_&nQ0H;e4a2WcfbRq)NSu4tx2$0i)!;WEuK`WR_*p+{EXISR=eL)>DQu+=99G^ zECy>%Wz3N!y)UjmH0*rbAYOI1(+M-~g!qqosF8Vp>wKqndkRfPp4jP78osCVuJ*ge zJjuCZH6Z7Xf9jg4b+^}wPA++MX4KuGYa-Xb%zj&(-SzeC+DiSdRHc4s)2@!e02he9 z2f$pKM2uY^`qlulAPL6LE|5yXkFBoKEFJKIR1yy0TC#(AvMnf?67{g2JO%-`Z@%}R zF!@&b`ALgI`ISYD9d6Nd5k1hgN5Bh?$i#sgnA?b#b)S&;!*29KstJr#&H*Y<@ zzj=+f8x$zt&&&Ci7nPTpYwj%89pl4)@>zez+mAzXs&eJ=I_K+nsB-wHr-QP)IiwzF zxF_6Kw53yKhu$v?<7}A%i-6Xq)67q(=}#CWq`!0S_2 zUXW2qHkAuQG*3N#+oj_8p0<5mdh`u_)uYP@mtk$>!mP=u74hp%PK}sSzkhMcX`#N@ z?x5+15#>8>3O|R|+nTq{(vzB6j#<+!V{}Z~x|A=)7Je_13RmtL6By~={j~NRcBiZ% zZ!`BYrUwsxeyZCS@x56`)-8QC(4HrFaV3g9dGjc)`@;cdYadk~_kG|TynV@=YZ<#1 z5%qkvsRNFG-nsX1a7rJeIRq=(DpKX&xeuIb{LAI+`E;M;F@j02gGvX5wm#sR-D`M$ z!e8Bk`TNV+^M52Bo%nD;a$5Fjzp6>SFP@lXvj4w&Wm z?@w^UGPZ_Z#^TFJ71OASDOAP8?^d!ElwZ?Alz`iwe|E<@rdzmT85c^!*C*ZW)RSkC=X-8CBz-kRCDqCdlL?!sD2$%fw-AA2jI;JPC%b=K7+|3@!R zRA){a_pM*rkn0D!s!z6Q^nTK+Yyb4QrIz^(a~3Y}{Wzp-dcR2n7U!S2J?De@XRk|D zZw}V+rjJ;(Yo6(9X5i4Ro62WfdGR;3yO;6g-J3mw(|fkl9_ZwqRJ5S~a`qVQ(MH>a zOLULUx}?=*R{4Qb$CsRXUN-c_?T-D`Zl=g*T5*L}*2c7v?0R_{-FzV6ESl=`PSj<< z!}m+WR=m3*9W2b16fdhdxwEzE2FO1ZC$tQ>h$$X0v8-U*(xCN)`$=Gvli-R zQfGI_UAo;&FMV4*#<}%xmTP)$T750pcScPAi?wGCB;3ilkyL;B2DSIgvHOvqH20)L zKbqU7m6!9*lRa2Y&oyge+^;-Wvo$-vVX%7}?)EDlSI?$SydfVIt_Ks&6*yYh*WzfQ zw(iTeXG=cMn@i6=wLi{2|Ex)G`9+O~o0sBXLGghNPX6zl{r}}eHTx7%a^Gsrz(K7G z+q~YAb;10`k{ihFlHLc-V{WNMWaN?IRRdQP<=S&X#&@?pyE!GauHC^jgOah)$L>44 zeKJ3Cpt+lshyB)u#wQ12o}T>@RPVUwz>AM3j}4pj`+~*m^OI^OZW9)q3qLW+d8kvz zimp>Pg?HUAIy`;&UFVN08!si9yZ*6T=fS?%*7~BTKCvlar3kF)S%KK4InAI~CP48?-n#ugVUbY@hzN(-TjVfwDi^7H;}{*t3dC z;+(JXH;hy_T6_PzXNvEovnzIvoH24>f~=b`sQ$Ius42ToY`r(EtFMvgoPZPj85M`r zR1;Ne;FNKTOP(u|w^i=$Z-0K`t%vK|pZwVR?3RyV-<=8ka^Ctc-Y18Z27F3`?~^NL z7dRCV{CCYRe}enR-skqOV>|uiqhdEKYZsl=9!!M!`s0l-nY4W!%wejWc@7dpj)#)8VFZx zeyn$A`KW#uMaB0xy-&r&oj%a(oSn0M*X|`2CEoVMzX|VI53y%mv6*+?e{*B%H6MNX zJ)bYjKXoQQclhw0AKTmRNXmM?-81txZ^jJUX&n1_gI@nx4(6?+GzXl%I#si6ALCKs z@s^)2CEJ{Oq<=f_NEH14pE`cHJ;ymzL*z3jWUbl~S%gFG=8Hz@w?0d~su#14yG#yP z(C6chi>tIshaY{dUEFbi%h~AZlMTYG5005JqlfvIx`5hBMiDq~``~?U#hu#!#T$eL z?Re0K=34>`LsYqX^xKX1I~yhQcN&9()c?5m@7XmK`>2XNiz;?f72EzJOYa}P`1twL z!l?K-`qM&p&rlD?AVCOx`{C{uBXl$tp$eHRFCb*P}&UQUIsjO&5aboofw`;^O)YqdR?TRdG%&{|9>Mk39}A{H&8jnWE?7G!_tK`1OO~zLbf?eD%gfik%}w~UCaC(1$CAA| zXDY_&IXZ35y3xvNd+DeJ6Q=h5Dl{DwSthsacl4dp$`xy~p5(P2m1*%H^To(%&$|wg zPt>@1A~xn=kB99hT3xtmwR^rDr^o(xg>Qm)4_o`Ty2N$pgo$G{JUP8KhSWWIc~c`R zV%q5KhhEOEz90!%xA*-Ej_t8d!WCa9&WIV&Ysf0k1%8Y?hR?ervG0qIby_nz?L)u2 z%a0!)H(~p!o)Zk;*&bbZ;+Fk!6PI@WUG{%z(^Wjev-B1i-)Y_qiAIkF2C%OC0O}kv^H1S}f1GBZi|J6|4&w2A! zFS*rUUKsrHVq)nIe)ihT@Qw9dF4S+l+tBLiLyI2W_v~NW?d(KJ_27L&I$a*SK7DCJ z*6!7&dp@0%wo2M3VaGo`6gAtTVD0I`&bjwDO?jHympZa*34hl@w;q~1XU?=?9!jt7 z+3W4+#nTpCaO-G9nsu{U&$l^r;a2`s>t*ty&YR%>y*U5t@QBAr_M~yjp#Bf?mJVNO Hb{73VGJbBM literal 0 HcmV?d00001 diff --git a/logs/Dummy File.txt b/logs/Dummy File.txt new file mode 100644 index 000000000..e69de29bb diff --git a/node_modules/.bin/sshpk-conv b/node_modules/.bin/sshpk-conv new file mode 100644 index 000000000..ecb743209 --- /dev/null +++ b/node_modules/.bin/sshpk-conv @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sshpk/bin/sshpk-conv" "$@" + ret=$? +else + node "$basedir/../sshpk/bin/sshpk-conv" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/sshpk-conv.cmd b/node_modules/.bin/sshpk-conv.cmd new file mode 100644 index 000000000..dde70b020 --- /dev/null +++ b/node_modules/.bin/sshpk-conv.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-conv" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sshpk\bin\sshpk-conv" %* +) \ No newline at end of file diff --git a/node_modules/.bin/sshpk-sign b/node_modules/.bin/sshpk-sign new file mode 100644 index 000000000..5a6a17ca2 --- /dev/null +++ b/node_modules/.bin/sshpk-sign @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sshpk/bin/sshpk-sign" "$@" + ret=$? +else + node "$basedir/../sshpk/bin/sshpk-sign" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/sshpk-sign.cmd b/node_modules/.bin/sshpk-sign.cmd new file mode 100644 index 000000000..45025ec15 --- /dev/null +++ b/node_modules/.bin/sshpk-sign.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-sign" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sshpk\bin\sshpk-sign" %* +) \ No newline at end of file diff --git a/node_modules/.bin/sshpk-verify b/node_modules/.bin/sshpk-verify new file mode 100644 index 000000000..80e3a6b3d --- /dev/null +++ b/node_modules/.bin/sshpk-verify @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../sshpk/bin/sshpk-verify" "$@" + ret=$? +else + node "$basedir/../sshpk/bin/sshpk-verify" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/sshpk-verify.cmd b/node_modules/.bin/sshpk-verify.cmd new file mode 100644 index 000000000..1b5fc0c17 --- /dev/null +++ b/node_modules/.bin/sshpk-verify.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\sshpk\bin\sshpk-verify" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\sshpk\bin\sshpk-verify" %* +) \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 100644 index 000000000..ca9624d48 --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../node-uuid/bin/uuid" "$@" + ret=$? +else + node "$basedir/../node-uuid/bin/uuid" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/uuid.cmd b/node_modules/.bin/uuid.cmd new file mode 100644 index 000000000..9f2abd08d --- /dev/null +++ b/node_modules/.bin/uuid.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\node-uuid\bin\uuid" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\node-uuid\bin\uuid" %* +) \ No newline at end of file diff --git a/node_modules/ajv/.tonic_example.js b/node_modules/ajv/.tonic_example.js new file mode 100644 index 000000000..0c3cc86ce --- /dev/null +++ b/node_modules/ajv/.tonic_example.js @@ -0,0 +1,20 @@ +var Ajv = require('ajv'); +var ajv = Ajv({allErrors: true}); + +var schema = { + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "number", "maximum": 3 } + } +}; + +var validate = ajv.compile(schema); + +test({"foo": "abc", "bar": 2}); +test({"foo": 2, "bar": 4}); + +function test(data) { + var valid = validate(data); + if (valid) console.log('Valid!'); + else console.log('Invalid: ' + ajv.errorsText(validate.errors)); +} \ No newline at end of file diff --git a/node_modules/ajv/LICENSE b/node_modules/ajv/LICENSE new file mode 100644 index 000000000..810539685 --- /dev/null +++ b/node_modules/ajv/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Evgeny Poberezkin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/ajv/README.md b/node_modules/ajv/README.md new file mode 100644 index 000000000..9d4fcbb9c --- /dev/null +++ b/node_modules/ajv/README.md @@ -0,0 +1,1213 @@ +Ajv logo + +# Ajv: Another JSON Schema Validator + +The fastest JSON Schema validator for node.js and browser. Supports [v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals). + + +[![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv) +[![npm version](https://badge.fury.io/js/ajv.svg)](https://www.npmjs.com/package/ajv) +[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) +[![Code Climate](https://codeclimate.com/github/epoberezkin/ajv/badges/gpa.svg)](https://codeclimate.com/github/epoberezkin/ajv) +[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master) +[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) + + +__Please note__: You can start using NEW beta version [5.0.4](https://github.com/epoberezkin/ajv/releases/tag/5.0.4-beta.3) (see [migration guide from 4.x.x](https://github.com/epoberezkin/ajv/releases/tag/5.0.1-beta.0)) with the support of JSON-Schema draft-06 (not officially published yet): `npm install ajv@^5.0.4-beta`. + +Also see [docs](https://github.com/epoberezkin/ajv/tree/5.0.4-beta.3) for 5.0.4. + + +## Contents + +- [Performance](#performance) +- [Features](#features) +- [Getting started](#getting-started) +- [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md) +- [Using in browser](#using-in-browser) +- [Command line interface](#command-line-interface) +- Validation + - [Keywords](#validation-keywords) + - [Formats](#formats) + - [$data reference](#data-reference) + - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) + - [Defining custom keywords](#defining-custom-keywords) + - [Asynchronous schema compilation](#asynchronous-compilation) + - [Asynchronous validation](#asynchronous-validation) +- Modifying data during validation + - [Filtering data](#filtering-data) + - [Assigning defaults](#assigning-defaults) + - [Coercing data types](#coercing-data-types) +- API + - [Methods](#api) + - [Options](#options) + - [Validation errors](#validation-errors) +- [Related packages](#related-packages) +- [Packages using Ajv](#some-packages-using-ajv) +- [Tests, Contributing, History, License](#tests) + + +## Performance + +Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON schemas into super-fast validation functions that are efficient for v8 optimization. + +Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: + +- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place +- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster +- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) +- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) + + +Performace of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): + +[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:%7Cajv%7Cis-my-json-valid%7Cjsen%7Cschemasaurus%7Cthemis%7Cz-schema%7Cjsck%7Cjsonschema%7Cskeemas%7Ctv4%7Cjayschema&chd=t:100,68,61,22.8,17.6,6.6,2.7,0.9,0.7,0.4,0.1)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) + + +## Features + +- Ajv implements full [JSON Schema draft 4](http://json-schema.org/) standard: + - all validation keywords (see [JSON-Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md)) + - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) + - support of circular references between schemas + - correct string lengths for strings with unicode pairs (can be turned off) + - [formats](#formats) defined by JSON Schema draft 4 standard and custom formats (can be turned off) + - [validates schemas against meta-schema](#api-validateschema) +- supports [browsers](#using-in-browser) and nodejs 0.10-6.x +- [asynchronous loading](#asynchronous-compilation) of referenced schemas during compilation +- "All errors" validation mode with [option allErrors](#options) +- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages +- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package +- [filtering data](#filtering-data) from additional properties +- [assigning defaults](#assigning-defaults) to missing properties and items +- [coercing data](#coercing-data-types) to the types specified in `type` keywords +- [custom keywords](#defining-custom-keywords) +- keywords `switch`, `constant`, `contains`, `patternGroups`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [option v5](#options) +- [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) for schemas using v5 keywords +- [v5 $data reference](#data-reference) to use values from the validated data as values for the schema keywords +- [asynchronous validation](#asynchronous-validation) of custom formats and keywords + +Currently Ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript). + + +## Install + +``` +npm install ajv +``` + +To install a stable beta version [5.0.4](https://github.com/epoberezkin/ajv/releases/tag/5.0.4-beta.3) (see [migration guide from 4.x.x](https://github.com/epoberezkin/ajv/releases/tag/5.0.1-beta.0)): + +``` +npm install ajv@^5.0.4-beta +``` + + +## Getting started + +Try it in the node REPL: https://tonicdev.com/npm/ajv + + +The fastest validation call: + +```javascript +var Ajv = require('ajv'); +var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} +var validate = ajv.compile(schema); +var valid = validate(data); +if (!valid) console.log(validate.errors); +``` + +or with less code + +```javascript +// ... +var valid = ajv.validate(schema, data); +if (!valid) console.log(ajv.errors); +// ... +``` + +or + +```javascript +// ... +ajv.addSchema(schema, 'mySchema'); +var valid = ajv.validate('mySchema', data); +if (!valid) console.log(ajv.errorsText()); +// ... +``` + +See [API](#api) and [Options](#options) for more details. + +Ajv compiles schemas to functions and caches them in all cases (using schema stringified with [json-stable-stringify](https://github.com/substack/json-stable-stringify) as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. + +The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). + +__Please note__: every time validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) + + +## Using in browser + +You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. + +If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). + +Then you need to load Ajv in the browser: +```html + +``` + +This bundle can be used with different module systems or creates global `Ajv` if no module system is found. + +The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). + +Ajv is tested with these browsers: + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) + +__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/epoberezkin/ajv/issues/234)). + + +## Command line interface + +CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports: + +- compiling JSON-schemas to test their validity +- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack)) +- validating data file(s) against JSON-schema +- testing expected validity of data against JSON-schema +- referenced schemas +- custom meta-schemas +- files in JSON and JavaScript format +- all Ajv options +- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format + + +## Validation keywords + +Ajv supports all validation keywords from draft 4 of JSON-schema standard: + +- [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type) +- [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf +- [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format +- [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems +- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minproperties, required, properties, patternProperties, additionalProperties, dependencies +- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, not, oneOf, anyOf, allOf + +With option `v5: true` Ajv also supports all validation keywords and [$data reference](#data-reference) from [v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON-schema standard: + +- [switch](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#switch-v5-proposal) - conditional validation with a sequence of if/then clauses +- [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains-v5-proposal) - check that array contains a valid item +- [constant](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#constant-v5-proposal) - check that data is equal to some value +- [patternGroups](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patterngroups-v5-proposal) - a more powerful alternative to patternProperties +- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-v5-proposal) - like `required` but with patterns that some property should match. +- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-v5-proposal) - setting limits for date, time, etc. + +See [JSON-Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details. + + +## Formats + +The following formats are supported for string validation with "format" keyword: + +- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). +- _time_: time with optional time-zone. +- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). +- _uri_: full uri with optional protocol. +- _email_: email address. +- _hostname_: host name acording to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). +- _ipv4_: IP address v4. +- _ipv6_: IP address v6. +- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. +- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). +- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). +- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). + +There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `email`, and `hostname`. See [Options](#options) for details. + +You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. + +The option `unknownFormats` allows to change the behaviour in case an unknown format is encountered - Ajv can either ignore them (default now) or fail schema compilation (will be the default in 5.0.0). + +You can find patterns used for format validation and the sources that were used in [formats.js](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js). + + +## $data reference + +With `v5` option you can use values from the validated data as the values for the schema keywords. See [v5 proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works. + +`$data` reference is supported in the keywords: constant, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. + +The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). + +Examples. + +This schema requires that the value in property `smaller` is less or equal than the value in the property larger: + +```javascript +var schema = { + "properties": { + "smaller": { + "type": "number", + "maximum": { "$data": "1/larger" } + }, + "larger": { "type": "number" } + } +}; + +var validData = { + smaller: 5, + larger: 7 +}; +``` + +This schema requires that the properties have the same format as their field names: + +```javascript +var schema = { + "additionalProperties": { + "type": "string", + "format": { "$data": "0#" } + } +}; + +var validData = { + 'date-time': '1963-06-19T08:30:06.283185Z', + email: 'joe.bloggs@example.com' +} +``` + +`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `constant` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. + + +## $merge and $patch keywords + +With v5 option and the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON-schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). + +To add keywords `$merge` and `$patch` to Ajv instance use this code: + +```javascript +require('ajv-merge-patch')(ajv); +``` + +Examples. + +Using `$merge`: + +```json +{ + "$merge": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": { + "properties": { "q": { "type": "number" } } + } + } +} +``` + +Using `$patch`: + +```json +{ + "$patch": { + "source": { + "type": "object", + "properties": { "p": { "type": "string" } }, + "additionalProperties": false + }, + "with": [ + { "op": "add", "path": "/properties/q", "value": { "type": "number" } } + ] + } +} +``` + +The schemas above are equivalent to this schema: + +```json +{ + "type": "object", + "properties": { + "p": { "type": "string" }, + "q": { "type": "number" } + }, + "additionalProperties": false +} +``` + +The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. + +See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information. + + +## Defining custom keywords + +The advantages of using custom keywords are: + +- allow creating validation scenarios that cannot be expressed using JSON-Schema +- simplify your schemas +- help bringing a bigger part of the validation logic to your schemas +- make your schemas more expressive, less verbose and closer to your application domain +- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated + +If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). + +The concerns you have to be aware of when extending JSON-schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. + +You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. + +Ajv allows defining keywords with: +- validation function +- compilation function +- macro function +- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. + +Example. `range` and `exclusiveRange` keywords using compiled schema: + +```javascript +ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { + var min = sch[0]; + var max = sch[1]; + + return parentSchema.exclusiveRange === true + ? function (data) { return data > min && data < max; } + : function (data) { return data >= min && data <= max; } +} }); + +var schema = { "range": [2, 4], "exclusiveRange": true }; +var validate = ajv.compile(schema); +console.log(validate(2.01)); // true +console.log(validate(3.99)); // true +console.log(validate(2)); // false +console.log(validate(4)); // false +``` + +Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. + +See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details. + + +## Asynchronous compilation + +During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` method and `loadSchema` [option](#options). + +Example: + +```javascript +var ajv = new Ajv({ loadSchema: loadSchema }); + +ajv.compileAsync(schema, function (err, validate) { + if (err) return; + var valid = validate(data); +}); + +function loadSchema(uri, callback) { + request.json(uri, function(err, res, body) { + if (err || res.statusCode >= 400) + callback(err || new Error('Loading error: ' + res.statusCode)); + else + callback(null, body); + }); +} +``` + +__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. + + +## Asynchronous validation + +Example in node REPL: https://tonicdev.com/esp/ajv-asynchronous-validation + +You can define custom formats and keywords that perform validation asyncronously by accessing database or some service. You should add `async: true` in the keyword or format defnition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). + +If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. + +__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. + +Validation function for an asynchronous custom format/keyword should return a promise that resolves to `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to either [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) (default) that can be optionally transpiled with [regenerator](https://github.com/facebook/regenerator) or to [es7 async function](http://tc39.github.io/ecmascript-asyncawait/) that can be transpiled with [nodent](https://github.com/MatAtBread/nodent) or with regenerator as well. You can also supply any other transpiler as a function. See [Options](#options). + +The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both syncronous and asynchronous schemas. + +If you are using generators, the compiled validation function can be either wrapped with [co](https://github.com/tj/co) (default) or returned as generator function, that can be used directly, e.g. in [koa](http://koajs.com/) 1.0. `co` is a small library, it is included in Ajv (both as npm dependency and in the browser bundle). + +Generator functions are currently supported in Chrome, Firefox and node.js (0.11+); if you are using Ajv in other browsers or in older versions of node.js you should use one of available transpiling options. All provided async modes use global Promise class. If your platform does not have Promise you should use a polyfill that defines it. + +Validation result will be a promise that resolves to `true` or rejects with an exception `Ajv.ValidationError` that has the array of validation errors in `errors` property. + + +Example: + +```javascript +/** + * without "async" and "transpile" options (or with option {async: true}) + * Ajv will choose the first supported/installed option in this order: + * 1. native generator function wrapped with co + * 2. es7 async functions transpiled with nodent + * 3. es7 async functions transpiled with regenerator + */ + +var ajv = new Ajv; + +ajv.addKeyword('idExists', { + async: true, + type: 'number', + validate: checkIdExists +}); + + +function checkIdExists(schema, data) { + return knex(schema.table) + .select('id') + .where('id', data) + .then(function (rows) { + return !!rows.length; // true if record is found + }); +} + +var schema = { + "$async": true, + "properties": { + "userId": { + "type": "integer", + "idExists": { "table": "users" } + }, + "postId": { + "type": "integer", + "idExists": { "table": "posts" } + } + } +}; + +var validate = ajv.compile(schema); + +validate({ userId: 1, postId: 19 })) +.then(function (valid) { + // "valid" is always true here + console.log('Data is valid'); +}) +.catch(function (err) { + if (!(err instanceof Ajv.ValidationError)) throw err; + // data is invalid + console.log('Validation errors:', err.errors); +}); + +``` + +### Using transpilers with asyncronous validation functions. + +To use a transpiler you should separately install it (or load its bundle in the browser). + +Ajv npm package includes minified browser bundles of regenerator and nodent in dist folder. + + +#### Using nodent + +```javascript +var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' }); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + +`npm install nodent` or use `nodent.min.js` from dist folder of npm package. + + +#### Using regenerator + +```javascript +var ajv = new Ajv({ /* async: 'es7', */ transpile: 'regenerator' }); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + +`npm install regenerator` or use `regenerator.min.js` from dist folder of npm package. + + +#### Using other transpilers + +```javascript +var ajv = new Ajv({ async: 'es7', transpile: transpileFunc }); +var validate = ajv.compile(schema); // transpiled es7 async function +validate(data).then(successFunc).catch(errorFunc); +``` + +See [Options](#options). + + +#### Comparison of async modes + +|mode|transpile
speed*|run-time
speed*|bundle
size| +|---|:-:|:-:|:-:| +|generators
(native)|-|1.0|-| +|es7.nodent|1.35|1.1|183Kb| +|es7.regenerator|1.0|2.7|322Kb| +|regenerator|1.0|3.2|322Kb| + +\* Relative performance in node v.4, smaller is better. + +[nodent](https://github.com/MatAtBread/nodent) has several advantages: + +- much smaller browser bundle than regenerator +- almost the same performance of generated code as native generators in nodejs and the latest Chrome +- much better performace than native generators in other browsers +- works in IE 9 (regenerator does not) + +[regenerator](https://github.com/facebook/regenerator) is a more widely adopted alternative. + + +## Filtering data + +With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. + +This option modifies original data. + +Example: + +```javascript +var ajv = new Ajv({ removeAdditional: true }); +var schema = { + "additionalProperties": false, + "properties": { + "foo": { "type": "number" }, + "bar": { + "additionalProperties": { "type": "number" }, + "properties": { + "baz": { "type": "string" } + } + } + } +} + +var data = { + "foo": 0, + "additional1": 1, // will be removed; `additionalProperties` == false + "bar": { + "baz": "abc", + "additional2": 2 // will NOT be removed; `additionalProperties` != false + }, +} + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } +``` + +If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. + +If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). + +__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: + +```json +{ + "type": "object", + "oneOf": [ + { + "properties": { + "foo": { "type": "string" } + }, + "required": [ "foo" ], + "additionalProperties": false + }, + { + "properties": { + "bar": { "type": "integer" } + }, + "required": [ "bar" ], + "additionalProperties": false + } + ] +} +``` + +The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. + +With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). + +While this behaviour is unexpected (issues [#129](https://github.com/epoberezkin/ajv/issues/129), [#134](https://github.com/epoberezkin/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: + +```json +{ + "type": "object", + "properties": { + "foo": { "type": "string" }, + "bar": { "type": "integer" } + }, + "additionalProperties": false, + "oneOf": [ + { "required": [ "foo" ] }, + { "required": [ "bar" ] } + ] +} +``` + +The schema above is also more efficient - it will compile into a faster function. + + +## Assigning defaults + +With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. + +This option modifies original data. + +__Please note__: by default the default value is inserted in the generated validation code as a literal (starting from v4.0), so the value inserted in the data will be the deep clone of the default in the schema. + +If you need to insert the default value in the data by reference pass the option `useDefaults: "shared"`. + +Inserting defaults by reference can be faster (in case you have an object in `default`) and it allows to have dynamic values in defaults, e.g. timestamp, without recompiling the schema. The side effect is that modifying the default value in any validated data instance will change the default in the schema and in other validated data instances. See example 3 below. + + +Example 1 (`default` in `properties`): + +```javascript +var ajv = new Ajv({ useDefaults: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "string", "default": "baz" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": 1 }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": "baz" } +``` + +Example 2 (`default` in `items`): + +```javascript +var schema = { + "type": "array", + "items": [ + { "type": "number" }, + { "type": "string", "default": "foo" } + ] +} + +var data = [ 1 ]; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // [ 1, "foo" ] +``` + +Example 3 (inserting "defaults" by reference): + +```javascript +var ajv = new Ajv({ useDefaults: 'shared' }); + +var schema = { + properties: { + foo: { + default: { bar: 1 } + } + } +} + +var validate = ajv.compile(schema); + +var data = {}; +console.log(validate(data)); // true +console.log(data); // { foo: { bar: 1 } } + +data.foo.bar = 2; + +var data2 = {}; +console.log(validate(data2)); // true +console.log(data2); // { foo: { bar: 2 } } +``` + +`default` keywords in other cases are ignored: + +- not in `properties` or `items` subschemas +- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42)) +- in `if` subschema of v5 `switch` keyword +- in schemas generated by custom macro keywords + + +## Coercing data types + +When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. + +This option modifies original data. + +__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. + + +Example 1: + +```javascript +var ajv = new Ajv({ coerceTypes: true }); +var schema = { + "type": "object", + "properties": { + "foo": { "type": "number" }, + "bar": { "type": "boolean" } + }, + "required": [ "foo", "bar" ] +}; + +var data = { "foo": "1", "bar": "false" }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": 1, "bar": false } +``` + +Example 2 (array coercions): + +```javascript +var ajv = new Ajv({ coerceTypes: 'array' }); +var schema = { + "properties": { + "foo": { "type": "array", "items": { "type": "number" } }, + "bar": { "type": "boolean" } + } +}; + +var data = { "foo": "1", "bar": ["false"] }; + +var validate = ajv.compile(schema); + +console.log(validate(data)); // true +console.log(data); // { "foo": [1], "bar": false } +``` + +The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). + +See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details. + + +## API + +##### new Ajv(Object options) -> Object + +Create Ajv instance. + +All the instance methods below are bound to the instance, so they can be used without the instance. + + +##### .compile(Object schema) -> Function<Object data> + +Generate validating function and cache the compiled schema for future use. + +Validating function returns boolean and has properties `errors` with the errors from the last validation (`null` if there were no errors) and `schema` with the reference to the original schema. + +Unless the option `validateSchema` is false, the schema will be validated against meta-schema and if schema is invalid the error will be thrown. See [options](#options). + + +##### .compileAsync(Object schema, Function callback) + +Asyncronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. Callback will always be called with 2 parameters: error (or null) and validating function. Error will be not null in the following cases: + +- missing schema can't be loaded (`loadSchema` calls callback with error). +- the schema containing missing reference is loaded, but the reference cannot be resolved. +- schema (or some referenced schema) is invalid. + +The function compiles schema and loads the first missing schema multiple times, until all missing schemas are loaded. + +See example in [Asynchronous compilation](#asynchronous-compilation). + + +##### .validate(Object schema|String key|String ref, data) -> Boolean + +Validate data using passed schema (it will be compiled and cached). + +Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. + +Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). + +__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. + +If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). + + +##### .addSchema(Array<Object>|Object schema [, String key]) + +Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. + +Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. + +Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. + + +Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. + +Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. + +By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. + + +##### .addMetaSchema(Array<Object>|Object schema [, String key]) + +Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). + +There is no need to explicitly add draft 4 meta schema (http://json-schema.org/draft-04/schema and http://json-schema.org/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. + +With option `v5: true` [meta-schema that includes v5 keywords](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json) also added. + + +##### .validateSchema(Object schema) -> Boolean + +Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON-Schema standard. + +By default this method is called automatically when the schema is added, so you rarely need to use it directly. + +If schema doesn't have `$schema` property it is validated against draft 4 meta-schema (option `meta` should not be false) or against [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) if option `v5` is true. + +If schema has `$schema` property then the schema with this id (that should be previously added) is used to validate passed schema. + +Errors will be available at `ajv.errors`. + + +##### .getSchema(String key) -> Function<Object data> + +Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). Returned validating function has `schema` property with the reference to the original schema. + + +##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) + +Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. + +Schema can be removed using: +- key passed to `addSchema` +- it's full reference (id) +- RegExp that should match schema id or key (meta-schemas won't be removed) +- actual schema object that will be stable-stringified to remove schema from cache + +If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. + + +##### .addFormat(String name, String|RegExp|Function|Object format) + +Add custom format to validate strings. It can also be used to replace pre-defined formats for Ajv instance. + +Strings are converted to RegExp. + +Function should return validation result as `true` or `false`. + +If object is passed it should have properties `validate`, `compare` and `async`: + +- _validate_: a string, RegExp or a function as described above. +- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (from [v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) - `v5` option should be used). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. +- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. + +Custom formats can be also added via `formats` option. + + +##### .addKeyword(String keyword, Object definition) + +Add custom validation keyword to Ajv instance. + +Keyword should be different from all standard JSON schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. + +Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. +It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. + +Example Keywords: +- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. +- `"example"`: valid, but not recommended as it could collide with future versions of JSON schema etc. +- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword + +Keyword definition is an object with the following properties: + +- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. +- _validate_: validating function +- _compile_: compiling function +- _macro_: macro function +- _inline_: compiling function that returns code (as string) +- _schema_: an optional `false` value used with "validate" keyword to not pass schema +- _metaSchema_: an optional meta-schema for keyword schema +- _modifying_: `true` MUST be passed if keyword modifies data +- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. +- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). +- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. +- _errors_: an optional boolean indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. + +_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. + +__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. + +See [Defining custom keywords](#defining-custom-keywords) for more details. + + +##### .getKeyword(String keyword) -> Object|Boolean + +Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. + + +##### .removeKeyword(String keyword) + +Removes custom or pre-defined keyword so you can redefine them. + +While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. + +__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. + + +##### .errorsText([Array<Object> errors [, Object options]]) -> String + +Returns the text with all errors in a String. + +Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). + + +## Options + +Defaults: + +```javascript +{ + // validation and reporting options: + v5: false, + allErrors: false, + verbose: false, + jsonPointers: false, + uniqueItems: true, + unicode: true, + format: 'fast', + formats: {}, + unknownFormats: 'ignore', + schemas: {}, + // referenced schema options: + missingRefs: true, + extendRefs: true, + loadSchema: undefined, // function(uri, cb) { /* ... */ cb(err, schema); }, + // options to modify validated data: + removeAdditional: false, + useDefaults: false, + coerceTypes: false, + // asynchronous validation options: + async: undefined, + transpile: undefined, + // advanced options: + meta: true, + validateSchema: true, + addUsedSchema: true, + inlineRefs: true, + passContext: false, + loopRequired: Infinity, + ownProperties: false, + multipleOfPrecision: false, + errorDataPath: 'object', + sourceCode: true, + messages: true, + beautify: false, + cache: new Cache +} +``` + +##### Validation and reporting options + +- _v5_: add keywords `switch`, `constant`, `contains`, `patternGroups`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals). With this option added schemas without `$schema` property are validated against [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#). `false` by default. +- _allErrors_: check all rules collecting all errors. Default is to return after the first error. +- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). +- _jsonPointers_: set `dataPath` propery of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. +- _uniqueItems_: validate `uniqueItems` keyword (true by default). +- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. +- _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. +- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. +- _unknownFormats_: handling of unknown formats. Option values: + - `true` (will be default in 5.0.0) - if the unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [v5 $data reference](#data-reference) and it is unknown the validation will fail. + - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if some other unknown format is used. If `format` keyword value is [v5 $data reference](#data-reference) and it is not in this array the validation will fail. + - `"ignore"` (default now) - to log warning during schema compilation and always pass validation. This option is not recommended, as it allows to mistype format name. This behaviour is required by JSON-schema specification. +- _schemas_: an array or object of schemas that will be added to the instance. If the order is important, pass array. In this case schemas must have IDs in them. Otherwise the object can be passed - `addSchema(value, key)` will be called for each schema in this object. + + +##### Referenced schema options + +- _missingRefs_: handling of missing referenced schemas. Option values: + - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). + - `"ignore"` - to log error during compilation and always pass validation. + - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. +- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: + - `true` (default) - validate all keywords in the schemas with `$ref`. + - `"ignore"` - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. + - `"fail"` - if other validation keywords are used together with `$ref` the exception will be throw when the schema is compiled. +- _loadSchema_: asynchronous function that will be used to load remote schemas when the method `compileAsync` is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept 2 parameters: remote schema uri and node-style callback. See example in [Asynchronous compilation](#asynchronous-compilation). + + +##### Options to modify validated data + +- _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: + - `false` (default) - not to remove additional properties + - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). + - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. + - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). +- _useDefaults_: replace missing properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: + - `false` (default) - do not use defaults + - `true` - insert defaults by value (safer and slower, object literal is used). + - `"shared"` - insert defaults by reference (faster). If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. +- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values: + - `false` (default) - no type coercion. + - `true` - coerce scalar data types. + - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). + + +##### Asynchronous validation options + +- _async_: determines how Ajv compiles asynchronous schemas (see [Asynchronous validation](#asynchronous-validation)) to functions. Option values: + - `"*"` / `"co*"` - compile to generator function ("co*" - wrapped with `co.wrap`). If generators are not supported and you don't provide `transpile` option, the exception will be thrown when Ajv instance is created. + - `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `transpile` option. Currently only MS Edge 13 with flag supports es7 async functions according to [compatibility table](http://kangax.github.io/compat-table/es7/)). + - `true` - if transpile option is not passed Ajv will choose the first supported/installed async/transpile modes in this order: "co*" (native generator with co.wrap), "es7"/"nodent", "co*"/"regenerator" during the creation of the Ajv instance. If none of the options is available the exception will be thrown. + - `undefined`- Ajv will choose the first available async mode in the same way as with `true` option but when the first asynchronous schema is compiled. +- _transpile_: determines whether Ajv transpiles compiled asynchronous validation function. Option values: + - `"nodent"` - transpile with [nodent](https://github.com/MatAtBread/nodent). If nodent is not installed, the exception will be thrown. nodent can only transpile es7 async functions; it will enforce this mode. + - `"regenerator"` - transpile with [regenerator](https://github.com/facebook/regenerator). If regenerator is not installed, the exception will be thrown. + - a function - this function should accept the code of validation function as a string and return transpiled code. This option allows you to use any other transpiler you prefer. + + +##### Advanced options + +- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). With option `v5: true` [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) will be added as well. If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. +- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can either be http://json-schema.org/schema or http://json-schema.org/draft-04/schema or absent (draft-4 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: + - `true` (default) - if the validation fails, throw the exception. + - `"log"` - if the validation fails, log error. + - `false` - skip schema validation. +- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `id` property that doesn't start with "#". If `id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `id` uniqueness check when these methods are used. This option does not affect `addSchema` method. +- _inlineRefs_: Affects compilation of referenced schemas. Option values: + - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. + - `false` - to not inline referenced schemas (they will be compiled as separate functions). + - integer number - to limit the maximum number of keywords of the schema that will be inlined. +- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. +- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. +- _ownProperties_: by default ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. +- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). +- _errorDataPath_: set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. +- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). +- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)). +- _beautify_: format the generated function with [js-beautify](https://github.com/beautify-web/js-beautify) (the validating function is generated without line-breaks). `npm install js-beautify` to use this option. `true` or js-beautify options can be passed. +- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. + + +## Validation errors + +In case of validation failure Ajv assigns the array of errors to `.errors` property of validation function (or to `.errors` property of Ajv instance in case `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation) the returned promise is rejected with the exception of the class `Ajv.ValidationError` that has `.errors` poperty. + + +### Error objects + +Each error is an object with the following properties: + +- _keyword_: validation keyword. +- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). +- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. +- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package). See below for parameters set by all keywords. +- _message_: the standard error message (can be excluded with option `messages` set to false). +- _schema_: the schema of the keyword (added with `verbose` option). +- _parentSchema_: the schema containing the keyword (added with `verbose` option) +- _data_: the data validated by the keyword (added with `verbose` option). + + +### Error parameters + +Properties of `params` object in errors depend on the keyword that failed validation. + +- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). +- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). +- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). +- `patternGroups` (with v5 option) - properties: + - `pattern` + - `reason` ("minimum"/"maximum"), + - `limit` (max/min allowed number of properties matching number) +- `dependencies` - properties: + - `property` (dependent property), + - `missingProperty` (required missing dependency - only the first one is reported currently) + - `deps` (required dependencies, comma separated list as a string), + - `depsCount` (the number of required dependedncies). +- `format` - property `format` (the schema of the keyword). +- `maximum`, `minimum` - properties: + - `limit` (number, the schema of the keyword), + - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), + - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") +- `multipleOf` - property `multipleOf` (the schema of the keyword) +- `pattern` - property `pattern` (the schema of the keyword) +- `required` - property `missingProperty` (required property that is missing). +- `patternRequired` (with v5 option) - property `missingPattern` (required pattern that did not match any property). +- `type` - property `type` (required type(s), a string, can be a comma-separated list) +- `uniqueItems` - properties `i` and `j` (indices of duplicate items). +- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). +- `$ref` - property `ref` with the referenced schema URI. +- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). + + +## Related packages + +- [ajv-cli](https://github.com/epoberezkin/ajv-cli) - command line interface for Ajv +- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages +- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch from v5 proposals. +- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - several custom keywords that can be used with Ajv (typeof, instanceof, range, propertyNames) + + +## Some packages using Ajv + +- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser +- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services +- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition +- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator +- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org +- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON-schema http://jsonschemalint.com +- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for node.js +- [table](https://github.com/gajus/table) - formats data into a string table +- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser +- [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content +- [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation +- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation +- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages +- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema +- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON-schema with expect in mocha tests +- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON-Schema +- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file +- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app +- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter +- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages + + +## Tests + +``` +npm install +git submodule update --init +npm test +``` + +## Contributing + +All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. + +`npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder. + +`npm run watch` - automatically compiles templates when files in dot folder change + +Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md) + + +## Changes history + +See https://github.com/epoberezkin/ajv/releases + +__Please note__: [Changes in version 5.0.1-beta](https://github.com/epoberezkin/ajv/releases/tag/5.0.1-beta.0). + +[Changes in version 4.6.0](https://github.com/epoberezkin/ajv/releases/tag/4.6.0). + +[Changes in version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0). + +[Changes in version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0). + +[Changes in version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0). + + +## License + +[MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE) diff --git a/node_modules/ajv/dist/ajv.bundle.js b/node_modules/ajv/dist/ajv.bundle.js new file mode 100644 index 000000000..b624d1367 --- /dev/null +++ b/node_modules/ajv/dist/ajv.bundle.js @@ -0,0 +1,8023 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Ajv = f()}})(function(){var define,module,exports;return (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= 1 && month <= 12 && day >= 1 && day <= DAYS[month]; +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +function hostname(str) { + // https://tools.ietf.org/html/rfc1034#section-3.5 + // https://tools.ietf.org/html/rfc1123#section-2 + return str.length <= 255 && HOSTNAME.test(str); +} + + +var NOT_URI_FRAGMENT = /\/|\:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +function regex(str) { + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} + + +function compareDate(d1, d2) { + if (!(d1 && d2)) return; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + if (d1 === d2) return 0; +} + + +function compareTime(t1, t2) { + if (!(t1 && t2)) return; + t1 = t1.match(TIME); + t2 = t2.match(TIME); + if (!(t1 && t2)) return; + t1 = t1[1] + t1[2] + t1[3] + (t1[4]||''); + t2 = t2[1] + t2[2] + t2[3] + (t2[4]||''); + if (t1 > t2) return 1; + if (t1 < t2) return -1; + if (t1 === t2) return 0; +} + + +function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return; + dt1 = dt1.split(DATE_TIME_SEPARATOR); + dt2 = dt2.split(DATE_TIME_SEPARATOR); + var res = compareDate(dt1[0], dt2[0]); + if (res === undefined) return; + return res || compareTime(dt1[1], dt2[1]); +} + +},{"./util":11}],6:[function(require,module,exports){ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , stableStringify = require('json-stable-stringify') + , async = require('../async'); + +var beautify; + +function loadBeautify(){ + if (beautify === undefined) { + var name = 'js-beautify'; + try { beautify = require(name).js_beautify; } + catch(e) { beautify = false; } + } +} + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var co = require('co'); +var ucs2length = util.ucs2length; +var equal = require('./equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = require('./validation_error'); + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = [] + , keepSourceCode = opts.sourceCode !== false; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (keepSourceCode) cv.sourceCode = v.sourceCode; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + function callValidate() { + var validate = compilation.validate; + var result = validate.apply(null, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + if ($async && !opts.transpile) async.setup(opts); + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.beautify) { + loadBeautify(); + /* istanbul ignore else */ + if (beautify) sourceCode = beautify(sourceCode, opts.beautify); + else console.error('"npm install js-beautify" to use beautify option'); + } + // console.log('\n\n\n *** \n', sourceCode); + var validate, validateCode + , transpile = opts._transpileFunc; + try { + validateCode = $async && transpile + ? transpile(sourceCode) + : sourceCode; + + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'co', + 'equal', + 'ucs2length', + 'ValidationError', + validateCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + co, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + console.error('Error compiling schema, function code:', validateCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (keepSourceCode) validate.sourceCode = sourceCode; + if (opts.sourceCode === true) { + validate.source = { + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (!v) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v) { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + var validateSchema = rule.definition.validateSchema; + if (validateSchema && self._opts.validateSchema !== false) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') console.error(message); + else throw new Error(message); + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + } + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; + +},{}],11:[function(require,module,exports){ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + cleanUpCode: cleanUpCode, + cleanUpVarErrors: cleanUpVarErrors, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + stableStringify: require('json-stable-stringify'), + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i', + $result = 'result' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op); + if (!$exclusive) { + out += '='; + } + out += ' 0;'; + } + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '}'; + return out; +} + +},{}],14:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limit(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<'; + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp); + if ($exclusive) { + out += '='; + } + out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {'; + } + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schema) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],15:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitItems(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'less'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],16:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitLength(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],17:[function(require,module,exports){ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'less'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],18:[function(require,module,exports){ +'use strict'; +module.exports = function generate_allOf(it, $keyword) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + out = it.util.cleanUpCode(out); + return out; +} + +},{}],19:[function(require,module,exports){ +'use strict'; +module.exports = function generate_anyOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return it.util.schemaHasRules($sch, it.RULES.all); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],20:[function(require,module,exports){ +'use strict'; +module.exports = function generate_constant(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('constant') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + return out; +} + +},{}],21:[function(require,module,exports){ +'use strict'; +module.exports = function generate_custom(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($validateSchema) { + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {'; + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += '' + (it.yieldAwait); + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + if ($validateSchema) { + out += ' }'; + } + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} + +},{}],26:[function(require,module,exports){ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schema) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],27:[function(require,module,exports){ +'use strict'; +module.exports = function generate_not(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} + +},{}],28:[function(require,module,exports){ +'use strict'; +module.exports = function generate_oneOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;'; + var $currentBaseId = $it.baseId; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + +},{}],29:[function(require,module,exports){ +'use strict'; +module.exports = function generate_pattern(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + +},{}],30:[function(require,module,exports){ +'use strict'; +module.exports = function generate_patternRequired(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $key = 'key' + $lvl, + $matched = 'patternMatched' + $lvl, + $closingBraces = '', + $ownProperties = it.opts.ownProperties; + out += 'var ' + ($valid) + ' = true;'; + var arr1 = $schema; + if (arr1) { + var $pProperty, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $pProperty = arr1[i1 += 1]; + out += ' var ' + ($matched) + ' = false; for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } '; + var $missingPattern = it.util.escapeQuotes($pProperty); + out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + out += '' + ($closingBraces); + return out; +} + +},{}],31:[function(require,module,exports){ +'use strict'; +module.exports = function generate_properties(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt; + var $schemaKeys = Object.keys($schema || {}), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); + if (it.opts.v5) { + var $pgProperties = it.schema.patternGroups || {}, + $pgPropertyKeys = Object.keys($pgProperties); + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($checkAdditional) { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 5) { + out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) { + var arr3 = $pgPropertyKeys; + if (arr3) { + var $pgProperty, $i = -1, + l3 = arr3.length - 1; + while ($i < l3) { + $pgProperty = arr3[$i += 1]; + out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have additional properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr4 = $schemaKeys; + if (arr4) { + var $propertyKey, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $propertyKey = arr4[i4 += 1]; + var $sch = $schema[$propertyKey]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + var arr5 = $pPropertyKeys; + if (arr5) { + var $pProperty, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $pProperty = arr5[i5 += 1]; + var $sch = $pProperties[$pProperty]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (it.opts.v5) { + var arr6 = $pgPropertyKeys; + if (arr6) { + var $pgProperty, i6 = -1, + l6 = arr6.length - 1; + while (i6 < l6) { + $pgProperty = arr6[i6 += 1]; + var $pgSchema = $pgProperties[$pgProperty], + $sch = $pgSchema.schema; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema'; + $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema'; + out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + var $pgMin = $pgSchema.minimum, + $pgMax = $pgSchema.maximum; + if ($pgMin !== undefined || $pgMax !== undefined) { + out += ' var ' + ($valid) + ' = true; '; + var $currErrSchemaPath = $errSchemaPath; + if ($pgMin !== undefined) { + var $limit = $pgMin, + $reason = 'minimum', + $moreOrLess = 'less'; + out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($pgMax !== undefined) { + out += ' else '; + } + } + if ($pgMax !== undefined) { + var $limit = $pgMax, + $reason = 'maximum', + $moreOrLess = 'more'; + out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} + +},{}],32:[function(require,module,exports){ +'use strict'; +module.exports = function generate_ref(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); + if ($refVal === undefined) { + var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId; + if (it.opts.missingRefs == 'fail') { + console.log($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; + } + if (it.opts.verbose) { + out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + console.log($message); + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + var $error = new Error($message); + $error.missingRef = it.resolve.url(it.baseId, $schema); + $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef)); + throw $error; + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + ($code) + ' '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + } + } else { + $async = $refVal.$async === true; + $refCode = $refVal.code; + } + } + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; + } else { + out += ' ' + ($refCode) + '( '; + } + out += ' ' + ($data) + ', (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); + out += ' try { '; + if ($breakOnError) { + out += 'var ' + ($valid) + ' ='; + } + out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + } + } else { + out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' else { '; + } + } + } + return out; +} + +},{}],33:[function(require,module,exports){ +'use strict'; +module.exports = function generate_required(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var _$property, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + _$property = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty(_$property); + out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $reqProperty, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $reqProperty = arr3[i3 += 1]; + var $prop = it.util.getProperty($reqProperty), + $missingProperty = it.util.escapeQuotes($reqProperty); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); + } + out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} + +},{}],34:[function(require,module,exports){ +'use strict'; +module.exports = function generate_switch(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $ifPassed = 'ifPassed' + it.level, + $currentBaseId = $it.baseId, + $shouldContinue; + out += 'var ' + ($ifPassed) + ';'; + var arr1 = $schema; + if (arr1) { + var $sch, $caseIndex = -1, + l1 = arr1.length - 1; + while ($caseIndex < l1) { + $sch = arr1[$caseIndex += 1]; + if ($caseIndex && !$shouldContinue) { + out += ' if (!' + ($ifPassed) + ') { '; + $closingBraces += '}'; + } + if ($sch.if && it.util.schemaHasRules($sch.if, it.RULES.all)) { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + $it.schema = $sch.if; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } '; + } else { + out += ' ' + ($ifPassed) + ' = true; '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + } + $shouldContinue = $sch.continue + } + } + out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + '; '; + out = it.util.cleanUpCode(out); + return out; +} + +},{}],35:[function(require,module,exports){ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + +},{}],36:[function(require,module,exports){ +'use strict'; +module.exports = function generate_validate(it, $keyword) { + var out = ''; + var $async = it.schema.$async === true; + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.root.schema.id); + it.baseId = it.baseId || it.rootId; + if ($async) { + it.async = true; + var $es7 = it.opts.async == 'es7'; + it.yieldAwait = $es7 ? 'await' : 'yield'; + } + delete it.isTop; + it.dataPathArr = [undefined]; + out += ' var validate = '; + if ($async) { + if ($es7) { + out += ' (async function '; + } else { + if (it.opts.async == 'co*') { + out += 'co.wrap'; + } + out += '(function* '; + } + } else { + out += ' (function '; + } + out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data;'; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + if ($coerceToTypes) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; + } + out += ' var ' + ($coerced) + ' = undefined; '; + var $bracesCoercion = ''; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($i) { + out += ' if (' + ($coerced) + ' === undefined) { '; + $bracesCoercion += '}'; + } + if (it.opts.coerceTypes == 'array' && $type != 'array') { + out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; + } + if ($type == 'string') { + out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } '; + } + } + var $refKeywords; + if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"'); + } else if (it.opts.extendRefs == 'ignore') { + $refKeywords = false; + console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } else if (it.opts.extendRefs !== true) { + console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour'); + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { '; + } + if (it.opts.useDefaults && !it.compositeRule) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + out += ' ' + ($rule.code(it, $rule.keyword)) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + var $typeChecked = true; + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($typeSchema && !$typeChecked && !$coerceToTypes) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return true; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }); return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + out = it.util.cleanUpCode(out); + if ($top && $breakOnError) { + out = it.util.cleanUpVarErrors(out, $async); + } + + function $shouldUseGroup($rulesGroup) { + for (var i = 0; i < $rulesGroup.rules.length; i++) + if ($shouldUseRule($rulesGroup.rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length))); + } + return out; +} + +},{}],37:[function(require,module,exports){ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i; +var customRuleCode = require('./dotjs/custom'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword +}; + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + if (definition.macro && definition.valid !== undefined) + throw new Error('"valid" option cannot be used with macro keywords'); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + var i, len = dataType.length; + for (i=0; i 2) res = slice.call(arguments, 1); + resolve(res); + }); + }); +} + +/** + * Convert an array of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Array} obj + * @return {Promise} + * @api private + */ + +function arrayToPromise(obj) { + return Promise.all(obj.map(toPromise, this)); +} + +/** + * Convert an object of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Object} obj + * @return {Promise} + * @api private + */ + +function objectToPromise(obj){ + var results = new obj.constructor(); + var keys = Object.keys(obj); + var promises = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var promise = toPromise.call(this, obj[key]); + if (promise && isPromise(promise)) defer(promise, key); + else results[key] = obj[key]; + } + return Promise.all(promises).then(function () { + return results; + }); + + function defer(promise, key) { + // predefine the key in the result + results[key] = undefined; + promises.push(promise.then(function (res) { + results[key] = res; + })); + } +} + +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isPromise(obj) { + return 'function' == typeof obj.then; +} + +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGenerator(obj) { + return 'function' == typeof obj.next && 'function' == typeof obj.throw; +} + +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ +function isGeneratorFunction(obj) { + var constructor = obj.constructor; + if (!constructor) return false; + if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; + return isGenerator(constructor.prototype); +} + +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ + +function isObject(val) { + return Object == val.constructor; +} + +},{}],42:[function(require,module,exports){ +var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); + +module.exports = function (obj, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var space = opts.space || ''; + if (typeof space === 'number') space = Array(space+1).join(' '); + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + var replacer = opts.replacer || function(key, value) { return value; }; + + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); + + var seen = []; + return (function stringify (parent, key, node, level) { + var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; + var colonSeparator = space ? ': ' : ':'; + + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + + node = replacer.call(parent, key, node); + + if (node === undefined) { + return; + } + if (typeof node !== 'object' || node === null) { + return json.stringify(node); + } + if (isArray(node)) { + var out = []; + for (var i = 0; i < node.length; i++) { + var item = stringify(node, i, node[i], level+1) || json.stringify(null); + out.push(indent + space + item); + } + return '[' + out.join(',') + indent + ']'; + } + else { + if (seen.indexOf(node) !== -1) { + if (cycles) return json.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } + else seen.push(node); + + var keys = objectKeys(node).sort(cmp && cmp(node)); + var out = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node, key, node[key], level+1); + + if(!value) continue; + + var keyValue = json.stringify(key) + + colonSeparator + + value; + ; + out.push(indent + space + keyValue); + } + seen.splice(seen.indexOf(node), 1); + return '{' + out.join(',') + indent + '}'; + } + })({ '': obj }, '', obj, 0); +}; + +var isArray = Array.isArray || function (x) { + return {}.toString.call(x) === '[object Array]'; +}; + +var objectKeys = Object.keys || function (obj) { + var has = Object.prototype.hasOwnProperty || function () { return true }; + var keys = []; + for (var key in obj) { + if (has.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"jsonify":43}],43:[function(require,module,exports){ +exports.parse = require('./lib/parse'); +exports.stringify = require('./lib/stringify'); + +},{"./lib/parse":44,"./lib/stringify":45}],44:[function(require,module,exports){ +var at, // The index of the current character + ch, // The current character + escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + }, + text, + + error = function (m) { + // Call error when something is wrong. + throw { + name: 'SyntaxError', + message: m, + at: at, + text: text + }; + }, + + next = function (c) { + // If a c parameter is provided, verify that it matches the current character. + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + + // Get the next character. When there are no more characters, + // return the empty string. + + ch = text.charAt(at); + at += 1; + return ch; + }, + + number = function () { + // Parse a number value. + var number, + string = ''; + + if (ch === '-') { + string = '-'; + next('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error("Bad number"); + } else { + return number; + } + }, + + string = function () { + // Parse a string value. + var hex, + i, + string = '', + uffff; + + // When parsing for string values, we must look for " and \ characters. + if (ch === '"') { + while (next()) { + if (ch === '"') { + next(); + return string; + } else if (ch === '\\') { + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + } else { + string += ch; + } + } + } + error("Bad string"); + }, + + white = function () { + +// Skip whitespace. + + while (ch && ch <= ' ') { + next(); + } + }, + + word = function () { + +// true, false, or null. + + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + } + error("Unexpected '" + ch + "'"); + }, + + value, // Place holder for the value function. + + array = function () { + +// Parse an array value. + + var array = []; + + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } + } + error("Bad array"); + }, + + object = function () { + +// Parse an object value. + + var key, + object = {}; + + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if (Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); + } + object[key] = value(); + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } + } + error("Bad object"); + }; + +value = function () { + +// Parse a JSON value. It could be an object, an array, a string, a number, +// or a word. + + white(); + switch (ch) { + case '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + return ch >= '0' && ch <= '9' ? number() : word(); + } +}; + +// Return the json_parse function. It will have access to all of the above +// functions and variables. + +module.exports = function (source, reviver) { + var result; + + text = source; + at = 0; + ch = ' '; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + + // If there is a reviver function, we recursively walk the new structure, + // passing each name/value pair to the reviver function for possible + // transformation, starting with a temporary root object that holds the result + // in an empty key. If there is not a reviver function, we simply return the + // result. + + return typeof reviver === 'function' ? (function walk(holder, key) { + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + }({'': result}, '')) : result; +}; + +},{}],45:[function(require,module,exports){ +var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + +function quote(string) { + // If the string contains no control characters, no quote characters, and no + // backslash characters, then we can safely slap some quotes around it. + // Otherwise we must also replace the offending characters with safe escape + // sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' ? c : + '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; +} + +function str(key, holder) { + // Produce a string from holder[key]. + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + + // If the value has a toJSON method, call it to obtain a replacement value. + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + + // If we were called with a replacer function, then call the replacer to + // obtain a replacement value. + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + + // What happens next depends on the value's type. + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + // JSON numbers must be finite. Encode non-finite numbers as null. + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + // If the value is a boolean or null, convert it to a string. Note: + // typeof null does not produce 'null'. The case is included here in + // the remote chance that this gets fixed someday. + return String(value); + + case 'object': + if (!value) return 'null'; + gap += indent; + partial = []; + + // Array.isArray + if (Object.prototype.toString.apply(value) === '[object Array]') { + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + + // Join all of the elements together, separated with commas, and + // wrap them in brackets. + v = partial.length === 0 ? '[]' : gap ? + '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : + '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + + // If the replacer is an array, use it to select the members to be + // stringified. + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + k = rep[i]; + if (typeof k === 'string') { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + else { + // Otherwise, iterate through all of the keys in the object. + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + + // Join all of the member texts together, separated with commas, + // and wrap them in braces. + + v = partial.length === 0 ? '{}' : gap ? + '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : + '{' + partial.join(',') + '}'; + gap = mind; + return v; + } +} + +module.exports = function (value, replacer, space) { + var i; + gap = ''; + indent = ''; + + // If the space parameter is a number, make an indent string containing that + // many spaces. + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + } + // If the space parameter is a string, it will be used as the indent string. + else if (typeof space === 'string') { + indent = space; + } + + // If there is a replacer, it must be a function or an array. + // Otherwise, throw an error. + rep = replacer; + if (replacer && typeof replacer !== 'function' + && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + + // Make a fake root object containing our value under the key of ''. + // Return the result of stringifying the value. + return str('', {'': value}); +}; + +},{}],46:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],47:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],48:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],49:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":47,"./encode":48}],50:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":51,"punycode":46,"querystring":49}],51:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],"ajv":[function(require,module,exports){ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , v5 = require('./v5') + , util = require('./compile/util') + , async = require('./async') + , co = require('co'); + +module.exports = Ajv; + +Ajv.prototype.compileAsync = async.compile; + +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.ValidationError = require('./compile/validation_error'); + +var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema'; +var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i; +function SCHEMA_URI_FORMAT_FUNC(str) { + return SCHEMA_URI_FORMAT.test(str); +} + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ]; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + var self = this; + + opts = this._opts = util.copy(opts) || {}; + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + + // this is done on purpose, so that methods are bound to the instance + // (without using bind) so that they can be used without the instance + this.validate = validate; + this.compile = compile; + this.addSchema = addSchema; + this.addMetaSchema = addMetaSchema; + this.validateSchema = validateSchema; + this.getSchema = getSchema; + this.removeSchema = removeSchema; + this.addFormat = addFormat; + this.errorsText = errorsText; + + this._addSchema = _addSchema; + this._compile = _compile; + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.async || opts.transpile) async.setup(opts); + if (opts.beautify === true) opts.beautify = { indent_size: 2 }; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + this._metaOpts = getMetaSchemaOptions(); + + if (opts.formats) addInitialFormats(); + addDraft4MetaSchema(); + if (opts.v5) v5.enable(this); + if (typeof opts.meta == 'object') addMetaSchema(opts.meta); + addInitialSchemas(); + + + /** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize. + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ + function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = _addSchema(schemaKeyRef); + v = schemaObj.validate || _compile(schemaObj); + } + + var valid = v(data); + if (v.$async === true) + return self._opts.async == '*' ? co(valid) : valid; + self.errors = v.errors; + return valid; + } + + + /** + * Create validating function for passed schema. + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ + function compile(schema, _meta) { + var schemaObj = _addSchema(schema, undefined, _meta); + return schemaObj.validate || _compile(schemaObj); + } + + + /** + * Adds schema to the instance. + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + */ + function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ + function errorsText(errors, options) { + errors = errors || self.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i=1&&t<=12&&a>=1&&a<=m[t]}function o(e,r){var t=e.match(v);if(!t)return!1;var a=t[1],s=t[2],o=t[3],i=t[5];return a<=23&&s<=59&&o<=59&&(!r||i)}function i(e){var r=e.split(b);return 2==r.length&&s(r[0])&&o(r[1],!0)}function n(e){return e.length<=255&&y.test(e)}function l(e){return w.test(e)&&g.test(e)}function c(e){try{return new RegExp(e),!0}catch(e){return!1}}function h(e,r){if(e&&r)return e>r?1:er?1:e=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:r,baseId:t},{index:a,compiling:!1})}function i(e,r,t){var a=n.call(this,e,r,t);a>=0&&this._compilations.splice(a,1)}function n(e,r,t){for(var a=0;a=55296&&r<=56319&&s=r)throw new Error("Cannot access property/index "+a+" levels up, current level is "+r);return t[r-a]}if(a>r)throw new Error("Cannot access data "+a+" levels up, current level is "+r);if(o="data"+(r-a||""),!s)return o}for(var n=o,c=s.split("/"),h=0;h",S="result"+s,$=e.opts.v5&&i&&i.$data;if($?(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+s):g=i,w){var x=e.util.getData(b.$data,o,e.dataPathArr),_="exclusive"+s,O="op"+s,R="' + "+O+" + '";a+=" var schemaExcl"+s+" = "+x+"; ",x="schemaExcl"+s,a+=" if (typeof "+x+" != 'boolean' && "+x+" !== undefined) { "+u+" = false; ";var t=E,I=I||[];I.push(a),a="",!1!==e.createErrors?(a+=" { keyword: '"+(t||"_formatExclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: '"+E+" should be boolean' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ";var A=a;a=I.pop(),a+=!e.compositeRule&&c?e.async?" throw new ValidationError(["+A+"]); ":" validate.errors = ["+A+"]; return false; ":" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c&&(p+="}",a+=" else { "),$&&(a+=" if ("+g+" === undefined) "+u+" = true; else if (typeof "+g+" != 'string') "+u+" = false; else { ",p+="}"),d&&(a+=" if (!"+y+") "+u+" = true; else { ",p+="}"),a+=" var "+S+" = "+y+"("+h+", ",a+=$?""+g:""+e.util.toQuotedString(i),a+=" ); if ("+S+" === undefined) "+u+" = false; var "+_+" = "+x+" === true; if ("+u+" === undefined) { "+u+" = "+_+" ? "+S+" "+j+" 0 : "+S+" "+j+"= 0; } if (!"+u+") var op"+s+" = "+_+" ? '"+j+"' : '"+j+"=';"}else{var _=!0===b,R=j;_||(R+="=");var O="'"+R+"'";$&&(a+=" if ("+g+" === undefined) "+u+" = true; else if (typeof "+g+" != 'string') "+u+" = false; else { ",p+="}"),d&&(a+=" if (!"+y+") "+u+" = true; else { ",p+="}"),a+=" var "+S+" = "+y+"("+h+", ",a+=$?""+g:""+e.util.toQuotedString(i),a+=" ); if ("+S+" === undefined) "+u+" = false; if ("+u+" === undefined) "+u+" = "+S+" "+j,_||(a+="="),a+=" 0;"}a+=p+"if (!"+u+") { ";var t=r,I=I||[];I.push(a),a="",!1!==e.createErrors?(a+=" { keyword: '"+(t||"_formatLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { comparison: "+O+", limit: ",a+=$?""+g:""+e.util.toQuotedString(i),a+=" , exclusive: "+_+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be "+R+' "',a+=$?"' + "+g+" + '":""+e.util.escapeQuotes(i),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=$?"validate.schema"+n:""+e.util.toQuotedString(i),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ";var A=a;return a=I.pop(),a+=!e.compositeRule&&c?e.async?" throw new ValidationError(["+A+"]); ":" validate.errors = ["+A+"]; return false; ":" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="}"}},{}],14:[function(e,r,t){"use strict";r.exports=function(e,r){var t,a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(i||""),f=e.opts.v5&&n&&n.$data;f?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;var d="maximum"==r,p=d?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[p],v=e.opts.v5&&m&&m.$data,y=d?"<":">",g=d?">":"<";if(v){var P=e.util.getData(m.$data,i,e.dataPathArr),E="exclusive"+o,b="op"+o,w="' + "+b+" + '";s+=" var schemaExcl"+o+" = "+P+"; ",P="schemaExcl"+o,s+=" var exclusive"+o+"; if (typeof "+P+" != 'boolean' && typeof "+P+" != 'undefined') { ";var t=p,j=j||[];j.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(t||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",!1!==e.opts.messages&&(s+=" , message: '"+p+" should be boolean' "),e.opts.verbose&&(s+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var S=s;s=j.pop(),s+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+S+"]); ":" validate.errors = ["+S+"]; return false; ":" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if( ",f&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ((exclusive"+o+" = "+P+" === true) ? "+u+" "+g+"= "+a+" : "+u+" "+g+" "+a+") || "+u+" !== "+u+") { var op"+o+" = exclusive"+o+" ? '"+y+"' : '"+y+"=';"}else{var E=!0===m,w=y;E||(w+="=");var b="'"+w+"'";s+=" if ( ",f&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+" "+g,E&&(s+="="),s+=" "+a+" || "+u+" !== "+u+") {"}var t=r,j=j||[];j.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(t||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { comparison: "+b+", limit: "+a+", exclusive: "+E+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+w+" ",s+=f?"' + "+a:n+"'"),e.opts.verbose&&(s+=" , schema: ",s+=f?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var S=s;return s=j.pop(),s+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+S+"]); ":" validate.errors = ["+S+"]; return false; ":" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",h&&(s+=" else { "),s}},{}],15:[function(e,r,t){"use strict";r.exports=function(e,r){var t,a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(i||""),f=e.opts.v5&&n&&n.$data;f?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;var d="maxItems"==r?">":"<";s+="if ( ",f&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+u+".length "+d+" "+a+") { ";var t=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(t||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==r?"more":"less",s+=" than ",s+=f?"' + "+a+" + '":""+n,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=f?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",h&&(s+=" else { "),s}},{}],16:[function(e,r,t){"use strict";r.exports=function(e,r){var t,a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(i||""),f=e.opts.v5&&n&&n.$data;f?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;var d="maxLength"==r?">":"<";s+="if ( ",f&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=!1===e.opts.unicode?" "+u+".length ":" ucs2length("+u+") ",s+=" "+d+" "+a+") { ";var t=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(t||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==r?"longer":"shorter",s+=" than ",s+=f?"' + "+a+" + '":""+n,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=f?"validate.schema"+l:""+n, +s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",h&&(s+=" else { "),s}},{}],17:[function(e,r,t){"use strict";r.exports=function(e,r){var t,a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(i||""),f=e.opts.v5&&n&&n.$data;f?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;var d="maxProperties"==r?">":"<";s+="if ( ",f&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+u+").length "+d+" "+a+") { ";var t=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(t||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==r?"more":"less",s+=" than ",s+=f?"' + "+a+" + '":""+n,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=f?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",h&&(s+=" else { "),s}},{}],18:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.schema[r],s=e.schemaPath+e.util.getProperty(r),o=e.errSchemaPath+"/"+r,i=!e.opts.allErrors,n=e.util.copy(e),l="";n.level++;var c="valid"+n.level,h=n.baseId,u=!0,f=a;if(f)for(var d,p=-1,m=f.length-1;p "+$+") { ";var _=c+"["+$+"]";f.schema=S,f.schemaPath=i+"["+$+"]",f.errSchemaPath=n+"/"+$,f.errorPath=e.util.getPathExpr(e.errorPath,$,e.opts.jsonPointers,!0),f.dataPathArr[v]=$;var O=e.validate(f);f.baseId=g,e.util.varOccurences(O,y)<2?t+=" "+e.util.varReplace(O,y,_)+" ":t+=" var "+y+" = "+_+"; "+O+" ",t+=" } ",l&&(t+=" if ("+p+") { ",d+="}")}if("object"==typeof P&&e.util.schemaHasRules(P,e.RULES.all)){f.schema=P,f.schemaPath=e.schemaPath+".additionalItems",f.errSchemaPath=e.errSchemaPath+"/additionalItems",t+=" "+p+" = true; if ("+c+".length > "+o.length+") { for (var "+m+" = "+o.length+"; "+m+" < "+c+".length; "+m+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var _=c+"["+m+"]";f.dataPathArr[v]=m;var O=e.validate(f);f.baseId=g,e.util.varOccurences(O,y)<2?t+=" "+e.util.varReplace(O,y,_)+" ":t+=" var "+y+" = "+_+"; "+O+" ",l&&(t+=" if (!"+p+") break; "),t+=" } } ",l&&(t+=" if ("+p+") { ",d+="}")}}else if(e.util.schemaHasRules(o,e.RULES.all)){f.schema=o,f.schemaPath=i,f.errSchemaPath=n,t+=" for (var "+m+" = 0; "+m+" < "+c+".length; "+m+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers,!0);var _=c+"["+m+"]";f.dataPathArr[v]=m;var O=e.validate(f);f.baseId=g,e.util.varOccurences(O,y)<2?t+=" "+e.util.varReplace(O,y,_)+" ":t+=" var "+y+" = "+_+"; "+O+" ",l&&(t+=" if (!"+p+") break; "),t+=" } ",l&&(t+=" if ("+p+") { ",d+="}")}return l&&(t+=" "+d+" if ("+u+" == errors) {"),t=e.util.cleanUpCode(t)}},{}],26:[function(e,r,t){"use strict";r.exports=function(e,r){var t,a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,h="data"+(o||""),u=e.opts.v5&&i&&i.$data;u?(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",t="schema"+s):t=i,a+="var division"+s+";if (",u&&(a+=" "+t+" !== undefined && ( typeof "+t+" != 'number' || "),a+=" (division"+s+" = "+h+" / "+t+", ",a+=e.opts.multipleOfPrecision?" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":" division"+s+" !== parseInt(division"+s+") ",a+=" ) ",u&&(a+=" ) "),a+=" ) { ";var f=f||[];f.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+t+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be multiple of ",a+=u?"' + "+t:i+"'"),e.opts.verbose&&(a+=" , schema: ",a+=u?"validate.schema"+n:""+i,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ";var d=a;return a=f.pop(),a+=!e.compositeRule&&c?e.async?" throw new ValidationError(["+d+"]); ":" validate.errors = ["+d+"]; return false; ":" var err = "+d+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+="} ",c&&(a+=" else { "),a}},{}],27:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),h="errs__"+a,u=e.util.copy(e);u.level++;var f="valid"+u.level;if(e.util.schemaHasRules(o,e.RULES.all)){u.schema=o,u.schemaPath=i,u.errSchemaPath=n,t+=" var "+h+" = errors; ";var d=e.compositeRule;e.compositeRule=u.compositeRule=!0,u.createErrors=!1;var p;u.opts.allErrors&&(p=u.opts.allErrors,u.opts.allErrors=!1),t+=" "+e.validate(u)+" ",u.createErrors=!0,p&&(u.opts.allErrors=p),e.compositeRule=u.compositeRule=d,t+=" if ("+f+") { ";var m=m||[];m.push(t),t="",!1!==e.createErrors?(t+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: {} ",!1!==e.opts.messages&&(t+=" , message: 'should NOT be valid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var v=t;t=m.pop(),t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+v+"]); ":" validate.errors = ["+v+"]; return false; ":" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; } ",e.opts.allErrors&&(t+=" } ")}else t+=" var err = ",!1!==e.createErrors?(t+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: {} ",!1!==e.opts.messages&&(t+=" , message: 'should NOT be valid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(t+=" if (false) { ");return t}},{}],28:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),h="valid"+a,u="errs__"+a,f=e.util.copy(e),d="";f.level++;var p="valid"+f.level;t+="var "+u+" = errors;var prevValid"+a+" = false;var "+h+" = false;";var m=f.baseId,v=e.compositeRule;e.compositeRule=f.compositeRule=!0;var y=o;if(y)for(var g,P=-1,E=y.length-1;P5)t+=" || validate.schema"+i+"["+m+"] ";else{var q=g;if(q)for(var D,L=-1,Q=q.length-1;L= "+pe+"; ",n=e.errSchemaPath+"/patternGroups/minimum",t+=" if (!"+h+") { ";var G=G||[];G.push(t),t="",!1!==e.createErrors?(t+=" { keyword: 'patternGroups' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { reason: '"+ye+"', limit: "+ve+", pattern: '"+e.util.escapeQuotes(M)+"' } ",!1!==e.opts.messages&&(t+=" , message: 'should NOT have "+ge+" than "+ve+' properties matching pattern "'+e.util.escapeQuotes(M)+"\"' "),e.opts.verbose&&(t+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var K=t;t=G.pop(),t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+K+"]); ":" validate.errors = ["+K+"]; return false; ":" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",void 0!==me&&(t+=" else ")}if(void 0!==me){var ve=me,ye="maximum",ge="more";t+=" "+h+" = pgPropCount"+a+" <= "+me+"; ",n=e.errSchemaPath+"/patternGroups/maximum",t+=" if (!"+h+") { ";var G=G||[];G.push(t),t="",!1!==e.createErrors?(t+=" { keyword: 'patternGroups' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { reason: '"+ye+"', limit: "+ve+", pattern: '"+e.util.escapeQuotes(M)+"' } ",!1!==e.opts.messages&&(t+=" , message: 'should NOT have "+ge+" than "+ve+' properties matching pattern "'+e.util.escapeQuotes(M)+"\"' "),e.opts.verbose&&(t+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var K=t;t=G.pop(),t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+K+"]); ":" validate.errors = ["+K+"]; return false; ":" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } "}n=J,l&&(t+=" if ("+h+") { ",d+="}")}}}}return l&&(t+=" "+d+" if ("+u+" == errors) {"),t=e.util.cleanUpCode(t)}},{}],32:[function(e,r,t){"use strict";r.exports=function(e,r){var t,a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,h="data"+(i||""),u="valid"+o;if("#"==n||"#/"==n)e.isRoot?(t=e.async,a="validate"):(t=!0===e.root.schema.$async,a="root.refVal[0]");else{var f=e.resolveRef(e.baseId,n,e.isRoot);if(void 0===f){var d="can't resolve reference "+n+" from id "+e.baseId;if("fail"==e.opts.missingRefs){console.log(d);var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(n)+"' } ",!1!==e.opts.messages&&(s+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(n)+"' "),e.opts.verbose&&(s+=" , schema: "+e.util.toQuotedString(n)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ";var m=s;s=p.pop(),s+=!e.compositeRule&&c?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c&&(s+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs){var v=new Error(d);throw v.missingRef=e.resolve.url(e.baseId,n),v.missingSchema=e.resolve.normalizeId(e.resolve.fullPath(v.missingRef)),v}console.log(d),c&&(s+=" if (true) { ")}}else if(f.inline){var y=e.util.copy(e);y.level++;var g="valid"+y.level;y.schema=f.schema,y.schemaPath="",y.errSchemaPath=n;var P=e.validate(y).replace(/validate\.schema/g,f.code);s+=" "+P+" ",c&&(s+=" if ("+g+") { ")}else t=!0===f.$async,a=f.code}if(a){var p=p||[];p.push(s),s="",s+=e.opts.passContext?" "+a+".call(this, ":" "+a+"( ",s+=" "+h+", (dataPath || '')",'""'!=e.errorPath&&(s+=" + "+e.errorPath);s+=" , "+(i?"data"+(i-1||""):"parentData")+" , "+(i?e.dataPathArr[i]:"parentDataProperty")+", rootData) ";var E=s;if(s=p.pop(),t){if(!e.async)throw new Error("async schema referenced by sync schema");s+=" try { ",c&&(s+="var "+u+" ="),s+=" "+e.yieldAwait+" "+E+"; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } ",c&&(s+=" if ("+u+") { ")}else s+=" if (!"+E+") { if (vErrors === null) vErrors = "+a+".errors; else vErrors = vErrors.concat("+a+".errors); errors = vErrors.length; } ",c&&(s+=" else { ")}return s}},{}],33:[function(e,r,t){"use strict";r.exports=function(e,r){var t=" ",a=e.level,s=e.dataLevel,o=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(s||""),h="valid"+a,u=e.opts.v5&&o&&o.$data;u&&(t+=" var schema"+a+" = "+e.util.getData(o.$data,s,e.dataPathArr)+"; ");var f="schema"+a;if(!u)if(o.length=e.opts.loopRequired;if(l)if(t+=" var missing"+a+"; ",E){u||(t+=" var "+f+" = validate.schema"+i+"; ");var b="i"+a,w="schema"+a+"["+b+"]",j="' + "+w+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(P,w,e.opts.jsonPointers)),t+=" var "+h+" = true; ",u&&(t+=" if (schema"+a+" === undefined) "+h+" = true; else if (!Array.isArray(schema"+a+")) "+h+" = false; else {"),t+=" for (var "+b+" = 0; "+b+" < "+f+".length; "+b+"++) { "+h+" = "+c+"["+f+"["+b+"]] !== undefined; if (!"+h+") break; } ",u&&(t+=" } "),t+=" if (!"+h+") { ";var S=S||[];S.push(t),t="",!1!==e.createErrors?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { missingProperty: '"+j+"' } ",!1!==e.opts.messages&&(t+=" , message: '",t+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+j+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),t+=" } "):t+=" {} ";var $=t;t=S.pop(),t+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+$+"]); ":" validate.errors = ["+$+"]; return false; ":" var err = "+$+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { "}else{t+=" if ( ";var x=d;if(x)for(var _,b=-1,O=x.length-1;b 1) { var i = "+h+".length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal("+h+"[i], "+h+"[j])) { "+u+" = false; break outer; } } } } ",f&&(a+=" } "),a+=" if (!"+u+") { ";var d=d||[];d.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(a+=" , schema: ",a+=f?"validate.schema"+n:""+i,a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),a+=" } "):a+=" {} ";var p=a;a=d.pop(),a+=!e.compositeRule&&c?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",c&&(a+=" else { ")}else c&&(a+=" if (true) { ");return a}},{}],36:[function(e,r,t){"use strict";r.exports=function(e,r){function t(r){return void 0!==e.schema[r.keyword]||"properties"==r.keyword&&(!1===e.schema.additionalProperties||"object"==typeof e.schema.additionalProperties||e.schema.patternProperties&&Object.keys(e.schema.patternProperties).length||e.opts.v5&&e.schema.patternGroups&&Object.keys(e.schema.patternGroups).length)}var a="",s=!0===e.schema.$async;if(e.isTop){var o=e.isTop,i=e.level=0,n=e.dataLevel=0,l="data";if(e.rootId=e.resolve.fullPath(e.root.schema.id),e.baseId=e.baseId||e.rootId,s){e.async=!0;var c="es7"==e.opts.async;e.yieldAwait=c?"await":"yield"}delete e.isTop,e.dataPathArr=[void 0],a+=" var validate = ",s?c?a+=" (async function ":("co*"==e.opts.async&&(a+="co.wrap"),a+="(function* "):a+=" (function ",a+=" (data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; var vErrors = null; ",a+=" var errors = 0; ",a+=" if (rootData === undefined) rootData = data;"}else{var i=e.level,n=e.dataLevel,l="data"+(n||"");if(e.schema.id&&(e.baseId=e.resolve.url(e.baseId,e.schema.id)),s&&!e.async)throw new Error("async schema in sync schema");a+=" var errs_"+i+" = errors;"}var h="valid"+i,u=!e.opts.allErrors,f="",d="",p=e.schema.type,m=Array.isArray(p);if(p&&e.opts.coerceTypes){var v=e.util.coerceToTypes(e.opts.coerceTypes,p);if(v){var y=e.schemaPath+".type",g=e.errSchemaPath+"/type",P=m?"checkDataTypes":"checkDataType";a+=" if ("+e.util[P](p,l,!0)+") { ";var E="dataType"+i,b="coerced"+i;a+=" var "+E+" = typeof "+l+"; ","array"==e.opts.coerceTypes&&(a+=" if ("+E+" == 'object' && Array.isArray("+l+")) "+E+" = 'array'; "),a+=" var "+b+" = undefined; ";var w="",j=v;if(j)for(var S,$=-1,x=j.length-1;$2&&(r=f.call(arguments,1)),t(r)})})}function i(e){return Promise.all(e.map(s,this))}function n(e){for(var r=new e.constructor,t=Object.keys(e),a=[],o=0;o="0"&&s<="9";)r+=s,c();if("."===s)for(r+=".";c()&&s>="0"&&s<="9";)r+=s;if("e"===s||"E"===s)for(r+=s,c(),"-"!==s&&"+"!==s||(r+=s,c());s>="0"&&s<="9";)r+=s,c();if(e=+r,isFinite(e))return e;l("Bad number")},u=function(){var e,r,t,a="";if('"'===s)for(;c();){if('"'===s)return c(),a;if("\\"===s)if(c(),"u"===s){for(t=0,r=0;r<4&&(e=parseInt(c(),16),isFinite(e));r+=1)t=16*t+e;a+=String.fromCharCode(t)}else{if("string"!=typeof n[s])break;a+=n[s]}else a+=s}l("Bad string")},f=function(){for(;s&&s<=" ";)c()},d=function(){switch(s){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null}l("Unexpected '"+s+"'")},p=function(){var e=[];if("["===s){if(c("["),f(),"]"===s)return c("]"),e;for(;s;){if(e.push(i()),f(),"]"===s)return c("]"),e;c(","),f()}}l("Bad array")},m=function(){var e,r={};if("{"===s){if(c("{"),f(),"}"===s)return c("}"),r;for(;s;){if(e=u(),f(),c(":"),Object.hasOwnProperty.call(r,e)&&l('Duplicate key "'+e+'"'),r[e]=i(),f(),"}"===s)return c("}"),r;c(","),f()}}l("Bad object")};i=function(){switch(f(),s){case"{":return m();case"[":return p();case'"':return u();case"-":return h();default:return s>="0"&&s<="9"?h():d()}},r.exports=function(e,r){var t;return o=e,a=0,s=" ",t=i(),f(),s&&l("Syntax error"),"function"==typeof r?function e(t,a){var s,o,i=t[a];if(i&&"object"==typeof i)for(s in i)Object.prototype.hasOwnProperty.call(i,s)&&(o=e(i,s),void 0!==o?i[s]=o:delete i[s]);return r.call(t,a,i)}({"":t},""):t}},{}],45:[function(e,r,t){function a(e){return l.lastIndex=0,l.test(e)?'"'+e.replace(l,function(e){var r=c[e];return"string"==typeof r?r:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function s(e,r){var t,l,c,h,u,f=o,d=r[e];switch(d&&"object"==typeof d&&"function"==typeof d.toJSON&&(d=d.toJSON(e)),"function"==typeof n&&(d=n.call(r,e,d)),typeof d){case"string":return a(d);case"number":return isFinite(d)?String(d):"null";case"boolean":case"null":return String(d);case"object":if(!d)return"null";if(o+=i,u=[],"[object Array]"===Object.prototype.toString.apply(d)){for(h=d.length,t=0;t1&&(a=t[0]+"@",e=t[1]),e=e.replace(q,"."),a+i(e.split("."),r).join(".")}function l(e){for(var r,t,a=[],s=0,o=e.length;s=55296&&r<=56319&&s65535&&(e-=65536,r+=C(e>>>10&1023|55296),e=56320|1023&e),r+=C(e)}).join("")}function h(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:j}function u(e,r){return e+22+75*(e<26)-((0!=r)<<5)}function f(e,r,t){var a=0;for(e=t?Q(e/_):e>>1,e+=Q(e/r);e>L*$>>1;a+=j)e=Q(e/L);return Q(a+(L+1)*e/(e+x))}function d(e){var r,t,a,s,i,n,l,u,d,p,m=[],v=e.length,y=0,g=R,P=O;for(t=e.lastIndexOf(I),t<0&&(t=0),a=0;a=128&&o("not-basic"),m.push(e.charCodeAt(a));for(s=t>0?t+1:0;s=v&&o("invalid-input"),u=h(e.charCodeAt(s++)),(u>=j||u>Q((w-y)/n))&&o("overflow"),y+=u*n,d=l<=P?S:l>=P+$?$:l-P,!(uQ(w/p)&&o("overflow"),n*=p;r=m.length+1,P=f(y-i,r,0==i),Q(y/r)>w-g&&o("overflow"),g+=Q(y/r),y%=r,m.splice(y++,0,g)}return c(m)}function p(e){var r,t,a,s,i,n,c,h,d,p,m,v,y,g,P,E=[];for(e=l(e),v=e.length,r=R,t=0,i=O,n=0;n=r&&mQ((w-t)/y)&&o("overflow"),t+=(c-r)*y,r=c,n=0;nw&&o("overflow"),m==r){for(h=t,d=j;p=d<=i?S:d>=i+$?$:d-i,!(h= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=j-S,Q=Math.floor,C=String.fromCharCode;if(E={version:"1.4.1",ucs2:{decode:l,encode:c},decode:d,encode:p,toASCII:v,toUnicode:m},"function"==typeof e&&"object"==typeof e.amd&&e.amd)e("punycode",function(){return E});else if(y&&g)if(t.exports==y)g.exports=E;else for(b in E)E.hasOwnProperty(b)&&(y[b]=E[b]);else s.punycode=E}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],47:[function(e,r,t){"use strict";function a(e,r){return Object.prototype.hasOwnProperty.call(e,r)}r.exports=function(e,r,t,o){r=r||"&",t=t||"=";var i={};if("string"!=typeof e||0===e.length)return i;e=e.split(r);var n=1e3;o&&"number"==typeof o.maxKeys&&(n=o.maxKeys);var l=e.length;n>0&&l>n&&(l=n);for(var c=0;c=0?(h=p.substr(0,m),u=p.substr(m+1)):(h=p,u=""),f=decodeURIComponent(h),d=decodeURIComponent(u),a(i,f)?s(i[f])?i[f].push(d):i[f]=[i[f],d]:i[f]=d}return i};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],48:[function(e,r,t){"use strict";function a(e,r){if(e.map)return e.map(r);for(var t=[],a=0;a",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),m=["'"].concat(p),v=["%","/","?",";","#"].concat(m),y=["/","?","#"],g={javascript:!0,"javascript:":!0},P={javascript:!0,"javascript:":!0},E={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");a.prototype.parse=function(e,r,t){if(!c.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var a=e.indexOf("?"),s=-1!==a&&a127?A+="x":A+=I[k];if(!A.match(/^[+a-z0-9A-Z_-]{0,63}$/)){var D=O.slice(0,j),L=O.slice(j+1),Q=I.match(/^([+a-z0-9A-Z_-]{0,63})(.*)$/);Q&&(D.push(Q[1]),L.unshift(Q[2])),L.length&&(i="/"+L.join(".")+i),this.hostname=D.join(".");break}}}this.hostname=this.hostname.length>255?"":this.hostname.toLowerCase(),_||(this.hostname=l.toASCII(this.hostname));var C=this.port?":"+this.port:"";this.host=(this.hostname||"")+C,this.href+=this.host,_&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==i[0]&&(i="/"+i))}if(!g[d])for(var j=0,R=m.length;j0)&&t.host.split("@");j&&(t.auth=j.shift(),t.host=t.hostname=j.shift())}return t.search=e.search,t.query=e.query,c.isNull(t.pathname)&&c.isNull(t.search)||(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.href=t.format(),t}if(!b.length)return t.pathname=null,t.path=t.search?"/"+t.search:null,t.href=t.format(),t;for(var S=b.slice(-1)[0],$=(t.host||e.host||b.length>1)&&("."===S||".."===S)||""===S,x=0,_=b.length;_>=0;_--)S=b[_],"."===S?b.splice(_,1):".."===S?(b.splice(_,1),x++):x&&(b.splice(_,1),x--);if(!y&&!g)for(;x--;x)b.unshift("..");!y||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),$&&"/"!==b.join("/").substr(-1)&&b.push("");var O=""===b[0]||b[0]&&"/"===b[0].charAt(0);if(w){t.hostname=t.host=O?"":b.length?b.shift():"";var j=!!(t.host&&t.host.indexOf("@")>0)&&t.host.split("@");j&&(t.auth=j.shift(),t.host=t.hostname=j.shift())}return y=y||t.host&&b.length,y&&!O&&b.unshift(""),b.length?t.pathname=b.join("/"):(t.pathname=null,t.path=null),c.isNull(t.pathname)&&c.isNull(t.search)||(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.auth=e.auth||t.auth,t.slashes=t.slashes||e.slashes,t.href=t.format(),t},a.prototype.parseHost=function(){var e=this.host,r=u.exec(e);r&&(r=r[0],":"!==r&&(this.port=r.substr(1)),e=e.substr(0,e.length-r.length)),e&&(this.hostname=e)}},{"./util":51,punycode:46,querystring:49}],51:[function(e,r,t){"use strict";r.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],ajv:[function(e,r,t){"use strict";function a(e){return g.test(e)}function s(r){function t(e,r){var t;if("string"==typeof e){if(!(t=S(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=R(e);t=a.validate||I(a)}var s=t(r);return!0===t.$async?"*"==D._opts.async?m(s):s:(D.errors=t.errors,s)}function v(e,r){var t=R(e,void 0,r);return t.validate||I(t)}function E(e,r,t,a){if(Array.isArray(e))for(var s=0;s=t}function i(e,t,n){var r=t.input.slice(t.start);return n&&(r=r.replace(p,"$1 $3")),e.test(r)}function s(e,t,n,r){var i=new e.constructor(e.options,e.input,t);if(n)for(var s in n)i[s]=n[s];var o=e,a=i;return["inFunction","inAsyncFunction","inAsync","inGenerator","inModule"].forEach(function(e){e in o&&(a[e]=o[e])}),r&&(i.options.preserveParens=!0),i.nextToken(),i}function o(e,t){var n=function(){};e.extend("initialContext",function(r){return function(){return this.options.ecmaVersion<7&&(n=function(t){e.raise(t.start,"async/await keywords only available when ecmaVersion>=7")}),this.reservedWords=new RegExp(this.reservedWords.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")),this.reservedWordsStrict=new RegExp(this.reservedWordsStrict.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")),this.reservedWordsStrictBind=new RegExp(this.reservedWordsStrictBind.toString().replace(/await|async/g,"").replace("|/","/").replace("/|","/").replace("||","|")),this.inAsyncFunction=t.inAsyncFunction,t.awaitAnywhere&&t.inAsyncFunction&&e.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive"),r.apply(this,arguments)}}),e.extend("shouldParseExportStatement",function(e){return function(){return!("name"!==this.type.label||"async"!==this.value||!i(c,this))||e.apply(this,arguments)}}),e.extend("parseStatement",function(e){return function(n,r){var s=this.start,o=this.startLoc;if("name"===this.type.label)if(i(c,this,!0)){var a=this.inAsyncFunction;try{this.inAsyncFunction=!0,this.next();var l=this.parseStatement(n,r);return l.async=!0,l.start=s,l.loc&&(l.loc.start=o),l.range&&(l.range[0]=s),l}finally{this.inAsyncFunction=a}}else if("object"==typeof t&&t.asyncExits&&i(u,this)){this.next();var l=this.parseStatement(n,r);return l.async=!0,l.start=s,l.loc&&(l.loc.start=o),l.range&&(l.range[0]=s),l}return e.apply(this,arguments)}}),e.extend("parseIdent",function(e){return function(t){var n=e.apply(this,arguments);return this.inAsyncFunction&&"await"===n.name&&0===arguments.length&&this.raise(n.start,"'await' is reserved within async functions"),n}}),e.extend("parseExprAtom",function(e){return function(i){var o,u=this.start,c=this.startLoc,p=e.apply(this,arguments);if("Identifier"===p.type)if("async"!==p.name||r(this,p.end)){if("await"===p.name){var h=this.startNodeAt(p.start,p.loc&&p.loc.start);if(this.inAsyncFunction)return o=this.parseExprSubscripts(),h.operator="await",h.argument=o,h=this.finishNodeAt(h,"AwaitExpression",o.end,o.loc&&o.loc.end),n(h),h;if(this.input.slice(p.end).match(l))return t.awaitAnywhere||"module"!==this.options.sourceType?p:this.raise(p.start,"'await' is reserved within modules");if("object"==typeof t&&t.awaitAnywhere&&(u=this.start,o=s(this,u-4).parseExprSubscripts(),o.end<=u))return o=s(this,u).parseExprSubscripts(),h.operator="await",h.argument=o,h=this.finishNodeAt(h,"AwaitExpression",o.end,o.loc&&o.loc.end),this.pos=o.end,this.end=o.end,this.endLoc=o.endLoc,this.next(),n(h),h;if(!t.awaitAnywhere&&"module"===this.options.sourceType)return this.raise(p.start,"'await' is reserved within modules")}}else{var f=this.inAsyncFunction;try{this.inAsyncFunction=!0;var d=this,y=!1,m={parseFunctionBody:function(e,t){try{var n=y;return y=!0,d.parseFunctionBody.apply(this,arguments)}finally{y=n}},raise:function(){try{return d.raise.apply(this,arguments)}catch(e){throw y?e:a}}};if(o=s(this,this.start,m,!0).parseExpression(),"SequenceExpression"===o.type&&(o=o.expressions[0]),"CallExpression"===o.type&&(o=o.callee),"FunctionExpression"===o.type||"FunctionDeclaration"===o.type||"ArrowFunctionExpression"===o.type)return o=s(this,this.start,m).parseExpression(),"SequenceExpression"===o.type&&(o=o.expressions[0]),"CallExpression"===o.type&&(o=o.callee),o.async=!0,o.start=u,o.loc&&(o.loc.start=c),o.range&&(o.range[0]=u),this.pos=o.end,this.end=o.end,this.endLoc=o.endLoc,this.next(),n(o),o}catch(e){if(e!==a)throw e}finally{this.inAsyncFunction=f}}return p}}),e.extend("finishNodeAt",function(e){return function(t,n,r,i){return t.__asyncValue&&(delete t.__asyncValue,t.value.async=!0),e.apply(this,arguments)}}),e.extend("finishNode",function(e){return function(t,n){return t.__asyncValue&&(delete t.__asyncValue,t.value.async=!0),e.apply(this,arguments)}});e.extend("parsePropertyName",function(e){return function(t){var i=(t.key&&t.key.name,e.apply(this,arguments));return"Identifier"!==i.type||"async"!==i.name||r(this,i.end)||this.input.slice(i.end).match(l)||(h.test(this.input.slice(i.end))?(i=e.apply(this,arguments),t.__asyncValue=!0):(n(t),"set"===t.kind&&this.raise(i.start,"'set (value)' cannot be be async"),i=e.apply(this,arguments),"Identifier"===i.type&&"set"===i.name&&this.raise(i.start,"'set (value)' cannot be be async"),t.__asyncValue=!0)),i}}),e.extend("parseClassMethod",function(e){return function(t,n,r){var i;n.__asyncValue&&("constructor"===n.kind&&this.raise(n.start,"class constructor() cannot be be async"),i=this.inAsyncFunction,this.inAsyncFunction=!0);var s=e.apply(this,arguments);return this.inAsyncFunction=i,s}}),e.extend("parseMethod",function(e){return function(t){var n;this.__currentProperty&&this.__currentProperty.__asyncValue&&(n=this.inAsyncFunction,this.inAsyncFunction=!0);var r=e.apply(this,arguments);return this.inAsyncFunction=n,r}}),e.extend("parsePropertyValue",function(e){return function(t,n,r,i,s,o){var a=this.__currentProperty;this.__currentProperty=t;var u;t.__asyncValue&&(u=this.inAsyncFunction,this.inAsyncFunction=!0);var c=e.apply(this,arguments);return this.inAsyncFunction=u,this.__currentProperty=a,c}})}var a={},u=/^async[\t ]+(return|throw)/,c=/^async[\t ]+function/,l=/^\s*[():;]/,p=/([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g,h=/\s*(get|set)\s*\(/;t.exports=o},{}],3:[function(e,t,n){function r(e,t){return e.lineStart>=t}function i(e,t,n){var r=t.input.slice(t.start);return n&&(r=r.replace(c,"$1 $3")),e.test(r)}function s(e,t,n){var r=new e.constructor(e.options,e.input,t);if(n)for(var i in n)r[i]=n[i];var s=e,o=r;return["inFunction","inAsync","inGenerator","inModule"].forEach(function(e){e in s&&(o[e]=s[e])}),r.nextToken(),r}function o(e,t){t&&"object"==typeof t||(t={}),e.extend("parse",function(n){return function(){return this.inAsync=t.inAsyncFunction,t.awaitAnywhere&&t.inAsyncFunction&&e.raise(node.start,"The options awaitAnywhere and inAsyncFunction are mutually exclusive"),n.apply(this,arguments)}}),e.extend("parseStatement",function(e){return function(n,r){var s=this.start,o=this.startLoc;if("name"===this.type.label&&t.asyncExits&&i(a,this)){this.next();var u=this.parseStatement(n,r);return u.async=!0,u.start=s,u.loc&&(u.loc.start=o),u.range&&(u.range[0]=s),u}return e.apply(this,arguments)}}),e.extend("parseIdent",function(e){return function(n){return"module"===this.options.sourceType&&this.options.ecmaVersion>=8&&t.awaitAnywhere?e.call(this,!0):e.apply(this,arguments)}}),e.extend("parseExprAtom",function(e){var n={};return function(r){var i,o=this.start,a=(this.startLoc,e.apply(this,arguments));if("Identifier"===a.type&&"await"===a.name&&!this.inAsync&&t.awaitAnywhere){var u=this.startNodeAt(a.start,a.loc&&a.loc.start);o=this.start;var c={raise:function(){try{return pp.raise.apply(this,arguments)}catch(e){throw n}}};try{if(i=s(this,o-4,c).parseExprSubscripts(),i.end<=o)return i=s(this,o,c).parseExprSubscripts(),u.argument=i,u=this.finishNodeAt(u,"AwaitExpression",i.end,i.loc&&i.loc.end),this.pos=i.end,this.end=i.end,this.endLoc=i.endLoc,this.next(),u}catch(e){if(e===n)return a;throw e}}return a}});var n={undefined:!0,get:!0,set:!0,static:!0,async:!0,constructor:!0};e.extend("parsePropertyName",function(e){return function(t){var i=t.key&&t.key.name,s=e.apply(this,arguments);"get"===this.value&&(t.__maybeStaticAsyncGetter=!0);return n[this.value]?s:("Identifier"!==s.type||"async"!==s.name&&"async"!==i||r(this,s.end)||this.input.slice(s.end).match(u)?delete t.__maybeStaticAsyncGetter:"set"===t.kind||"set"===s.name?this.raise(s.start,"'set (value)' cannot be be async"):(this.__isAsyncProp=!0,s=e.apply(this,arguments),"Identifier"===s.type&&"set"===s.name&&this.raise(s.start,"'set (value)' cannot be be async")),s)}}),e.extend("parseClassMethod",function(e){return function(t,n,r){var i=e.apply(this,arguments);return n.__maybeStaticAsyncGetter&&(delete n.__maybeStaticAsyncGetter,"get"!==n.key.name&&(n.kind="get")),i}}),e.extend("parseFunctionBody",function(e){return function(t,n){var r=this.inAsync;this.__isAsyncProp&&(t.async=!0,this.inAsync=!0,delete this.__isAsyncProp);var i=e.apply(this,arguments);return this.inAsync=r,i}})}var a=/^async[\t ]+(return|throw)/,u=/^\s*[):;]/,c=/([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g;t.exports=o},{}],4:[function(e,t,n){"use strict";function r(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return 3*e.length/4-r(e)}function s(e){var t,n,i,s,o,a,u=e.length;o=r(e),a=new p(3*u/4-o),i=o>0?u-4:u;var c=0;for(t=0,n=0;t>16&255,a[c++]=s>>8&255,a[c++]=255&s;return 2===o?(s=l[e.charCodeAt(t)]<<2|l[e.charCodeAt(t+1)]>>4,a[c++]=255&s):1===o&&(s=l[e.charCodeAt(t)]<<10|l[e.charCodeAt(t+1)]<<4|l[e.charCodeAt(t+2)]>>2,a[c++]=s>>8&255,a[c++]=255&s),a}function o(e){return c[e>>18&63]+c[e>>12&63]+c[e>>6&63]+c[63&e]}function a(e,t,n){for(var r,i=[],s=t;su?u:o+16383));return 1===r?(t=e[n-1],i+=c[t>>2],i+=c[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=c[t>>10],i+=c[t>>4&63],i+=c[t<<2&63],i+="="),s.push(i),s.join("")}n.byteLength=i,n.toByteArray=s,n.fromByteArray=u;for(var c=[],l=[],p="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=0,d=h.length;fH)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return u(e)}return s(e,t,n)}function s(e,t,n){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return e instanceof ArrayBuffer?p(e,t,n):"string"==typeof e?c(e,t):h(e)}function o(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function a(e,t,n){return o(e),e<=0?r(e):void 0!==t?"string"==typeof n?r(e).fill(t,n):r(e).fill(t):r(e)}function u(e){return o(e),r(e<0?0:0|f(e))}function c(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var n=0|y(e,t),s=r(n),o=s.write(e,t);return o!==n&&(s=s.slice(0,o)),s}function l(e){for(var t=e.length<0?0:0|f(e.length),n=r(t),i=0;i=H)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+H.toString(16)+" bytes");return 0|e}function d(e){return+e!=e&&(e=0),i.alloc(+e)}function y(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(r)return V(e).length;t=(""+t).toLowerCase(),r=!0}}function m(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return P(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return _(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return F(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function g(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function v(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:b(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,r,i){function s(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}var o=1,a=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,u/=2,n/=2}var c;if(i){var l=-1;for(c=n;ca&&(n=a-u),c=n;c>=0;c--){for(var p=!0,h=0;hi&&(r=i):r=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o239?4:s>223?3:s>191?2:1;if(i+a<=n){var u,c,l,p;switch(a){case 1:s<128&&(o=s);break;case 2:u=e[i+1],128==(192&u)&&(p=(31&s)<<6|63&u)>127&&(o=p);break;case 3:u=e[i+1],c=e[i+2],128==(192&u)&&128==(192&c)&&(p=(15&s)<<12|(63&u)<<6|63&c)>2047&&(p<55296||p>57343)&&(o=p);break;case 4:u=e[i+1],c=e[i+2],l=e[i+3],128==(192&u)&&128==(192&c)&&128==(192&l)&&(p=(15&s)<<18|(63&u)<<12|(63&c)<<6|63&l)>65535&&p<1114112&&(o=p)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,r.push(o>>>10&1023|55296),o=56320|1023&o),r.push(o),i+=a}return L(r)}function L(e){var t=e.length;if(t<=Z)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,s,o){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw new RangeError("Index out of range")}function B(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function R(e,t,n,r,i){return t=+t,n>>>=0,i||B(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Y.write(e,t,n,r,23,4),n+4}function I(e,t,n,r,i){return t=+t,n>>>=0,i||B(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Y.write(e,t,n,r,52,8),n+8}function j(e){if(e=M(e).replace(Q,""),e.length<2)return"";for(;e.length%4!=0;)e+="=";return e}function M(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function D(e){return e<16?"0"+e.toString(16):e.toString(16)}function V(e,t){t=t||1/0;for(var n,r=e.length,i=null,s=[],o=0;o55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function q(e){for(var t=[],n=0;n>8,i=n%256,s.push(i),s.push(r);return s}function z(e){return J.toByteArray(j(e))}function W(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function G(e){return e!==e}var J=e("base64-js"),Y=e("ieee754");n.Buffer=i,n.SlowBuffer=d,n.INSPECT_MAX_BYTES=50;var H=2147483647;n.kMaxLength=H,i.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return s(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return a(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer},i.compare=function(e,t){if(!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,s=0,o=Math.min(n,r);s0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},i.prototype.compare=function(e,t,n,r,s){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,s>>>=0,this===e)return 0;for(var o=s-r,a=n-t,u=Math.min(o,a),c=this.slice(r,s),l=e.slice(t,n),p=0;p>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return x(this,e,t,n);case"utf8":case"utf-8":return w(this,e,t,n);case"ascii":return E(this,e,t,n);case"latin1":case"binary":return S(this,e,t,n);case"base64":return k(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Z=4096;i.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t>>=0,t>>>=0,n||$(e,t,this.length);for(var r=this[e],i=1,s=0;++s>>=0,t>>>=0,n||$(e,t,this.length);for(var r=this[e+--t],i=1;t>0&&(i*=256);)r+=this[e+--t]*i;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||$(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||$(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||$(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||$(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||$(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||$(e,t,this.length);for(var r=this[e],i=1,s=0;++s=i&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||$(e,t,this.length);for(var r=t,i=1,s=this[e+--r];r>0&&(i*=256);)s+=this[e+--r]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||$(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||$(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||$(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||$(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||$(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||$(e,4,this.length),Y.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||$(e,4,this.length),Y.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||$(e,8,this.length),Y.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||$(e,8,this.length),Y.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){O(this,e,t,n,Math.pow(2,8*n)-1,0)}var i=1,s=0;for(this[t]=255&e;++s>>=0,n>>>=0,!r){O(this,e,t,n,Math.pow(2,8*n)-1,0)}var i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var s=0,o=1,a=0;for(this[t]=255&e;++s>0)-a&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var i=Math.pow(2,8*n-1);O(this,e,t,n,i-1,-i)}var s=n-1,o=1,a=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===a&&0!==this[t+s+1]&&(a=1),this[t+s]=(e/o>>0)-a&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return R(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return R(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return I(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return I(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--i)e[i+t]=this[i+n];else if(s<1e3)for(i=0;i>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var o;if("number"==typeof e)for(o=t;o>1,l=-7,p=n?i-1:0,h=n?-1:1,f=e[t+p];for(p+=h,s=f&(1<<-l)-1,f>>=-l,l+=a;l>0;s=256*s+e[t+p],p+=h,l-=8);for(o=s&(1<<-l)-1,s>>=-l,l+=r;l>0;o=256*o+e[t+p],p+=h,l-=8);if(0===s)s=1-c;else{if(s===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=c}return(f?-1:1)*o*Math.pow(2,s-r)},n.write=function(e,t,n,r,i,s){var o,a,u,c=8*s-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,d=r?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),t+=o+p>=1?h/u:h*Math.pow(2,1-p),t*u>=2&&(o++,u/=2),o+p>=l?(a=0,o=l):o+p>=1?(a=(t*u-1)*Math.pow(2,i),o+=p):(a=t*Math.pow(2,p-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=d,a/=256,i-=8);for(o=o<0;e[n+f]=255&o,f+=d,o/=256,c-=8);e[n+f-d]|=128*y}},{}],8:[function(e,t,n){"use strict";function r(e,t){if(Function.prototype.$asyncspawn||Object.defineProperty(Function.prototype,"$asyncspawn",{value:r,enumerable:!1,configurable:!0,writable:!0}),this instanceof Function){var n=this;return new e(function(e,r){function i(t,n){var o;try{if(o=t.call(s,n),o.done){if(o.value!==e){if(o.value&&o.value===o.value.then)return o.value(e,r);e&&e(o.value),e=null}return}o.value.then?o.value.then(function(e){i(s.next,e)},function(e){i(s.throw,e)}):i(s.next,o.value)}catch(e){return r&&r(e),void(r=null)}}var s=n.call(t,e,r);i(s.next)})}}var i=function(e,t){for(var n=t.toString(),r="return "+n,i=n.match(/.*\(([^)]*)\)/)[1],s=/['"]!!!([^'"]*)['"]/g,o=[];;){var a=s.exec(r);if(!a)break;o.push(a)}return o.reverse().forEach(function(t){r=r.slice(0,t.index)+e[t[1]]+r.substr(t.index+t[0].length)}),r=r.replace(/\/\*[^*]*\*\//g," ").replace(/\s+/g," "),new Function(i,r)()}({zousan:e("./zousan").toString(),thenable:e("./thenableFactory").toString()},function e(t,n){function r(){return i.apply(t,arguments)}Function.prototype.$asyncbind||Object.defineProperty(Function.prototype,"$asyncbind",{value:e,enumerable:!1,configurable:!0,writable:!0}),e.trampoline||(e.trampoline=function(e,t,n,r,i){return function s(o){for(;o;){if(o.then)return o=o.then(s,r),i?void 0:o;try{ +if(o.pop){if(o.length)return o.pop()?t.call(e):o;o=n}else o=o.call(e)}catch(e){return r(e)}}}}),e.LazyThenable||(e.LazyThenable="!!!thenable"(),e.EagerThenable=e.Thenable=(e.EagerThenableFactory="!!!zousan")());var i=this;switch(n){case!0:return new e.Thenable(r);case 0:return new e.LazyThenable(r);case void 0:return r.then=r,r;default:return function(){try{return i.apply(t,arguments)}catch(e){return n(e)}}}});i(),r(),t.exports={$asyncbind:i,$asyncspawn:r}},{"./thenableFactory":9,"./zousan":10}],9:[function(e,t,n){t.exports=function(){function e(e){return e&&e instanceof Object&&"function"==typeof e.then}function t(n,r,i){try{var s=i?i(r):r;if(n===s)return n.reject(new TypeError("Promise resolution loop"));e(s)?s.then(function(e){t(n,e)},function(e){n.reject(e)}):n.resolve(s)}catch(e){n.reject(e)}}function n(){}function r(e){}function i(e,t){this.resolve=e,this.reject=t}function s(r,i){var s=new n;try{this._resolver(function(n){return e(n)?n.then(r,i):t(s,n,r)},function(e){t(s,e,i)})}catch(e){t(s,e,i)}return s}function o(e){this._resolver=e,this.then=s}return n.prototype={resolve:r,reject:r,then:i},o.resolve=function(e){return o.isThenable(e)?e:{then:function(t){return t(e)}}},o.isThenable=e,o}},{}],10:[function(e,t,n){(function(e){"use strict";t.exports=function(t){function n(e){if(e){var t=this;e(function(e){t.resolve(e)},function(e){t.reject(e)})}}function r(e,t){if("function"==typeof e.y)try{var n=e.y.call(void 0,t);e.p.resolve(n)}catch(t){e.p.reject(t)}else e.p.resolve(t)}function i(e,t){if("function"==typeof e.n)try{var n=e.n.call(void 0,t);e.p.resolve(n)}catch(t){e.p.reject(t)}else e.p.reject(t)}t=t||"object"==typeof e&&e.nextTick||"function"==typeof setImmediate&&setImmediate||function(e){setTimeout(e,0)};var s=function(){function e(){for(;n.length-r;){try{n[r]()}catch(e){}n[r++]=void 0,r===i&&(n.splice(0,i),r=0)}}var n=[],r=0,i=1024;return function(i){n.push(i),n.length-r==1&&t(e)}}();return n.prototype={resolve:function(e){if(void 0===this.state){if(e===this)return this.reject(new TypeError("Attempt to resolve promise with self"));var t=this;if(e&&("function"==typeof e||"object"==typeof e))try{var n=0,i=e.then;if("function"==typeof i)return void i.call(e,function(e){n++||t.resolve(e)},function(e){n++||t.reject(e)})}catch(e){return void(n||this.reject(e))}this.state=r,this.v=e,t.c&&s(function(){for(var n=0,i=t.c.length;n]*>)(.*)/i,/(.*)(<\/script>)(.*)/i],o=0,a=!0;t=t.split("\n");for(var u=0;u0){if(!a)return t(e);delete e.async}return void(!a&&i?t():(e.type="ReturnStatement",e.$mapped=!0,e.argument={type:"CallExpression",callee:A(s,[n]).$error,arguments:[e.argument]}))}return"TryStatement"===e.type?(i++,t(e),void i--):o(e).isFunction?(r++,t(e),void r--):void t(e)}if(r>0){if(!o(e).isAsync)return t(e);delete e.async}return e.$mapped=!0,void(o(e.argument).isUnaryExpression&&"void"===e.argument.operator?e.argument=e.argument.argument:e.argument={type:"CallExpression",callee:A(s,[n]).$return,arguments:e.argument?[e.argument]:[]})},t)}function $(e,t){return Array.isArray(e)?e.map(function(e){return $(e,t)}):(y.treeWalker(e,function(e,t,n){if(t(),"ConditionalExpression"===e.type&&(u(e.alternate)||u(e.consequent))){h(E("condOp"));i(e,L(y.part("if ($0) return $1 ; return $2",[e.test,e.consequent,e.alternate]).body))}},t),e)}function O(e,t){return Array.isArray(e)?e.map(function(e){return O(e,t)}):(y.treeWalker(e,function(e,t,n){if(t(),"LogicalExpression"===e.type&&u(e.right)){var r,s=h(E("logical"+("&&"===e.operator?"And":"Or")));if("||"===e.operator)r="var $0; if (!($0 = $1)) {$0 = $2} return $0";else{if("&&"!==e.operator)throw new Error(v(e)+"Illegal logical operator: "+e.operator);r="var $0; if ($0 = $1) {$0 = $2} return $0"}i(e,L(y.part(r,[s,e.left,e.right]).body))}},t),e)}function B(e,t,n){if("SwitchCase"!==e.type&&o(e).isBlockStatement)for(var r=0;r { $$setMapped: while (q) { if (q.then) "+(1===s?" return void q.then($idTrampoline, $exit); ":" return q.then($idTrampoline, $exit); ")+" try { if (q.pop) if (q.length) return q.pop() ? $idContinuation.call(this) : q; else q = $idStep; else q = q.call(this) } catch (_exception) { return $exit(_exception); } } }))($idIter)":"($idTrampoline = (function (q) { $$setMapped: while (q) { if (q.then) "+(1===s?" return void q.then($idTrampoline, $exit); ":" return q.then($idTrampoline, $exit); ")+" try { if (q.pop) if (q.length) return q.pop() ? $idContinuation.call(this) : q; else q = $idStep; else q = q.call(this) } catch (_exception) { return $exit(_exception); } } }).bind(this))($idIter)",{setMapped:function(e){return e.$mapped=!0,e},idTrampoline:E,exit:$,idIter:S,idContinuation:_,idStep:k}).expr:y.part("(Function.$0.trampoline(this,$1,$2,$3,$5)($4))",[me.asyncbind,_,k,$,S,b(1===s)]).expr,l.push({type:"ReturnStatement",argument:F}),l.push({$label:e.$label,type:"FunctionDeclaration",id:S,params:[],body:{type:"BlockStatement",body:m}}),d&&l.push({type:"FunctionDeclaration",id:k,params:[],body:{type:"BlockStatement",body:[d,P]}}),!p||"VariableDeclaration"!==p.type||"let"!==p.kind&&"const"!==p.kind?(l.push(x),t[0].replace(l.map(r))):("const"===p.kind&&(p.kind="let"),t[0].replace([{type:"BlockStatement",body:l.map(r)},r(x)]))}}function Y(e,t){return y.treeWalker(e,function(e,t,s){function a(e){return{type:"ReturnStatement",argument:{type:"UnaryExpression",operator:"void",prefix:!0,argument:P(e||S)}}}function c(e,t){if("BreakStatement"===e.type)i(e,r(A(e.label&&n.generatedSymbolPrefix+"Loop_"+e.label.name+"_exit")));else if("ContinueStatement"===e.type)i(e,r(a(e.label&&n.generatedSymbolPrefix+"Loop_"+e.label.name+"_next")));else if(o(e).isFunction)return!0;t()}"ForInStatement"===e.type&&u(e)?W(e,s):"ForOfStatement"===e.type&&u(e)&&G(e,s),t();var p;if(o(e).isLoop&&u(e)){var f=e.init,d=e.test||b(!0),g=e.update,v=e.body,x=l(v);f&&(o(f).isStatement||(f={type:"ExpressionStatement",expression:f})),g=g&&{type:"ExpressionStatement",expression:g},v=o(v).isBlockStatement?r(v).body:[r(v)];var w=e.$label&&e.$label.name;w="Loop_"+(w||ye++);var E=n.generatedSymbolPrefix+(w+"_exit"),S=n.generatedSymbolPrefix+(w+"_next"),k=h(n.generatedSymbolPrefix+w),A=function(e){return{type:"ReturnStatement",argument:{type:"UnaryExpression",operator:"void",prefix:!0,argument:{type:"CallExpression",callee:h(e||E),arguments:[]}}}},_=C(S,[{type:"ReturnStatement",argument:{type:"CallExpression",callee:x?m(k):k,arguments:[h(E),me.error]}}]);g&&_.body.body.unshift(g);for(var L=0;L0&&o(e).isAsync)return delete e.async,e.argument={type:"CallExpression",callee:"ThrowStatement"===e.type?me.error:me.return,arguments:e.argument?[e.argument]:[]},void(e.type="ReturnStatement");n(e)})}function K(e,t){if(n.noRuntime)throw new Error("Nodent: 'noRuntime' option only compatible with -promise and -engine modes");return y.part("{ return (function*($return,$error){ $:body }).$asyncspawn(Promise,this) }",{return:me.return,error:me.error,asyncspawn:me.asyncspawn,body:X(e).concat(t?[{type:"ReturnStatement",argument:me.return}]:[])}).body[0]}function ee(e){e.$asyncgetwarninig||(e.$asyncgetwarninig=!0,d(v(e)+"'async get "+printNode(e)+"(){...}' is non-standard. See https://github.com/MatAtBread/nodent#differences-from-the-es7-specification"))}function te(e,t){function s(e,t){y.treeWalker(e,function(n,r,i){n!==e&&o(n).isFunction||(o(n).isAwait?t?(n.$hidden=!0,r()):(delete n.operator,n.delegate=!1,n.type="YieldExpression",r()):r())})}function a(e){var t=n.promises;n.promises=!0,_(e,!0),n.promises=t}function u(e){return"BlockStatement"!==e.body.type&&(e.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:e.body}]}),e}function c(e,n){n.$asyncexitwarninig||(n.$asyncexitwarninig=!0,d(v(e)+"'async "+{ReturnStatement:"return",ThrowStatement:"throw"}[e.type]+"' not possible in "+(t?"engine":"generator")+" mode. Using Promises for function at "+v(n)))}y.treeWalker(e,function(e,n,r){n();var l,p,h;if(o(e).isAsync&&o(e).isFunction){var f;(f=x(r[0].parent))&&o(f).isAsync&&"get"===r[0].parent.kind&&ee(r[0].parent.key),(p=H(e))?(c(p,e.body),a(e)):t?"get"!==r[0].parent.kind&&s(e,!0):(l=e,delete l.async,h=w(l),s(l,!1),l=u(l),l.body=K(l.body.body,p),h&&D(l.body.body,[ge]),l.id&&"ExpressionStatement"===r[0].parent.type?(l.type="FunctionDeclaration",r[1].replace(l)):r[0].replace(l))}else(l=x(e))&&o(l).isAsync&&((p=H(l))?(c(p,l),a(e)):t&&"get"!==e.kind||(t?a(e):(e.async=!1,h=w(l),s(l,!1),i(l,u(l)),l.body=K(l.body.body,p)),h&&D(l.body.body,[ge])))});var l=r(n);return n.engine=!1,n.generators=!1,ce(e),oe(e),M(e,l.engine),O(e),$(e),U(e,[q,J,R,I,B]),z(e,"warn"),n.engine=l.engine,n.generators=l.generators,e}function ne(e,t,n){var r=[];return y.treeWalker(e,function(i,s,a){return i===e?s():t(i,a)?void r.push([].concat(a)):void(n||o(i).isScope||s())}),r}function re(e,t){var n=[],i={};if(e=e.filter(function(e){return"ExportNamedDeclaration"!==e[0].parent.type}),e.length){var s={};e.forEach(function(e){function t(e){e in s?i[e]=o.declarations[u]:s[e]=o.declarations[u]}for(var n=e[0],o=n.self,a=(o.kind,[]),u=0;u1?{type:"SequenceExpression",expressions:a}:a[0];"For"!==n.parent.type.slice(0,3)&&(p={type:"ExpressionStatement",expression:p}),n.replace(p)}});var o=Object.keys(s);o.length&&(o=o.map(function(e){return{type:"VariableDeclarator",id:h(e),loc:s[e].loc,start:s[e].start,end:s[e].end}}),n[0]&&"VariableDeclaration"===n[0].type?n[0].declarations=n[0].declarations.concat(o):n.unshift({type:"VariableDeclaration",kind:t,declarations:o}))}return{decls:n,duplicates:i}}function ie(e){if(!e)return[];if(Array.isArray(e))return e.reduce(function(e,t){return e.concat(ie(t.id))},[]);switch(e.type){case"Identifier":return[e.name];case"AssignmentPattern":return ie(e.left);case"ArrayPattern":return e.elements.reduce(function(e,t){return e.concat(ie(t))},[]);case"ObjectPattern":return e.properties.reduce(function(e,t){return e.concat(ie(t))},[]);case"ObjectProperty":case"Property":return ie(e.value);case"RestElement":case"RestProperty":return ie(e.argument)}}function se(e){function t(e){d(v(e)+"Possible assignment to 'const "+printNode(e)+"'")}function n(e){switch(e.type){case"Identifier":"const"===r[e.name]&&t(e);break;case"ArrayPattern":e.elements.forEach(function(e){"const"===r[e.name]&&t(e)});break;case"ObjectPattern":e.properties.forEach(function(e){"const"===r[e.key.name]&&t(e)})}}var r={};y.treeWalker(e,function(e,t,i){var s=o(e).isBlockStatement;if(s){r=Object.create(r);for(var a=0;a=0){var r=n[0];return("left"!=r.field||"ForInStatement"!==r.parent.type&&"ForOfStatement"!==r.parent.type)&&("init"!=r.field||"ForStatement"!==r.parent.type||"const"!==t.kind&&"let"!==t.kind)}}}function s(e,t){return!("FunctionDeclaration"!==e.type||!e.id)&&(o(e).isAsync||!e.$continuation)}var c={TemplateLiteral:function(e){return e.expressions},NewExpression:function(e){return e.arguments},CallExpression:function(e){return e.arguments},SequenceExpression:function(e){return e.expressions},ArrayExpression:function(e){return e.elements},ObjectExpression:function(e){return e.properties.map(function(e){return e.value})}};y.treeWalker(e,function(e,n,s){var a;if(n(),e.type in c&&!e.$hoisted){var s,l=c[e.type](e),p=[];for(a=0;a0;a--)if(e.declarations[a]&&e.declarations[a].init&&u(e.declarations[a].init)){var h={type:"VariableDeclaration",kind:e.kind,declarations:e.declarations.splice(a)},f=s[0];if(!("index"in f))throw new Error("VariableDeclaration not in a block");f.parent[f.field].splice(f.index+1,0,h)}}),se(e);var l=!1;return y.treeWalker(e,function(e,t,r){var i=l;if(l=l||pe(e),o(e).isBlockStatement){if(u(e)){var a,c,p,f,y,m=!r[0].parent||o(r[0].parent).isScope;if(m){c=ne(e,n(["const"]),!1);var g={},b={};c.forEach(function(e){e[0].self.declarations.forEach(function(e){ie(e.id).forEach(function(t){g[t]||b[t]?(delete g[t],b[t]=e):g[t]=e})})}),c.forEach(function(e){for(var t=0;t=0&&"ReturnStatement"===i[1].self.type){var s=e.$thisCallName,a=r(de[s].def.body.body);de[s].$inlined=!0,o(i[1].self).isJump||a.push({type:"ReturnStatement"}),i[1].replace(a)}});var n=Object.keys(de).map(function(e){return de[e].$inlined&&de[e].def});y.treeWalker(e,function(e,t,r){t(),n.indexOf(e)>=0&&r[0].remove()})}if(!("Program"===e.type&&"module"===e.sourceType||a(e,function(e){return o(e).isES6},!0))){var i=pe(e);!function(e){y.treeWalker(e,function(e,t,n){if("Program"===e.type||"FunctionDeclaration"===e.type||"FunctionExpression"===e.type){var r=i;if(i=i||pe(e)){t();var s="Program"===e.type?e:e.body,o=ne(s,function(e,t){if("FunctionDeclaration"===e.type)return t[0].parent!==s});o=o.map(function(e){return e[0].remove()}),[].push.apply(s.body,o)}else t();i=r}else t()})}(e)}return y.treeWalker(e,function(e,t,n){t(),Object.keys(e).filter(function(e){return"$"===e[0]}).forEach(function(t){delete e[t]})}),e}var de={},ye=1,me={};Object.keys(n).filter(function(e){return"$"===e[0]}).forEach(function(e){me[e.slice(1)]=h(n[e])});var ge=y.part("var $0 = arguments",[me.arguments]).body[0];return n.engine?(e.ast=ue(e.ast,!0),e.ast=te(e.ast,n.engine),e.ast=le(e.ast),fe(e.ast)):n.generators?(e.ast=ue(e.ast),e.ast=te(e.ast),e.ast=le(e.ast),fe(e.ast)):(e.ast=ue(e.ast),_(e.ast)),n.babelTree&&y.treeWalker(e.ast,function(e,t,n){t(),"Literal"===e.type&&i(e,b(e.value))}),e}var y=e("./parser"),m=e("./output");n.printNode=function e(t){if(!t)return"";if(Array.isArray(t))return t.map(e).join("|\n");try{return m(t)}catch(e){return e.message+": "+(t&&t.type)}};var g={start:!0,end:!0,loc:!0,range:!0},v={getScope:function(){return"FunctionDeclaration"===this.node.type||"FunctionExpression"===this.node.type||"Function"===this.node.type||"ObjectMethod"===this.node.type||"ClassMethod"===this.node.type||"ArrowFunctionExpression"===this.node.type&&"BlockStatement"===this.node.body.type?this.node.body.body:"Program"===this.node.type?this.node.body:null},isScope:function(){return"FunctionDeclaration"===this.node.type||"FunctionExpression"===this.node.type||"Function"===this.node.type||"Program"===this.node.type||"ObjectMethod"===this.node.type||"ClassMethod"===this.node.type||"ArrowFunctionExpression"===this.node.type&&"BlockStatement"===this.node.body.type},isFunction:function(){return"FunctionDeclaration"===this.node.type||"FunctionExpression"===this.node.type||"Function"===this.node.type||"ObjectMethod"===this.node.type||"ClassMethod"===this.node.type||"ArrowFunctionExpression"===this.node.type},isClass:function(){return"ClassDeclaration"===this.node.type||"ClassExpression"===this.node.type},isBlockStatement:function(){return"ClassBody"===this.node.type||"Program"===this.node.type||"BlockStatement"===this.node.type?this.node.body:"SwitchCase"===this.node.type&&this.node.consequent},isExpressionStatement:function(){return"ExpressionStatement"===this.node.type},isLiteral:function(){return"Literal"===this.node.type||"BooleanLiteral"===this.node.type||"RegExpLiteral"===this.node.type||"NumericLiteral"===this.node.type||"StringLiteral"===this.node.type||"NullLiteral"===this.node.type},isDirective:function(){return"ExpressionStatement"===this.node.type&&("StringLiteral"===this.node.expression.type||"Literal"===this.node.expression.type&&"string"==typeof this.node.expression.value)},isUnaryExpression:function(){return"UnaryExpression"===this.node.type},isAwait:function(){return"AwaitExpression"===this.node.type&&!this.node.$hidden},isAsync:function(){return this.node.async},isStatement:function(){return null!==this.node.type.match(/[a-zA-Z]+Declaration/)||null!==this.node.type.match(/[a-zA-Z]+Statement/)},isExpression:function(){return null!==this.node.type.match(/[a-zA-Z]+Expression/)},isLoop:function(){return"ForStatement"===this.node.type||"WhileStatement"===this.node.type||"DoWhileStatement"===this.node.type},isJump:function(){return"ReturnStatement"===this.node.type||"ThrowStatement"===this.node.type||"BreakStatement"===this.node.type||"ContinueStatement"===this.node.type},isES6:function(){switch(this.node.type){case"ExportNamedDeclaration":case"ExportSpecifier":case"ExportDefaultDeclaration":case"ExportAllDeclaration":case"ImportDeclaration":case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ArrowFunctionExpression":case"ForOfStatement":case"YieldExpression":case"Super":case"RestElement":case"RestProperty":case"SpreadElement":case"TemplateLiteral":case"ClassDeclaration":case"ClassExpression":return!0;case"VariableDeclaration":return this.node.kind&&"var"!==this.node.kind;case"FunctionDeclaration":case"FunctionExpression":return!!this.node.generator}}},b={};Object.keys(v).forEach(function(e){Object.defineProperty(b,e,{get:v[e]})}),t.exports={printNode:printNode,babelLiteralNode:p,asynchronize:function(e,t,n,r){try{return d(e,t,n,r)}catch(t){if(t instanceof SyntaxError){var i=e.origCode.substr(t.pos-t.loc.column);i=i.split("\n")[0],t.message+=" (nodent)\n"+i+"\n"+i.replace(/[\S ]/g,"-").substring(0,t.loc.column)+"^",t.stack=""}throw t}}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./output":13,"./parser":14}],13:[function(e,t,n){"use strict";function r(e){var t=y[e.type]||y[e.type+e.operator]||y[e.type+e.operator+(e.prefix?"prefix":"")];return void 0!==t?t:20}function i(e,t,n){var r=this[n||e.type];r?r.call(this,e,t):t.write(e,"/*"+e.type+"?*/ "+t.sourceAt(e.start,e.end))}function s(e,t,n,i){2===i||r(n)0){this.out(e[0],t,e[0].type);for(var r=1,i=e.length;r>":13,"BinaryExpression>>>":13,"BinaryExpression<":12,"BinaryExpression<=":12,"BinaryExpression>":12,"BinaryExpression>=":12,BinaryExpressionin:12,BinaryExpressioninstanceof:12,"BinaryExpression==":11,"BinaryExpression===":11,"BinaryExpression!=":11,"BinaryExpression!==":11,"BinaryExpression&":10,"BinaryExpression^":9,"BinaryExpression|":8,"LogicalExpression&&":7,"LogicalExpression||":6,ConditionalExpression:5,AssignmentPattern:4,AssignmentExpression:4,yield:3,YieldExpression:3,SpreadElement:2,"comma-separated-list":1.5,SequenceExpression:1},m={type:"comma-separated-list"},g={out:i,expr:s,formatParameters:o,Program:function(e,t){var n,r,i=h(t.indent,t.indentLevel),s=t.lineEnd;n=e.body;for(var o=0,a=n.length;o0){t.write(null,s);for(var a=0,u=n.length;a0){this.out(n[0],t,"VariableDeclarator");for(var i=1;i0){for(var n=0;n0)for(var r=0;r ")):(this.formatParameters(e.params,t),t.write(e,"=> ")),"ObjectExpression"===e.body.type||"SequenceExpression"===e.body.type?(t.write(null,"("),this.out(e.body,t,e.body.type),t.write(null,")")):this.out(e.body,t,e.body.type)},ThisExpression:function(e,t){t.write(e,"this")},Super:function(e,t){t.write(e,"super")},RestElement:u=function(e,t){t.write(e,"..."),this.out(e.argument,t,e.argument.type)},SpreadElement:u,YieldExpression:function(e,t){t.write(e,e.delegate?"yield*":"yield"),e.argument&&(t.write(null," "),this.expr(t,e,e.argument))},AwaitExpression:function(e,t){t.write(e,"await "),this.expr(t,e,e.argument)},TemplateLiteral:function(e,t){var n,r=e.quasis,i=e.expressions;t.write(e,"`");for(var s=0,o=i.length;s0)for(var n=e.elements,r=n.length,i=0;;){var s=n[i];if(s&&this.expr(t,m,s),i+=1,(i=r)break;t.lineLength()>t.wrapColumn&&t.write(null,t.lineEnd,h(t.indent,t.indentLevel+1))}t.write(null,"]")},ArrayPattern:l,ObjectExpression:function(e,t){var n,r=h(t.indent,t.indentLevel++),i=t.lineEnd,s=r+t.indent;if(t.write(e,"{"),e.properties.length>0){t.write(null,i);for(var o=e.properties,a=o.length,u=0;n=o[u],t.write(null,s),this.out(n,t,"Property"),++ut.wrapColumn&&t.write(null,t.lineEnd,h(t.indent,t.indentLevel+1));t.write(null,i,r,"}")}else t.write(null,"}");t.indentLevel--},Property:function(e,t){e.method||"get"===e.kind||"set"===e.kind?this.MethodDefinition(e,t):(e.shorthand||(e.computed?(t.write(null,"["),this.out(e.key,t,e.key.type),t.write(null,"]")):this.out(e.key,t,e.key.type),t.write(null,": ")),this.expr(t,m,e.value))},ObjectPattern:function(e,t){if(t.write(e,"{"),e.properties.length>0)for(var n=e.properties,r=n.length,i=0;this.out(n[i],t,"Property"),++i0)for(var i=r.length,s=0;s1&&t.write(e," "),this.expr(t,e,e.argument,!0)):(this.expr(t,e,e.argument),t.write(e,e.operator))},UpdateExpression:function(e,t){e.prefix?(t.write(e,e.operator),this.out(e.argument,t,e.argument.type)):(this.out(e.argument,t,e.argument.type),t.write(e,e.operator))},BinaryExpression:c=function(e,t){var n=e.operator;"in"===n&&t.inForInit&&t.write(null,"("),this.expr(t,e,e.left),t.write(e," ",n," "),this.expr(t,e,e.right,"ArrowFunctionExpression"===e.right.type?2:0),"in"===n&&t.inForInit&&t.write(null,")")},LogicalExpression:c,AssignmentExpression:function(e,t){"ObjectPattern"===e.left.type&&t.write(null,"("),this.BinaryExpression(e,t),"ObjectPattern"===e.left.type&&t.write(null,")")},AssignmentPattern:function(e,t){this.expr(t,e,e.left),t.write(e," = "),this.expr(t,e,e.right)},ConditionalExpression:function(e,t){this.expr(t,e,e.test,!0),t.write(e," ? "),this.expr(t,e,e.consequent),t.write(null," : "),this.expr(t,e,e.alternate)},NewExpression:function(e,t){t.write(e,"new "),this.out(e,t,"CallExpression")},CallExpression:function(e,t){this.expr(t,e,e.callee,"ObjectExpression"===e.callee.type?2:0),t.write(e,"(");var n=e.arguments;if(n.length>0)for(var r=n.length,i=0;i=0&&r({self:i,parent:e,field:a[u],index:!0}):c instanceof Object&&i===c&&r({self:i,parent:e,field:a[u]})}})}return n||(n=[{self:e}],n.replace=function(e,t){n[e].replace(t)}),t(e,s,n),e}function s(t,n){var r=[],s={ecmaVersion:8,allowHashBang:!0,allowReturnOutsideFunction:!0,allowImportExportEverywhere:!0,locations:!0,onComment:r};if((!n||!n.noNodentExtensions||parseInt(a.version)<4)&&(h||(parseInt(a.version)<4&&console.warn("Nodent: Warning - noNodentExtensions option requires acorn >=v4.x. Extensions installed."),e("acorn-es7-plugin")(a),h=!0),s.plugins=s.plugins||{},s.plugins.asyncawait={asyncExits:!0,awaitAnywhere:!0}),n)for(var o in n)"noNodentExtensions"!==o&&(s[o]=n[o]);var u=a.parse(t,s);return i(u,function(e,t,n){for(t();r.length&&e.loc&&e.loc.start.line>=r[0].loc.start.line&&e.loc.end.line>=r[0].loc.end.line;)e.$comments=e.$comments||[],e.$comments.push(r.shift())}),u}function o(e,t){function n(e,r){if(Array.isArray(r)&&!Array.isArray(e))throw new Error("Can't substitute an array for a node");return r=r||{},Object.keys(e).forEach(function(i){function s(e){return"function"==typeof e&&(e=e()),r=r.concat(e)}function o(e){return"function"==typeof e&&(e=e()),r[i]=e,r}if(!(e[i]instanceof Object))return r[i]=e[i];if(Array.isArray(e[i]))return r[i]=n(e[i],[]);var a;if(a=Array.isArray(r)?s:o,"Identifier"===e[i].type&&"$"===e[i].name[0])return a(t[e[i].name.slice(1)]);if("LabeledStatement"===e[i].type&&"$"===e[i].label.name){var u=e[i].body.expression;return a(t[u.name||u.value])}return a("LabeledStatement"===e[i].type&&"$$"===e[i].label.name.slice(0,2)?t[e[i].label.name.slice(2)](n(e[i]).body):n(e[i]))}),r}f[e]||(f[e]=s(e,{noNodentExtensions:!0,locations:!1,ranges:!1,onComment:null}));var r=n(f[e]);return{body:r.body,expr:"ExpressionStatement"===r.body[0].type?r.body[0].expression:null}}var a=e("acorn"),u=e("acorn/dist/walk"),c={AwaitExpression:function(e,t,n){n(e.argument,t,"Expression")},SwitchStatement:function(e,t,n){n(e.discriminant,t,"Expression");for(var r=0;re)return!1;if((n+=t[r+1])>=e)return!0}}function n(e,n){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&k.test(String.fromCharCode(e)):!1!==n&&t(e,_)))}function r(e,n){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&A.test(String.fromCharCode(e)):!1!==n&&(t(e,_)||t(e,C)))))}function i(e,t){ +return new L(e,{beforeExpr:!0,binop:t})}function s(e,t){return void 0===t&&(t={}),t.keyword=e,T[e]=new L(e,t)}function o(e){return 10===e||13===e||8232===e||8233===e}function a(e,t){return j.call(e,t)}function u(e,t){for(var n=1,r=0;;){O.lastIndex=r;var i=O.exec(e);if(!(i&&i.index=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),D(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return D(t.onComment)&&(t.onComment=l(t,t.onComment)),t}function l(e,t){return function(n,r,i,s,o,a){var u={type:n?"Block":"Line",value:r,start:i,end:s};e.locations&&(u.loc=new q(this,o,a)),e.ranges&&(u.range=[i,s]),t.push(u)}}function p(e){return new RegExp("^("+e.replace(/ /g,"|")+")$")}function h(e,t,n,r){return e.type=t,e.end=n,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=n),e}function f(e,t,n,r){try{return new RegExp(e,t)}catch(e){if(void 0!==n)throw e instanceof SyntaxError&&r.raise(n,"Error parsing regular expression: "+e.message),e}}function d(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10),56320+(1023&e)))}function y(e,t){return new W(t,e).parse()}function m(e,t,n){var r=new W(n,e,t);return r.nextToken(),r.parseExpression()}function g(e,t){return new W(t,e)}function v(t,n,r){e.parse_dammit=t,e.LooseParser=n,e.pluginsLoose=r}var b={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},x="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",w={5:x,6:x+" const class extends export import super"},E="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",S="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",k=new RegExp("["+E+"]"),A=new RegExp("["+E+S+"]");E=S=null;var _=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541],C=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239],L=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null},P={beforeExpr:!0},N={startsExpr:!0},T={},F={num:new L("num",N),regexp:new L("regexp",N),string:new L("string",N),name:new L("name",N),eof:new L("eof"),bracketL:new L("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new L("]"),braceL:new L("{",{beforeExpr:!0,startsExpr:!0}),braceR:new L("}"),parenL:new L("(",{beforeExpr:!0,startsExpr:!0}),parenR:new L(")"),comma:new L(",",P),semi:new L(";",P),colon:new L(":",P),dot:new L("."),question:new L("?",P),arrow:new L("=>",P),template:new L("template"),ellipsis:new L("...",P),backQuote:new L("`",N),dollarBraceL:new L("${",{beforeExpr:!0,startsExpr:!0}),eq:new L("=",{beforeExpr:!0,isAssign:!0}),assign:new L("_=",{beforeExpr:!0,isAssign:!0}),incDec:new L("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new L("prefix",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:i("||",1),logicalAND:i("&&",2),bitwiseOR:i("|",3),bitwiseXOR:i("^",4),bitwiseAND:i("&",5),equality:i("==/!=",6),relational:i("",7),bitShift:i("<>",8),plusMin:new L("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:i("%",10),star:i("*",10),slash:i("/",10),starstar:new L("**",{beforeExpr:!0}),_break:s("break"),_case:s("case",P),_catch:s("catch"),_continue:s("continue"),_debugger:s("debugger"),_default:s("default",P),_do:s("do",{isLoop:!0,beforeExpr:!0}),_else:s("else",P),_finally:s("finally"),_for:s("for",{isLoop:!0}),_function:s("function",N),_if:s("if"),_return:s("return",P),_switch:s("switch"),_throw:s("throw",P),_try:s("try"),_var:s("var"),_const:s("const"),_while:s("while",{isLoop:!0}),_with:s("with"),_new:s("new",{beforeExpr:!0,startsExpr:!0}),_this:s("this",N),_super:s("super",N),_class:s("class"),_extends:s("extends",P),_export:s("export"),_import:s("import"),_null:s("null",N),_true:s("true",N),_false:s("false",N),_in:s("in",{beforeExpr:!0,binop:7}),_instanceof:s("instanceof",{beforeExpr:!0,binop:7}),_typeof:s("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:s("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:s("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},$=/\r\n?|\n|\u2028|\u2029/,O=new RegExp($.source,"g"),B=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,R=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,I=Object.prototype,j=I.hasOwnProperty,M=I.toString,D=Array.isArray||function(e){return"[object Array]"===M.call(e)},V=function(e,t){this.line=e,this.column=t};V.prototype.offset=function(e){return new V(this.line,this.column+e)};var q=function(e,t,n){this.start=t,this.end=n,null!==e.sourceFile&&(this.source=e.sourceFile)},U={ecmaVersion:7,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1,plugins:{}},z={},W=function(e,t,n){this.options=e=c(e),this.sourceFile=e.sourceFile,this.keywords=p(w[e.ecmaVersion>=6?6:5]);var r="";if(!e.allowReserved){for(var i=e.ecmaVersion;!(r=b[i]);i--);"module"==e.sourceType&&(r+=" await")}this.reservedWords=p(r);var s=(r?r+" ":"")+b.strict;this.reservedWordsStrict=p(s),this.reservedWordsStrictBind=p(s+" "+b.strictBind),this.input=String(t),this.containsEsc=!1,this.loadPlugins(e.plugins),n?(this.pos=n,this.lineStart=this.input.lastIndexOf("\n",n-1)+1,this.curLine=this.input.slice(0,this.lineStart).split($).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=F.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.inFunction=this.inGenerator=this.inAsync=!1,this.yieldPos=this.awaitPos=0,this.labels=[],0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterFunctionScope()};W.prototype.isKeyword=function(e){return this.keywords.test(e)},W.prototype.isReservedWord=function(e){return this.reservedWords.test(e)},W.prototype.extend=function(e,t){this[e]=t(this[e])},W.prototype.loadPlugins=function(e){var t=this;for(var n in e){var r=z[n];if(!r)throw new Error("Plugin '"+n+"' not found");r(t,e[n])}},W.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)};var G=W.prototype,J=/^(?:'((?:[^']|\.)*)'|"((?:[^"]|\.)*)"|;)/;G.strictDirective=function(e){for(var t=this;;){R.lastIndex=e,e+=R.exec(t.input)[0].length;var n=J.exec(t.input.slice(e));if(!n)return!1;if("use strict"==(n[1]||n[2]))return!0;e+=n[0].length}},G.eat=function(e){return this.type===e&&(this.next(),!0)},G.isContextual=function(e){return this.type===F.name&&this.value===e},G.eatContextual=function(e){return this.value===e&&this.eat(F.name)},G.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},G.canInsertSemicolon=function(){return this.type===F.eof||this.type===F.braceR||$.test(this.input.slice(this.lastTokEnd,this.start))},G.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},G.semicolon=function(){this.eat(F.semi)||this.insertSemicolon()||this.unexpected()},G.afterTrailingComma=function(e,t){if(this.type==e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},G.expect=function(e){this.eat(e)||this.unexpected()},G.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var Y=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=-1};G.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var n=t?e.parenthesizedAssign:e.parenthesizedBind;n>-1&&this.raiseRecoverable(n,"Parenthesized pattern")}},G.checkExpressionErrors=function(e,t){var n=e?e.shorthandAssign:-1;if(!t)return n>=0;n>-1&&this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")},G.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos=6&&(e.sourceType=this.options.sourceType),this.finishNode(e,"Program")};var Z={kind:"loop"},Q={kind:"switch"};H.isLet=function(){if(this.type!==F.name||this.options.ecmaVersion<6||"let"!=this.value)return!1;R.lastIndex=this.pos;var e=R.exec(this.input),t=this.pos+e[0].length,i=this.input.charCodeAt(t);if(91===i||123==i)return!0;if(n(i,!0)){for(var s=t+1;r(this.input.charCodeAt(s),!0);)++s;var o=this.input.slice(t,s);if(!this.isKeyword(o))return!0}return!1},H.isAsyncFunction=function(){if(this.type!==F.name||this.options.ecmaVersion<8||"async"!=this.value)return!1;R.lastIndex=this.pos;var e=R.exec(this.input),t=this.pos+e[0].length;return!($.test(this.input.slice(this.pos,t))||"function"!==this.input.slice(t,t+8)||t+8!=this.input.length&&r(this.input.charAt(t+8)))},H.parseStatement=function(e,t,n){var r,i=this.type,s=this.startNode();switch(this.isLet()&&(i=F._var,r="let"),i){case F._break:case F._continue:return this.parseBreakContinueStatement(s,i.keyword);case F._debugger:return this.parseDebuggerStatement(s);case F._do:return this.parseDoStatement(s);case F._for:return this.parseForStatement(s);case F._function:return!e&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(s,!1);case F._class:return e||this.unexpected(),this.parseClass(s,!0);case F._if:return this.parseIfStatement(s);case F._return:return this.parseReturnStatement(s);case F._switch:return this.parseSwitchStatement(s);case F._throw:return this.parseThrowStatement(s);case F._try:return this.parseTryStatement(s);case F._const:case F._var:return r=r||this.value,e||"var"==r||this.unexpected(),this.parseVarStatement(s,r);case F._while:return this.parseWhileStatement(s);case F._with:return this.parseWithStatement(s);case F.braceL:return this.parseBlock();case F.semi:return this.parseEmptyStatement(s);case F._export:case F._import:return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),i===F._import?this.parseImport(s):this.parseExport(s,n);default:if(this.isAsyncFunction()&&e)return this.next(),this.parseFunctionStatement(s,!0);var o=this.value,a=this.parseExpression();return i===F.name&&"Identifier"===a.type&&this.eat(F.colon)?this.parseLabeledStatement(s,o,a):this.parseExpressionStatement(s,a)}},H.parseBreakContinueStatement=function(e,t){var n=this,r="break"==t;this.next(),this.eat(F.semi)||this.insertSemicolon()?e.label=null:this.type!==F.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var i=0;i=6?this.eat(F.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},H.parseForStatement=function(e){if(this.next(),this.labels.push(Z),this.enterLexicalScope(),this.expect(F.parenL),this.type===F.semi)return this.parseFor(e,null);var t=this.isLet();if(this.type===F._var||this.type===F._const||t){var n=this.startNode(),r=t?"let":this.value;return this.next(),this.parseVar(n,!0,r),this.finishNode(n,"VariableDeclaration"),!(this.type===F._in||this.options.ecmaVersion>=6&&this.isContextual("of"))||1!==n.declarations.length||"var"!==r&&n.declarations[0].init?this.parseFor(e,n):this.parseForIn(e,n)}var i=new Y,s=this.parseExpression(!0,i);return this.type===F._in||this.options.ecmaVersion>=6&&this.isContextual("of")?(this.toAssignable(s),this.checkLVal(s),this.checkPatternErrors(i,!0),this.parseForIn(e,s)):(this.checkExpressionErrors(i,!0),this.parseFor(e,s))},H.parseFunctionStatement=function(e,t){return this.next(),this.parseFunction(e,!0,!1,t)},H.isFunction=function(){return this.type===F._function||this.isAsyncFunction()},H.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(!this.strict&&this.isFunction()),e.alternate=this.eat(F._else)?this.parseStatement(!this.strict&&this.isFunction()):null,this.finishNode(e,"IfStatement")},H.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(F.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},H.parseSwitchStatement=function(e){var t=this;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(F.braceL),this.labels.push(Q),this.enterLexicalScope();for(var n,r=!1;this.type!=F.braceR;)if(t.type===F._case||t.type===F._default){var i=t.type===F._case;n&&t.finishNode(n,"SwitchCase"),e.cases.push(n=t.startNode()),n.consequent=[],t.next(),i?n.test=t.parseExpression():(r&&t.raiseRecoverable(t.lastTokStart,"Multiple default clauses"),r=!0,n.test=null),t.expect(F.colon)}else n||t.unexpected(),n.consequent.push(t.parseStatement(!0));return this.exitLexicalScope(),n&&this.finishNode(n,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},H.parseThrowStatement=function(e){return this.next(),$.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var X=[];H.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===F._catch){var t=this.startNode();this.next(),this.expect(F.parenL),t.param=this.parseBindingAtom(),this.enterLexicalScope(),this.checkLVal(t.param,"let"),this.expect(F.parenR),t.body=this.parseBlock(!1),this.exitLexicalScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(F._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},H.parseVarStatement=function(e,t){return this.next(),this.parseVar(e,!1,t),this.semicolon(),this.finishNode(e,"VariableDeclaration")},H.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(Z),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"WhileStatement")},H.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(!1),this.finishNode(e,"WithStatement")},H.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},H.parseLabeledStatement=function(e,t,n){for(var r=this,i=0;i=0;o--){var a=r.labels[o];if(a.statementStart!=e.start)break;a.statementStart=r.start,a.kind=s}return this.labels.push({name:t,kind:s,statementStart:this.start}),e.body=this.parseStatement(!0),("ClassDeclaration"==e.body.type||"VariableDeclaration"==e.body.type&&"var"!=e.body.kind||"FunctionDeclaration"==e.body.type&&(this.strict||e.body.generator))&&this.raiseRecoverable(e.body.start,"Invalid labeled declaration"),this.labels.pop(),e.label=n,this.finishNode(e,"LabeledStatement")},H.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},H.parseBlock=function(e){var t=this;void 0===e&&(e=!0);var n=this.startNode();for(n.body=[],this.expect(F.braceL),e&&this.enterLexicalScope();!this.eat(F.braceR);){var r=t.parseStatement(!0);n.body.push(r)}return e&&this.exitLexicalScope(),this.finishNode(n,"BlockStatement")},H.parseFor=function(e,t){return e.init=t,this.expect(F.semi),e.test=this.type===F.semi?null:this.parseExpression(),this.expect(F.semi),e.update=this.type===F.parenR?null:this.parseExpression(),this.expect(F.parenR),this.exitLexicalScope(),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"ForStatement")},H.parseForIn=function(e,t){var n=this.type===F._in?"ForInStatement":"ForOfStatement";return this.next(),e.left=t,e.right=this.parseExpression(),this.expect(F.parenR),this.exitLexicalScope(),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,n)},H.parseVar=function(e,t,n){var r=this;for(e.declarations=[],e.kind=n;;){var i=r.startNode();if(r.parseVarId(i,n),r.eat(F.eq)?i.init=r.parseMaybeAssign(t):"const"!==n||r.type===F._in||r.options.ecmaVersion>=6&&r.isContextual("of")?"Identifier"==i.id.type||t&&(r.type===F._in||r.isContextual("of"))?i.init=null:r.raise(r.lastTokEnd,"Complex binding patterns require an initialization value"):r.unexpected(),e.declarations.push(r.finishNode(i,"VariableDeclarator")),!r.eat(F.comma))break}return e},H.parseVarId=function(e,t){e.id=this.parseBindingAtom(t),this.checkLVal(e.id,t,!1)},H.parseFunction=function(e,t,n,r){this.initFunction(e),this.options.ecmaVersion>=6&&!r&&(e.generator=this.eat(F.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&&(e.id="nullableID"===t&&this.type!=F.name?null:this.parseIdent(),e.id&&this.checkLVal(e.id,"var"));var i=this.inGenerator,s=this.inAsync,o=this.yieldPos,a=this.awaitPos,u=this.inFunction;return this.inGenerator=e.generator,this.inAsync=e.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),t||(e.id=this.type==F.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,n),this.inGenerator=i,this.inAsync=s,this.yieldPos=o,this.awaitPos=a,this.inFunction=u,this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression")},H.parseFunctionParams=function(e){this.expect(F.parenL),e.params=this.parseBindingList(F.parenR,!1,this.options.ecmaVersion>=8,!0),this.checkYieldAwaitInDefaultParams()},H.parseClass=function(e,t){var n=this;this.next(),this.parseClassId(e,t),this.parseClassSuper(e);var r=this.startNode(),i=!1;for(r.body=[],this.expect(F.braceL);!this.eat(F.braceR);)if(!n.eat(F.semi)){var s=n.startNode(),o=n.eat(F.star),a=!1,u=n.type===F.name&&"static"===n.value;n.parsePropertyName(s),s.static=u&&n.type!==F.parenL,s.static&&(o&&n.unexpected(),o=n.eat(F.star),n.parsePropertyName(s)),n.options.ecmaVersion>=8&&!o&&!s.computed&&"Identifier"===s.key.type&&"async"===s.key.name&&n.type!==F.parenL&&!n.canInsertSemicolon()&&(a=!0,n.parsePropertyName(s)),s.kind="method";var c=!1;if(!s.computed){var l=s.key;o||a||"Identifier"!==l.type||n.type===F.parenL||"get"!==l.name&&"set"!==l.name||(c=!0,s.kind=l.name,l=n.parsePropertyName(s)),!s.static&&("Identifier"===l.type&&"constructor"===l.name||"Literal"===l.type&&"constructor"===l.value)&&(i&&n.raise(l.start,"Duplicate constructor in the same class"),c&&n.raise(l.start,"Constructor can't have get/set modifier"),o&&n.raise(l.start,"Constructor can't be a generator"),a&&n.raise(l.start,"Constructor can't be an async method"),s.kind="constructor",i=!0)}if(n.parseClassMethod(r,s,o,a),c){var p="get"===s.kind?0:1;if(s.value.params.length!==p){var h=s.value.start;"get"===s.kind?n.raiseRecoverable(h,"getter should have no params"):n.raiseRecoverable(h,"setter should have exactly one param")}else"set"===s.kind&&"RestElement"===s.value.params[0].type&&n.raiseRecoverable(s.value.params[0].start,"Setter cannot use rest params")}}return e.body=this.finishNode(r,"ClassBody"),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},H.parseClassMethod=function(e,t,n,r){t.value=this.parseMethod(n,r),e.body.push(this.finishNode(t,"MethodDefinition"))},H.parseClassId=function(e,t){e.id=this.type===F.name?this.parseIdent():!0===t?this.unexpected():null},H.parseClassSuper=function(e){e.superClass=this.eat(F._extends)?this.parseExprSubscripts():null},H.parseExport=function(e,t){var n=this;if(this.next(),this.eat(F.star))return this.expectContextual("from"),e.source=this.type===F.string?this.parseExprAtom():this.unexpected(),this.semicolon(),this.finishNode(e,"ExportAllDeclaration");if(this.eat(F._default)){this.checkExport(t,"default",this.lastTokStart);var r;if(this.type===F._function||(r=this.isAsyncFunction())){var i=this.startNode();this.next(),r&&this.next(),e.declaration=this.parseFunction(i,"nullableID",!1,r)}else if(this.type===F._class){var s=this.startNode();e.declaration=this.parseClass(s,"nullableID")}else e.declaration=this.parseMaybeAssign(),this.semicolon();return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement())e.declaration=this.parseStatement(!0),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id.name,e.declaration.id.start),e.specifiers=[],e.source=null;else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))e.source=this.type===F.string?this.parseExprAtom():this.unexpected();else{for(var o=0;o=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Can not use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var r=0;r=6&&(e.computed||e.method||e.shorthand))){var n,r=e.key;switch(r.type){case"Identifier":n=r.name;break;case"Literal":n=String(r.value);break;default:return}var i=e.kind;if(this.options.ecmaVersion>=6)return void("__proto__"===n&&"init"===i&&(t.proto&&this.raiseRecoverable(r.start,"Redefinition of __proto__ property"),t.proto=!0));n="$"+n;var s=t[n];if(s){var o;o="init"===i?this.strict&&s.init||s.get||s.set:s.init||s[i],o&&this.raiseRecoverable(r.start,"Redefinition of property")}else s=t[n]={init:!1,get:!1,set:!1};s[i]=!0}},ee.parseExpression=function(e,t){var n=this,r=this.start,i=this.startLoc,s=this.parseMaybeAssign(e,t);if(this.type===F.comma){var o=this.startNodeAt(r,i);for(o.expressions=[s];this.eat(F.comma);)o.expressions.push(n.parseMaybeAssign(e,t));return this.finishNode(o,"SequenceExpression")}return s},ee.parseMaybeAssign=function(e,t,n){if(this.inGenerator&&this.isContextual("yield"))return this.parseYield();var r=!1,i=-1,s=-1;t?(i=t.parenthesizedAssign,s=t.trailingComma,t.parenthesizedAssign=t.trailingComma=-1):(t=new Y,r=!0);var o=this.start,a=this.startLoc;this.type!=F.parenL&&this.type!=F.name||(this.potentialArrowAt=this.start);var u=this.parseMaybeConditional(e,t);if(n&&(u=n.call(this,u,o,a)),this.type.isAssign){this.checkPatternErrors(t,!0),r||Y.call(t);var c=this.startNodeAt(o,a);return c.operator=this.value,c.left=this.type===F.eq?this.toAssignable(u):u,t.shorthandAssign=-1,this.checkLVal(u),this.next(),c.right=this.parseMaybeAssign(e),this.finishNode(c,"AssignmentExpression")}return r&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),s>-1&&(t.trailingComma=s),u},ee.parseMaybeConditional=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if(this.eat(F.question)){var s=this.startNodeAt(n,r);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(F.colon),s.alternate=this.parseMaybeAssign(e),this.finishNode(s,"ConditionalExpression")}return i},ee.parseExprOps=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(t,!1);return this.checkExpressionErrors(t)?i:i.start==n&&"ArrowFunctionExpression"===i.type?i:this.parseExprOp(i,n,r,-1,e)},ee.parseExprOp=function(e,t,n,r,i){var s=this.type.binop;if(null!=s&&(!i||this.type!==F._in)&&s>r){var o=this.type===F.logicalOR||this.type===F.logicalAND,a=this.value;this.next();var u=this.start,c=this.startLoc,l=this.parseExprOp(this.parseMaybeUnary(null,!1),u,c,s,i),p=this.buildBinary(t,n,e,l,a,o);return this.parseExprOp(p,t,n,r,i)}return e},ee.buildBinary=function(e,t,n,r,i,s){var o=this.startNodeAt(e,t);return o.left=n,o.operator=i,o.right=r,this.finishNode(o,s?"LogicalExpression":"BinaryExpression")},ee.parseMaybeUnary=function(e,t){var n,r=this,i=this.start,s=this.startLoc;if(this.inAsync&&this.isContextual("await"))n=this.parseAwait(e),t=!0;else if(this.type.prefix){var o=this.startNode(),a=this.type===F.incDec;o.operator=this.value,o.prefix=!0,this.next(),o.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(e,!0),a?this.checkLVal(o.argument):this.strict&&"delete"===o.operator&&"Identifier"===o.argument.type?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):t=!0,n=this.finishNode(o,a?"UpdateExpression":"UnaryExpression")}else{if(n=this.parseExprSubscripts(e),this.checkExpressionErrors(e))return n;for(;this.type.postfix&&!this.canInsertSemicolon();){var u=r.startNodeAt(i,s);u.operator=r.value,u.prefix=!1,u.argument=n,r.checkLVal(n),r.next(),n=r.finishNode(u,"UpdateExpression")}}return!t&&this.eat(F.starstar)?this.buildBinary(i,s,n,this.parseMaybeUnary(null,!1),"**",!1):n},ee.parseExprSubscripts=function(e){var t=this.start,n=this.startLoc,r=this.parseExprAtom(e),i="ArrowFunctionExpression"===r.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd);if(this.checkExpressionErrors(e)||i)return r;var s=this.parseSubscripts(r,t,n);return e&&"MemberExpression"===s.type&&(e.parenthesizedAssign>=s.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=s.start&&(e.parenthesizedBind=-1)),s},ee.parseSubscripts=function(e,t,n,r){for(var i,s=this,o=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd==e.end&&!this.canInsertSemicolon();;)if((i=s.eat(F.bracketL))||s.eat(F.dot)){var a=s.startNodeAt(t,n);a.object=e,a.property=i?s.parseExpression():s.parseIdent(!0),a.computed=!!i,i&&s.expect(F.bracketR),e=s.finishNode(a,"MemberExpression")}else if(!r&&s.eat(F.parenL)){var u=new Y,c=s.yieldPos,l=s.awaitPos;s.yieldPos=0,s.awaitPos=0;var p=s.parseExprList(F.parenR,s.options.ecmaVersion>=8,!1,u);if(o&&!s.canInsertSemicolon()&&s.eat(F.arrow))return s.checkPatternErrors(u,!1),s.checkYieldAwaitInDefaultParams(),s.yieldPos=c,s.awaitPos=l,s.parseArrowExpression(s.startNodeAt(t,n),p,!0);s.checkExpressionErrors(u,!0),s.yieldPos=c||s.yieldPos,s.awaitPos=l||s.awaitPos;var h=s.startNodeAt(t,n);h.callee=e,h.arguments=p,e=s.finishNode(h,"CallExpression")}else{if(s.type!==F.backQuote)return e;var f=s.startNodeAt(t,n);f.tag=e,f.quasi=s.parseTemplate(),e=s.finishNode(f,"TaggedTemplateExpression")}},ee.parseExprAtom=function(e){var t,n=this.potentialArrowAt==this.start;switch(this.type){case F._super:this.inFunction||this.raise(this.start,"'super' outside of function or class");case F._this:var r=this.type===F._this?"ThisExpression":"Super";return t=this.startNode(),this.next(),this.finishNode(t,r);case F.name:var i=this.start,s=this.startLoc,o=this.parseIdent(this.type!==F.name);if(this.options.ecmaVersion>=8&&"async"===o.name&&!this.canInsertSemicolon()&&this.eat(F._function))return this.parseFunction(this.startNodeAt(i,s),!1,!1,!0);if(n&&!this.canInsertSemicolon()){if(this.eat(F.arrow))return this.parseArrowExpression(this.startNodeAt(i,s),[o],!1);if(this.options.ecmaVersion>=8&&"async"===o.name&&this.type===F.name)return o=this.parseIdent(),!this.canInsertSemicolon()&&this.eat(F.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(i,s),[o],!0)}return o;case F.regexp:var a=this.value;return t=this.parseLiteral(a.value),t.regex={pattern:a.pattern,flags:a.flags},t;case F.num:case F.string:return this.parseLiteral(this.value);case F._null:case F._true:case F._false:return t=this.startNode(),t.value=this.type===F._null?null:this.type===F._true,t.raw=this.type.keyword,this.next(),this.finishNode(t,"Literal");case F.parenL:var u=this.start,c=this.parseParenAndDistinguishExpression(n);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)&&(e.parenthesizedAssign=u),e.parenthesizedBind<0&&(e.parenthesizedBind=u)),c;case F.bracketL:return t=this.startNode(),this.next(),t.elements=this.parseExprList(F.bracketR,!0,!0,e),this.finishNode(t,"ArrayExpression");case F.braceL:return this.parseObj(!1,e);case F._function:return t=this.startNode(),this.next(),this.parseFunction(t,!1);case F._class:return this.parseClass(this.startNode(),!1);case F._new:return this.parseNew();case F.backQuote:return this.parseTemplate();default:this.unexpected()}},ee.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(t,"Literal")},ee.parseParenExpression=function(){this.expect(F.parenL);var e=this.parseExpression();return this.expect(F.parenR),e},ee.parseParenAndDistinguishExpression=function(e){var t,n=this,r=this.start,i=this.startLoc,s=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o,a,u=this.start,c=this.startLoc,l=[],p=!0,h=!1,f=new Y,d=this.yieldPos,y=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==F.parenR;){if(p?p=!1:n.expect(F.comma),s&&n.afterTrailingComma(F.parenR,!0)){h=!0;break}if(n.type===F.ellipsis){o=n.start,l.push(n.parseParenItem(n.parseRest())),n.type===F.comma&&n.raise(n.start,"Comma is not permitted after the rest element");break}n.type!==F.parenL||a||(a=n.start),l.push(n.parseMaybeAssign(!1,f,n.parseParenItem))}var m=this.start,g=this.startLoc;if(this.expect(F.parenR),e&&!this.canInsertSemicolon()&&this.eat(F.arrow))return this.checkPatternErrors(f,!1),this.checkYieldAwaitInDefaultParams(),a&&this.unexpected(a),this.yieldPos=d,this.awaitPos=y,this.parseParenArrowList(r,i,l);l.length&&!h||this.unexpected(this.lastTokStart),o&&this.unexpected(o),this.checkExpressionErrors(f,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=y||this.awaitPos,l.length>1?(t=this.startNodeAt(u,c),t.expressions=l,this.finishNodeAt(t,"SequenceExpression",m,g)):t=l[0]}else t=this.parseParenExpression();if(this.options.preserveParens){var v=this.startNodeAt(r,i);return v.expression=t,this.finishNode(v,"ParenthesizedExpression")}return t},ee.parseParenItem=function(e){return e},ee.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var te=[];ee.parseNew=function(){var e=this.startNode(),t=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(F.dot))return e.meta=t,e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is new.target"),this.inFunction||this.raiseRecoverable(e.start,"new.target can only be used in functions"),this.finishNode(e,"MetaProperty");var n=this.start,r=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(),n,r,!0),this.eat(F.parenL)?e.arguments=this.parseExprList(F.parenR,this.options.ecmaVersion>=8,!1):e.arguments=te,this.finishNode(e,"NewExpression")},ee.parseTemplateElement=function(){var e=this.startNode();return e.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),e.tail=this.type===F.backQuote,this.finishNode(e,"TemplateElement")},ee.parseTemplate=function(){var e=this,t=this.startNode();this.next(),t.expressions=[];var n=this.parseTemplateElement();for(t.quasis=[n];!n.tail;)e.expect(F.dollarBraceL),t.expressions.push(e.parseExpression()),e.expect(F.braceR),t.quasis.push(n=e.parseTemplateElement());return this.next(),this.finishNode(t,"TemplateLiteral")},ee.parseObj=function(e,t){var n=this,r=this.startNode(),i=!0,s={};for(r.properties=[],this.next();!this.eat(F.braceR);){if(i)i=!1;else if(n.expect(F.comma),n.afterTrailingComma(F.braceR))break;var o,a,u,c,l=n.startNode();n.options.ecmaVersion>=6&&(l.method=!1,l.shorthand=!1,(e||t)&&(u=n.start,c=n.startLoc),e||(o=n.eat(F.star))),n.parsePropertyName(l),e||!(n.options.ecmaVersion>=8)||o||l.computed||"Identifier"!==l.key.type||"async"!==l.key.name||n.type===F.parenL||n.type===F.colon||n.canInsertSemicolon()?a=!1:(a=!0,n.parsePropertyName(l,t)),n.parsePropertyValue(l,e,o,a,u,c,t),n.checkPropClash(l,s),r.properties.push(n.finishNode(l,"Property"))}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")},ee.parsePropertyValue=function(e,t,n,r,i,s,o){if((n||r)&&this.type===F.colon&&this.unexpected(),this.eat(F.colon))e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind="init";else if(this.options.ecmaVersion>=6&&this.type===F.parenL)t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(n,r);else if(this.options.ecmaVersion>=5&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&this.type!=F.comma&&this.type!=F.braceR){(n||r||t)&&this.unexpected(),e.kind=e.key.name,this.parsePropertyName(e),e.value=this.parseMethod(!1);var a="get"===e.kind?0:1;if(e.value.params.length!==a){var u=e.value.start;"get"===e.kind?this.raiseRecoverable(u,"getter should have no params"):this.raiseRecoverable(u,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}else this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((this.keywords.test(e.key.name)||(this.strict?this.reservedWordsStrict:this.reservedWords).test(e.key.name)||this.inGenerator&&"yield"==e.key.name||this.inAsync&&"await"==e.key.name)&&this.raiseRecoverable(e.key.start,"'"+e.key.name+"' can not be used as shorthand property"),e.kind="init",t?e.value=this.parseMaybeDefault(i,s,e.key):this.type===F.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,s,e.key)):e.value=e.key,e.shorthand=!0):this.unexpected()},ee.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(F.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(F.bracketR),e.key;e.computed=!1}return e.key=this.type===F.num||this.type===F.string?this.parseExprAtom():this.parseIdent(!0)},ee.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=!1,e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},ee.parseMethod=function(e,t){var n=this.startNode(),r=this.inGenerator,i=this.inAsync,s=this.yieldPos,o=this.awaitPos,a=this.inFunction;return this.initFunction(n),this.options.ecmaVersion>=6&&(n.generator=e),this.options.ecmaVersion>=8&&(n.async=!!t),this.inGenerator=n.generator,this.inAsync=n.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),this.expect(F.parenL),n.params=this.parseBindingList(F.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(n,!1),this.inGenerator=r,this.inAsync=i,this.yieldPos=s,this.awaitPos=o,this.inFunction=a,this.finishNode(n,"FunctionExpression")},ee.parseArrowExpression=function(e,t,n){var r=this.inGenerator,i=this.inAsync,s=this.yieldPos,o=this.awaitPos,a=this.inFunction;return this.enterFunctionScope(),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!n),this.inGenerator=!1,this.inAsync=e.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0),this.inGenerator=r,this.inAsync=i,this.yieldPos=s,this.awaitPos=o,this.inFunction=a,this.finishNode(e,"ArrowFunctionExpression")},ee.parseFunctionBody=function(e,t){var n=t&&this.type!==F.braceL,r=this.strict,i=!1;if(n)e.body=this.parseMaybeAssign(),e.expression=!0,this.checkParams(e,!1);else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);r&&!s||(i=this.strictDirective(this.end))&&s&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var o=this.labels;this.labels=[],i&&(this.strict=!0),this.checkParams(e,!r&&!i&&!t&&this.isSimpleParamList(e.params)),e.body=this.parseBlock(!1),e.expression=!1,this.labels=o}this.exitFunctionScope(),this.strict&&e.id&&this.checkLVal(e.id,"none"),this.strict=r},ee.isSimpleParamList=function(e){for(var t=0;t=6||-1==this.input.slice(this.start,this.end).indexOf("\\"))&&this.raiseRecoverable(this.start,"The keyword '"+this.value+"' is reserved"),this.inGenerator&&"yield"===this.value&&this.raiseRecoverable(this.start,"Can not use 'yield' as identifier inside a generator"),this.inAsync&&"await"===this.value&&this.raiseRecoverable(this.start,"Can not use 'await' as identifier inside an async function"),t.name=this.value):e&&this.type.keyword?t.name=this.type.keyword:this.unexpected(),this.next(),this.finishNode(t,"Identifier")},ee.parseYield=function(){this.yieldPos||(this.yieldPos=this.start);var e=this.startNode();return this.next(),this.type==F.semi||this.canInsertSemicolon()||this.type!=F.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(F.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")},ee.parseAwait=function(){this.awaitPos||(this.awaitPos=this.start);var e=this.startNode();return this.next(),e.argument=this.parseMaybeUnary(null,!0),this.finishNode(e,"AwaitExpression")};var ne=W.prototype;ne.raise=function(e,t){var n=u(this.input,e);t+=" ("+n.line+":"+n.column+")";var r=new SyntaxError(t);throw r.pos=e,r.loc=n,r.raisedAt=this.pos,r},ne.raiseRecoverable=ne.raise,ne.curPosition=function(){if(this.options.locations)return new V(this.curLine,this.pos-this.lineStart)};var re=W.prototype,ie=Object.assign||function(e){for(var t=[],n=arguments.length-1;n-- >0;)t[n]=arguments[n+1];for(var r=0;r=0;t--)if(e.context[t].generator)return!0;return!1},ce.updateContext=function(e){var t,n=this.type;n.keyword&&e==F.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},F.parenR.updateContext=F.braceR.updateContext=function(){if(1==this.context.length)return void(this.exprAllowed=!0);var e,t=this.context.pop();t===ue.b_stat&&(e=this.curContext())&&"function"===e.token?(this.context.pop(),this.exprAllowed=!1):t===ue.b_tmpl?this.exprAllowed=!0:this.exprAllowed=!t.isExpr},F.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?ue.b_stat:ue.b_expr),this.exprAllowed=!0},F.dollarBraceL.updateContext=function(){this.context.push(ue.b_tmpl),this.exprAllowed=!0},F.parenL.updateContext=function(e){var t=e===F._if||e===F._for||e===F._with||e===F._while;this.context.push(t?ue.p_stat:ue.p_expr),this.exprAllowed=!0},F.incDec.updateContext=function(){},F._function.updateContext=function(e){e.beforeExpr&&e!==F.semi&&e!==F._else&&(e!==F.colon&&e!==F.braceL||this.curContext()!==ue.b_stat)&&this.context.push(ue.f_expr),this.exprAllowed=!1},F.backQuote.updateContext=function(){this.curContext()===ue.q_tmpl?this.context.pop():this.context.push(ue.q_tmpl),this.exprAllowed=!1},F.star.updateContext=function(e){e==F._function&&(this.curContext()===ue.f_expr?this.context[this.context.length-1]=ue.f_expr_gen:this.context.push(ue.f_gen)),this.exprAllowed=!0},F.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&("of"==this.value&&!this.exprAllowed||"yield"==this.value&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var le=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new q(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},pe=W.prototype,he="object"==typeof Packages&&"[object JavaPackage]"==Object.prototype.toString.call(Packages);pe.next=function(){this.options.onToken&&this.options.onToken(new le(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},pe.getToken=function(){return this.next(),new le(this)},"undefined"!=typeof Symbol&&(pe[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===F.eof,value:t}}}}),pe.curContext=function(){return this.context[this.context.length-1]},pe.nextToken=function(){var e=this.curContext();return e&&e.preserveSpace||this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length?this.finishToken(F.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},pe.readToken=function(e){return n(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},pe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);return e<=55295||e>=57344?e:(e<<10)+this.input.charCodeAt(this.pos+1)-56613888},pe.skipBlockComment=function(){var e=this,t=this.options.onComment&&this.curPosition(),n=this.pos,r=this.input.indexOf("*/",this.pos+=2);if(-1===r&&this.raise(this.pos-2,"Unterminated comment"),this.pos=r+2,this.options.locations){O.lastIndex=n;for(var i;(i=O.exec(this.input))&&i.index8&&t<14||t>=5760&&B.test(String.fromCharCode(t))))break e;++e.pos}}},pe.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=e,this.value=t,this.updateContext(n)},pe.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(F.ellipsis)):(++this.pos,this.finishToken(F.dot))},pe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(F.assign,2):this.finishOp(F.slash,1)},pe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=42===e?F.star:F.modulo;return this.options.ecmaVersion>=7&&42===t&&(++n,r=F.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(F.assign,n+1):this.finishOp(r,n)},pe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.finishOp(124===e?F.logicalOR:F.logicalAND,2):61===t?this.finishOp(F.assign,2):this.finishOp(124===e?F.bitwiseOR:F.bitwiseAND,1)},pe.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(F.assign,2):this.finishOp(F.bitwiseXOR,1)},pe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45==t&&62==this.input.charCodeAt(this.pos+2)&&$.test(this.input.slice(this.lastTokEnd,this.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(F.incDec,2):61===t?this.finishOp(F.assign,2):this.finishOp(F.plusMin,1)},pe.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),n=1;return t===e?(n=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+n)?this.finishOp(F.assign,n+1):this.finishOp(F.bitShift,n)):33==t&&60==e&&45==this.input.charCodeAt(this.pos+2)&&45==this.input.charCodeAt(this.pos+3)?(this.inModule&&this.unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===t&&(n=2),this.finishOp(F.relational,n))},pe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(F.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(F.arrow)):this.finishOp(61===e?F.eq:F.prefix,1)},pe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(F.parenL);case 41:return++this.pos,this.finishToken(F.parenR);case 59:return++this.pos,this.finishToken(F.semi);case 44:return++this.pos,this.finishToken(F.comma);case 91:return++this.pos,this.finishToken(F.bracketL);case 93:return++this.pos,this.finishToken(F.bracketR);case 123:return++this.pos,this.finishToken(F.braceL);case 125:return++this.pos,this.finishToken(F.braceR);case 58:return++this.pos,this.finishToken(F.colon);case 63:return++this.pos,this.finishToken(F.question);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(F.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(F.prefix,1)}this.raise(this.pos,"Unexpected character '"+d(e)+"'")},pe.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)};var fe=!!f("￿","u");pe.readRegexp=function(){for(var e,t,n=this,r=this.pos;;){n.pos>=n.input.length&&n.raise(r,"Unterminated regular expression");var i=n.input.charAt(n.pos);if($.test(i)&&n.raise(r,"Unterminated regular expression"),e)e=!1;else{if("["===i)t=!0;else if("]"===i&&t)t=!1;else if("/"===i&&!t)break;e="\\"===i}++n.pos}var s=this.input.slice(r,this.pos);++this.pos;var o=this.readWord1(),a=s,u="";if(o){var c=/^[gim]*$/;this.options.ecmaVersion>=6&&(c=/^[gimuy]*$/),c.test(o)||this.raise(r,"Invalid regular expression flag"),o.indexOf("u")>=0&&(fe?u="u":(a=a.replace(/\\u\{([0-9a-fA-F]+)\}/g,function(e,t,i){return t=Number("0x"+t),t>1114111&&n.raise(r+i+3,"Code point out of bounds"),"x"}),a=a.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x"),u=u.replace("u","")))}var l=null;return he||(f(a,u,r,this),l=f(s,o)),this.finishToken(F.regexp,{pattern:s,flags:o,value:l})},pe.readInt=function(e,t){for(var n=this,r=this.pos,i=0,s=0,o=null==t?1/0:t;s=97?u-97+10:u>=65?u-65+10:u>=48&&u<=57?u-48:1/0)>=e)break;++n.pos,i=i*e+a}return this.pos===r||null!=t&&this.pos-r!==t?null:i},pe.readRadixNumber=function(e){this.pos+=2;var t=this.readInt(e);return null==t&&this.raise(this.start+2,"Expected number in radix "+e),n(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(F.num,t)},pe.readNumber=function(e){var t=this.pos,r=!1,i=48===this.input.charCodeAt(this.pos);e||null!==this.readInt(10)||this.raise(t,"Invalid number"),i&&this.pos==t+1&&(i=!1);var s=this.input.charCodeAt(this.pos);46!==s||i||(++this.pos,this.readInt(10),r=!0,s=this.input.charCodeAt(this.pos)),69!==s&&101!==s||i||(s=this.input.charCodeAt(++this.pos),43!==s&&45!==s||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number"),r=!0),n(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var o,a=this.input.slice(t,this.pos);return r?o=parseFloat(a):i&&1!==a.length?/[89]/.test(a)||this.strict?this.raise(t,"Invalid number"):o=parseInt(a,8):o=parseInt(a,10),this.finishToken(F.num,o)},pe.readCodePoint=function(){var e,t=this.input.charCodeAt(this.pos);if(123===t){this.options.ecmaVersion<6&&this.unexpected();var n=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.raise(n,"Code point out of bounds")}else e=this.readHexChar(4);return e},pe.readString=function(e){for(var t=this,n="",r=++this.pos;;){t.pos>=t.input.length&&t.raise(t.start,"Unterminated string constant");var i=t.input.charCodeAt(t.pos);if(i===e)break;92===i?(n+=t.input.slice(r,t.pos),n+=t.readEscapedChar(!1),r=t.pos):(o(i)&&t.raise(t.start,"Unterminated string constant"),++t.pos)}return n+=this.input.slice(r,this.pos++),this.finishToken(F.string,n)},pe.readTmplToken=function(){for(var e=this,t="",n=this.pos;;){e.pos>=e.input.length&&e.raise(e.start,"Unterminated template");var r=e.input.charCodeAt(e.pos);if(96===r||36===r&&123===e.input.charCodeAt(e.pos+1))return e.pos===e.start&&e.type===F.template?36===r?(e.pos+=2,e.finishToken(F.dollarBraceL)):(++e.pos,e.finishToken(F.backQuote)):(t+=e.input.slice(n,e.pos),e.finishToken(F.template,t));if(92===r)t+=e.input.slice(n,e.pos),t+=e.readEscapedChar(!0),n=e.pos;else if(o(r)){switch(t+=e.input.slice(n,e.pos),++e.pos,r){case 13:10===e.input.charCodeAt(e.pos)&&++e.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(r)}e.options.locations&&(++e.curLine,e.lineStart=e.pos),n=e.pos}else++e.pos}},pe.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return d(this.readCodePoint());case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";default:if(t>=48&&t<=55){var n=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],r=parseInt(n,8);return r>255&&(n=n.slice(0,-1),r=parseInt(n,8)),"0"!==n&&(this.strict||e)&&this.raise(this.pos-2,"Octal literal in strict mode"), +this.pos+=n.length-1,String.fromCharCode(r)}return String.fromCharCode(t)}},pe.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return null===n&&this.raise(t,"Bad character escape sequence"),n},pe.readWord1=function(){var e=this;this.containsEsc=!1;for(var t="",i=!0,s=this.pos,o=this.options.ecmaVersion>=6;this.pos=r)&&o[u](t,i,e),(null==n||t.start==n)&&(null==r||t.end==r)&&s(u,t))throw new h(t,i)}(t,a)}catch(e){if(e instanceof h)return e;throw e}}function o(t,n,r,s,o){r=i(r),s||(s=e.base);try{!function e(t,i,o){var a=o||t.type;if(!(t.start>n||t.end=n&&r(a,t))throw new h(t,i);s[a](t,i,e)}}(t,o)}catch(e){if(e instanceof h)return e;throw e}}function u(t,n,r,s,o){r=i(r),s||(s=e.base);var a;return function e(t,i,o){if(!(t.start>n)){var u=o||t.type;t.end<=n&&(!a||a.node.end=0&&e>1;return t?-n:n}var s=e("./base64");n.encode=function(e){var t,n="",i=r(e);do{t=31&i,i>>>=5,i>0&&(t|=32),n+=s.encode(t)}while(i>0);return n},n.decode=function(e,t,n){var r,o,a=e.length,u=0,c=0;do{if(t>=a)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(o=s.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));r=!!(32&o),o&=31,u+=o<0?t-u>1?r(u,t,i,s,o,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,i,s,o,a):a==n.LEAST_UPPER_BOUND?u:e<0?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,i,s){if(0===t.length)return-1;var o=r(-1,t.length,e,t,i,s||n.GREATEST_LOWER_BOUND);if(o<0)return-1;for(;o-1>=0&&0===i(t[o],t[o-1],!0);)--o;return o}},{}],21:[function(e,t,n){function r(e,t){var n=e.generatedLine,r=t.generatedLine,i=e.generatedColumn,o=t.generatedColumn;return r>n||r==n&&o>=i||s.compareByGeneratedPositionsInflated(e,t)<=0}function i(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var s=e("./util");i.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},i.prototype.add=function(e){r(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},i.prototype.toArray=function(){return this._sorted||(this._array.sort(s.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=i},{"./util":26}],22:[function(e,t,n){function r(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function i(e,t){return Math.round(e+Math.random()*(t-e))}function s(e,t,n,o){if(n=0){var s=this._originalMappings[i];if(void 0===e.column)for(var o=s.originalLine;s&&s.originalLine===o;)r.push({line:a.getArg(s,"generatedLine",null),column:a.getArg(s,"generatedColumn",null),lastColumn:a.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i];else for(var c=s.originalColumn;s&&s.originalLine===t&&s.originalColumn==c;)r.push({line:a.getArg(s,"generatedLine",null),column:a.getArg(s,"generatedColumn",null),lastColumn:a.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i]}return r},n.SourceMapConsumer=r,i.prototype=Object.create(r.prototype),i.prototype.consumer=r,i.fromSourceMap=function(e){var t=Object.create(i.prototype),n=t._names=c.fromArray(e._names.toArray(),!0),r=t._sources=c.fromArray(e._sources.toArray(),!0);t.sourceRoot=e._sourceRoot,t.sourcesContent=e._generateSourcesContent(t._sources.toArray(),t.sourceRoot),t.file=e._file;for(var o=e._mappings.toArray().slice(),u=t.__generatedMappings=[],l=t.__originalMappings=[],h=0,f=o.length;h1&&(n.source=y+i[1],y+=i[1],n.originalLine=f+i[2],f=n.originalLine,n.originalLine+=1,n.originalColumn=d+i[3],d=n.originalColumn,i.length>4&&(n.name=m+i[4],m+=i[4])),E.push(n),"number"==typeof n.originalLine&&w.push(n)}p(E,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=E,p(w,a.compareByOriginalPositions),this.__originalMappings=w},i.prototype._findMapping=function(e,t,n,r,i,s){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[r]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[r]);return u.search(e,t,i,s)},i.prototype.computeColumnSpans=function(){for(var e=0;e=0){var i=this._generatedMappings[n];if(i.generatedLine===t.generatedLine){var s=a.getArg(i,"source",null);null!==s&&(s=this._sources.at(s),null!=this.sourceRoot&&(s=a.join(this.sourceRoot,s)));var o=a.getArg(i,"name",null);return null!==o&&(o=this._names.at(o)),{source:s,line:a.getArg(i,"originalLine",null),column:a.getArg(i,"originalColumn",null),name:o}}}return{source:null,line:null,column:null,name:null}},i.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},i.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=a.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var n;if(null!=this.sourceRoot&&(n=a.urlParse(this.sourceRoot))){var r=e.replace(/^file:\/\//,"");if("file"==n.scheme&&this._sources.has(r))return this.sourcesContent[this._sources.indexOf(r)];if((!n.path||"/"==n.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},i.prototype.generatedPositionFor=function(e){var t=a.getArg(e,"source");if(null!=this.sourceRoot&&(t=a.relative(this.sourceRoot,t)),!this._sources.has(t))return{line:null,column:null,lastColumn:null};t=this._sources.indexOf(t);var n={source:t,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},i=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",r.GREATEST_LOWER_BOUND));if(i>=0){var s=this._originalMappings[i];if(s.source===n.source)return{line:a.getArg(s,"generatedLine",null),column:a.getArg(s,"generatedColumn",null),lastColumn:a.getArg(s,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=i,o.prototype=Object.create(r.prototype),o.prototype.constructor=r,o.prototype._version=3,Object.defineProperty(o.prototype,"sources",{get:function(){for(var e=[],t=0;t0&&e.column>=0)||t||n||r)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:r}))},r.prototype._serializeMappings=function(){for(var e,t,n,r,o=0,a=1,u=0,c=0,l=0,p=0,h="",f=this._mappings.toArray(),d=0,y=f.length;d0){if(!s.compareByGeneratedPositionsInflated(t,f[d-1]))continue;e+=","}e+=i.encode(t.generatedColumn-o),o=t.generatedColumn,null!=t.source&&(r=this._sources.indexOf(t.source),e+=i.encode(r-p),p=r,e+=i.encode(t.originalLine-1-c),c=t.originalLine-1,e+=i.encode(t.originalColumn-u),u=t.originalColumn,null!=t.name&&(n=this._names.indexOf(t.name),e+=i.encode(n-l),l=n)),h+=e}return h},r.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=s.relative(t,e));var n=s.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)},r.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},r.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=r},{"./array-set":17,"./base64-vlq":18,"./mapping-list":21,"./util":26}],25:[function(e,t,n){function r(e,t,n,r,i){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==t?null:t,this.source=null==n?null:n,this.name=null==i?null:i,this[o]=!0,null!=r&&this.add(r)}var i=e("./source-map-generator").SourceMapGenerator,s=e("./util"),o="$$$isSourceNode$$$";r.fromStringWithSourceMap=function(e,t,n){function i(e,t){if(null===e||void 0===e.source)o.add(t);else{var i=n?s.join(n,e.source):e.source;o.add(new r(e.originalLine,e.originalColumn,i,t,e.name))}}var o=new r,a=e.split(/(\r?\n)/),u=function(){return a.shift()+(a.shift()||"")},c=1,l=0,p=null;return t.eachMapping(function(e){if(null!==p){if(!(c0&&(p&&i(p,u()),o.add(a.join(""))),t.sources.forEach(function(e){var r=t.sourceContentFor(e);null!=r&&(null!=n&&(e=s.join(n,e)),o.setSourceContent(e,r))}),o},r.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[o]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},r.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else{if(!e[o]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},r.prototype.walk=function(e){for(var t,n=0,r=this.children.length;n0){for(t=[],n=0;n=0;l--)o=u[l],"."===o?u.splice(l,1):".."===o?c++:c>0&&(""===o?(u.splice(l+1,c),c=0):(u.splice(l,2),c--));return t=u.join("/"),""===t&&(t=a?"/":"."),r?(r.path=t,s(r)):t}function a(e,t){""===e&&(e="."),""===t&&(t=".");var n=i(t),r=i(e);if(r&&(e=r.path||"/"),n&&!n.scheme)return r&&(n.scheme=r.scheme),s(n);if(n||t.match(v))return t;if(r&&!r.host&&!r.path)return r.host=t,s(r);var a="/"===t.charAt(0)?t:o(e.replace(/\/+$/,"")+"/"+t);return r?(r.path=a,s(r)):a}function u(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var n=0;0!==t.indexOf(e+"/");){var r=e.lastIndexOf("/");if(r<0)return t;if(e=e.slice(0,r),e.match(/^([^\/]+:\/)?\/*$/))return t;++n}return Array(n+1).join("../")+t.substr(e.length+1)}function c(e){return e}function l(e){return h(e)?"$"+e:e}function p(e){return h(e)?e.slice(1):e}function h(e){if(!e)return!1;var t=e.length;if(t<9)return!1 +;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var n=t-10;n>=0;n--)if(36!==e.charCodeAt(n))return!1;return!0}function f(e,t,n){var r=e.source-t.source;return 0!==r?r:0!==(r=e.originalLine-t.originalLine)?r:0!==(r=e.originalColumn-t.originalColumn)||n?r:0!==(r=e.generatedColumn-t.generatedColumn)?r:(r=e.generatedLine-t.generatedLine,0!==r?r:e.name-t.name)}function d(e,t,n){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!==(r=e.generatedColumn-t.generatedColumn)||n?r:0!==(r=e.source-t.source)?r:0!==(r=e.originalLine-t.originalLine)?r:(r=e.originalColumn-t.originalColumn,0!==r?r:e.name-t.name)}function y(e,t){return e===t?0:e>t?1:-1}function m(e,t){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!==(n=e.generatedColumn-t.generatedColumn)?n:0!==(n=y(e.source,t.source))?n:0!==(n=e.originalLine-t.originalLine)?n:(n=e.originalColumn-t.originalColumn,0!==n?n:y(e.name,t.name))}n.getArg=r;var g=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,v=/^data:.+\,.+$/;n.urlParse=i,n.urlGenerate=s,n.normalize=o,n.join=a,n.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(g)},n.relative=u;var b=function(){return!("__proto__"in Object.create(null))}();n.toSetString=b?c:l,n.fromSetString=b?c:p,n.compareByOriginalPositions=f,n.compareByGeneratedPositionsDeflated=d,n.compareByGeneratedPositionsInflated=m},{}],27:[function(e,t,n){n.SourceMapGenerator=e("./lib/source-map-generator").SourceMapGenerator,n.SourceMapConsumer=e("./lib/source-map-consumer").SourceMapConsumer,n.SourceNode=e("./lib/source-node").SourceNode},{"./lib/source-map-consumer":23,"./lib/source-map-generator":24,"./lib/source-node":25}],28:[function(e,t,n){t.exports={_args:[[{raw:"nodent@^3.0.17",scope:null,escapedName:"nodent",name:"nodent",rawSpec:"^3.0.17",spec:">=3.0.17 <4.0.0",type:"range"},"/Users/evgenypoberezkin/JSON/ajv-v4"]],_from:"nodent@>=3.0.17 <4.0.0",_id:"nodent@3.0.17",_inCache:!0,_location:"/nodent",_nodeVersion:"6.9.1",_npmOperationalInternal:{host:"packages-12-west.internal.npmjs.com",tmp:"tmp/nodent-3.0.17.tgz_1490780005669_0.5196401283610612"},_npmUser:{name:"matatbread",email:"npm@mailed.me.uk"},_npmVersion:"3.10.8",_phantomChildren:{},_requested:{raw:"nodent@^3.0.17",scope:null,escapedName:"nodent",name:"nodent",rawSpec:"^3.0.17",spec:">=3.0.17 <4.0.0",type:"range"},_requiredBy:["#DEV:/"],_resolved:"https://registry.npmjs.org/nodent/-/nodent-3.0.17.tgz",_shasum:"22df57d33c5346d6acc3722d9d69fa68bff518e4",_shrinkwrap:null,_spec:"nodent@^3.0.17",_where:"/Users/evgenypoberezkin/JSON/ajv-v4",author:{name:"Mat At Bread",email:"nodent@mailed.me.uk"},bin:{nodentjs:"./nodent.js"},bugs:{url:"https://github.com/MatAtBread/nodent/issues"},dependencies:{acorn:">=2.5.2","acorn-es7-plugin":">=1.1.6","nodent-runtime":">=3.0.4",resolve:"^1.2.0","source-map":"^0.5.6"},description:"NoDent - Asynchronous Javascript language extensions",devDependencies:{},directories:{},dist:{shasum:"22df57d33c5346d6acc3722d9d69fa68bff518e4",tarball:"https://registry.npmjs.org/nodent/-/nodent-3.0.17.tgz"},engines:"node >= 0.10.0",gitHead:"1a48bd0e8d0b4df69aa7b4b3cf8483c03c1cfbd5",homepage:"https://github.com/MatAtBread/nodent#readme",keywords:["Javascript","ES7","async","await","language","extensions","Node","callback","generator","Promise","asynchronous"],license:"BSD-2-Clause",main:"nodent.js",maintainers:[{name:"matatbread",email:"npm@mailed.me.uk"}],name:"nodent",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/MatAtBread/nodent.git"},scripts:{cover:"istanbul cover ./nodent.js tests -- --quick --syntax ; open ./coverage/lcov-report/index.html",start:"./nodent.js",test:"cd tests && npm i --prod && cd .. && node --expose-gc ./nodent.js tests --syntax --quick && node --expose-gc ./nodent.js tests --quick --notStrict","test-loader":"cd tests/loader/app && npm test && cd ../../.."},version:"3.0.17"}},{}],29:[function(e,t,n){(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function r(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r=-1&&!i;s--){var o=s>=0?arguments[s]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(n=o+"/"+n,i="/"===o.charAt(0))}return n=t(r(n.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+n||"."},n.normalize=function(e){var i=n.isAbsolute(e),s="/"===o(e,-1);return e=t(r(e.split("/"),function(e){return!!e}),!i).join("/"),e||i||(e="."),e&&s&&(e+="/"),(i?"/":"")+e},n.isAbsolute=function(e){return"/"===e.charAt(0)},n.join=function(){var e=Array.prototype.slice.call(arguments,0);return n.normalize(r(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},n.relative=function(e,t){function r(e){for(var t=0;t=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=n.resolve(e).substr(1),t=n.resolve(t).substr(1);for(var i=r(e.split("/")),s=r(t.split("/")),o=Math.min(i.length,s.length),a=o,u=0;u1)for(var n=1;n=(t[n]||0))return!0;return!1}(o))for(var a=0;a"))}return o.promises||o.es7||o.generators||o.engine?((o.promises||o.es7)&&o.generators&&(n("No valid 'use nodent' directive, assumed -es7 mode"),o=I.es7),(o.generators||o.engine)&&(o.promises=!0),o.promises&&(o.es7=!0),o):null}function y(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),"#!"===e.substring(0,2)&&(e="//"+e),e}function m(e){var t;return t=e instanceof i?e:new i(e.toString(),"binary"),t.toString("base64")}function g(e,t){return t=t||e.log,function(n,r,i){var s=y(N.readFileSync(r,"utf8")),o=e.parse(s,r,i);i=i||d(o.ast,t,r),e.asynchronize(o,void 0,i,t),e.prettyPrint(o,i),n._compile(o.code,o.filename)}}function v(e){return e=e||q,function(t,n,r){if(Array.isArray(n)){var i=n;n=function(e,t){return i.indexOf(e)>=0}}else n=n||function(e,t){return!(e.match(/Sync$/)&&e.replace(/Sync$/,"")in t)};r||(r="");var s=Object.create(t);for(var o in s)!function(){var i=o;try{"function"!=typeof t[i]||s[i+r]&&s[i+r].isAsync||!n(i,s)||(s[i+r]=function(){var n=Array.prototype.slice.call(arguments);return new e(function(e,r){var s=function(t,n){if(t)return r(t);switch(arguments.length){case 0:return e();case 2:return e(n);default:return e(Array.prototype.slice.call(arguments,1))}};n.length>t[i].length?n.push(s):n[t[i].length-1]=s;t[i].apply(t,n)})},s[i+r].isAsync=!0)}catch(e){}}();return s.super=t,s}}function b(t,n){var r=t.filename.split("/"),i=r.pop(),s=T(t.ast,n&&n.sourcemap?{map:{startLine:n.mapStartLine||0,file:i+"(original)",sourceMapRoot:r.join("/"),sourceContent:t.origCode}}:null,t.origCode);if(n&&n.sourcemap)try{var o="",a=s.map.toJSON();if(a){var u=e("source-map").SourceMapConsumer;t.sourcemap=a,P[t.filename]={map:a,smc:new u(a)},o="\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+m(JSON.stringify(a))+"\n"}t.code=s.code+o}catch(e){t.code=s}else t.code=s;return t}function x(e,t,n,r){"object"==typeof n&&void 0===r&&(r=n);var i={origCode:e.toString(),filename:t};try{return i.ast=F.parse(i.origCode,r&&r.parser),r.babelTree&&F.treeWalker(i.ast,function(e,t,n){"Literal"===e.type?n[0].replace($.babelLiteralNode(e.value)):"Property"===e.type&&("ClassBody"===n[0].parent.type?e.type="ClassProperty":e.type="ObjectProperty"),t()}),i}catch(e){if(e instanceof SyntaxError){var s=i.origCode.substr(e.pos-e.loc.column);s=s.split("\n")[0],e.message+=" "+t+" (nodent)\n"+s+"\n"+s.replace(/[\S ]/g,"-").substring(0,e.loc.column)+"^",e.stack=""}throw e}}function w(t,n){n=n||{};var r=t+"|"+Object.keys(n).sort().reduce(function(e,t){return e+t+JSON.stringify(n[t])},"");return this.covers[r]||(t.indexOf("/")>=0?this.covers[r]=e(t):this.covers[r]=e(c+"/covers/"+t)),this.covers[r](this,n)}function E(e,t,n,r){"object"==typeof n&&void 0===r&&(r=n),r=r||{};for(var i in R)i in r||(r[i]=R[i]);var s=this.parse(e,t,null,r);return this.asynchronize(s,null,r,this.log||h),this.prettyPrint(s,r),s}function S(t,n,r){var i={},s=this;n||(n=/\.njs$/),r?r.compiler||(r.compiler={}):r={compiler:{}};var o=l([B,r.compiler]);return function(a,u,c){function l(e){u.statusCode=500,u.write(e.toString()),u.end()}if(i[a.url])return u.setHeader("Content-Type",i[a.url].contentType),r.setHeaders&&r.setHeaders(u),u.write(i[a.url].output),void u.end();if(!(a.url.match(n)||r.htmlScriptRegex&&a.url.match(r.htmlScriptRegex)))return c&&c();var p=t+a.url;if(r.extensions&&!N.existsSync(p))for(var h=0;h …"+n.source+":"+n.line+":"+n.column+(e.getFunctionName()?")":"")}}return"\n at "+e}return e+t.map(n).join("")}function _(e){var t={};t[R.$asyncbind]={value:D,writable:!0,enumerable:!1,configurable:!0},t[R.$asyncspawn]={value:V,writable:!0,enumerable:!1,configurable:!0};try{Object.defineProperties(Function.prototype,t)}catch(t){e.log("Function prototypes already assigned: ",t.messsage)}R[R.$error]in r||(r[R[R.$error]]=p),e.augmentObject&&Object.defineProperties(Object.prototype,{asyncify:{value:function(e,t,n){return v(e)(this,t,n)},writable:!0,configurable:!0},isThenable:{value:function(){return q.isThenable(this)},writable:!0,configurable:!0}}),Object[R.$makeThenable]=q.resolve}function C(t){function n(e,t){e=e.split("."),t=t.split(".");for(var n=0;n<3;n++){if(e[n]t[n])return 1}return 0}function r(i,s){if(!s.match(/nodent\/nodent\.js$/)){if(s.match(/node_modules\/nodent\/.*\.js$/))return L(i,s);for(var u=0;u=3&&function(){function t(e,t){try{var n,s;if(o.fromast){if(e=JSON.parse(e),n={origCode:"",filename:i,ast:e},!(s=d(e,a.log))){var u=o.use?'"use nodent-'+o.use+'";':'"use nodent";';s=d(u,a.log),console.warn("/* "+i+": No 'use nodent*' directive, assumed "+u+" */")}}else s=d(o.use?'"use nodent-'+o.use+'";':e,a.log),s||(s=d('"use nodent";',a.log),o.dest||console.warn("/* "+i+": 'use nodent*' directive missing/ignored, assumed 'use nodent;' */")),n=a.parse(e,i,s);if(o.parseast||o.pretty||a.asynchronize(n,void 0,s,a.log),a.prettyPrint(n,s),o.out||o.pretty||o.dest){if(o.dest&&!t)throw new Error("Can't write unknown file to "+o.dest);var c="";o.runtime&&(c+="Function.prototype.$asyncbind = "+Function.prototype.$asyncbind.toString()+";\n",c+="global.$error = global.$error || "+r.$error.toString()+";\n"),c+=n.code,t&&o.dest?(N.writeFileSync(o.dest+t,c),console.log("Compiled",o.dest+t)):console.log(c)}(o.minast||o.parseast)&&console.log(JSON.stringify(n.ast,function(e,t){return"$"===e[0]||e.match(/^(start|end|loc)$/)?void 0:t},2,null)),o.ast&&console.log(JSON.stringify(n.ast,function(e,t){return"$"===e[0]?void 0:t},0)),o.exec&&new Function(n.code)()}catch(e){console.error(e)}}var i,s=e("path"),o=(n.env.NODENT_OPTS&&JSON.parse(n.env.NODENT_OPTS),function(e){for(var t=[],r=e||2;r<]/g}},{}],2:[function(e,t,r){"use strict";function n(){var e={modifiers:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},colors:{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]},bgColors:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]}};return e.colors.grey=e.colors.gray,Object.keys(e).forEach(function(t){var r=e[t];Object.keys(r).forEach(function(t){var n=r[t];e[t]=r[t]={open:"["+n[0]+"m",close:"["+n[1]+"m"}}),Object.defineProperty(e,t,{value:r,enumerable:!1})}),e}Object.defineProperty(t,"exports",{enumerable:!0,get:n})},{}],3:[function(e,t,r){(function(r){"use strict";function n(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,i=0,s=Math.min(r,n);i=0;o--)if(u[o]!==l[o])return!1;for(o=u.length-1;o>=0;o--)if(a=u[o],!f(e[a],t[a],r,n))return!1;return!0}function y(e,t,r){f(e,t,!0)&&p(e,t,r,"notDeepStrictEqual",y)}function g(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function b(e){var t;try{e()}catch(e){t=e}return t}function v(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=b(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&p(i,r,"Missing expected exception"+n);var s="string"==typeof n,a=!e&&x.isError(i),o=!e&&i&&!r;if((a&&s&&g(i,r)||o)&&p(i,r,"Got unwanted exception"+n),e&&i&&r&&!g(i,r)||!e&&i)throw i}var x=e("util/"),E=Object.prototype.hasOwnProperty,A=Array.prototype.slice,D=function(){return"foo"===function(){}.name}(),C=t.exports=h,S=/\s*function\s+([^\(\s]*)\s*/;C.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=c(this),this.generatedMessage=!0);var t=e.stackStartFunction||p;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var r=new Error;if(r.stack){var n=r.stack,i=o(t),s=n.indexOf("\n"+i);if(s>=0){var a=n.indexOf("\n",s+1);n=n.substring(a+1)}this.stack=n}}},x.inherits(C.AssertionError,Error),C.fail=p,C.ok=h,C.equal=function(e,t,r){e!=t&&p(e,t,r,"==",C.equal)},C.notEqual=function(e,t,r){e==t&&p(e,t,r,"!=",C.notEqual)},C.deepEqual=function(e,t,r){f(e,t,!1)||p(e,t,r,"deepEqual",C.deepEqual)},C.deepStrictEqual=function(e,t,r){f(e,t,!0)||p(e,t,r,"deepStrictEqual",C.deepStrictEqual)},C.notDeepEqual=function(e,t,r){f(e,t,!1)&&p(e,t,r,"notDeepEqual",C.notDeepEqual)},C.notDeepStrictEqual=y,C.strictEqual=function(e,t,r){e!==t&&p(e,t,r,"===",C.strictEqual)},C.notStrictEqual=function(e,t,r){e===t&&p(e,t,r,"!==",C.notStrictEqual)},C.throws=function(e,t,r){v(!0,e,t,r)},C.doesNotThrow=function(e,t,r){v(!1,e,t,r)},C.ifError=function(e){if(e)throw e};var _=Object.keys||function(e){var t=[];for(var r in e)E.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":601}],4:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=t.use(e("../lib/shared")).defaults,i=r.Type.def,s=r.Type.or;i("Noop").bases("Node").build(),i("DoExpression").bases("Expression").build("body").field("body",[i("Statement")]),i("Super").bases("Expression").build(),i("BindExpression").bases("Expression").build("object","callee").field("object",s(i("Expression"),null)).field("callee",i("Expression")),i("Decorator").bases("Node").build("expression").field("expression",i("Expression")),i("Property").field("decorators",s([i("Decorator")],null),n.null),i("MethodDefinition").field("decorators",s([i("Decorator")],null),n.null),i("MetaProperty").bases("Expression").build("meta","property").field("meta",i("Identifier")).field("property",i("Identifier")),i("ParenthesizedExpression").bases("Expression").build("expression").field("expression",i("Expression")),i("ImportSpecifier").bases("ModuleSpecifier").build("imported","local").field("imported",i("Identifier")),i("ImportDefaultSpecifier").bases("ModuleSpecifier").build("local"),i("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("local"),i("ExportDefaultDeclaration").bases("Declaration").build("declaration").field("declaration",s(i("Declaration"),i("Expression"))),i("ExportNamedDeclaration").bases("Declaration").build("declaration","specifiers","source").field("declaration",s(i("Declaration"),null)).field("specifiers",[i("ExportSpecifier")],n.emptyArray).field("source",s(i("Literal"),null),n.null),i("ExportSpecifier").bases("ModuleSpecifier").build("local","exported").field("exported",i("Identifier")),i("ExportNamespaceSpecifier").bases("Specifier").build("exported").field("exported",i("Identifier")),i("ExportDefaultSpecifier").bases("Specifier").build("exported").field("exported",i("Identifier")),i("ExportAllDeclaration").bases("Declaration").build("exported","source").field("exported",s(i("Identifier"),null)).field("source",i("Literal")),i("CommentBlock").bases("Comment").build("value","leading","trailing"),i("CommentLine").bases("Comment").build("value","leading","trailing")}},{"../lib/shared":20,"../lib/types":21,"./es7":9}],5:[function(e,t,r){t.exports=function(t){t.use(e("./babel")),t.use(e("./flow"));var r=t.use(e("../lib/types")),n=t.use(e("../lib/shared")).defaults,i=r.Type.def,s=r.Type.or;i("Directive").bases("Node").build("value").field("value",i("DirectiveLiteral")),i("DirectiveLiteral").bases("Node","Expression").build("value").field("value",String,n["use strict"]),i("BlockStatement").bases("Statement").build("body").field("body",[i("Statement")]).field("directives",[i("Directive")],n.emptyArray),i("Program").bases("Node").build("body").field("body",[i("Statement")]).field("directives",[i("Directive")],n.emptyArray),i("StringLiteral").bases("Literal").build("value").field("value",String),i("NumericLiteral").bases("Literal").build("value").field("value",Number),i("NullLiteral").bases("Literal").build(),i("BooleanLiteral").bases("Literal").build("value").field("value",Boolean),i("RegExpLiteral").bases("Literal").build("pattern","flags").field("pattern",String).field("flags",String);var a=s(i("Property"),i("ObjectMethod"),i("ObjectProperty"),i("SpreadProperty"));i("ObjectExpression").bases("Expression").build("properties").field("properties",[a]),i("ObjectMethod").bases("Node","Function").build("kind","key","params","body","computed").field("kind",s("method","get","set")).field("key",s(i("Literal"),i("Identifier"),i("Expression"))).field("params",[i("Pattern")]).field("body",i("BlockStatement")).field("computed",Boolean,n.false).field("generator",Boolean,n.false).field("async",Boolean,n.false).field("decorators",s([i("Decorator")],null),n.null),i("ObjectProperty").bases("Node").build("key","value").field("key",s(i("Literal"),i("Identifier"),i("Expression"))).field("value",s(i("Expression"),i("Pattern"))).field("computed",Boolean,n.false);var o=s(i("MethodDefinition"),i("VariableDeclarator"),i("ClassPropertyDefinition"),i("ClassProperty"),i("ClassMethod"));i("ClassBody").bases("Declaration").build("body").field("body",[o]),i("ClassMethod").bases("Declaration","Function").build("kind","key","params","body","computed","static").field("kind",s("get","set","method","constructor")).field("key",s(i("Literal"),i("Identifier"),i("Expression"))).field("params",[i("Pattern")]).field("body",i("BlockStatement")).field("computed",Boolean,n.false).field("static",Boolean,n.false).field("generator",Boolean,n.false).field("async",Boolean,n.false).field("decorators",s([i("Decorator")],null),n.null);var u=s(i("Property"),i("PropertyPattern"),i("SpreadPropertyPattern"),i("SpreadProperty"),i("ObjectProperty"),i("RestProperty"));i("ObjectPattern").bases("Pattern").build("properties").field("properties",[u]).field("decorators",s([i("Decorator")],null),n.null),i("SpreadProperty").bases("Node").build("argument").field("argument",i("Expression")),i("RestProperty").bases("Node").build("argument").field("argument",i("Expression")),i("ForAwaitStatement").bases("Statement").build("left","right","body").field("left",s(i("VariableDeclaration"),i("Expression"))).field("right",i("Expression")).field("body",i("Statement")),i("Import").bases("Expression").build()}},{"../lib/shared":20,"../lib/types":21,"./babel":4,"./flow":11}],6:[function(e,t,r){t.exports=function(t){var r=t.use(e("../lib/types")),n=r.Type,i=n.def,s=n.or,a=t.use(e("../lib/shared")),o=a.defaults,u=a.geq;i("Printable").field("loc",s(i("SourceLocation"),null),o.null,!0),i("Node").bases("Printable").field("type",String).field("comments",s([i("Comment")],null),o.null,!0),i("SourceLocation").build("start","end","source").field("start",i("Position")).field("end",i("Position")).field("source",s(String,null),o.null),i("Position").build("line","column").field("line",u(1)).field("column",u(0)),i("File").bases("Node").build("program","name").field("program",i("Program")).field("name",s(String,null),o.null),i("Program").bases("Node").build("body").field("body",[i("Statement")]),i("Function").bases("Node").field("id",s(i("Identifier"),null),o.null).field("params",[i("Pattern")]).field("body",i("BlockStatement")),i("Statement").bases("Node"),i("EmptyStatement").bases("Statement").build(),i("BlockStatement").bases("Statement").build("body").field("body",[i("Statement")]),i("ExpressionStatement").bases("Statement").build("expression").field("expression",i("Expression")),i("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",i("Expression")).field("consequent",i("Statement")).field("alternate",s(i("Statement"),null),o.null),i("LabeledStatement").bases("Statement").build("label","body").field("label",i("Identifier")).field("body",i("Statement")),i("BreakStatement").bases("Statement").build("label").field("label",s(i("Identifier"),null),o.null),i("ContinueStatement").bases("Statement").build("label").field("label",s(i("Identifier"),null),o.null),i("WithStatement").bases("Statement").build("object","body").field("object",i("Expression")).field("body",i("Statement")),i("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",i("Expression")).field("cases",[i("SwitchCase")]).field("lexical",Boolean,o.false),i("ReturnStatement").bases("Statement").build("argument").field("argument",s(i("Expression"),null)),i("ThrowStatement").bases("Statement").build("argument").field("argument",i("Expression")),i("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",i("BlockStatement")).field("handler",s(i("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[i("CatchClause")],function(){return this.handler?[this.handler]:[]},!0).field("guardedHandlers",[i("CatchClause")],o.emptyArray).field("finalizer",s(i("BlockStatement"),null),o.null),i("CatchClause").bases("Node").build("param","guard","body").field("param",i("Pattern")).field("guard",s(i("Expression"),null),o.null).field("body",i("BlockStatement")),i("WhileStatement").bases("Statement").build("test","body").field("test",i("Expression")).field("body",i("Statement")),i("DoWhileStatement").bases("Statement").build("body","test").field("body",i("Statement")).field("test",i("Expression")),i("ForStatement").bases("Statement").build("init","test","update","body").field("init",s(i("VariableDeclaration"),i("Expression"),null)).field("test",s(i("Expression"),null)).field("update",s(i("Expression"),null)).field("body",i("Statement")),i("ForInStatement").bases("Statement").build("left","right","body").field("left",s(i("VariableDeclaration"),i("Expression"))).field("right",i("Expression")).field("body",i("Statement")),i("DebuggerStatement").bases("Statement").build(),i("Declaration").bases("Statement"),i("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",i("Identifier")),i("FunctionExpression").bases("Function","Expression").build("id","params","body"),i("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",s("var","let","const")).field("declarations",[i("VariableDeclarator")]),i("VariableDeclarator").bases("Node").build("id","init").field("id",i("Pattern")).field("init",s(i("Expression"),null)),i("Expression").bases("Node","Pattern"),i("ThisExpression").bases("Expression").build(),i("ArrayExpression").bases("Expression").build("elements").field("elements",[s(i("Expression"),null)]),i("ObjectExpression").bases("Expression").build("properties").field("properties",[i("Property")]),i("Property").bases("Node").build("kind","key","value").field("kind",s("init","get","set")).field("key",s(i("Literal"),i("Identifier"))).field("value",i("Expression")),i("SequenceExpression").bases("Expression").build("expressions").field("expressions",[i("Expression")]);var l=s("-","+","!","~","typeof","void","delete");i("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",l).field("argument",i("Expression")).field("prefix",Boolean,o.true);var c=s("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");i("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",c).field("left",i("Expression")).field("right",i("Expression"));var p=s("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");i("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",p).field("left",i("Pattern")).field("right",i("Expression"));var h=s("++","--");i("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",h).field("argument",i("Expression")).field("prefix",Boolean);var f=s("||","&&");i("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",f).field("left",i("Expression")).field("right",i("Expression")),i("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",i("Expression")).field("consequent",i("Expression")).field("alternate",i("Expression")),i("NewExpression").bases("Expression").build("callee","arguments").field("callee",i("Expression")).field("arguments",[i("Expression")]),i("CallExpression").bases("Expression").build("callee","arguments").field("callee",i("Expression")).field("arguments",[i("Expression")]),i("MemberExpression").bases("Expression").build("object","property","computed").field("object",i("Expression")).field("property",s(i("Identifier"),i("Expression"))).field("computed",Boolean,function(){var e=this.property.type;return"Literal"===e||"MemberExpression"===e||"BinaryExpression"===e}),i("Pattern").bases("Node"),i("SwitchCase").bases("Node").build("test","consequent").field("test",s(i("Expression"),null)).field("consequent",[i("Statement")]),i("Identifier").bases("Node","Expression","Pattern").build("name").field("name",String),i("Literal").bases("Node","Expression").build("value").field("value",s(String,Boolean,null,Number,RegExp)).field("regex",s({pattern:String,flags:String},null),function(){if(this.value instanceof RegExp){var e="";return this.value.ignoreCase&&(e+="i"),this.value.multiline&&(e+="m"),this.value.global&&(e+="g"),{pattern:this.value.source,flags:e}}return null}),i("Comment").bases("Printable").field("value",String).field("leading",Boolean,o.true).field("trailing",Boolean,o.false)}},{"../lib/shared":20,"../lib/types":21}],7:[function(e,t,r){t.exports=function(t){t.use(e("./core"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or;n("XMLDefaultDeclaration").bases("Declaration").field("namespace",n("Expression")),n("XMLAnyName").bases("Expression"),n("XMLQualifiedIdentifier").bases("Expression").field("left",i(n("Identifier"),n("XMLAnyName"))).field("right",i(n("Identifier"),n("Expression"))).field("computed",Boolean),n("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",i(n("Identifier"),n("Expression"))).field("computed",Boolean),n("XMLAttributeSelector").bases("Expression").field("attribute",n("Expression")),n("XMLFilterExpression").bases("Expression").field("left",n("Expression")).field("right",n("Expression")),n("XMLElement").bases("XML","Expression").field("contents",[n("XML")]),n("XMLList").bases("XML","Expression").field("contents",[n("XML")]),n("XML").bases("Node"),n("XMLEscape").bases("XML").field("expression",n("Expression")),n("XMLText").bases("XML").field("text",String),n("XMLStartTag").bases("XML").field("contents",[n("XML")]),n("XMLEndTag").bases("XML").field("contents",[n("XML")]),n("XMLPointTag").bases("XML").field("contents",[n("XML")]),n("XMLName").bases("XML").field("contents",i(String,[n("XML")])),n("XMLAttribute").bases("XML").field("value",String),n("XMLCdata").bases("XML").field("contents",String),n("XMLComment").bases("XML").field("contents",String),n("XMLProcessingInstruction").bases("XML").field("target",String).field("contents",i(String,null))}},{"../lib/types":21,"./core":6}],8:[function(e,t,r){t.exports=function(t){t.use(e("./core"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")).defaults;n("Function").field("generator",Boolean,s.false).field("expression",Boolean,s.false).field("defaults",[i(n("Expression"),null)],s.emptyArray).field("rest",i(n("Identifier"),null),s.null),n("RestElement").bases("Pattern").build("argument").field("argument",n("Pattern")),n("SpreadElementPattern").bases("Pattern").build("argument").field("argument",n("Pattern")),n("FunctionDeclaration").build("id","params","body","generator","expression"),n("FunctionExpression").build("id","params","body","generator","expression"),n("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,s.null).field("body",i(n("BlockStatement"),n("Expression"))).field("generator",!1,s.false),n("YieldExpression").bases("Expression").build("argument","delegate").field("argument",i(n("Expression"),null)).field("delegate",Boolean,s.false),n("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",n("Expression")).field("blocks",[n("ComprehensionBlock")]).field("filter",i(n("Expression"),null)),n("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",n("Expression")).field("blocks",[n("ComprehensionBlock")]).field("filter",i(n("Expression"),null)),n("ComprehensionBlock").bases("Node").build("left","right","each").field("left",n("Pattern")).field("right",n("Expression")).field("each",Boolean),n("Property").field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("value",i(n("Expression"),n("Pattern"))).field("method",Boolean,s.false).field("shorthand",Boolean,s.false).field("computed",Boolean,s.false),n("PropertyPattern").bases("Pattern").build("key","pattern").field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("pattern",n("Pattern")).field("computed",Boolean,s.false),n("ObjectPattern").bases("Pattern").build("properties").field("properties",[i(n("PropertyPattern"),n("Property"))]),n("ArrayPattern").bases("Pattern").build("elements").field("elements",[i(n("Pattern"),null)]),n("MethodDefinition").bases("Declaration").build("kind","key","value","static").field("kind",i("constructor","method","get","set")).field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("value",n("Function")).field("computed",Boolean,s.false).field("static",Boolean,s.false),n("SpreadElement").bases("Node").build("argument").field("argument",n("Expression")),n("ArrayExpression").field("elements",[i(n("Expression"),n("SpreadElement"),n("RestElement"),null)]),n("NewExpression").field("arguments",[i(n("Expression"),n("SpreadElement"))]),n("CallExpression").field("arguments",[i(n("Expression"),n("SpreadElement"))]),n("AssignmentPattern").bases("Pattern").build("left","right").field("left",n("Pattern")).field("right",n("Expression"));var a=i(n("MethodDefinition"),n("VariableDeclarator"),n("ClassPropertyDefinition"),n("ClassProperty"));n("ClassProperty").bases("Declaration").build("key").field("key",i(n("Literal"),n("Identifier"),n("Expression"))).field("computed",Boolean,s.false),n("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",a),n("ClassBody").bases("Declaration").build("body").field("body",[a]),n("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",i(n("Identifier"),null)).field("body",n("ClassBody")).field("superClass",i(n("Expression"),null),s.null),n("ClassExpression").bases("Expression").build("id","body","superClass").field("id",i(n("Identifier"),null),s.null).field("body",n("ClassBody")).field("superClass",i(n("Expression"),null),s.null).field("implements",[n("ClassImplements")],s.emptyArray),n("ClassImplements").bases("Node").build("id").field("id",n("Identifier")).field("superClass",i(n("Expression"),null),s.null),n("Specifier").bases("Node"),n("ModuleSpecifier").bases("Specifier").field("local",i(n("Identifier"),null),s.null).field("id",i(n("Identifier"),null),s.null).field("name",i(n("Identifier"),null),s.null),n("TaggedTemplateExpression").bases("Expression").build("tag","quasi").field("tag",n("Expression")).field("quasi",n("TemplateLiteral")),n("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[n("TemplateElement")]).field("expressions",[n("Expression")]),n("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:String,raw:String}).field("tail",Boolean)}},{"../lib/shared":20,"../lib/types":21,"./core":6}],9:[function(e,t,r){t.exports=function(t){t.use(e("./es6"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=(r.builtInTypes,t.use(e("../lib/shared")).defaults);n("Function").field("async",Boolean,s.false),n("SpreadProperty").bases("Node").build("argument").field("argument",n("Expression")),n("ObjectExpression").field("properties",[i(n("Property"),n("SpreadProperty"))]),n("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",n("Pattern")),n("ObjectPattern").field("properties",[i(n("Property"),n("PropertyPattern"),n("SpreadPropertyPattern"))]),n("AwaitExpression").bases("Expression").build("argument","all").field("argument",i(n("Expression"),null)).field("all",Boolean,s.false)}},{"../lib/shared":20,"../lib/types":21,"./es6":8}],10:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=t.use(e("../lib/shared")).defaults,i=r.Type.def,s=r.Type.or;i("VariableDeclaration").field("declarations",[s(i("VariableDeclarator"),i("Identifier"))]),i("Property").field("value",s(i("Expression"),i("Pattern"))),i("ArrayPattern").field("elements",[s(i("Pattern"),i("SpreadElement"),null)]),i("ObjectPattern").field("properties",[s(i("Property"),i("PropertyPattern"),i("SpreadPropertyPattern"),i("SpreadProperty"))]),i("ExportSpecifier").bases("ModuleSpecifier").build("id","name"),i("ExportBatchSpecifier").bases("Specifier").build(),i("ImportSpecifier").bases("ModuleSpecifier").build("id","name"),i("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("id"),i("ImportDefaultSpecifier").bases("ModuleSpecifier").build("id"),i("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",Boolean).field("declaration",s(i("Declaration"),i("Expression"),null)).field("specifiers",[s(i("ExportSpecifier"),i("ExportBatchSpecifier"))],n.emptyArray).field("source",s(i("Literal"),null),n.null),i("ImportDeclaration").bases("Declaration").build("specifiers","source","importKind").field("specifiers",[s(i("ImportSpecifier"),i("ImportNamespaceSpecifier"),i("ImportDefaultSpecifier"))],n.emptyArray).field("source",i("Literal")).field("importKind",s("value","type"),function(){return"value"}),i("Block").bases("Comment").build("value","leading","trailing"),i("Line").bases("Comment").build("value","leading","trailing")}},{"../lib/shared":20,"../lib/types":21,"./es7":9}],11:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")).defaults;n("Type").bases("Node"),n("AnyTypeAnnotation").bases("Type").build(),n("EmptyTypeAnnotation").bases("Type").build(),n("MixedTypeAnnotation").bases("Type").build(),n("VoidTypeAnnotation").bases("Type").build(),n("NumberTypeAnnotation").bases("Type").build(),n("NumberLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",Number).field("raw",String),n("NumericLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",Number).field("raw",String),n("StringTypeAnnotation").bases("Type").build(),n("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",String).field("raw",String),n("BooleanTypeAnnotation").bases("Type").build(),n("BooleanLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",Boolean).field("raw",String),n("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",n("Type")),n("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",n("Type")),n("NullLiteralTypeAnnotation").bases("Type").build(),n("NullTypeAnnotation").bases("Type").build(),n("ThisTypeAnnotation").bases("Type").build(),n("ExistsTypeAnnotation").bases("Type").build(),n("ExistentialTypeParam").bases("Type").build(),n("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[n("FunctionTypeParam")]).field("returnType",n("Type")).field("rest",i(n("FunctionTypeParam"),null)).field("typeParameters",i(n("TypeParameterDeclaration"),null)),n("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",n("Identifier")).field("typeAnnotation",n("Type")).field("optional",Boolean),n("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",n("Type")),n("ObjectTypeAnnotation").bases("Type").build("properties","indexers","callProperties").field("properties",[n("ObjectTypeProperty")]).field("indexers",[n("ObjectTypeIndexer")],s.emptyArray).field("callProperties",[n("ObjectTypeCallProperty")],s.emptyArray).field("exact",Boolean,s.false),n("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",i(n("Literal"),n("Identifier"))).field("value",n("Type")).field("optional",Boolean).field("variance",i("plus","minus",null),s.null),n("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",n("Identifier")).field("key",n("Type")).field("value",n("Type")).field("variance",i("plus","minus",null),s.null),n("ObjectTypeCallProperty").bases("Node").build("value").field("value",n("FunctionTypeAnnotation")).field("static",Boolean,s.false),n("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",i(n("Identifier"),n("QualifiedTypeIdentifier"))).field("id",n("Identifier")),n("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",i(n("Identifier"),n("QualifiedTypeIdentifier"))).field("typeParameters",i(n("TypeParameterInstantiation"),null)),n("MemberTypeAnnotation").bases("Type").build("object","property").field("object",n("Identifier")).field("property",i(n("MemberTypeAnnotation"),n("GenericTypeAnnotation"))),n("UnionTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",n("Type")),n("Identifier").field("typeAnnotation",i(n("TypeAnnotation"),null),s.null),n("TypeParameterDeclaration").bases("Node").build("params").field("params",[n("TypeParameter")]),n("TypeParameterInstantiation").bases("Node").build("params").field("params",[n("Type")]),n("TypeParameter").bases("Type").build("name","variance","bound").field("name",String).field("variance",i("plus","minus",null),s.null).field("bound",i(n("TypeAnnotation"),null),s.null),n("Function").field("returnType",i(n("TypeAnnotation"),null),s.null).field("typeParameters",i(n("TypeParameterDeclaration"),null),s.null),n("ClassProperty").build("key","value","typeAnnotation","static").field("value",i(n("Expression"),null)).field("typeAnnotation",i(n("TypeAnnotation"),null)).field("static",Boolean,s.false).field("variance",i("plus","minus",null),s.null),n("ClassImplements").field("typeParameters",i(n("TypeParameterInstantiation"),null),s.null),n("InterfaceDeclaration").bases("Declaration").build("id","body","extends").field("id",n("Identifier")).field("typeParameters",i(n("TypeParameterDeclaration"),null),s.null).field("body",n("ObjectTypeAnnotation")).field("extends",[n("InterfaceExtends")]),n("DeclareInterface").bases("InterfaceDeclaration").build("id","body","extends"),n("InterfaceExtends").bases("Node").build("id").field("id",n("Identifier")).field("typeParameters",i(n("TypeParameterInstantiation"),null)),n("TypeAlias").bases("Declaration").build("id","typeParameters","right").field("id",n("Identifier")).field("typeParameters",i(n("TypeParameterDeclaration"),null)).field("right",n("Type")),n("DeclareTypeAlias").bases("TypeAlias").build("id","typeParameters","right"), +n("TypeCastExpression").bases("Expression").build("expression","typeAnnotation").field("expression",n("Expression")).field("typeAnnotation",n("TypeAnnotation")),n("TupleTypeAnnotation").bases("Type").build("types").field("types",[n("Type")]),n("DeclareVariable").bases("Statement").build("id").field("id",n("Identifier")),n("DeclareFunction").bases("Statement").build("id").field("id",n("Identifier")),n("DeclareClass").bases("InterfaceDeclaration").build("id"),n("DeclareModule").bases("Statement").build("id","body").field("id",i(n("Identifier"),n("Literal"))).field("body",n("BlockStatement")),n("DeclareModuleExports").bases("Statement").build("typeAnnotation").field("typeAnnotation",n("Type")),n("DeclareExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",Boolean).field("declaration",i(n("DeclareVariable"),n("DeclareFunction"),n("DeclareClass"),n("Type"),null)).field("specifiers",[i(n("ExportSpecifier"),n("ExportBatchSpecifier"))],s.emptyArray).field("source",i(n("Literal"),null),s.null),n("DeclareExportAllDeclaration").bases("Declaration").build("source").field("source",i(n("Literal"),null),s.null)}},{"../lib/shared":20,"../lib/types":21,"./es7":9}],12:[function(e,t,r){t.exports=function(t){t.use(e("./es7"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")).defaults;n("JSXAttribute").bases("Node").build("name","value").field("name",i(n("JSXIdentifier"),n("JSXNamespacedName"))).field("value",i(n("Literal"),n("JSXExpressionContainer"),null),s.null),n("JSXIdentifier").bases("Identifier").build("name").field("name",String),n("JSXNamespacedName").bases("Node").build("namespace","name").field("namespace",n("JSXIdentifier")).field("name",n("JSXIdentifier")),n("JSXMemberExpression").bases("MemberExpression").build("object","property").field("object",i(n("JSXIdentifier"),n("JSXMemberExpression"))).field("property",n("JSXIdentifier")).field("computed",Boolean,s.false);var a=i(n("JSXIdentifier"),n("JSXNamespacedName"),n("JSXMemberExpression"));n("JSXSpreadAttribute").bases("Node").build("argument").field("argument",n("Expression"));var o=[i(n("JSXAttribute"),n("JSXSpreadAttribute"))];n("JSXExpressionContainer").bases("Expression").build("expression").field("expression",n("Expression")),n("JSXElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",n("JSXOpeningElement")).field("closingElement",i(n("JSXClosingElement"),null),s.null).field("children",[i(n("JSXElement"),n("JSXExpressionContainer"),n("JSXText"),n("Literal"))],s.emptyArray).field("name",a,function(){return this.openingElement.name},!0).field("selfClosing",Boolean,function(){return this.openingElement.selfClosing},!0).field("attributes",o,function(){return this.openingElement.attributes},!0),n("JSXOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",a).field("attributes",o,s.emptyArray).field("selfClosing",Boolean,s.false),n("JSXClosingElement").bases("Node").build("name").field("name",a),n("JSXText").bases("Literal").build("value").field("value",String),n("JSXEmptyExpression").bases("Expression").build()}},{"../lib/shared":20,"../lib/types":21,"./es7":9}],13:[function(e,t,r){t.exports=function(t){t.use(e("./core"));var r=t.use(e("../lib/types")),n=r.Type.def,i=r.Type.or,s=t.use(e("../lib/shared")),a=s.geq,o=s.defaults;n("Function").field("body",i(n("BlockStatement"),n("Expression"))),n("ForInStatement").build("left","right","body","each").field("each",Boolean,o.false),n("ForOfStatement").bases("Statement").build("left","right","body").field("left",i(n("VariableDeclaration"),n("Expression"))).field("right",n("Expression")).field("body",n("Statement")),n("LetStatement").bases("Statement").build("head","body").field("head",[n("VariableDeclarator")]).field("body",n("Statement")),n("LetExpression").bases("Expression").build("head","body").field("head",[n("VariableDeclarator")]).field("body",n("Expression")),n("GraphExpression").bases("Expression").build("index","expression").field("index",a(0)).field("expression",n("Literal")),n("GraphIndexExpression").bases("Expression").build("index").field("index",a(0))}},{"../lib/shared":20,"../lib/types":21,"./core":6}],14:[function(e,t,r){t.exports=function(t){function r(e){var t=n.indexOf(e);return-1===t&&(t=n.length,n.push(e),i[t]=e(s)),i[t]}var n=[],i=[],s={};s.use=r;var a=r(e("./lib/types"));t.forEach(r),a.finalize();var o={Type:a.Type,builtInTypes:a.builtInTypes,namedTypes:a.namedTypes,builders:a.builders,defineMethod:a.defineMethod,getFieldNames:a.getFieldNames,getFieldValue:a.getFieldValue,eachField:a.eachField,someField:a.someField,getSupertypeNames:a.getSupertypeNames,astNodesAreEquivalent:r(e("./lib/equiv")),finalize:a.finalize,Path:r(e("./lib/path")),NodePath:r(e("./lib/node-path")),PathVisitor:r(e("./lib/path-visitor")),use:r};return o.visit=o.PathVisitor.visit,o}},{"./lib/equiv":15,"./lib/node-path":16,"./lib/path":18,"./lib/path-visitor":17,"./lib/types":21}],15:[function(e,t,r){t.exports=function(t){function r(e,t,r){return c.check(r)?r.length=0:r=null,i(e,t,r)}function n(e){return/[_$a-z][_$a-z0-9]*/i.test(e)?"."+e:"["+JSON.stringify(e)+"]"}function i(e,t,r){return e===t||(c.check(e)?s(e,t,r):p.check(e)?a(e,t,r):h.check(e)?h.check(t)&&+e==+t:f.check(e)?f.check(t)&&e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.ignoreCase===t.ignoreCase:e==t)}function s(e,t,r){c.assert(e);var n=e.length;if(!c.check(t)||t.length!==n)return r&&r.push("length"),!1;for(var s=0;so)return!0;if(t===o&&"right"===this.name){if(n.right!==r)throw new Error("Nodes must be equal");return!0}default:return!1}case"SequenceExpression":switch(n.type){case"ForStatement":return!1;case"ExpressionStatement":return"expression"!==this.name;default:return!0}case"YieldExpression":switch(n.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return!0;default:return!1}case"Literal":return"MemberExpression"===n.type&&p.check(r.value)&&"object"===this.name&&n.object===r;case"AssignmentExpression":case"ConditionalExpression":switch(n.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return!0;case"CallExpression":return"callee"===this.name&&n.callee===r;case"ConditionalExpression":return"test"===this.name&&n.test===r;case"MemberExpression":return"object"===this.name&&n.object===r;default:return!1}default:if("NewExpression"===n.type&&"callee"===this.name&&n.callee===r)return i(r)}return!(!0===e||this.canBeFirstInStatement()||!this.firstInStatement())};var y={};return[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,t){e.forEach(function(e){y[e]=t})}),m.canBeFirstInStatement=function(){var e=this.node;return!l.FunctionExpression.check(e)&&!l.ObjectExpression.check(e)},m.firstInStatement=function(){return s(this)},r}},{"./path":18,"./scope":19,"./types":21}],17:[function(e,t,r){var n=Object.prototype.hasOwnProperty;t.exports=function(t){function r(){if(!(this instanceof r))throw new Error("PathVisitor constructor cannot be invoked without 'new'");this._reusableContextStack=[],this._methodNameTable=i(this),this._shouldVisitComments=n.call(this._methodNameTable,"Block")||n.call(this._methodNameTable,"Line"),this.Context=o(this),this._visiting=!1,this._changeReported=!1}function i(e){var t=Object.create(null);for(var r in e)/^visit[A-Z]/.test(r)&&(t[r.slice("visit".length)]=!0);for(var n=u.computeSupertypeLookupTable(t),i=Object.create(null),t=Object.keys(n),s=t.length,a=0;a=0&&(s[e.name=a]=e)}else i[e.name]=e.value,s[e.name]=e;if(i[e.name]!==e.value)throw new Error("");if(e.parentPath.get(e.name)!==e)throw new Error("");return e}var l=t.use(e("./types")),c=l.builtInTypes.array,p=l.builtInTypes.number,h=r.prototype;return h.getValueProperty=function(e){return this.value[e]},h.get=function(e){for(var t=this,r=arguments,n=r.length,s=0;s=e},a+" >= "+e)},r.defaults={null:function(){return null},emptyArray:function(){return[]},false:function(){return!1},true:function(){return!0},undefined:function(){}};var o=i.or(s.string,s.number,s.boolean,s.null,s.undefined);return r.isPrimitive=new i(function(e){if(null===e)return!0;var t=typeof e;return!("object"===t||"function"===t)},o.toString()),r}},{"../lib/types":21}],21:[function(e,t,r){var n=Array.prototype,i=n.slice,s=(n.map,n.forEach,Object.prototype),a=s.toString,o=a.call(function(){}),u=a.call(""),l=s.hasOwnProperty;t.exports=function(){function e(t,r){var n=this;if(!(n instanceof e))throw new Error("Type constructor cannot be invoked without 'new'");if(a.call(t)!==o)throw new Error(t+" is not a function");var i=a.call(r);if(i!==o&&i!==u)throw new Error(r+" is neither a function nor a string");Object.defineProperties(n,{name:{value:r},check:{value:function(e,r){var i=t.call(n,e,r);return!i&&r&&a.call(r)===o&&r(n,e),i}}})}function t(e){return _.check(e)?"{"+Object.keys(e).map(function(t){return t+": "+e[t]}).join(", ")+"}":S.check(e)?"["+e.map(t).join(", ")+"]":JSON.stringify(e)}function r(t,r){var n=a.call(t),i=new e(function(e){return a.call(e)===n},r);return A[r]=i,t&&"function"==typeof t.constructor&&(x.push(t.constructor),E.push(i)),i}function n(t,r){if(t instanceof e)return t;if(t instanceof c)return t.type;if(S.check(t))return e.fromArray(t);if(_.check(t))return e.fromObject(t);if(C.check(t)){var n=x.indexOf(t);return n>=0?E[n]:new e(t,r)}return new e(function(e){return e===t},k.check(r)?function(){return t+""}:r)}function s(e,t,r,i){var a=this;if(!(a instanceof s))throw new Error("Field constructor cannot be invoked without 'new'");D.assert(e),t=n(t);var o={name:{value:e},type:{value:t},hidden:{value:!!i}};C.check(r)&&(o.defaultFn={value:r}),Object.defineProperties(a,o)}function c(t){var r=this;if(!(r instanceof c))throw new Error("Def constructor cannot be invoked without 'new'");Object.defineProperties(r,{typeName:{value:t},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new e(function(e,t){return r.check(e,t)},t)}})}function p(e){return e.replace(/^[A-Z]+/,function(e){var t=e.length;switch(t){case 0:return"";case 1:return e.toLowerCase();default:return e.slice(0,t-1).toLowerCase()+e.charAt(t-1)}})}function h(e){return e=p(e),e.replace(/(Expression)?$/,"Statement")}function f(e){var t=c.fromValue(e);if(t)return t.fieldNames.slice(0);if("type"in e)throw new Error("did not recognize object of type "+JSON.stringify(e.type));return Object.keys(e)}function d(e,t){var r=c.fromValue(e);if(r){var n=r.allFields[t];if(n)return n.getValue(e)}return e&&e[t]}function m(e){var t=h(e);if(!B[t]){var r=B[p(e)];r&&(B[t]=function(){return B.expressionStatement(r.apply(B,arguments))})}}function y(e,t){t.length=0,t.push(e);for(var r=Object.create(null),n=0;n=0&&m(e.typeName)}},b.finalize=function(){Object.keys(T).forEach(function(e){T[e].finalize()})},b}},{}],22:[function(e,t,r){t.exports=e("./fork")([e("./def/core"),e("./def/es6"),e("./def/es7"),e("./def/mozilla"),e("./def/e4x"),e("./def/jsx"),e("./def/flow"),e("./def/esprima"),e("./def/babel"),e("./def/babel6")])},{"./def/babel":4,"./def/babel6":5,"./def/core":6,"./def/e4x":7,"./def/es6":8,"./def/es7":9,"./def/esprima":10,"./def/flow":11,"./def/jsx":12,"./def/mozilla":13,"./fork":14}],23:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){return{keyword:e.cyan,capitalized:e.yellow,jsx_tag:e.yellow,punctuator:e.yellow,number:e.magenta,string:e.green,regex:e.magenta,comment:e.grey,invalid:e.white.bgRed.bold,gutter:e.grey,marker:e.red.bold}}function s(e){var t=e.slice(-2),r=t[0],n=t[1],i=(0,o.matchToToken)(e);if("name"===i.type){if(c.default.keyword.isReservedWordES6(i.value))return"keyword";if(d.test(i.value)&&("<"===n[r-1]||"3&&void 0!==arguments[3]?arguments[3]:{};r=Math.max(r,0);var s=n.highlightCode&&h.default.supportsColor||n.forceColor,o=h.default;n.forceColor&&(o=new h.default.constructor({enabled:!0}));var u=function(e,t){return s?e(t):t},l=i(o);s&&(e=a(l,e));var c=n.linesAbove||2,p=n.linesBelow||3,d=e.split(f),m=Math.max(t-(c+1),0),y=Math.min(d.length,t+p);t||r||(m=0,y=d.length);var g=String(y).length,b=d.slice(m,y).map(function(e,n){var i=m+1+n,s=(" "+i).slice(-g),a=" "+s+" | ";if(i===t){var o="";if(r){var c=e.slice(0,r-1).replace(/[^\t]/g," ");o=["\n ",u(l.gutter,a.replace(/\d/g," ")),c,u(l.marker,"^")].join("")}return[u(l.marker,">"),u(l.gutter,a),e,o].join("")}return" "+u(l.gutter,a)+e}).join("\n");return s?o.reset(b):b};var o=e("js-tokens"),u=n(o),l=e("esutils"),c=n(l),p=e("chalk"),h=n(p),f=/\r\n|[\n\r\u2028\u2029]/,d=/^[a-z][\w-]*$/i,m=/^[()\[\]{}]$/;t.exports=r.default},{chalk:185,esutils:27,"js-tokens":311}],24:[function(e,t,r){!function(){"use strict";function e(e){if(null==e)return!1;switch(e.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return!0}return!1}function r(e){if(null==e)return!1;switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return!0}return!1}function n(e){if(null==e)return!1;switch(e.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return!0}return!1}function i(e){return n(e)||null!=e&&"FunctionDeclaration"===e.type}function s(e){switch(e.type){case"IfStatement":return null!=e.alternate?e.alternate:e.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return e.body}return null}function a(e){var t;if("IfStatement"!==e.type)return!1;if(null==e.alternate)return!1;t=e.consequent;do{if("IfStatement"===t.type&&null==t.alternate)return!0;t=s(t)}while(t);return!1}t.exports={isExpression:e,isStatement:n,isIterationStatement:r,isSourceElement:i,isProblematicIfStatement:a,trailingStatement:s}}()},{}],25:[function(e,t,r){!function(){"use strict";function e(e){return 48<=e&&e<=57}function r(e){return 48<=e&&e<=57||97<=e&&e<=102||65<=e&&e<=70}function n(e){return e>=48&&e<=55}function i(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&f.indexOf(e)>=0}function s(e){return 10===e||13===e||8232===e||8233===e}function a(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(Math.floor((e-65536)/1024)+55296)+String.fromCharCode((e-65536)%1024+56320)}function o(e){return e<128?d[e]:h.NonAsciiIdentifierStart.test(a(e))}function u(e){return e<128?m[e]:h.NonAsciiIdentifierPart.test(a(e))}function l(e){return e<128?d[e]:p.NonAsciiIdentifierStart.test(a(e))}function c(e){return e<128?m[e]:p.NonAsciiIdentifierPart.test(a(e))}var p,h,f,d,m,y;for(h={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,NonAsciiIdentifierPart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/},p={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},f=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],d=new Array(128),y=0;y<128;++y)d[y]=y>=97&&y<=122||y>=65&&y<=90||36===y||95===y;for(m=new Array(128),y=0;y<128;++y)m[y]=y>=97&&y<=122||y>=65&&y<=90||y>=48&&y<=57||36===y||95===y;t.exports={isDecimalDigit:e,isHexDigit:r,isOctalDigit:n,isWhiteSpace:i,isLineTerminator:s,isIdentifierStartES5:o,isIdentifierPartES5:u,isIdentifierStartES6:l,isIdentifierPartES6:c}}()},{}],26:[function(e,t,r){!function(){"use strict";function r(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}function n(e,t){return!(!t&&"yield"===e)&&i(e,t)}function i(e,t){if(t&&r(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function s(e,t){return"null"===e||"true"===e||"false"===e||n(e,t)}function a(e,t){return"null"===e||"true"===e||"false"===e||i(e,t)}function o(e){return"eval"===e||"arguments"===e}function u(e){var t,r,n;if(0===e.length)return!1;if(n=e.charCodeAt(0),!f.isIdentifierStartES5(n))return!1 +;for(t=1,r=e.length;t=r)return!1;if(!(56320<=(i=e.charCodeAt(t))&&i<=57343))return!1;n=l(n,i)}if(!s(n))return!1;s=f.isIdentifierPartES6}return!0}function p(e,t){return u(e)&&!s(e,t)}function h(e,t){return c(e)&&!a(e,t)}var f=e("./code");t.exports={isKeywordES5:n,isKeywordES6:i,isReservedWordES5:s,isReservedWordES6:a,isRestrictedWord:o,isIdentifierNameES5:u,isIdentifierNameES6:c,isIdentifierES5:p,isIdentifierES6:h}}()},{"./code":25}],27:[function(e,t,r){!function(){"use strict";r.ast=e("./ast"),r.code=e("./code"),r.keyword=e("./keyword")}()},{"./ast":24,"./code":25,"./keyword":26}],28:[function(e,t,r){t.exports=e("./lib/api/node.js")},{"./lib/api/node.js":29}],29:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e){throw new Error("The ("+e+") Babel 5 plugin is being run with Babel 6.")}function a(e,t,r){"function"==typeof t&&(r=t,t={}),t.filename=e,y.default.readFile(e,function(e,n){var i=void 0;if(!e)try{i=T(n,t)}catch(t){e=t}e?r(e):r(null,i)})}function o(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t.filename=e,T(y.default.readFileSync(e,"utf8"),t)}r.__esModule=!0,r.transformFromAst=r.transform=r.analyse=r.Pipeline=r.OptionManager=r.traverse=r.types=r.messages=r.util=r.version=r.resolvePreset=r.resolvePlugin=r.template=r.buildExternalHelpers=r.options=r.File=void 0;var u=e("../transformation/file");Object.defineProperty(r,"File",{enumerable:!0,get:function(){return i(u).default}});var l=e("../transformation/file/options/config");Object.defineProperty(r,"options",{enumerable:!0,get:function(){return i(l).default}});var c=e("../tools/build-external-helpers");Object.defineProperty(r,"buildExternalHelpers",{enumerable:!0,get:function(){return i(c).default}});var p=e("babel-template");Object.defineProperty(r,"template",{enumerable:!0,get:function(){return i(p).default}});var h=e("../helpers/resolve-plugin");Object.defineProperty(r,"resolvePlugin",{enumerable:!0,get:function(){return i(h).default}});var f=e("../helpers/resolve-preset");Object.defineProperty(r,"resolvePreset",{enumerable:!0,get:function(){return i(f).default}});var d=e("../../package");Object.defineProperty(r,"version",{enumerable:!0,get:function(){return d.version}}),r.Plugin=s,r.transformFile=a,r.transformFileSync=o;var m=e("fs"),y=i(m),g=e("../util"),b=n(g),v=e("babel-messages"),x=n(v),E=e("babel-types"),A=n(E),D=e("babel-traverse"),C=i(D),S=e("../transformation/file/options/option-manager"),_=i(S),w=e("../transformation/pipeline"),k=i(w);r.util=b,r.messages=x,r.types=A,r.traverse=C.default,r.OptionManager=_.default,r.Pipeline=k.default;var F=new k.default,T=(r.analyse=F.analyse.bind(F),r.transform=F.transform.bind(F));r.transformFromAst=F.transformFromAst.bind(F)},{"../../package":66,"../helpers/resolve-plugin":35,"../helpers/resolve-preset":36,"../tools/build-external-helpers":39,"../transformation/file":40,"../transformation/file/options/config":44,"../transformation/file/options/option-manager":46,"../transformation/pipeline":51,"../util":54,"babel-messages":103,"babel-template":132,"babel-traverse":136,"babel-types":169,fs:182}],30:[function(e,t,r){"use strict";function n(e){return["babel-plugin-"+e,e]}r.__esModule=!0,r.default=n,t.exports=r.default},{}],31:[function(e,t,r){"use strict";function n(e){var t=["babel-preset-"+e,e],r=e.match(/^(@[^\/]+)\/(.+)$/);if(r){var n=r[1],i=r[2];t.push(n+"/babel-preset-"+i)}return t}r.__esModule=!0,r.default=n,t.exports=r.default},{}],32:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/core-js/get-iterator"),s=n(i);r.default=function(e,t){if(e&&t)return(0,o.default)(e,t,function(e,t){if(t&&Array.isArray(e)){for(var r=t.slice(0),n=e,i=Array.isArray(n),a=0,n=i?n:(0,s.default)(n);;){var o;if(i){if(a>=n.length)break;o=n[a++]}else{if(a=n.next(),a.done)break;o=a.value}var u=o;r.indexOf(u)<0&&r.push(u)}return r}})};var a=e("lodash/mergeWith"),o=n(a);t.exports=r.default},{"babel-runtime/core-js/get-iterator":113,"lodash/mergeWith":516}],33:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t,r){if(e){if("Program"===e.type)return i.file(e,t||[],r||[]);if("File"===e.type)return e}throw new Error("Not a valid ast?")};var n=e("babel-types"),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(n);t.exports=r.default},{"babel-types":169}],34:[function(e,t,r){"use strict";function n(e,t){return e.reduce(function(e,r){return e||(0,s.default)(r,t)},null)}r.__esModule=!0,r.default=n;var i=e("./resolve"),s=function(e){return e&&e.__esModule?e:{default:e}}(i);t.exports=r.default},{"./resolve":37}],35:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();return(0,o.default)((0,l.default)(e),t)}r.__esModule=!0,r.default=s;var a=e("./resolve-from-possible-names"),o=i(a),u=e("./get-possible-plugin-names"),l=i(u);t.exports=r.default}).call(this,e("_process"))},{"./get-possible-plugin-names":30,"./resolve-from-possible-names":34,_process:539}],36:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();return(0,o.default)((0,l.default)(e),t)}r.__esModule=!0,r.default=s;var a=e("./resolve-from-possible-names"),o=i(a),u=e("./get-possible-preset-names"),l=i(u);t.exports=r.default}).call(this,e("_process"))},{"./get-possible-preset-names":31,"./resolve-from-possible-names":34,_process:539}],37:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var s=e("babel-runtime/helpers/typeof"),a=i(s);r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();if("object"===(void 0===u.default?"undefined":(0,a.default)(u.default)))return null;var r=p[t];if(!r){r=new u.default;var i=c.default.join(t,".babelrc");r.id=i,r.filename=i,r.paths=u.default._nodeModulePaths(t),p[t]=r}try{return u.default._resolveFilename(e,r)}catch(e){return null}};var o=e("module"),u=i(o),l=e("path"),c=i(l),p={};t.exports=r.default}).call(this,e("_process"))},{_process:539,"babel-runtime/helpers/typeof":131,module:182,path:535}],38:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/core-js/map"),s=n(i),a=e("babel-runtime/helpers/classCallCheck"),o=n(a),u=e("babel-runtime/helpers/possibleConstructorReturn"),l=n(u),c=e("babel-runtime/helpers/inherits"),p=n(c),h=function(e){function t(){(0,o.default)(this,t);var r=(0,l.default)(this,e.call(this));return r.dynamicData={},r}return(0,p.default)(t,e),t.prototype.setDynamic=function(e,t){this.dynamicData[e]=t},t.prototype.get=function(t){if(this.has(t))return e.prototype.get.call(this,t);if(Object.prototype.hasOwnProperty.call(this.dynamicData,t)){var r=this.dynamicData[t]();return this.set(t,r),r}},t}(s.default);r.default=h,t.exports=r.default},{"babel-runtime/core-js/map":115,"babel-runtime/helpers/classCallCheck":127,"babel-runtime/helpers/inherits":128,"babel-runtime/helpers/possibleConstructorReturn":130}],39:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function s(e,t){var r=[],n=b.functionExpression(null,[b.identifier("global")],b.blockStatement(r)),i=b.program([b.expressionStatement(b.callExpression(n,[c.get("selfGlobal")]))]);return r.push(b.variableDeclaration("var",[b.variableDeclarator(e,b.assignmentExpression("=",b.memberExpression(b.identifier("global"),e),b.objectExpression([])))])),t(r),i}function a(e,t){var r=[];return r.push(b.variableDeclaration("var",[b.variableDeclarator(e,b.identifier("global"))])),t(r),b.program([v({FACTORY_PARAMETERS:b.identifier("global"),BROWSER_ARGUMENTS:b.assignmentExpression("=",b.memberExpression(b.identifier("root"),e),b.objectExpression([])),COMMON_ARGUMENTS:b.identifier("exports"),AMD_ARGUMENTS:b.arrayExpression([b.stringLiteral("exports")]),FACTORY_BODY:r,UMD_ROOT:b.identifier("this")})])}function o(e,t){var r=[];return r.push(b.variableDeclaration("var",[b.variableDeclarator(e,b.objectExpression([]))])),t(r),r.push(b.expressionStatement(e)),b.program(r)}function u(e,t,r){c.list.forEach(function(n){if(!(r&&r.indexOf(n)<0)){var i=b.identifier(n);e.push(b.expressionStatement(b.assignmentExpression("=",b.memberExpression(t,i),c.get(n))))}})}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"global",r=b.identifier("babelHelpers"),n=function(t){return u(t,r,e)},i=void 0,l={global:s,umd:a,var:o}[t];if(!l)throw new Error(d.get("unsupportedOutputType",t));return i=l(r,n),(0,h.default)(i).code};var l=e("babel-helpers"),c=i(l),p=e("babel-generator"),h=n(p),f=e("babel-messages"),d=i(f),m=e("babel-template"),y=n(m),g=e("babel-types"),b=i(g),v=(0,y.default)('\n (function (root, factory) {\n if (typeof define === "function" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === "object") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n');t.exports=r.default},{"babel-generator":78,"babel-helpers":102,"babel-messages":103,"babel-template":132,"babel-types":169}],40:[function(e,t,r){(function(t){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0,r.File=void 0;var s=e("babel-runtime/core-js/get-iterator"),a=i(s),o=e("babel-runtime/core-js/object/create"),u=i(o),l=e("babel-runtime/core-js/object/assign"),c=i(l),p=e("babel-runtime/helpers/classCallCheck"),h=i(p),f=e("babel-runtime/helpers/possibleConstructorReturn"),d=i(f),m=e("babel-runtime/helpers/inherits"),y=i(m),g=e("babel-helpers"),b=i(g),v=e("./metadata"),x=n(v),E=e("convert-source-map"),A=i(E),D=e("./options/option-manager"),C=i(D),S=e("../plugin-pass"),_=i(S),w=e("babel-traverse"),k=i(w),F=e("source-map"),T=i(F),P=e("babel-generator"),B=i(P),O=e("babel-code-frame"),j=i(O),N=e("lodash/defaults"),I=i(N),L=e("./logger"),M=i(L),R=e("../../store"),U=i(R),V=e("babylon"),q=e("../../util"),G=n(q),X=e("path"),J=i(X),W=e("babel-types"),K=n(W),z=e("../../helpers/resolve"),Y=i(z),H=e("../internal-plugins/block-hoist"),$=i(H),Q=e("../internal-plugins/shadow-functions"),Z=i(Q),ee=/^#!.*/,te=[[$.default],[Z.default]],re={enter:function(e,t){var r=e.node.loc;r&&(t.loc=r,e.stop())}},ne=function(r){function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];(0,h.default)(this,n);var i=(0,d.default)(this,r.call(this));return i.pipeline=t,i.log=new M.default(i,e.filename||"unknown"),i.opts=i.initOptions(e),i.parserOpts={sourceType:i.opts.sourceType,sourceFileName:i.opts.filename,plugins:[]},i.pluginVisitors=[],i.pluginPasses=[],i.buildPluginsForOptions(i.opts),i.opts.passPerPreset&&(i.perPresetOpts=[],i.opts.presets.forEach(function(e){var t=(0,c.default)((0,u.default)(i.opts),e);i.perPresetOpts.push(t),i.buildPluginsForOptions(t)})),i.metadata={usedHelpers:[],marked:[],modules:{imports:[],exports:{exported:[],specifiers:[]}}},i.dynamicImportTypes={},i.dynamicImportIds={},i.dynamicImports=[],i.declarations={},i.usedHelpers={},i.path=null,i.ast={},i.code="",i.shebang="",i.hub=new w.Hub(i),i}return(0,y.default)(n,r),n.prototype.getMetadata=function(){for(var e=!1,t=this.ast.program.body,r=Array.isArray(t),n=0,t=r?t:(0,a.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;if(K.isModuleDeclaration(s)){e=!0;break}}e&&this.path.traverse(x,this)},n.prototype.initOptions=function(e){e=new C.default(this.log,this.pipeline).init(e),e.inputSourceMap&&(e.sourceMaps=!0),e.moduleId&&(e.moduleIds=!0),e.basename=J.default.basename(e.filename,J.default.extname(e.filename)),e.ignore=G.arrayify(e.ignore,G.regexify),e.only&&(e.only=G.arrayify(e.only,G.regexify)),(0,I.default)(e,{moduleRoot:e.sourceRoot}),(0,I.default)(e,{sourceRoot:e.moduleRoot}),(0,I.default)(e,{filenameRelative:e.filename});var t=J.default.basename(e.filenameRelative);return(0,I.default)(e,{sourceFileName:t,sourceMapTarget:t}),e},n.prototype.buildPluginsForOptions=function(e){if(Array.isArray(e.plugins)){for(var t=e.plugins.concat(te),r=[],n=[],i=t,s=Array.isArray(i),o=0,i=s?i:(0,a.default)(i);;){var u;if(s){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var l=u,c=l[0],p=l[1];r.push(c.visitor),n.push(new _.default(this,c,p)),c.manipulateOptions&&c.manipulateOptions(e,this.parserOpts,this)}this.pluginVisitors.push(r),this.pluginPasses.push(n)}},n.prototype.getModuleName=function(){var e=this.opts;if(!e.moduleIds)return null;if(null!=e.moduleId&&!e.getModuleId)return e.moduleId;var t=e.filenameRelative,r="";if(null!=e.moduleRoot&&(r=e.moduleRoot+"/"),!e.filenameRelative)return r+e.filename.replace(/^\//,"");if(null!=e.sourceRoot){var n=new RegExp("^"+e.sourceRoot+"/?");t=t.replace(n,"")}return t=t.replace(/\.(\w*?)$/,""),r+=t,r=r.replace(/\\/g,"/"),e.getModuleId?e.getModuleId(r)||r:r},n.prototype.resolveModuleSource=function(e){var t=this.opts.resolveModuleSource;return t&&(e=t(e,this.opts.filename)),e},n.prototype.addImport=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,n=e+":"+t,i=this.dynamicImportIds[n];if(!i){e=this.resolveModuleSource(e),i=this.dynamicImportIds[n]=this.scope.generateUidIdentifier(r);var s=[];"*"===t?s.push(K.importNamespaceSpecifier(i)):"default"===t?s.push(K.importDefaultSpecifier(i)):s.push(K.importSpecifier(i,K.identifier(t)));var a=K.importDeclaration(s,K.stringLiteral(e));a._blockHoist=3,this.path.unshiftContainer("body",a)}return i},n.prototype.addHelper=function(e){var t=this.declarations[e];if(t)return t;this.usedHelpers[e]||(this.metadata.usedHelpers.push(e),this.usedHelpers[e]=!0);var r=this.get("helperGenerator"),n=this.get("helpersNamespace");if(r){var i=r(e);if(i)return i}else if(n)return K.memberExpression(n,K.identifier(e));var s=(0,b.default)(e),a=this.declarations[e]=this.scope.generateUidIdentifier(e);return K.isFunctionExpression(s)&&!s.id?(s.body._compact=!0,s._generated=!0,s.id=a,s.type="FunctionDeclaration",this.path.unshiftContainer("body",s)):(s._compact=!0,this.scope.push({id:a,init:s,unique:!0})),a},n.prototype.addTemplateObject=function(e,t,r){var n=r.elements.map(function(e){return e.value}),i=e+"_"+r.elements.length+"_"+n.join(","),s=this.declarations[i];if(s)return s;var a=this.declarations[i]=this.scope.generateUidIdentifier("templateObject"),o=this.addHelper(e),u=K.callExpression(o,[t,r]);return u._compact=!0,this.scope.push({id:a,init:u,_blockHoist:1.9}),a},n.prototype.buildCodeFrameError=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:SyntaxError,n=e&&(e.loc||e._loc),i=new r(t);return n?i.loc=n.start:((0,k.default)(e,re,this.scope,i),i.message+=" (This is an error on an internal node. Probably an internal error",i.loc&&(i.message+=". Location has been estimated."),i.message+=")"),i},n.prototype.mergeSourceMap=function(e){var t=this.opts.inputSourceMap;if(t){var r=new T.default.SourceMapConsumer(t),n=new T.default.SourceMapConsumer(e),i=new T.default.SourceMapGenerator({file:r.file,sourceRoot:r.sourceRoot}),s=n.sources[0];r.eachMapping(function(e){var t=n.generatedPositionFor({line:e.generatedLine,column:e.generatedColumn,source:s});null!=t.column&&i.addMapping({source:e.source,original:null==e.source?null:{line:e.originalLine,column:e.originalColumn},generated:t})});var a=i.toJSON();return t.mappings=a.mappings,t}return e},n.prototype.parse=function(r){var n=V.parse,i=this.opts.parserOpts;if(i&&(i=(0,c.default)({},this.parserOpts,i),i.parser)){if("string"==typeof i.parser){var s=J.default.dirname(this.opts.filename)||t.cwd(),a=(0,Y.default)(i.parser,s);if(!a)throw new Error("Couldn't find parser "+i.parser+' with "parse" method relative to directory '+s);n=e(a).parse}else n=i.parser;i.parser={parse:function(e){return(0,V.parse)(e,i)}}}this.log.debug("Parse start");var o=n(r,i||this.parserOpts);return this.log.debug("Parse stop"),o},n.prototype._addAst=function(e){this.path=w.NodePath.get({hub:this.hub,parentPath:null,parent:e,container:e,key:"program"}).setContext(),this.scope=this.path.scope,this.ast=e,this.getMetadata()},n.prototype.addAst=function(e){this.log.debug("Start set AST"),this._addAst(e),this.log.debug("End set AST")},n.prototype.transform=function(){for(var e=0;e=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var o=s,u=o.plugin,l=u[e];l&&l.call(o,this)}},n.prototype.parseInputSourceMap=function(e){var t=this.opts;if(!1!==t.inputSourceMap){var r=A.default.fromSource(e);r&&(t.inputSourceMap=r.toObject(),e=A.default.removeComments(e))}return e},n.prototype.parseShebang=function(){var e=ee.exec(this.code);e&&(this.shebang=e[0],this.code=this.code.replace(ee,""))},n.prototype.makeResult=function(e){var t=e.code,r=e.map,n=e.ast,i=e.ignored,s={metadata:null,options:this.opts,ignored:!!i,code:null,ast:null,map:r||null};return this.opts.code&&(s.code=t),this.opts.ast&&(s.ast=n),this.opts.metadata&&(s.metadata=this.metadata),s},n.prototype.generate=function(){var r=this.opts,n=this.ast,i={ast:n};if(!r.code)return this.makeResult(i);var s=B.default;if(r.generatorOpts.generator&&"string"==typeof(s=r.generatorOpts.generator)){var a=J.default.dirname(this.opts.filename)||t.cwd(),o=(0,Y.default)(s,a);if(!o)throw new Error("Couldn't find generator "+s+' with "print" method relative to directory '+a);s=e(o).print}this.log.debug("Generation start");var u=s(n,r.generatorOpts?(0,c.default)(r,r.generatorOpts):r,this.code);return i.code=u.code,i.map=u.map,this.log.debug("Generation end"),this.shebang&&(i.code=this.shebang+"\n"+i.code),i.map&&(i.map=this.mergeSourceMap(i.map)),"inline"!==r.sourceMaps&&"both"!==r.sourceMaps||(i.code+="\n"+A.default.fromObject(i.map).toComment()),"inline"===r.sourceMaps&&(i.map=null),this.makeResult(i)},n}(U.default);r.default=ne,r.File=ne}).call(this,e("_process"))},{"../../helpers/resolve":37,"../../store":38,"../../util":54,"../internal-plugins/block-hoist":49,"../internal-plugins/shadow-functions":50,"../plugin-pass":52,"./logger":41,"./metadata":42,"./options/option-manager":46,_process:539,"babel-code-frame":23,"babel-generator":78,"babel-helpers":102,"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/object/assign":117,"babel-runtime/core-js/object/create":118,"babel-runtime/helpers/classCallCheck":127,"babel-runtime/helpers/inherits":128,"babel-runtime/helpers/possibleConstructorReturn":130,"babel-traverse":136,"babel-types":169,babylon:177,"convert-source-map":187,"lodash/defaults":484,path:535,"source-map":65}],41:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/helpers/classCallCheck"),s=n(i),a=e("debug/node"),o=n(a),u=(0,o.default)("babel:verbose"),l=(0,o.default)("babel"),c=[],p=function(){function e(t,r){(0,s.default)(this,e),this.filename=r,this.file=t}return e.prototype._buildMessage=function(e){var t="[BABEL] "+this.filename;return e&&(t+=": "+e),t},e.prototype.warn=function(e){console.warn(this._buildMessage(e))},e.prototype.error=function(e){throw new(arguments.length>1&&void 0!==arguments[1]?arguments[1]:Error)(this._buildMessage(e))},e.prototype.deprecate=function(e){this.file.opts&&this.file.opts.suppressDeprecationMessages||(e=this._buildMessage(e),c.indexOf(e)>=0||(c.push(e),console.error(e)))},e.prototype.verbose=function(e){u.enabled&&u(this._buildMessage(e))},e.prototype.debug=function(e){l.enabled&&l(this._buildMessage(e))},e.prototype.deopt=function(e,t){this.debug(t)},e}();r.default=p,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":127,"debug/node":295}],42:[function(e,t,r){"use strict";function n(e,t){var r=e.node,n=r.source?r.source.value:null,i=t.metadata.modules.exports,s=e.get("declaration");if(s.isStatement()){var o=s.getBindingIdentifiers();for(var l in o)i.exported.push(l),i.specifiers.push({kind:"local",local:l,exported:e.isExportDefaultDeclaration()?"default":l})}if(e.isExportNamedDeclaration()&&r.specifiers)for(var c=r.specifiers,p=Array.isArray(c),h=0,c=p?c:(0,a.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var d=f,m=d.exported.name;i.exported.push(m),u.isExportDefaultSpecifier(d)&&i.specifiers.push({kind:"external",local:m,exported:m,source:n}),u.isExportNamespaceSpecifier(d)&&i.specifiers.push({kind:"external-namespace",exported:m,source:n});var y=d.local;y&&(n&&i.specifiers.push({kind:"external",local:y.name,exported:m,source:n}),n||i.specifiers.push({kind:"local",local:y.name,exported:m}))}e.isExportAllDeclaration()&&i.specifiers.push({kind:"external-all",source:n})}function i(e){e.skip()}r.__esModule=!0,r.ImportDeclaration=r.ModuleDeclaration=void 0;var s=e("babel-runtime/core-js/get-iterator"),a=function(e){return e&&e.__esModule?e:{default:e}}(s);r.ExportDeclaration=n,r.Scope=i;var o=e("babel-types"),u=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(o);r.ModuleDeclaration={enter:function(e,t){var r=e.node;r.source&&(r.source.value=t.resolveModuleSource(r.source.value))}},r.ImportDeclaration={exit:function(e,t){var r=e.node,n=[],i=[];t.metadata.modules.imports.push({source:r.source.value,imported:i,specifiers:n});for(var s=e.get("specifiers"),o=Array.isArray(s),u=0,s=o?s:(0,a.default)(s);;){var l;if(o){if(u>=s.length)break;l=s[u++]}else{if(u=s.next(),u.done)break;l=u.value}var c=l,p=c.node.local.name;if(c.isImportDefaultSpecifier()&&(i.push("default"),n.push({kind:"named",imported:"default",local:p})),c.isImportSpecifier()){var h=c.node.imported.name;i.push(h),n.push({kind:"named",imported:h,local:p})}c.isImportNamespaceSpecifier()&&(i.push("*"),n.push({kind:"namespace",local:p}))}}}},{"babel-runtime/core-js/get-iterator":113,"babel-types":169}],43:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=E[e];return null==t?E[e]=x.default.existsSync(e):t}function a(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],r=e.filename,n=new D(t);return!1!==e.babelrc&&n.findConfigs(r),n.mergeConfig({options:e,alias:"base",dirname:r&&b.default.dirname(r)}),n.configs}r.__esModule=!0;var o=e("babel-runtime/core-js/object/assign"),u=i(o),l=e("babel-runtime/helpers/classCallCheck"),c=i(l);r.default=a;var p=e("../../../helpers/resolve"),h=i(p),f=e("json5"),d=i(f),m=e("path-is-absolute"),y=i(m),g=e("path"),b=i(g),v=e("fs"),x=i(v),E={},A={},D=function(){function e(t){(0,c.default)(this,e),this.resolvedConfigs=[],this.configs=[],this.log=t}return e.prototype.findConfigs=function(e){if(e){(0,y.default)(e)||(e=b.default.join(n.cwd(),e));for(var t=!1,r=!1;e!==(e=b.default.dirname(e));){if(!t){var i=b.default.join(e,".babelrc");s(i)&&(this.addConfig(i),t=!0);var a=b.default.join(e,"package.json");!t&&s(a)&&(t=this.addConfig(a,"babel",JSON))}if(!r){var o=b.default.join(e,".babelignore");s(o)&&(this.addIgnoreConfig(o),r=!0)}if(r&&t)return}}},e.prototype.addIgnoreConfig=function(e){var t=x.default.readFileSync(e,"utf8"),r=t.split("\n");r=r.map(function(e){return e.replace(/#(.*?)$/,"").trim()}).filter(function(e){return!!e}),r.length&&this.mergeConfig({options:{ignore:r},alias:e,dirname:b.default.dirname(e)})},e.prototype.addConfig=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d.default;if(this.resolvedConfigs.indexOf(e)>=0)return!1;this.resolvedConfigs.push(e);var n=x.default.readFileSync(e,"utf8"),i=void 0;try{i=A[n]=A[n]||r.parse(n),t&&(i=i[t])}catch(t){throw t.message=e+": Error while parsing JSON - "+t.message,t}return this.mergeConfig({options:i,alias:e,dirname:b.default.dirname(e)}),!!i},e.prototype.mergeConfig=function(e){var t=e.options,r=e.alias,i=e.loc,s=e.dirname;if(!t)return!1;if(t=(0,u.default)({},t),s=s||n.cwd(),i=i||r,t.extends){var a=(0,h.default)(t.extends,s);a?this.addConfig(a):this.log&&this.log.error("Couldn't resolve extends clause of "+t.extends+" in "+r),delete t.extends}this.configs.push({options:t,alias:r,loc:i,dirname:s});var o=void 0,l=n.env.BABEL_ENV||n.env.NODE_ENV||"development";t.env&&(o=t.env[l],delete t.env),this.mergeConfig({options:o,alias:r+".env."+l,dirname:s})},e}();t.exports=r.default}).call(this,e("_process"))},{"../../../helpers/resolve":37,_process:539,"babel-runtime/core-js/object/assign":117,"babel-runtime/helpers/classCallCheck":127,fs:182,json5:313,path:535,"path-is-absolute":536}],44:[function(e,t,r){"use strict";t.exports={filename:{type:"filename",description:"filename to use when reading from stdin - this will be used in source-maps, errors etc",default:"unknown",shorthand:"f"},filenameRelative:{hidden:!0,type:"string"},inputSourceMap:{hidden:!0},env:{hidden:!0,default:{}},mode:{description:"",hidden:!0},retainLines:{type:"boolean",default:!1,description:"retain line numbers - will result in really ugly code"},highlightCode:{description:"enable/disable ANSI syntax highlighting of code frames (on by default)",type:"boolean",default:!0},suppressDeprecationMessages:{type:"boolean",default:!1,hidden:!0},presets:{type:"list",description:"",default:[]},plugins:{type:"list",default:[],description:""},ignore:{type:"list",description:"list of glob paths to **not** compile",default:[]},only:{type:"list",description:"list of glob paths to **only** compile"},code:{hidden:!0,default:!0,type:"boolean"},metadata:{hidden:!0,default:!0,type:"boolean"},ast:{hidden:!0,default:!0,type:"boolean"},extends:{type:"string",hidden:!0},comments:{type:"boolean",default:!0,description:"write comments to generated output (true by default)"},shouldPrintComment:{hidden:!0,description:"optional callback to control whether a comment should be inserted, when this is used the comments option is ignored"},wrapPluginVisitorMethod:{hidden:!0,description:"optional callback to wrap all visitor methods"},compact:{type:"booleanString",default:"auto",description:"do not include superfluous whitespace characters and line terminators [true|false|auto]"},minified:{type:"boolean",default:!1,description:"save as much bytes when printing [true|false]"},sourceMap:{alias:"sourceMaps",hidden:!0},sourceMaps:{type:"booleanString",description:"[true|false|inline]",default:!1,shorthand:"s"},sourceMapTarget:{type:"string",description:"set `file` on returned source map"},sourceFileName:{type:"string",description:"set `sources[0]` on returned source map"},sourceRoot:{type:"filename",description:"the root from which all sources are relative"},babelrc:{description:"Whether or not to look up .babelrc and .babelignore files",type:"boolean",default:!0},sourceType:{description:"",default:"module"},auxiliaryCommentBefore:{type:"string",description:"print a comment before any injected non-user code"},auxiliaryCommentAfter:{type:"string",description:"print a comment after any injected non-user code"},resolveModuleSource:{hidden:!0},getModuleId:{hidden:!0},moduleRoot:{type:"filename",description:"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"},moduleIds:{type:"boolean",default:!1,shorthand:"M",description:"insert an explicit id for modules"},moduleId:{description:"specify a custom name for module ids",type:"string"},passPerPreset:{description:"Whether to spawn a traversal pass per a preset. By default all presets are merged.",type:"boolean",default:!1,hidden:!0},parserOpts:{description:"Options to pass into the parser, or to change parsers (parserOpts.parser)",default:!1},generatorOpts:{description:"Options to pass into the generator, or to change generators (generatorOpts.generator)",default:!1}}},{}],45:[function(e,t,r){"use strict";function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e){var r=e[t];if(null!=r){var n=o.default[t];if(n&&n.alias&&(n=o.default[n.alias]),n){var i=s[n.type];i&&(r=i(r)),e[t]=r}}}return e}r.__esModule=!0,r.config=void 0,r.normaliseOptions=n;var i=e("./parsers"),s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(i),a=e("./config"),o=function(e){return e&&e.__esModule?e:{default:e}}(a);r.config=o.default},{"./config":44,"./parsers":47}],46:[function(e,t,r){(function(n){"use strict";function i(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function s(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var a=e("babel-runtime/helpers/objectWithoutProperties"),o=s(a),u=e("babel-runtime/core-js/json/stringify"),l=s(u),c=e("babel-runtime/core-js/object/assign"),p=s(c),h=e("babel-runtime/core-js/get-iterator"),f=s(h),d=e("babel-runtime/helpers/typeof"),m=s(d),y=e("babel-runtime/helpers/classCallCheck"),g=s(y),b=e("../../../api/node"),v=i(b),x=e("../../plugin"),E=s(x),A=e("babel-messages"),D=i(A),C=e("./index"),S=e("../../../helpers/resolve-plugin"),_=s(S),w=e("../../../helpers/resolve-preset"),k=s(w),F=e("lodash/cloneDeepWith"),T=s(F),P=e("lodash/clone"),B=s(P),O=e("../../../helpers/merge"),j=s(O),N=e("./config"),I=s(N),L=e("./removed"),M=s(L),R=e("./build-config-chain"),U=s(R),V=e("path"),q=s(V),G=function(){function t(e){(0,g.default)(this,t),this.resolvedConfigs=[],this.options=t.createBareOptions(),this.log=e}return t.memoisePluginContainer=function(e,r,n,i){for(var s=t.memoisedPlugins,a=Array.isArray(s),o=0,s=a?s:(0,f.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u;if(l.container===e)return l.plugin}var c=void 0;if(c="function"==typeof e?e(v):e,"object"===(void 0===c?"undefined":(0,m.default)(c))){var p=new E.default(c,i);return t.memoisedPlugins.push({container:e,plugin:p}),p}throw new TypeError(D.get("pluginNotObject",r,n,void 0===c?"undefined":(0,m.default)(c))+r+n)},t.createBareOptions=function(){var e={};for(var t in I.default){ +var r=I.default[t];e[t]=(0,B.default)(r.default)}return e},t.normalisePlugin=function(e,r,n,i){if(!((e=e.__esModule?e.default:e)instanceof E.default)){if("function"!=typeof e&&"object"!==(void 0===e?"undefined":(0,m.default)(e)))throw new TypeError(D.get("pluginNotFunction",r,n,void 0===e?"undefined":(0,m.default)(e)));e=t.memoisePluginContainer(e,r,n,i)}return e.init(r,n),e},t.normalisePlugins=function(r,n,i){return i.map(function(i,s){var a=void 0,o=void 0;if(!i)throw new TypeError("Falsy value found in plugins");Array.isArray(i)?(a=i[0],o=i[1]):a=i;var u="string"==typeof a?a:r+"$"+s;if("string"==typeof a){var l=(0,_.default)(a,n);if(!l)throw new ReferenceError(D.get("pluginUnknown",a,r,s,n));a=e(l)}return a=t.normalisePlugin(a,r,s,u),[a,o]})},t.prototype.mergeOptions=function(e){var r=this,i=e.options,s=e.extending,a=e.alias,o=e.loc,u=e.dirname;if(a=a||"foreign",i){("object"!==(void 0===i?"undefined":(0,m.default)(i))||Array.isArray(i))&&this.log.error("Invalid options type for "+a,TypeError);var l=(0,T.default)(i,function(e){if(e instanceof E.default)return e});u=u||n.cwd(),o=o||a;for(var c in l){if(!I.default[c]&&this.log)if(M.default[c])this.log.error("Using removed Babel 5 option: "+a+"."+c+" - "+M.default[c].message,ReferenceError);else{var h="Unknown option: "+a+"."+c+". Check out http://babeljs.io/docs/usage/options/ for more information about options.";this.log.error(h+"\n\nA common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.",ReferenceError)}}(0,C.normaliseOptions)(l),l.plugins&&(l.plugins=t.normalisePlugins(o,u,l.plugins)),l.presets&&(l.passPerPreset?l.presets=this.resolvePresets(l.presets,u,function(e,t){r.mergeOptions({options:e,extending:e,alias:t,loc:t,dirname:u})}):(this.mergePresets(l.presets,u),delete l.presets)),i===s?(0,p.default)(s,l):(0,j.default)(s||this.options,l)}},t.prototype.mergePresets=function(e,t){var r=this;this.resolvePresets(e,t,function(e,t){r.mergeOptions({options:e,alias:t,loc:t,dirname:q.default.dirname(t||"")})})},t.prototype.resolvePresets=function(t,r,n){return t.map(function(t){var i=void 0;if(Array.isArray(t)){if(t.length>2)throw new Error("Unexpected extra options "+(0,l.default)(t.slice(2))+" passed to preset.");var s=t;t=s[0],i=s[1]}var a=void 0;try{if("string"==typeof t){if(!(a=(0,k.default)(t,r)))throw new Error("Couldn't find preset "+(0,l.default)(t)+" relative to directory "+(0,l.default)(r));t=e(a)}if("object"===(void 0===t?"undefined":(0,m.default)(t))&&t.__esModule)if(t.default)t=t.default;else{var u=t,c=(u.__esModule,(0,o.default)(u,["__esModule"]));t=c}if("object"===(void 0===t?"undefined":(0,m.default)(t))&&t.buildPreset&&(t=t.buildPreset),"function"!=typeof t&&void 0!==i)throw new Error("Options "+(0,l.default)(i)+" passed to "+(a||"a preset")+" which does not accept options.");if("function"==typeof t&&(t=t(v,i,{dirname:r})),"object"!==(void 0===t?"undefined":(0,m.default)(t)))throw new Error("Unsupported preset format: "+t+".");n&&n(t,a)}catch(e){throw a&&(e.message+=" (While processing preset: "+(0,l.default)(a)+")"),e}return t})},t.prototype.normaliseOptions=function(){var e=this.options;for(var t in I.default){var r=I.default[t],n=e[t];!n&&r.optional||(r.alias?e[r.alias]=e[r.alias]||n:e[t]=n)}},t.prototype.init=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=(0,U.default)(e,this.log),r=Array.isArray(t),n=0,t=r?t:(0,f.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;this.mergeOptions(s)}return this.normaliseOptions(e),this.options},t}();r.default=G,G.memoisedPlugins=[],t.exports=r.default}).call(this,e("_process"))},{"../../../api/node":29,"../../../helpers/merge":32,"../../../helpers/resolve-plugin":35,"../../../helpers/resolve-preset":36,"../../plugin":53,"./build-config-chain":43,"./config":44,"./index":45,"./removed":48,_process:539,"babel-messages":103,"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/json/stringify":114,"babel-runtime/core-js/object/assign":117,"babel-runtime/helpers/classCallCheck":127,"babel-runtime/helpers/objectWithoutProperties":129,"babel-runtime/helpers/typeof":131,"lodash/clone":480,"lodash/cloneDeepWith":482,path:535}],47:[function(e,t,r){"use strict";function n(e){return!!e}function i(e){return l.booleanify(e)}function s(e){return l.list(e)}r.__esModule=!0,r.filename=void 0,r.boolean=n,r.booleanString=i,r.list=s;var a=e("slash"),o=function(e){return e&&e.__esModule?e:{default:e}}(a),u=e("../../../util"),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(u);r.filename=o.default},{"../../../util":54,slash:589}],48:[function(e,t,r){"use strict";t.exports={auxiliaryComment:{message:"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"},blacklist:{message:"Put the specific transforms you want in the `plugins` option"},breakConfig:{message:"This is not a necessary option in Babel 6"},experimental:{message:"Put the specific transforms you want in the `plugins` option"},externalHelpers:{message:"Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"},extra:{message:""},jsxPragma:{message:"use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/"},loose:{message:"Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."},metadataUsedHelpers:{message:"Not required anymore as this is enabled by default"},modules:{message:"Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules"},nonStandard:{message:"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"},optional:{message:"Put the specific transforms you want in the `plugins` option"},sourceMapName:{message:"Use the `sourceMapTarget` option"},stage:{message:"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"},whitelist:{message:"Put the specific transforms you want in the `plugins` option"}}},{}],49:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("../plugin"),s=n(i),a=e("lodash/sortBy"),o=n(a);r.default=new s.default({name:"internal.blockHoist",visitor:{Block:{exit:function(e){for(var t=e.node,r=!1,n=0;n1&&void 0!==arguments[1]?arguments[1]:{};return t.code=!1,t.mode="lint",this.transform(e,t)},e.prototype.pretransform=function(e,t){var r=new p.default(t,this);return r.wrap(e,function(){return r.addCode(e),r.parseCode(e),r})},e.prototype.transform=function(e,t){var r=new p.default(t,this);return r.wrap(e,function(){return r.addCode(e),r.parseCode(e),r.transform()})},e.prototype.analyse=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments[2];return t.code=!1,r&&(t.plugins=t.plugins||[],t.plugins.push(new l.default({visitor:r}))),this.transform(e,t).metadata},e.prototype.transformFromAst=function(e,t,r){e=(0,o.default)(e);var n=new p.default(r,this);return n.wrap(t,function(){return n.addCode(t),n.addAst(e),n.transform()})},e}();r.default=h,t.exports=r.default},{"../helpers/normalize-ast":33,"./file":40,"./plugin":53,"babel-runtime/helpers/classCallCheck":127}],52:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/helpers/classCallCheck"),s=n(i),a=e("babel-runtime/helpers/possibleConstructorReturn"),o=n(a),u=e("babel-runtime/helpers/inherits"),l=n(u),c=e("../store"),p=n(c),h=e("./file"),f=(n(h),function(e){function t(r,n){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};(0,s.default)(this,t);var a=(0,o.default)(this,e.call(this));return a.plugin=n,a.key=n.key,a.file=r,a.opts=i,a}return(0,l.default)(t,e),t.prototype.addHelper=function(){var e;return(e=this.file).addHelper.apply(e,arguments)},t.prototype.addImport=function(){var e;return(e=this.file).addImport.apply(e,arguments)},t.prototype.getModuleName=function(){var e;return(e=this.file).getModuleName.apply(e,arguments)},t.prototype.buildCodeFrameError=function(){var e;return(e=this.file).buildCodeFrameError.apply(e,arguments)},t}(p.default));r.default=f,t.exports=r.default},{"../store":38,"./file":40,"babel-runtime/helpers/classCallCheck":127,"babel-runtime/helpers/inherits":128,"babel-runtime/helpers/possibleConstructorReturn":130}],53:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/core-js/get-iterator"),s=n(i),a=e("babel-runtime/helpers/classCallCheck"),o=n(a),u=e("babel-runtime/helpers/possibleConstructorReturn"),l=n(u),c=e("babel-runtime/helpers/inherits"),p=n(c),h=e("./file/options/option-manager"),f=n(h),d=e("babel-messages"),m=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(d),y=e("../store"),g=n(y),b=e("babel-traverse"),v=n(b),x=e("lodash/assign"),E=n(x),A=e("lodash/clone"),D=n(A),C=["enter","exit"],S=function(e){function t(r,n){(0,o.default)(this,t);var i=(0,l.default)(this,e.call(this));return i.initialized=!1,i.raw=(0,E.default)({},r),i.key=i.take("name")||n,i.manipulateOptions=i.take("manipulateOptions"),i.post=i.take("post"),i.pre=i.take("pre"),i.visitor=i.normaliseVisitor((0,D.default)(i.take("visitor"))||{}),i}return(0,p.default)(t,e),t.prototype.take=function(e){var t=this.raw[e];return delete this.raw[e],t},t.prototype.chain=function(e,t){if(!e[t])return this[t];if(!this[t])return e[t];var r=[e[t],this[t]];return function(){for(var e=void 0,t=arguments.length,n=Array(t),i=0;i=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;if(c){var p=c.apply(this,n);null!=p&&(e=p)}}return e}},t.prototype.maybeInherit=function(e){var t=this.take("inherits");t&&(t=f.default.normalisePlugin(t,e,"inherits"),this.manipulateOptions=this.chain(t,"manipulateOptions"),this.post=this.chain(t,"post"),this.pre=this.chain(t,"pre"),this.visitor=v.default.visitors.merge([t.visitor,this.visitor]))},t.prototype.init=function(e,t){if(!this.initialized){this.initialized=!0,this.maybeInherit(e);for(var r in this.raw)throw new Error(m.get("pluginInvalidProperty",e,t,r))}},t.prototype.normaliseVisitor=function(e){for(var t=C,r=Array.isArray(t),n=0,t=r?t:(0,s.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}if(e[i])throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.")}return v.default.explode(e),e},t}(g.default);r.default=S,t.exports=r.default},{"../store":38,"./file/options/option-manager":46,"babel-messages":103,"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/classCallCheck":127,"babel-runtime/helpers/inherits":128,"babel-runtime/helpers/possibleConstructorReturn":130,"babel-traverse":136,"lodash/assign":477,"lodash/clone":480}],54:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){var r=t||i.EXTENSIONS,n=S.default.extname(e);return(0,E.default)(r,n)}function s(e){return e?Array.isArray(e)?e:"string"==typeof e?e.split(","):[e]:[]}function a(e){if(!e)return new RegExp(/.^/);if(Array.isArray(e)&&(e=new RegExp(e.map(m.default).join("|"),"i")),"string"==typeof e){e=(0,w.default)(e),((0,g.default)(e,"./")||(0,g.default)(e,"*/"))&&(e=e.slice(2)),(0,g.default)(e,"**/")&&(e=e.slice(3));var t=v.default.makeRe(e,{nocase:!0});return new RegExp(t.source.slice(1,-1),"i")}if((0,D.default)(e))return e;throw new TypeError("illegal type for regexify")}function o(e,t){return e?"boolean"==typeof e?o([e],t):"string"==typeof e?o(s(e),t):Array.isArray(e)?(t&&(e=e.map(t)),e):[e]:[]}function u(e){return"true"===e||1==e||!("false"===e||0==e||!e)&&e}function l(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments[2];if(e=e.replace(/\\/g,"/"),r){for(var n=r,i=Array.isArray(n),s=0,n=i?n:(0,h.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}if(c(a,e))return!1}return!0}if(t.length)for(var o=t,u=Array.isArray(o),l=0,o=u?o:(0,h.default)(o);;){var p;if(u){if(l>=o.length)break;p=o[l++]}else{if(l=o.next(),l.done)break;p=l.value}var f=p;if(c(f,e))return!0}return!1}function c(e,t){return"function"==typeof e?e(t):e.test(t)}r.__esModule=!0,r.inspect=r.inherits=void 0;var p=e("babel-runtime/core-js/get-iterator"),h=n(p),f=e("util");Object.defineProperty(r,"inherits",{enumerable:!0,get:function(){return f.inherits}}),Object.defineProperty(r,"inspect",{enumerable:!0,get:function(){return f.inspect}}),r.canCompile=i,r.list=s,r.regexify=a,r.arrayify=o,r.booleanify=u,r.shouldIgnore=l;var d=e("lodash/escapeRegExp"),m=n(d),y=e("lodash/startsWith"),g=n(y),b=e("minimatch"),v=n(b),x=e("lodash/includes"),E=n(x),A=e("lodash/isRegExp"),D=n(A),C=e("path"),S=n(C),_=e("slash"),w=n(_);i.EXTENSIONS=[".js",".jsx",".es6",".es"]},{"babel-runtime/core-js/get-iterator":113,"lodash/escapeRegExp":486,"lodash/includes":496,"lodash/isRegExp":508,"lodash/startsWith":521,minimatch:531,path:535,slash:589,util:601}],55:[function(e,t,r){function n(){this._array=[],this._set=Object.create(null)}var i=e("./util"),s=Object.prototype.hasOwnProperty;n.fromArray=function(e,t){for(var r=new n,i=0,s=e.length;i=0&&e>1;return t?-r:r}var s=e("./base64");r.encode=function(e){var t,r="",i=n(e);do{t=31&i,i>>>=5,i>0&&(t|=32),r+=s.encode(t)}while(i>0);return r},r.decode=function(e,t,r){var n,a,o=e.length,u=0,l=0;do{if(t>=o)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(a=s.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));n=!!(32&a),a&=31,u+=a<0?t-u>1?n(u,t,i,s,a,o):o==r.LEAST_UPPER_BOUND?t1?n(e,u,i,s,a,o):o==r.LEAST_UPPER_BOUND?u:e<0?-1:e}r.GREATEST_LOWER_BOUND=1,r.LEAST_UPPER_BOUND=2,r.search=function(e,t,i,s){if(0===t.length)return-1;var a=n(-1,t.length,e,t,i,s||r.GREATEST_LOWER_BOUND);if(a<0)return-1;for(;a-1>=0&&0===i(t[a],t[a-1],!0);)--a;return a}},{}],59:[function(e,t,r){function n(e,t){var r=e.generatedLine,n=t.generatedLine,i=e.generatedColumn,a=t.generatedColumn;return n>r||n==r&&a>=i||s.compareByGeneratedPositionsInflated(e,t)<=0}function i(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var s=e("./util");i.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},i.prototype.add=function(e){n(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},i.prototype.toArray=function(){return this._sorted||(this._array.sort(s.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},r.MappingList=i},{"./util":64}],60:[function(e,t,r){function n(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function i(e,t){return Math.round(e+Math.random()*(t-e))}function s(e,t,r,a){if(r=0){var s=this._originalMappings[i];if(void 0===e.column)for(var a=s.originalLine;s&&s.originalLine===a;)n.push({line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:o.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i];else for(var l=s.originalColumn;s&&s.originalLine===t&&s.originalColumn==l;)n.push({line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:o.getArg(s,"lastGeneratedColumn",null)}),s=this._originalMappings[++i]}return n},r.SourceMapConsumer=n,i.prototype=Object.create(n.prototype),i.prototype.consumer=n,i.fromSourceMap=function(e){var t=Object.create(i.prototype),r=t._names=l.fromArray(e._names.toArray(),!0),n=t._sources=l.fromArray(e._sources.toArray(),!0);t.sourceRoot=e._sourceRoot,t.sourcesContent=e._generateSourcesContent(t._sources.toArray(),t.sourceRoot),t.file=e._file;for(var a=e._mappings.toArray().slice(),u=t.__generatedMappings=[],c=t.__originalMappings=[],h=0,f=a.length;h1&&(r.source=m+i[1],m+=i[1],r.originalLine=f+i[2],f=r.originalLine,r.originalLine+=1,r.originalColumn=d+i[3],d=r.originalColumn,i.length>4&&(r.name=y+i[4],y+=i[4])),A.push(r),"number"==typeof r.originalLine&&E.push(r)}p(A,o.compareByGeneratedPositionsDeflated),this.__generatedMappings=A,p(E,o.compareByOriginalPositions),this.__originalMappings=E},i.prototype._findMapping=function(e,t,r,n,i,s){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[n]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[n]);return u.search(e,t,i,s)},i.prototype.computeColumnSpans=function(){for(var e=0;e=0){var i=this._generatedMappings[r];if(i.generatedLine===t.generatedLine){var s=o.getArg(i,"source",null);null!==s&&(s=this._sources.at(s),null!=this.sourceRoot&&(s=o.join(this.sourceRoot,s)));var a=o.getArg(i,"name",null);return null!==a&&(a=this._names.at(a)),{source:s,line:o.getArg(i,"originalLine",null),column:o.getArg(i,"originalColumn",null),name:a}}}return{source:null,line:null,column:null,name:null}},i.prototype.hasContentsOfAllSources=function(){return!!this.sourcesContent&&(this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}))},i.prototype.sourceContentFor=function(e,t){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=o.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var r;if(null!=this.sourceRoot&&(r=o.urlParse(this.sourceRoot))){var n=e.replace(/^file:\/\//,"");if("file"==r.scheme&&this._sources.has(n))return this.sourcesContent[this._sources.indexOf(n)];if((!r.path||"/"==r.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(t)return null;throw new Error('"'+e+'" is not in the SourceMap.')},i.prototype.generatedPositionFor=function(e){var t=o.getArg(e,"source");if(null!=this.sourceRoot&&(t=o.relative(this.sourceRoot,t)),!this._sources.has(t))return{line:null,column:null,lastColumn:null};t=this._sources.indexOf(t);var r={source:t,originalLine:o.getArg(e,"line"),originalColumn:o.getArg(e,"column")},i=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",o.compareByOriginalPositions,o.getArg(e,"bias",n.GREATEST_LOWER_BOUND));if(i>=0){var s=this._originalMappings[i];if(s.source===r.source)return{line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:o.getArg(s,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},r.BasicSourceMapConsumer=i,a.prototype=Object.create(n.prototype),a.prototype.constructor=n,a.prototype._version=3,Object.defineProperty(a.prototype,"sources",{get:function(){for(var e=[],t=0;t0&&e.column>=0)||t||r||n)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:t,name:n}))},n.prototype._serializeMappings=function(){for(var e,t,r,n,a=0,o=1,u=0,l=0,c=0,p=0,h="",f=this._mappings.toArray(),d=0,m=f.length;d0){if(!s.compareByGeneratedPositionsInflated(t,f[d-1]))continue;e+=","}e+=i.encode(t.generatedColumn-a),a=t.generatedColumn,null!=t.source&&(n=this._sources.indexOf(t.source),e+=i.encode(n-p),p=n,e+=i.encode(t.originalLine-1-l),l=t.originalLine-1,e+=i.encode(t.originalColumn-u),u=t.originalColumn,null!=t.name&&(r=this._names.indexOf(t.name),e+=i.encode(r-c),c=r)),h+=e}return h},n.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=s.relative(t,e));var r=s.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},n.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},n.prototype.toString=function(){return JSON.stringify(this.toJSON())},r.SourceMapGenerator=n},{"./array-set":55,"./base64-vlq":56,"./mapping-list":59,"./util":64}],63:[function(e,t,r){function n(e,t,r,n,i){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==t?null:t,this.source=null==r?null:r,this.name=null==i?null:i,this[a]=!0,null!=n&&this.add(n)}var i=e("./source-map-generator").SourceMapGenerator,s=e("./util"),a="$$$isSourceNode$$$";n.fromStringWithSourceMap=function(e,t,r){function i(e,t){if(null===e||void 0===e.source)a.add(t);else{var i=r?s.join(r,e.source):e.source;a.add(new n(e.originalLine,e.originalColumn,i,t,e.name))}}var a=new n,o=e.split(/(\r?\n)/),u=function(){return o.shift()+(o.shift()||"")},l=1,c=0,p=null;return t.eachMapping(function(e){if(null!==p){if(!(l0&&(p&&i(p,u()),a.add(o.join(""))),t.sources.forEach(function(e){var n=t.sourceContentFor(e);null!=n&&(null!=r&&(e=s.join(r,e)),a.setSourceContent(e,n))}),a},n.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[a]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},n.prototype.prepend=function(e){if(Array.isArray(e))for(var t=e.length-1;t>=0;t--)this.prepend(e[t]);else{if(!e[a]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},n.prototype.walk=function(e){for(var t,r=0,n=this.children.length;r0){for(t=[],r=0;r=0;c--)a=u[c],"."===a?u.splice(c,1):".."===a?l++:l>0&&(""===a?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return t=u.join("/"),""===t&&(t=o?"/":"."),n?(n.path=t,s(n)):t}function o(e,t){""===e&&(e="."),""===t&&(t=".");var r=i(t),n=i(e);if(n&&(e=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),s(r);if(r||t.match(b))return t;if(n&&!n.host&&!n.path)return n.host=t,s(n);var o="/"===t.charAt(0)?t:a(e.replace(/\/+$/,"")+"/"+t);return n?(n.path=o,s(n)):o}function u(e,t){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==t.indexOf(e+"/");){var n=e.lastIndexOf("/");if(n<0)return t;if(e=e.slice(0,n),e.match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)}function l(e){return e}function c(e){return h(e)?"$"+e:e}function p(e){return h(e)?e.slice(1):e}function h(e){if(!e)return!1;var t=e.length;if(t<9)return!1;if(95!==e.charCodeAt(t-1)||95!==e.charCodeAt(t-2)||111!==e.charCodeAt(t-3)||116!==e.charCodeAt(t-4)||111!==e.charCodeAt(t-5)||114!==e.charCodeAt(t-6)||112!==e.charCodeAt(t-7)||95!==e.charCodeAt(t-8)||95!==e.charCodeAt(t-9))return!1;for(var r=t-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function f(e,t,r){var n=e.source-t.source;return 0!==n?n:0!==(n=e.originalLine-t.originalLine)?n:0!==(n=e.originalColumn-t.originalColumn)||r?n:0!==(n=e.generatedColumn-t.generatedColumn)?n:(n=e.generatedLine-t.generatedLine,0!==n?n:e.name-t.name)}function d(e,t,r){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!==(n=e.generatedColumn-t.generatedColumn)||r?n:0!==(n=e.source-t.source)?n:0!==(n=e.originalLine-t.originalLine)?n:(n=e.originalColumn-t.originalColumn,0!==n?n:e.name-t.name)}function m(e,t){return e===t?0:e>t?1:-1}function y(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!==(r=e.generatedColumn-t.generatedColumn)?r:0!==(r=m(e.source,t.source))?r:0!==(r=e.originalLine-t.originalLine)?r:(r=e.originalColumn-t.originalColumn,0!==r?r:m(e.name,t.name))}r.getArg=n;var g=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,b=/^data:.+\,.+$/;r.urlParse=i,r.urlGenerate=s,r.normalize=a,r.join=o,r.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(g)},r.relative=u;var v=function(){return!("__proto__"in Object.create(null))}();r.toSetString=v?l:c,r.fromSetString=v?l:p,r.compareByOriginalPositions=f,r.compareByGeneratedPositionsDeflated=d,r.compareByGeneratedPositionsInflated=y},{}],65:[function(e,t,r){r.SourceMapGenerator=e("./lib/source-map-generator").SourceMapGenerator,r.SourceMapConsumer=e("./lib/source-map-consumer").SourceMapConsumer,r.SourceNode=e("./lib/source-node").SourceNode},{"./lib/source-map-consumer":61,"./lib/source-map-generator":62,"./lib/source-node":63}],66:[function(e,t,r){t.exports={_args:[[{raw:"babel-core@^6.18.2",scope:null,escapedName:"babel-core",name:"babel-core",rawSpec:"^6.18.2",spec:">=6.18.2 <7.0.0",type:"range"},"/Users/evgenypoberezkin/JSON/ajv-v4/node_modules/regenerator"]],_from:"babel-core@>=6.18.2 <7.0.0",_id:"babel-core@6.24.0",_inCache:!0,_location:"/babel-core",_nodeVersion:"6.9.0",_npmOperationalInternal:{host:"packages-18-east.internal.npmjs.com",tmp:"tmp/babel-core-6.24.0.tgz_1489371490272_0.8722315817140043"},_npmUser:{name:"hzoo",email:"hi@henryzoo.com"},_npmVersion:"3.10.10",_phantomChildren:{},_requested:{raw:"babel-core@^6.18.2",scope:null,escapedName:"babel-core",name:"babel-core",rawSpec:"^6.18.2",spec:">=6.18.2 <7.0.0",type:"range"},_requiredBy:["/babel-register","/regenerator"],_resolved:"https://registry.npmjs.org/babel-core/-/babel-core-6.24.0.tgz",_shasum:"8f36a0a77f5c155aed6f920b844d23ba56742a02",_shrinkwrap:null,_spec:"babel-core@^6.18.2",_where:"/Users/evgenypoberezkin/JSON/ajv-v4/node_modules/regenerator",author:{name:"Sebastian McKenzie",email:"sebmck@gmail.com"},dependencies:{"babel-code-frame":"^6.22.0","babel-generator":"^6.24.0","babel-helpers":"^6.23.0","babel-messages":"^6.23.0","babel-register":"^6.24.0","babel-runtime":"^6.22.0","babel-template":"^6.23.0","babel-traverse":"^6.23.1","babel-types":"^6.23.0",babylon:"^6.11.0","convert-source-map":"^1.1.0",debug:"^2.1.1",json5:"^0.5.0",lodash:"^4.2.0",minimatch:"^3.0.2","path-is-absolute":"^1.0.0",private:"^0.1.6",slash:"^1.0.0","source-map":"^0.5.0"},description:"Babel compiler core.",devDependencies:{"babel-helper-fixtures":"^6.22.0","babel-helper-transform-fixture-test-runner":"^6.24.0","babel-polyfill":"^6.23.0"},directories:{},dist:{shasum:"8f36a0a77f5c155aed6f920b844d23ba56742a02",tarball:"https://registry.npmjs.org/babel-core/-/babel-core-6.24.0.tgz"},homepage:"https://babeljs.io/",keywords:["6to5","babel","classes","const","es6","harmony","let","modules","transpile","transpiler","var","babel-core","compiler"],license:"MIT",maintainers:[{name:"amasad",email:"amjad.masad@gmail.com"},{name:"hzoo",email:"hi@henryzoo.com"},{name:"jmm",email:"npm-public@jessemccarthy.net"},{name:"loganfsmyth",email:"loganfsmyth@gmail.com"},{name:"sebmck",email:"sebmck@gmail.com"},{name:"thejameskyle",email:"me@thejameskyle.com"}],name:"babel-core",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"https://github.com/babel/babel/tree/master/packages/babel-core"},scripts:{bench:"make bench",test:"make test"},version:"6.24.0"}},{}],67:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/helpers/classCallCheck"),s=n(i),a=e("trim-right"),o=n(a),u=/^[ \t]+$/,l=function(){function e(t){(0,s.default)(this,e),this._map=null,this._buf=[],this._last="",this._queue=[],this._position={line:1,column:0},this._sourcePosition={identifierName:null,line:null,column:null,filename:null},this._map=t}return e.prototype.get=function(){this._flush();var e=this._map,t={code:(0,o.default)(this._buf.join("")),map:null,rawMappings:e&&e.getRawMappings()};return e&&Object.defineProperty(t,"map",{configurable:!0,enumerable:!0,get:function(){return this.map=e.get()},set:function(e){Object.defineProperty(this,"map",{value:e,writable:!0})}}),t},e.prototype.append=function(e){this._flush();var t=this._sourcePosition,r=t.line,n=t.column,i=t.filename,s=t.identifierName;this._append(e,r,n,s,i)},e.prototype.queue=function(e){if("\n"===e)for(;this._queue.length>0&&u.test(this._queue[0][0]);)this._queue.shift();var t=this._sourcePosition,r=t.line,n=t.column,i=t.filename,s=t.identifierName;this._queue.unshift([e,r,n,s,i])},e.prototype._flush=function(){for(var e=void 0;e=this._queue.pop();)this._append.apply(this,e)},e.prototype._append=function(e,t,r,n,i){this._map&&"\n"!==e[0]&&this._map.mark(this._position.line,this._position.column,t,r,n,i),this._buf.push(e),this._last=e[e.length-1];for(var s=0;s0&&"\n"===this._queue[0][0]&&this._queue.shift()},e.prototype.removeLastSemicolon=function(){this._queue.length>0&&";"===this._queue[0][0]&&this._queue.shift()},e.prototype.endsWith=function(e){if(1===e.length){var t=void 0;if(this._queue.length>0){var r=this._queue[0][0];t=r[r.length-1]}else t=this._last;return t===e}var n=this._last+this._queue.reduce(function(e,t){return t[0]+e},"");return e.length<=n.length&&n.slice(-e.length)===e},e.prototype.hasContent=function(){return this._queue.length>0||!!this._last},e.prototype.source=function(e,t){if(!e||t){var r=t?t[e]:null;this._sourcePosition.identifierName=t&&t.identifierName||null,this._sourcePosition.line=r?r.line:null,this._sourcePosition.column=r?r.column:null,this._sourcePosition.filename=t&&t.filename||null}},e.prototype.withSource=function(e,t,r){if(!this._map)return r();var n=this._sourcePosition.line,i=this._sourcePosition.column,s=this._sourcePosition.filename,a=this._sourcePosition.identifierName;this.source(e,t),r(),this._sourcePosition.line=n,this._sourcePosition.column=i,this._sourcePosition.filename=s,this._sourcePosition.identifierName=a},e.prototype.getCurrentColumn=function(){var e=this._queue.reduce(function(e,t){return t[0]+e},""),t=e.lastIndexOf("\n");return-1===t?this._position.column+e.length:e.length-1-t},e.prototype.getCurrentLine=function(){for(var e=this._queue.reduce(function(e,t){return t[0]+e},""),t=0,r=0;r")),this.space(),this.print(e.returnType,e)}function g(e){this.print(e.name,e),e.optional&&this.token("?"),this.token(":"),this.space(),this.print(e.typeAnnotation,e)}function b(e){this.print(e.id,e),this.print(e.typeParameters,e)}function v(e){this.print(e.id,e),this.print(e.typeParameters,e),e.extends.length&&(this.space(),this.word("extends"),this.space(),this.printList(e.extends,e)),e.mixins&&e.mixins.length&&(this.space(),this.word("mixins"),this.space(),this.printList(e.mixins,e)),this.space(),this.print(e.body,e)}function x(e){"plus"===e.variance?this.token("+"):"minus"===e.variance&&this.token("-")}function E(e){this.word("interface"),this.space(),this._interfaceish(e)}function A(){this.space(),this.token("&"),this.space()}function D(e){this.printJoin(e.types,e,{separator:A})}function C(){this.word("mixed")}function S(){this.word("empty")}function _(e){this.token("?"),this.print(e.typeAnnotation,e)}function w(){this.word("number")}function k(){this.word("string")}function F(){this.word("this")}function T(e){this.token("["),this.printList(e.types,e),this.token("]")}function P(e){this.word("typeof"),this.space(),this.print(e.argument,e)}function B(e){this.word("type"),this.space(),this.print(e.id,e),this.print(e.typeParameters,e),this.space(),this.token("="),this.space(),this.print(e.right,e),this.semicolon()}function O(e){this.token(":"),this.space(),e.optional&&this.token("?"),this.print(e.typeAnnotation,e)}function j(e){this._variance(e),this.word(e.name),e.bound&&this.print(e.bound,e),e.default&&(this.space(),this.token("="),this.space(),this.print(e.default,e))}function N(e){this.token("<"),this.printList(e.params,e,{}),this.token(">")}function I(e){var t=this;e.exact?this.token("{|"):this.token("{");var r=e.properties.concat(e.callProperties,e.indexers);r.length&&(this.space(),this.printJoin(r,e,{addNewlines:function(e){if(e&&!r[0])return 1},indent:!0,statement:!0,iterator:function(){1!==r.length&&(t.format.flowCommaSeparator?t.token(","):t.semicolon(),t.space())}}),this.space()),e.exact?this.token("|}"):this.token("}")}function L(e){e.static&&(this.word("static"),this.space()),this.print(e.value,e)}function M(e){e.static&&(this.word("static"),this.space()),this._variance(e),this.token("["),this.print(e.id,e),this.token(":"),this.space(),this.print(e.key,e),this.token("]"),this.token(":"),this.space(),this.print(e.value,e)}function R(e){e.static&&(this.word("static"),this.space()),this._variance(e),this.print(e.key,e),e.optional&&this.token("?"),this.token(":"),this.space(),this.print(e.value,e)}function U(e){this.print(e.qualification,e),this.token("."),this.print(e.id,e)}function V(){this.space(),this.token("|"),this.space()}function q(e){this.printJoin(e.types,e,{separator:V})}function G(e){this.token("("),this.print(e.expression,e),this.print(e.typeAnnotation,e),this.token(")")}function X(){this.word("void")}r.__esModule=!0,r.AnyTypeAnnotation=n,r.ArrayTypeAnnotation=i,r.BooleanTypeAnnotation=s,r.BooleanLiteralTypeAnnotation=a,r.NullLiteralTypeAnnotation=o,r.DeclareClass=u,r.DeclareFunction=l,r.DeclareInterface=c,r.DeclareModule=p,r.DeclareModuleExports=h,r.DeclareTypeAlias=f,r.DeclareVariable=d,r.ExistentialTypeParam=m,r.FunctionTypeAnnotation=y,r.FunctionTypeParam=g,r.InterfaceExtends=b,r._interfaceish=v,r._variance=x,r.InterfaceDeclaration=E,r.IntersectionTypeAnnotation=D,r.MixedTypeAnnotation=C,r.EmptyTypeAnnotation=S,r.NullableTypeAnnotation=_;var J=e("./types");Object.defineProperty(r,"NumericLiteralTypeAnnotation",{enumerable:!0,get:function(){return J.NumericLiteral}}),Object.defineProperty(r,"StringLiteralTypeAnnotation",{enumerable:!0,get:function(){return J.StringLiteral}}),r.NumberTypeAnnotation=w,r.StringTypeAnnotation=k,r.ThisTypeAnnotation=F,r.TupleTypeAnnotation=T,r.TypeofTypeAnnotation=P,r.TypeAlias=B,r.TypeAnnotation=O,r.TypeParameter=j,r.TypeParameterInstantiation=N,r.ObjectTypeAnnotation=I,r.ObjectTypeCallProperty=L,r.ObjectTypeIndexer=M,r.ObjectTypeProperty=R,r.QualifiedTypeIdentifier=U,r.UnionTypeAnnotation=q,r.TypeCastExpression=G,r.VoidTypeAnnotation=X,r.ClassImplements=b,r.GenericTypeAnnotation=b,r.TypeParameterDeclaration=N},{"./types":77}],72:[function(e,t,r){"use strict";function n(e){this.print(e.name,e),e.value&&(this.token("="),this.print(e.value,e))}function i(e){this.word(e.name)}function s(e){this.print(e.namespace,e),this.token(":"),this.print(e.name,e)}function a(e){this.print(e.object,e),this.token("."),this.print(e.property,e)}function o(e){this.token("{"),this.token("..."),this.print(e.argument,e),this.token("}")}function u(e){this.token("{"),this.print(e.expression,e),this.token("}")}function l(e){this.token("{"),this.token("..."),this.print(e.expression,e),this.token("}")}function c(e){this.token(e.value)}function p(e){var t=e.openingElement;if(this.print(t,e),!t.selfClosing){this.indent();for(var r=e.children,n=Array.isArray(r),i=0,r=n?r:(0,g.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;this.print(a,e)}this.dedent(),this.print(e.closingElement,e)}}function h(){this.space()}function f(e){this.token("<"),this.print(e.name,e),e.attributes.length>0&&(this.space(),this.printJoin(e.attributes,e,{separator:h})),e.selfClosing?(this.space(),this.token("/>")):this.token(">")}function d(e){this.token("")}function m(){}r.__esModule=!0;var y=e("babel-runtime/core-js/get-iterator"),g=function(e){return e&&e.__esModule?e:{default:e}}(y);r.JSXAttribute=n,r.JSXIdentifier=i,r.JSXNamespacedName=s,r.JSXMemberExpression=a,r.JSXSpreadAttribute=o,r.JSXExpressionContainer=u,r.JSXSpreadChild=l,r.JSXText=c,r.JSXElement=p,r.JSXOpeningElement=f,r.JSXClosingElement=d,r.JSXEmptyExpression=m},{"babel-runtime/core-js/get-iterator":113}],73:[function(e,t,r){"use strict";function n(e){var t=this;this.print(e.typeParameters,e),this.token("("),this.printList(e.params,e,{iterator:function(e){e.optional&&t.token("?"),t.print(e.typeAnnotation,e)}}),this.token(")"),e.returnType&&this.print(e.returnType,e)}function i(e){var t=e.kind,r=e.key;"method"!==t&&"init"!==t||e.generator&&this.token("*"),"get"!==t&&"set"!==t||(this.word(t),this.space()),e.async&&(this.word("async"),this.space()),e.computed?(this.token("["),this.print(r,e),this.token("]")):this.print(r,e),this._params(e),this.space(),this.print(e.body,e)}function s(e){e.async&&(this.word("async"),this.space()),this.word("function"),e.generator&&this.token("*"),e.id?(this.space(),this.print(e.id,e)):this.space(),this._params(e),this.space(),this.print(e.body,e)}function a(e){e.async&&(this.word("async"),this.space());var t=e.params[0];1===e.params.length&&l.isIdentifier(t)&&!o(e,t)?this.print(t,e):this._params(e),this.space(),this.token("=>"),this.space(),this.print(e.body,e)}function o(e,t){return e.typeParameters||e.returnType||t.typeAnnotation||t.optional||t.trailingComments}r.__esModule=!0,r.FunctionDeclaration=void 0,r._params=n,r._method=i,r.FunctionExpression=s,r.ArrowFunctionExpression=a;var u=e("babel-types"),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(u);r.FunctionDeclaration=s},{"babel-types":169}],74:[function(e,t,r){"use strict";function n(e){"type"!==e.importKind&&"typeof"!==e.importKind||(this.word(e.importKind),this.space()),this.print(e.imported,e),e.local&&e.local.name!==e.imported.name&&(this.space(),this.word("as"),this.space(),this.print(e.local,e))}function i(e){this.print(e.local,e)}function s(e){this.print(e.exported,e)}function a(e){this.print(e.local,e),e.exported&&e.local.name!==e.exported.name&&(this.space(),this.word("as"),this.space(),this.print(e.exported,e))}function o(e){this.token("*"),this.space(),this.word("as"),this.space(),this.print(e.exported,e)}function u(e){this.word("export"),this.space(),this.token("*"),this.space(),this.word("from"),this.space(),this.print(e.source,e),this.semicolon()}function l(){this.word("export"),this.space(),p.apply(this,arguments)}function c(){this.word("export"),this.space(),this.word("default"),this.space(),p.apply(this,arguments)}function p(e){if(e.declaration){var t=e.declaration;this.print(t,e),m.isStatement(t)||this.semicolon()}else{"type"===e.exportKind&&(this.word("type"),this.space());for(var r=e.specifiers.slice(0),n=!1;;){var i=r[0];if(!m.isExportDefaultSpecifier(i)&&!m.isExportNamespaceSpecifier(i))break;n=!0,this.print(r.shift(),e),r.length&&(this.token(","),this.space())}(r.length||!r.length&&!n)&&(this.token("{"),r.length&&(this.space(),this.printList(r,e),this.space()),this.token("}")),e.source&&(this.space(),this.word("from"),this.space(),this.print(e.source,e)),this.semicolon()}}function h(e){this.word("import"),this.space(),"type"!==e.importKind&&"typeof"!==e.importKind||(this.word(e.importKind),this.space());var t=e.specifiers.slice(0);if(t&&t.length){for(;;){var r=t[0];if(!m.isImportDefaultSpecifier(r)&&!m.isImportNamespaceSpecifier(r))break;this.print(t.shift(),e),t.length&&(this.token(","),this.space())}t.length&&(this.token("{"),this.space(),this.printList(t,e),this.space(),this.token("}")),this.space(),this.word("from"),this.space()}this.print(e.source,e),this.semicolon()}function f(e){this.token("*"),this.space(),this.word("as"),this.space(),this.print(e.local,e)}r.__esModule=!0,r.ImportSpecifier=n,r.ImportDefaultSpecifier=i,r.ExportDefaultSpecifier=s,r.ExportSpecifier=a, +r.ExportNamespaceSpecifier=o,r.ExportAllDeclaration=u,r.ExportNamedDeclaration=l,r.ExportDefaultDeclaration=c,r.ImportDeclaration=h,r.ImportNamespaceSpecifier=f;var d=e("babel-types"),m=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(d)},{"babel-types":169}],75:[function(e,t,r){"use strict";function n(e){this.word("with"),this.space(),this.token("("),this.print(e.object,e),this.token(")"),this.printBlock(e)}function i(e){this.word("if"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.space();var t=e.alternate&&D.isIfStatement(s(e.consequent));t&&(this.token("{"),this.newline(),this.indent()),this.printAndIndentOnComments(e.consequent,e),t&&(this.dedent(),this.newline(),this.token("}")),e.alternate&&(this.endsWith("}")&&this.space(),this.word("else"),this.space(),this.printAndIndentOnComments(e.alternate,e))}function s(e){return D.isStatement(e.body)?s(e.body):e}function a(e){this.word("for"),this.space(),this.token("("),this.inForStatementInitCounter++,this.print(e.init,e),this.inForStatementInitCounter--,this.token(";"),e.test&&(this.space(),this.print(e.test,e)),this.token(";"),e.update&&(this.space(),this.print(e.update,e)),this.token(")"),this.printBlock(e)}function o(e){this.word("while"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.printBlock(e)}function u(e){this.word("do"),this.space(),this.print(e.body,e),this.space(),this.word("while"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.semicolon()}function l(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"label";return function(r){this.word(e);var n=r[t];if(n){this.space();var i=this.startTerminatorless();this.print(n,r),this.endTerminatorless(i)}this.semicolon()}}function c(e){this.print(e.label,e),this.token(":"),this.space(),this.print(e.body,e)}function p(e){this.word("try"),this.space(),this.print(e.block,e),this.space(),e.handlers?this.print(e.handlers[0],e):this.print(e.handler,e),e.finalizer&&(this.space(),this.word("finally"),this.space(),this.print(e.finalizer,e))}function h(e){this.word("catch"),this.space(),this.token("("),this.print(e.param,e),this.token(")"),this.space(),this.print(e.body,e)}function f(e){this.word("switch"),this.space(),this.token("("),this.print(e.discriminant,e),this.token(")"),this.space(),this.token("{"),this.printSequence(e.cases,e,{indent:!0,addNewlines:function(t,r){if(!t&&e.cases[e.cases.length-1]===r)return-1}}),this.token("}")}function d(e){e.test?(this.word("case"),this.space(),this.print(e.test,e),this.token(":")):(this.word("default"),this.token(":")),e.consequent.length&&(this.newline(),this.printSequence(e.consequent,e,{indent:!0}))}function m(){this.word("debugger"),this.semicolon()}function y(){if(this.token(","),this.newline(),this.endsWith("\n"))for(var e=0;e<4;e++)this.space(!0)}function g(){if(this.token(","),this.newline(),this.endsWith("\n"))for(var e=0;e<6;e++)this.space(!0)}function b(e,t){this.word(e.kind),this.space();var r=!1;if(!D.isFor(t))for(var n=e.declarations,i=Array.isArray(n),s=0,n=i?n:(0,E.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;o.init&&(r=!0)}var u=void 0;r&&(u="const"===e.kind?g:y),this.printList(e.declarations,e,{separator:u}),(!D.isFor(t)||t.left!==e&&t.init!==e)&&this.semicolon()}function v(e){this.print(e.id,e),this.print(e.id.typeAnnotation,e),e.init&&(this.space(),this.token("="),this.space(),this.print(e.init,e))}r.__esModule=!0,r.ThrowStatement=r.BreakStatement=r.ReturnStatement=r.ContinueStatement=r.ForAwaitStatement=r.ForOfStatement=r.ForInStatement=void 0;var x=e("babel-runtime/core-js/get-iterator"),E=function(e){return e&&e.__esModule?e:{default:e}}(x);r.WithStatement=n,r.IfStatement=i,r.ForStatement=a,r.WhileStatement=o,r.DoWhileStatement=u,r.LabeledStatement=c,r.TryStatement=p,r.CatchClause=h,r.SwitchStatement=f,r.SwitchCase=d,r.DebuggerStatement=m,r.VariableDeclaration=b,r.VariableDeclarator=v;var A=e("babel-types"),D=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(A),C=function(e){return function(t){this.word("for"),this.space(),"await"===e&&(this.word("await"),this.space()),this.token("("),this.print(t.left,t),this.space(),this.word("await"===e?"of":e),this.space(),this.print(t.right,t),this.token(")"),this.printBlock(t)}};r.ForInStatement=C("in"),r.ForOfStatement=C("of"),r.ForAwaitStatement=C("await"),r.ContinueStatement=l("continue"),r.ReturnStatement=l("return","argument"),r.BreakStatement=l("break"),r.ThrowStatement=l("throw","argument")},{"babel-runtime/core-js/get-iterator":113,"babel-types":169}],76:[function(e,t,r){"use strict";function n(e){this.print(e.tag,e),this.print(e.quasi,e)}function i(e,t){var r=t.quasis[0]===e,n=t.quasis[t.quasis.length-1]===e,i=(r?"`":"}")+e.value.raw+(n?"`":"${");this.token(i)}function s(e){for(var t=e.quasis,r=0;r0&&this.space(),this.print(i,e),n=0||e.indexOf("@preserve")>=0},"auto"===a.compact&&(a.compact=e.length>5e5,a.compact&&console.error("[BABEL] "+g.get("codeGeneratorDeopt",t.filename,"500KB"))),a.compact&&(a.indent.adjustMultilineComment=!1),a}function s(e,t){if(!e)return"double";for(var r={single:0,double:0},n=0,i=0;i=3)break}}return r.single>r.double?"single":"double"}r.__esModule=!0,r.CodeGenerator=void 0;var a=e("babel-runtime/helpers/classCallCheck"),o=n(a),u=e("babel-runtime/helpers/possibleConstructorReturn"),l=n(u),c=e("babel-runtime/helpers/inherits"),p=n(c);r.default=function(e,t,r){return new x(e,t,r).generate()};var h=e("detect-indent"),f=n(h),d=e("./source-map"),m=n(d),y=e("babel-messages"),g=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(y),b=e("./printer"),v=n(b),x=function(e){function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments[2];(0,o.default)(this,t);var a=r.tokens||[],u=i(s,n,a),c=n.sourceMaps?new m.default(n,s):null,p=(0,l.default)(this,e.call(this,u,c,a));return p.ast=r,p}return(0,p.default)(t,e),t.prototype.generate=function(){return e.prototype.generate.call(this,this.ast)},t}(v.default);r.CodeGenerator=function(){function e(t,r,n){(0,o.default)(this,e),this._generator=new x(t,r,n)}return e.prototype.generate=function(){return this._generator.generate()},e}()},{"./printer":82,"./source-map":83,"babel-messages":103,"babel-runtime/helpers/classCallCheck":127,"babel-runtime/helpers/inherits":128,"babel-runtime/helpers/possibleConstructorReturn":130,"detect-indent":299}],79:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e){function t(e,t){var n=r[e];r[e]=n?function(e,r,i){var s=n(e,r,i);return null==s?t(e,r,i):s}:t}for(var r={},n=(0,m.default)(e),i=Array.isArray(n),s=0,n=i?n:(0,f.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a,u=E.FLIPPED_ALIAS_KEYS[o];if(u)for(var l=u,c=Array.isArray(l),p=0,l=c?l:(0,f.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if(p=l.next(),p.done)break;h=p.value}var d=h;t(d,e[o])}else t(o,e[o])}return r}function a(e,t,r,n){var i=e[t.type];return i?i(t,r,n):null}function o(e){return!!E.isCallExpression(e)||!!E.isMemberExpression(e)&&(o(e.object)||!e.computed&&o(e.property))}function u(e,t,r){if(!e)return 0;E.isExpressionStatement(e)&&(e=e.expression);var n=a(D,e,t);if(!n){var i=a(C,e,t);if(i)for(var s=0;ss)return!0}return!1}function u(e,t){return"in"===e.operator&&(v.isVariableDeclarator(t)||v.isFor(t))}function l(e,t){return!(v.isForStatement(t)||v.isThrowStatement(t)||v.isReturnStatement(t)||v.isIfStatement(t)&&t.test===e||v.isWhileStatement(t)&&t.test===e||v.isForInStatement(t)&&t.right===e||v.isSwitchStatement(t)&&t.discriminant===e||v.isExpressionStatement(t)&&t.expression===e)}function c(e,t){return v.isBinary(t)||v.isUnaryLike(t)||v.isCallExpression(t)||v.isMemberExpression(t)||v.isNewExpression(t)||v.isConditionalExpression(t)&&e===t.test}function p(e,t,r){return g(r,{considerDefaultExports:!0})}function h(e,t){return v.isMemberExpression(t,{object:e})||v.isCallExpression(t,{callee:e})||v.isNewExpression(t,{callee:e})}function f(e,t,r){return g(r,{considerDefaultExports:!0})}function d(e,t){return!!(v.isExportDeclaration(t)||v.isBinaryExpression(t)||v.isLogicalExpression(t)||v.isUnaryExpression(t)||v.isTaggedTemplateExpression(t))||h(e,t)}function m(e,t){return!!(v.isUnaryLike(t)||v.isBinary(t)||v.isConditionalExpression(t,{test:e})||v.isAwaitExpression(t))||h(e,t)}function y(e){return!!v.isObjectPattern(e.left)||m.apply(void 0,arguments)}function g(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.considerArrow,n=void 0!==r&&r,i=t.considerDefaultExports,s=void 0!==i&&i,a=e.length-1,o=e[a];a--;for(var u=e[a];a>0;){if(v.isExpressionStatement(u,{expression:o})||v.isTaggedTemplateExpression(u)||s&&v.isExportDefaultDeclaration(u,{declaration:o})||n&&v.isArrowFunctionExpression(u,{body:o}))return!0;if(!(v.isCallExpression(u,{callee:o})||v.isSequenceExpression(u)&&u.expressions[0]===o||v.isMemberExpression(u,{object:o})||v.isConditional(u,{test:o})||v.isBinary(u,{left:o})||v.isAssignmentExpression(u,{left:o})))return!1;o=u,a--,u=e[a]}return!1}r.__esModule=!0,r.AwaitExpression=r.FunctionTypeAnnotation=void 0,r.NullableTypeAnnotation=n,r.UpdateExpression=i,r.ObjectExpression=s,r.DoExpression=a,r.Binary=o,r.BinaryExpression=u,r.SequenceExpression=l,r.YieldExpression=c,r.ClassExpression=p,r.UnaryLike=h,r.FunctionExpression=f,r.ArrowFunctionExpression=d,r.ConditionalExpression=m,r.AssignmentExpression=y;var b=e("babel-types"),v=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(b),x={"||":0,"&&":1,"|":2,"^":3,"&":4,"==":5,"===":5,"!=":5,"!==":5,"<":6,">":6,"<=":6,">=":6,in:6,instanceof:6,">>":7,"<<":7,">>>":7,"+":8,"-":8,"*":9,"/":9,"%":9,"**":10};r.FunctionTypeAnnotation=n,r.AwaitExpression=c},{"babel-types":169}],81:[function(e,t,r){"use strict";function n(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return l.isMemberExpression(e)?(n(e.object,t),e.computed&&n(e.property,t)):l.isBinary(e)||l.isAssignmentExpression(e)?(n(e.left,t),n(e.right,t)):l.isCallExpression(e)?(t.hasCall=!0,n(e.callee,t)):l.isFunction(e)?t.hasFunction=!0:l.isIdentifier(e)&&(t.hasHelper=t.hasHelper||i(e.callee)),t}function i(e){return l.isMemberExpression(e)?i(e.object)||i(e.property):l.isIdentifier(e)?"require"===e.name||"_"===e.name[0]:l.isCallExpression(e)?i(e.callee):!(!l.isBinary(e)&&!l.isAssignmentExpression(e))&&(l.isIdentifier(e.left)&&i(e.left)||i(e.right))}function s(e){return l.isLiteral(e)||l.isObjectExpression(e)||l.isArrayExpression(e)||l.isIdentifier(e)||l.isMemberExpression(e)}var a=e("lodash/map"),o=function(e){return e&&e.__esModule?e:{default:e}}(a),u=e("babel-types"),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(u);r.nodes={AssignmentExpression:function(e){var t=n(e.right);if(t.hasCall&&t.hasHelper||t.hasFunction)return{before:t.hasFunction,after:!0}},SwitchCase:function(e,t){return{before:e.consequent.length||t.cases[0]===e}},LogicalExpression:function(e){if(l.isFunction(e.left)||l.isFunction(e.right))return{after:!0}},Literal:function(e){if("use strict"===e.value)return{after:!0}},CallExpression:function(e){if(l.isFunction(e.callee)||i(e))return{before:!0,after:!0}},VariableDeclaration:function(e){for(var t=0;t0?new F.default(n):null}return e.prototype.generate=function(e){return this.print(e),this._maybeAddAuxComment(),this._buf.get()},e.prototype.indent=function(){this.format.compact||this.format.concise||this._indent++},e.prototype.dedent=function(){this.format.compact||this.format.concise||this._indent--},e.prototype.semicolon=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._maybeAddAuxComment(),this._append(";",!e)},e.prototype.rightBrace=function(){this.format.minified&&this._buf.removeLastSemicolon(),this.token("}")},e.prototype.space=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.format.compact||(this._buf.hasContent()&&!this.endsWith(" ")&&!this.endsWith("\n")||e)&&this._space()},e.prototype.word=function(e){this._endsWithWord&&this._space(),this._maybeAddAuxComment(),this._append(e),this._endsWithWord=!0},e.prototype.number=function(e){this.word(e),this._endsWithInteger=(0,E.default)(+e)&&!j.test(e)&&!B.test(e)&&!O.test(e)&&"."!==e[e.length-1]},e.prototype.token=function(e){("--"===e&&this.endsWith("!")||"+"===e[0]&&this.endsWith("+")||"-"===e[0]&&this.endsWith("-")||"."===e[0]&&this._endsWithInteger)&&this._space(),this._maybeAddAuxComment(),this._append(e)},e.prototype.newline=function(e){if(!this.format.retainLines&&!this.format.compact){if(this.format.concise)return void this.space();if(!(this.endsWith("\n\n")||("number"!=typeof e&&(e=1),e=Math.min(2,e),(this.endsWith("{\n")||this.endsWith(":\n"))&&e--,e<=0)))for(var t=0;t1&&void 0!==arguments[1]&&arguments[1];this._maybeAddParen(e),this._maybeIndent(e),t?this._buf.queue(e):this._buf.append(e),this._endsWithWord=!1,this._endsWithInteger=!1},e.prototype._maybeIndent=function(e){this._indent&&this.endsWith("\n")&&"\n"!==e[0]&&this._buf.queue(this._getIndent())},e.prototype._maybeAddParen=function(e){var t=this._parenPushNewlineState;if(t){this._parenPushNewlineState=null;var r=void 0;for(r=0;r2&&void 0!==arguments[2]?arguments[2]:{};if(e&&e.length){r.indent&&this.indent();for(var n={addNewlines:r.addNewlines},i=0;i1&&void 0!==arguments[1])||arguments[1];e.innerComments&&(t&&this.indent(),this._printComments(e.innerComments),t&&this.dedent())},e.prototype.printSequence=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return r.statement=!0,this.printJoin(e,t,r)},e.prototype.printList=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return null==r.separator&&(r.separator=s),this.printJoin(e,t,r)},e.prototype._printNewline=function(e,t,r,n){var i=this;if(!this.format.retainLines&&!this.format.compact){if(this.format.concise)return void this.space();var s=0;if(null!=t.start&&!t._ignoreUserWhitespace&&this._whitespace)if(e){var a=t.leadingComments,o=a&&(0,g.default)(a,function(e){return!!e.loc&&i.format.shouldPrintComment(e.value)});s=this._whitespace.getNewlinesBefore(o||t)}else{var u=t.trailingComments,l=u&&(0,v.default)(u,function(e){return!!e.loc&&i.format.shouldPrintComment(e.value)});s=this._whitespace.getNewlinesAfter(l||t)}else{e||s++,n.addNewlines&&(s+=n.addNewlines(e,t)||0);var c=w.needsWhitespaceAfter;e&&(c=w.needsWhitespaceBefore),c(t,r)&&s++,this._buf.hasContent()||(s=0)}this.newline(s)}},e.prototype._getComments=function(e,t){return t&&(e?t.leadingComments:t.trailingComments)||[]},e.prototype._printComment=function(e){var t=this;if(this.format.shouldPrintComment(e.value)&&!e.ignore&&!this._printedComments.has(e)){if(this._printedComments.add(e),null!=e.start){if(this._printedCommentStarts[e.start])return;this._printedCommentStarts[e.start]=!0}this.newline(this._whitespace?this._whitespace.getNewlinesBefore(e):0),this.endsWith("[")||this.endsWith("{")||this.space();var r="CommentLine"===e.type?"//"+e.value+"\n":"/*"+e.value+"*/";if("CommentBlock"===e.type&&this.format.indent.adjustMultilineComment){var n=e.loc&&e.loc.start.column;if(n){var i=new RegExp("\\n\\s{1,"+n+"}","g");r=r.replace(i,"\n")}var s=Math.max(this._getIndent().length,this._buf.getCurrentColumn());r=r.replace(/\n(?!$)/g,"\n"+(0,D.default)(" ",s))}this.withSource("start",e.loc,function(){t._append(r)}),this.newline((this._whitespace?this._whitespace.getNewlinesAfter(e):0)+("CommentLine"===e.type?-1:0))}},e.prototype._printComments=function(e){if(e&&e.length)for(var t=e,r=Array.isArray(t),n=0,t=r?t:(0,l.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;this._printComment(s)}},e}();r.default=N;for(var I=[e("./generators/template-literals"),e("./generators/expressions"),e("./generators/statements"),e("./generators/classes"),e("./generators/methods"),e("./generators/modules"),e("./generators/types"),e("./generators/flow"),e("./generators/base"),e("./generators/jsx")],L=0;L=0){for(;i&&e.start===n[i-1].start;)--i;t=n[i-1],r=n[i]}return this._getNewlinesBetween(t,r)},e.prototype.getNewlinesAfter=function(e){var t=void 0,r=void 0,n=this.tokens,i=this._findToken(function(t){return t.end-e.end},0,n.length);if(i>=0){for(;i&&e.end===n[i-1].end;)--i;t=n[i],r=n[i+1],","===r.type.label&&(r=n[i+2])}return r&&"eof"===r.type.label?1:this._getNewlinesBetween(t,r)},e.prototype._getNewlinesBetween=function(e,t){if(!t||!t.loc)return 0;for(var r=e?e.loc.end.line:1,n=t.loc.start.line,i=0,s=r;s=r)return-1;var n=t+r>>>1,i=e(this.tokens[n]);return i<0?this._findToken(e,n+1,r):i>0?this._findToken(e,t,n):0===i?n:-1},e}();r.default=s,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":127}],85:[function(e,t,r){arguments[4][55][0].apply(r,arguments)},{"./util":94,dup:55}],86:[function(e,t,r){arguments[4][56][0].apply(r,arguments)},{"./base64":87,dup:56}],87:[function(e,t,r){arguments[4][57][0].apply(r,arguments)},{dup:57}],88:[function(e,t,r){arguments[4][58][0].apply(r,arguments)},{dup:58}],89:[function(e,t,r){arguments[4][59][0].apply(r,arguments)},{"./util":94,dup:59}],90:[function(e,t,r){arguments[4][60][0].apply(r,arguments)},{dup:60}],91:[function(e,t,r){arguments[4][61][0].apply(r,arguments)},{"./array-set":85,"./base64-vlq":86,"./binary-search":88,"./quick-sort":90,"./util":94,dup:61}],92:[function(e,t,r){arguments[4][62][0].apply(r,arguments)},{"./array-set":85,"./base64-vlq":86,"./mapping-list":89,"./util":94,dup:62}],93:[function(e,t,r){arguments[4][63][0].apply(r,arguments)},{"./source-map-generator":92,"./util":94,dup:63}],94:[function(e,t,r){arguments[4][64][0].apply(r,arguments)},{dup:64}],95:[function(e,t,r){arguments[4][65][0].apply(r,arguments)},{"./lib/source-map-consumer":91,"./lib/source-map-generator":92,"./lib/source-node":93,dup:65}],96:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){return!g.isClassMethod(e)&&!g.isObjectMethod(e)||"get"!==e.kind&&"set"!==e.kind?"value":e.kind}function s(e,t,r,n,s){var a=g.toKeyAlias(t),o={};if((0,m.default)(e,a)&&(o=e[a]),e[a]=o,o._inherits=o._inherits||[],o._inherits.push(t),o._key=t.key,t.computed&&(o._computed=!0),t.decorators){var u=o.decorators=o.decorators||g.arrayExpression([]);u.elements=u.elements.concat(t.decorators.map(function(e){return e.expression}).reverse())}if(o.value||o.initializer)throw n.buildCodeFrameError(t,"Key conflict with sibling node");var l=void 0,c=void 0;(g.isObjectProperty(t)||g.isObjectMethod(t)||g.isClassMethod(t))&&(l=g.toComputedKey(t,t.key)), +g.isObjectProperty(t)||g.isClassProperty(t)?c=t.value:(g.isObjectMethod(t)||g.isClassMethod(t))&&(c=g.functionExpression(null,t.params,t.body,t.generator,t.async),c.returnType=t.returnType);var p=i(t);return r&&"value"===p||(r=p),s&&g.isStringLiteral(l)&&("value"===r||"initializer"===r)&&g.isFunctionExpression(c)&&(c=(0,f.default)({id:l,node:c,scope:s})),c&&(g.inheritsComments(c,t),o[r]=c),o}function a(e){for(var t in e)if(e[t]._computed)return!0;return!1}function o(e){for(var t=g.arrayExpression([]),r=0;r1&&void 0!==arguments[1]&&arguments[1];(0,l.default)(this,e),this.forceSuperMemoisation=t.forceSuperMemoisation,this.methodPath=t.methodPath,this.methodNode=t.methodNode,this.superRef=t.superRef,this.isStatic=t.isStatic,this.hasSuper=!1,this.inClass=r,this.isLoose=t.isLoose,this.scope=this.methodPath.scope,this.file=t.file,this.opts=t,this.bareSupers=[],this.returns=[],this.thises=[]}return e.prototype.getObjectRef=function(){return this.opts.objectRef||this.opts.getObjectRef()},e.prototype.setSuperProperty=function(e,t,r){return g.callExpression(this.file.addHelper("set"),[o(this.getObjectRef(),this.isStatic),r?e:g.stringLiteral(e.name),t,g.thisExpression()])},e.prototype.getSuperProperty=function(e,t){return g.callExpression(this.file.addHelper("get"),[o(this.getObjectRef(),this.isStatic),t?e:g.stringLiteral(e.name),g.thisExpression()])},e.prototype.replace=function(){this.methodPath.traverse(v,this)},e.prototype.getLooseSuperProperty=function(e,t){var r=this.methodNode,n=this.superRef||g.identifier("Function");return t.property===e?void 0:g.isCallExpression(t,{callee:e})?void 0:g.isMemberExpression(t)&&!r.static?g.memberExpression(n,g.identifier("prototype")):n},e.prototype.looseHandle=function(e){var t=e.node;if(e.isSuper())return this.getLooseSuperProperty(t,e.parent);if(e.isCallExpression()){var r=t.callee;if(!g.isMemberExpression(r))return;if(!g.isSuper(r.object))return;return g.appendToMemberExpression(r,g.identifier("call")),t.arguments.unshift(g.thisExpression()),!0}},e.prototype.specHandleAssignmentExpression=function(e,t,r){return"="===r.operator?this.setSuperProperty(r.left.property,r.right,r.left.computed):(e=e||t.scope.generateUidIdentifier("ref"),[g.variableDeclaration("var",[g.variableDeclarator(e,r.left)]),g.expressionStatement(g.assignmentExpression("=",r.left,g.binaryExpression(r.operator[0],e,r.right)))])},e.prototype.specHandle=function(e){var t=void 0,r=void 0,n=void 0,i=e.parent,o=e.node;if(s(o,i))throw e.buildCodeFrameError(m.get("classesIllegalBareSuper"));if(g.isCallExpression(o)){var u=o.callee;if(g.isSuper(u))return;a(u)&&(t=u.property,r=u.computed,n=o.arguments)}else if(g.isMemberExpression(o)&&g.isSuper(o.object))t=o.property,r=o.computed;else{if(g.isUpdateExpression(o)&&a(o.argument)){var l=g.binaryExpression(o.operator[0],o.argument,g.numericLiteral(1));if(o.prefix)return this.specHandleAssignmentExpression(null,e,l);var c=e.scope.generateUidIdentifier("ref");return this.specHandleAssignmentExpression(c,e,l).concat(g.expressionStatement(c))}if(g.isAssignmentExpression(o)&&a(o.left))return this.specHandleAssignmentExpression(null,e,o)}if(t){var p=this.getSuperProperty(t,r);return n?this.optimiseCall(p,n):p}},e.prototype.optimiseCall=function(e,t){var r=g.thisExpression();return r[b]=!0,(0,f.default)(e,r,t)},e}();r.default=x,t.exports=r.default},{"babel-helper-optimise-call-expression":99,"babel-messages":103,"babel-runtime/core-js/symbol":122,"babel-runtime/helpers/classCallCheck":127,"babel-types":169}],101:[function(e,t,r){"use strict";r.__esModule=!0;var n=e("babel-template"),i=function(e){return e&&e.__esModule?e:{default:e}}(n),s={};r.default=s,s.typeof=(0,i.default)('\n (typeof Symbol === "function" && typeof Symbol.iterator === "symbol")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? "symbol"\n : typeof obj;\n };\n'),s.jsx=(0,i.default)('\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === "function" && Symbol.for && Symbol.for("react.element")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we\'re going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : \'\' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n'),s.asyncIterator=(0,i.default)('\n (function (iterable) {\n if (typeof Symbol === "function") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError("Object is not async iterable");\n })\n'),s.asyncGenerator=(0,i.default)('\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume("next", arg); },\n function (arg) { resume("throw", arg); });\n } else {\n settle(result.done ? "return" : "normal", result.value);\n }\n } catch (err) {\n settle("throw", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case "return":\n front.resolve({ value: value, done: true });\n break;\n case "throw":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide "return" method if generator return is not supported\n if (typeof gen.return !== "function") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === "function" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n'),s.asyncGeneratorDelegate=(0,i.default)('\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === "function" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump("next", value);\n };\n\n if (typeof inner.throw === "function") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump("throw", value);\n };\n }\n\n if (typeof inner.return === "function") {\n iter.return = function (value) {\n return pump("return", value);\n };\n }\n\n return iter;\n })\n'),s.asyncToGenerator=(0,i.default)('\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n step("next", value);\n }, function (err) {\n step("throw", err);\n });\n }\n }\n\n return step("next");\n });\n };\n })\n'),s.classCallCheck=(0,i.default)('\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError("Cannot call a class as a function");\n }\n });\n'),s.createClass=(0,i.default)('\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if ("value" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n'),s.defineEnumerableProperties=(0,i.default)('\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if ("value" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n'),s.defaults=(0,i.default)("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n"),s.defineProperty=(0,i.default)("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n"),s.extends=(0,i.default)("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n"),s.get=(0,i.default)('\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if ("value" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n'),s.inherits=(0,i.default)('\n (function (subClass, superClass) {\n if (typeof superClass !== "function" && superClass !== null) {\n throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n'),s.instanceof=(0,i.default)('\n (function (left, right) {\n if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n'),s.interopRequireDefault=(0,i.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"),s.interopRequireWildcard=(0,i.default)("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n"),s.newArrowCheck=(0,i.default)('\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError("Cannot instantiate an arrow function");\n }\n });\n'),s.objectDestructuringEmpty=(0,i.default)('\n (function (obj) {\n if (obj == null) throw new TypeError("Cannot destructure undefined");\n });\n'),s.objectWithoutProperties=(0,i.default)("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n"),s.possibleConstructorReturn=(0,i.default)('\n (function (self, call) {\n if (!self) {\n throw new ReferenceError("this hasn\'t been initialised - super() hasn\'t been called");\n }\n return call && (typeof call === "object" || typeof call === "function") ? call : self;\n });\n'),s.selfGlobal=(0,i.default)('\n typeof global === "undefined" ? self : global\n'),s.set=(0,i.default)('\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if ("value" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n'),s.slicedToArray=(0,i.default)('\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i["return"]) _i["return"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError("Invalid attempt to destructure non-iterable instance");\n }\n };\n })();\n'),s.slicedToArrayLoose=(0,i.default)('\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError("Invalid attempt to destructure non-iterable instance");\n }\n });\n'),s.taggedTemplateLiteral=(0,i.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"),s.taggedTemplateLiteralLoose=(0,i.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"),s.temporalRef=(0,i.default)('\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + " is not defined - temporal dead zone");\n } else {\n return val;\n }\n })\n'),s.temporalUndefined=(0,i.default)("\n ({})\n"),s.toArray=(0,i.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"),s.toConsumableArray=(0,i.default)("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n"),t.exports=r.default},{"babel-template":132}],102:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=u.default[e];if(!t)throw new ReferenceError("Unknown helper "+e);return t().expression}r.__esModule=!0,r.list=void 0;var s=e("babel-runtime/core-js/object/keys"),a=n(s);r.get=i;var o=e("./helpers"),u=n(o);r.list=(0,a.default)(u.default).map(function(e){return e.replace(/^_/,"")}).filter(function(e){return"__esModule"!==e});r.default=i},{"./helpers":101,"babel-runtime/core-js/object/keys":120}],103:[function(e,t,r){"use strict";function n(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n4&&void 0!==arguments[4]&&arguments[4];if(t||(t=e.node),!v.isFor(r))for(var s=0;s0&&e.traverse(k,t),e.skip()}},g.visitor]),k=y.default.visitors.merge([{ReferencedIdentifier:function(e,t){var r=t.letReferences[e.node.name];if(r){var n=e.scope.getBindingIdentifier(e.node.name);n&&n!==r||(t.closurify=!0)}}},g.visitor]),F={enter:function(e,t){var r=e.node;e.parent;if(e.isForStatement()){if(o(r.init)){var n=t.pushDeclar(r.init);1===n.length?r.init=n[0]:r.init=v.sequenceExpression(n)}}else if(e.isFor())o(r.left)&&(t.pushDeclar(r.left),r.left=r.left.declarations[0].id);else if(o(r))e.replaceWithMultiple(t.pushDeclar(r).map(function(e){return v.expressionStatement(e)}));else if(e.isFunction())return e.skip()}},T={LabeledStatement:function(e,t){var r=e.node;t.innerLabels.push(r.label.name)}},P={enter:function(e,t){if(e.isAssignmentExpression()||e.isUpdateExpression()){var r=e.getBindingIdentifiers();for(var n in r)t.outsideReferences[n]===e.scope.getBindingIdentifier(n)&&(t.reassignments[n]=!0)}}},B={Loop:function(e,t){var r=t.ignoreLabeless;t.ignoreLabeless=!0,e.traverse(B,t),t.ignoreLabeless=r,e.skip()},Function:function(e){e.skip()},SwitchCase:function(e,t){var r=t.inSwitchCase;t.inSwitchCase=!0,e.traverse(B,t),t.inSwitchCase=r,e.skip()},"BreakStatement|ContinueStatement|ReturnStatement":function(e,t){var r=e.node,n=e.parent,i=e.scope;if(!r[this.LOOP_IGNORE]){var s=void 0,a=u(r);if(a){if(r.label){if(t.innerLabels.indexOf(r.label.name)>=0)return;a=a+"|"+r.label.name}else{if(t.ignoreLabeless)return;if(t.inSwitchCase)return;if(v.isBreakStatement(r)&&v.isSwitchCase(n))return}t.hasBreakContinue=!0,t.map[a]=r,s=v.stringLiteral(a)}e.isReturnStatement()&&(t.hasReturn=!0,s=v.objectExpression([v.objectProperty(v.identifier("v"),r.argument||i.buildUndefinedNode())])),s&&(s=v.returnStatement(s),s[this.LOOP_IGNORE]=!0,e.skip(),e.replaceWith(v.inherits(s,r)))}}},O=function(){function e(t,r,n,i,s){(0,d.default)(this,e),this.parent=n,this.scope=i,this.file=s,this.blockPath=r,this.block=r.node,this.outsideLetReferences=(0,h.default)(null),this.hasLetReferences=!1,this.letReferences=(0,h.default)(null),this.body=[],t&&(this.loopParent=t.parent,this.loopLabel=v.isLabeledStatement(this.loopParent)&&this.loopParent.label,this.loopPath=t,this.loop=t.node)}return e.prototype.run=function(){var e=this.block;if(!e._letDone){e._letDone=!0;var t=this.getLetReferences();if(v.isFunction(this.parent)||v.isProgram(this.block))return void this.updateScopeInfo();if(this.hasLetReferences)return t?this.wrapClosure():this.remap(),this.updateScopeInfo(t),this.loopLabel&&!v.isLabeledStatement(this.loopParent)?v.labeledStatement(this.loopLabel,this.loop):void 0}},e.prototype.updateScopeInfo=function(e){var t=this.scope,r=t.getFunctionParent(),n=this.letReferences;for(var i in n){var s=n[i],a=t.getBinding(s.name);a&&("let"!==a.kind&&"const"!==a.kind||(a.kind="var",e?t.removeBinding(s.name):t.moveBindingTo(s.name,r)))}},e.prototype.remap=function(){var e=this.letReferences,t=this.scope;for(var r in e){var n=e[r];(t.parentHasBinding(r)||t.hasGlobal(r))&&(t.hasOwnBinding(r)&&t.rename(n.name),this.blockPath.scope.hasOwnBinding(r)&&this.blockPath.scope.rename(n.name))}},e.prototype.wrapClosure=function(){if(this.file.opts.throwIfClosureRequired)throw this.blockPath.buildCodeFrameError("Compiling let/const in this block would add a closure (throwIfClosureRequired).");var e=this.block,t=this.outsideLetReferences;if(this.loop)for(var r in t){var n=t[r];(this.scope.hasGlobal(n.name)||this.scope.parentHasBinding(n.name))&&(delete t[n.name],delete this.letReferences[n.name],this.scope.rename(n.name),this.letReferences[n.name]=n,t[n.name]=n)}this.has=this.checkLoop(),this.hoistVarDeclarations();var i=(0,E.default)(t),s=(0,E.default)(t),a=this.blockPath.isSwitchStatement(),o=v.functionExpression(null,i,v.blockStatement(a?[e]:e.body));o.shadow=!0,this.addContinuations(o);var u=o;this.loop&&(u=this.scope.generateUidIdentifier("loop"),this.loopPath.insertBefore(v.variableDeclaration("var",[v.variableDeclarator(u,o)])));var l=v.callExpression(u,s),c=this.scope.generateUidIdentifier("ret");y.default.hasType(o.body,this.scope,"YieldExpression",v.FUNCTION_TYPES)&&(o.generator=!0,l=v.yieldExpression(l,!0)),y.default.hasType(o.body,this.scope,"AwaitExpression",v.FUNCTION_TYPES)&&(o.async=!0,l=v.awaitExpression(l)),this.buildClosure(c,l),a?this.blockPath.replaceWithMultiple(this.body):e.body=this.body},e.prototype.buildClosure=function(e,t){var r=this.has;r.hasReturn||r.hasBreakContinue?this.buildHas(e,t):this.body.push(v.expressionStatement(t))},e.prototype.addContinuations=function(e){var t={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(e,P,t);for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"value",n=arguments[3],i=void 0;e.static?(this.hasStaticDescriptors=!0,i=this.staticMutatorMap):(this.hasInstanceDescriptors=!0,i=this.instanceMutatorMap);var s=m.push(i,e,r,this.file,n);return t&&(s.enumerable=v.booleanLiteral(!0)),s},e.prototype.constructorMeMaybe=function(){for(var e=!1,t=this.path.get("body.body"),r=t,n=Array.isArray(r),i=0,r=n?r:(0,a.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}if(e=s.equals("kind","constructor"))break}if(!e){var o=void 0,u=void 0;if(this.isDerived){var l=x().expression;o=l.params,u=l.body}else o=[],u=v.blockStatement([]);this.path.get("body").unshiftContainer("body",v.classMethod("constructor",v.identifier("constructor"),o,u))}},e.prototype.buildBody=function(){if(this.constructorMeMaybe(),this.pushBody(),this.verifyConstructor(),this.userConstructor){var e=this.constructorBody;e.body=e.body.concat(this.userConstructor.body.body),v.inherits(this.constructor,this.userConstructor),v.inherits(e,this.userConstructor.body)}this.pushDescriptors()},e.prototype.pushBody=function(){for(var e=this.path.get("body.body"),t=e,r=Array.isArray(t),n=0,t=r?t:(0,a.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i,o=s.node;if(s.isClassProperty())throw s.buildCodeFrameError("Missing class properties transform.");if(o.decorators)throw s.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");if(v.isClassMethod(o)){var u="constructor"===o.kind;if(u&&(s.traverse(A,this),!this.hasBareSuper&&this.isDerived))throw s.buildCodeFrameError("missing super() call in constructor");var l=new p.default({forceSuperMemoisation:u,methodPath:s,methodNode:o,objectRef:this.classRef,superRef:this.superName,isStatic:o.static,isLoose:this.isLoose,scope:this.scope,file:this.file},!0);l.replace(),u?this.pushConstructor(l,o,s):this.pushMethod(o,s)}}},e.prototype.clearDescriptors=function(){this.hasInstanceDescriptors=!1,this.hasStaticDescriptors=!1,this.instanceMutatorMap={},this.staticMutatorMap={}},e.prototype.pushDescriptors=function(){this.pushInherits();var e=this.body,t=void 0,r=void 0;if(this.hasInstanceDescriptors&&(t=m.toClassObject(this.instanceMutatorMap)),this.hasStaticDescriptors&&(r=m.toClassObject(this.staticMutatorMap)),t||r){t&&(t=m.toComputedObjectFromClass(t)),r&&(r=m.toComputedObjectFromClass(r));var n=v.nullLiteral(),i=[this.classRef,n,n,n,n];t&&(i[1]=t),r&&(i[2]=r),this.instanceInitializersId&&(i[3]=this.instanceInitializersId,e.unshift(this.buildObjectAssignment(this.instanceInitializersId))),this.staticInitializersId&&(i[4]=this.staticInitializersId,e.unshift(this.buildObjectAssignment(this.staticInitializersId)));for(var s=0,a=0;a=o.length)break;c=o[l++]}else{if(l=o.next(),l.done)break;c=l.value}var p=c;this.wrapSuperCall(p,i,s,r),n&&p.find(function(e){return e===t||(e.isLoop()||e.isConditional()?(n=!1,!0):void 0)})}for(var h=this.superThises,f=Array.isArray(h),d=0,h=f?h:(0,a.default)(h);;){var m;if(f){if(d>=h.length)break;m=h[d++]}else{if(d=h.next(),d.done)break;m=d.value}m.replaceWith(s)}var y=function(t){return v.callExpression(e.file.addHelper("possibleConstructorReturn"),[s].concat(t||[]))},g=r.get("body");g.length&&!g.pop().isReturnStatement()&&r.pushContainer("body",v.returnStatement(n?s:y()));for(var b=this.superReturns,x=Array.isArray(b),E=0,b=x?b:(0,a.default)(b);;){var A;if(x){if(E>=b.length)break;A=b[E++]}else{if(E=b.next(),E.done)break;A=E.value}var C=A;if(C.node.argument){var S=C.scope.generateDeclaredUidIdentifier("ret");C.get("argument").replaceWithMultiple([v.assignmentExpression("=",S,C.node.argument),y(S)])}else C.get("argument").replaceWith(y())}}},e.prototype.pushMethod=function(e,t){var r=t?t.scope:this.scope;"method"===e.kind&&this._processMethod(e,r)||this.pushToMap(e,!1,null,r)},e.prototype._processMethod=function(){return!1},e.prototype.pushConstructor=function(e,t,r){this.bareSupers=e.bareSupers,this.superReturns=e.returns,r.scope.hasOwnBinding(this.classRef.name)&&r.scope.rename(this.classRef.name);var n=this.constructor;this.userConstructorPath=r,this.userConstructor=t,this.hasConstructor=!0,v.inheritsComments(n,t),n._ignoreUserWhitespace=!0,n.params=t.params,v.inherits(n.body,t.body),n.body.directives=t.body.directives,this._pushConstructor()},e.prototype._pushConstructor=function(){this.pushedConstructor||(this.pushedConstructor=!0,(this.hasInstanceDescriptors||this.hasStaticDescriptors)&&this.pushDescriptors(),this.body.push(this.constructor),this.pushInherits())},e.prototype.pushInherits=function(){this.isDerived&&!this.pushedInherits&&(this.pushedInherits=!0,this.body.unshift(v.expressionStatement(v.callExpression(this.file.addHelper("inherits"),[this.classRef,this.superName]))))},e}();r.default=C,t.exports=r.default},{"babel-helper-define-map":96,"babel-helper-optimise-call-expression":99,"babel-helper-replace-supers":100,"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/classCallCheck":127,"babel-template":132,"babel-traverse":136,"babel-types":169}],112:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e){function t(e){var t=e.node,r=e.scope,n=[],i=t.right;if(!a.isIdentifier(i)||!r.hasBinding(i.name)){var s=r.generateUidIdentifier("arr");n.push(a.variableDeclaration("var",[a.variableDeclarator(s,i)])),i=s}var u=r.generateUidIdentifier("i"),l=o({BODY:t.body,KEY:u,ARR:i});a.inherits(l,t),a.ensureBlock(l);var c=a.memberExpression(i,u,!0),p=t.left;return a.isVariableDeclaration(p)?(p.declarations[0].init=c,l.body.body.unshift(p)):l.body.body.unshift(a.expressionStatement(a.assignmentExpression("=",p,c))),e.parentPath.isLabeledStatement()&&(l=a.labeledStatement(e.parentPath.node.label,l)),n.push(l),n}function r(e,t){var r=e.node,n=e.scope,s=e.parent,o=r.left,l=void 0,c=void 0;if(a.isIdentifier(o)||a.isPattern(o)||a.isMemberExpression(o))c=o;else{if(!a.isVariableDeclaration(o))throw t.buildCodeFrameError(o,i.get("unknownForHead",o.type));c=n.generateUidIdentifier("ref"),l=a.variableDeclaration(o.kind,[a.variableDeclarator(o.declarations[0].id,c)])}var p=n.generateUidIdentifier("iterator"),h=n.generateUidIdentifier("isArray"),f=u({LOOP_OBJECT:p,IS_ARRAY:h,OBJECT:r.right,INDEX:n.generateUidIdentifier("i"),ID:c});l||f.body.body.shift();var d=a.isLabeledStatement(s),m=void 0;return d&&(m=a.labeledStatement(s.label,f)),{replaceParent:d,declar:l,node:m||f,loop:f}}function n(e,t){var r=e.node,n=e.scope,s=e.parent,o=r.left,u=void 0,c=n.generateUidIdentifier("step"),p=a.memberExpression(c,a.identifier("value"));if(a.isIdentifier(o)||a.isPattern(o)||a.isMemberExpression(o))u=a.expressionStatement(a.assignmentExpression("=",o,p));else{if(!a.isVariableDeclaration(o))throw t.buildCodeFrameError(o,i.get("unknownForHead",o.type));u=a.variableDeclaration(o.kind,[a.variableDeclarator(o.declarations[0].id,p)])}var h=n.generateUidIdentifier("iterator"),f=l({ITERATOR_HAD_ERROR_KEY:n.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:n.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:n.generateUidIdentifier("iteratorError"),ITERATOR_KEY:h,STEP_KEY:c,OBJECT:r.right,BODY:null}),d=a.isLabeledStatement(s),m=f[3].block.body,y=m[0];return d&&(m[0]=a.labeledStatement(s.label,y)),{replaceParent:d,declar:u,loop:y,node:f}}var i=e.messages,s=e.template,a=e.types,o=s("\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "),u=s("\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "),l=s("\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n ");return{visitor:{ForOfStatement:function(e,i){if(e.get("right").isArrayExpression())return e.parentPath.isLabeledStatement()?e.parentPath.replaceWithMultiple(t(e)):e.replaceWithMultiple(t(e));var s=n;i.opts.loose&&(s=r);var o=e.node,u=s(e,i),l=u.declar,c=u.loop,p=c.body;e.ensureBlock(),l&&p.body.push(l),p.body=p.body.concat(o.body.body),a.inherits(c,o),a.inherits(c.body,o.body),u.replaceParent?(e.parentPath.replaceWithMultiple(u.node),e.remove()):e.replaceWithMultiple(u.node)}}}},t.exports=r.default},{}],113:[function(e,t,r){t.exports={default:e("core-js/library/fn/get-iterator"),__esModule:!0}},{"core-js/library/fn/get-iterator":188}],114:[function(e,t,r){t.exports={default:e("core-js/library/fn/json/stringify"),__esModule:!0}},{"core-js/library/fn/json/stringify":189}],115:[function(e,t,r){t.exports={default:e("core-js/library/fn/map"),__esModule:!0}},{"core-js/library/fn/map":190}],116:[function(e,t,r){t.exports={default:e("core-js/library/fn/number/max-safe-integer"),__esModule:!0}},{"core-js/library/fn/number/max-safe-integer":191}],117:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/assign"),__esModule:!0}},{"core-js/library/fn/object/assign":192}],118:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/create"),__esModule:!0}},{"core-js/library/fn/object/create":193}],119:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/get-own-property-symbols"),__esModule:!0}},{"core-js/library/fn/object/get-own-property-symbols":194}],120:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/keys"),__esModule:!0}},{"core-js/library/fn/object/keys":195}],121:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/set-prototype-of"),__esModule:!0}},{"core-js/library/fn/object/set-prototype-of":196}],122:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol"),__esModule:!0}},{"core-js/library/fn/symbol":198}],123:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol/for"),__esModule:!0}},{"core-js/library/fn/symbol/for":197}],124:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol/iterator"),__esModule:!0}},{"core-js/library/fn/symbol/iterator":199}],125:[function(e,t,r){t.exports={default:e("core-js/library/fn/weak-map"),__esModule:!0}},{"core-js/library/fn/weak-map":200}],126:[function(e,t,r){t.exports={default:e("core-js/library/fn/weak-set"),__esModule:!0}},{"core-js/library/fn/weak-set":201}],127:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},{}],128:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("../core-js/object/set-prototype-of"),s=n(i),a=e("../core-js/object/create"),o=n(a),u=e("../helpers/typeof"),l=n(u);r.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,l.default)(t)));e.prototype=(0,o.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(s.default?(0,s.default)(e,t):e.__proto__=t)}},{"../core-js/object/create":118,"../core-js/object/set-prototype-of":121,"../helpers/typeof":131}],129:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}},{}],130:[function(e,t,r){"use strict";r.__esModule=!0;var n=e("../helpers/typeof"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);r.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,i.default)(t))&&"function"!=typeof t?e:t}},{"../helpers/typeof":131}],131:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("../core-js/symbol/iterator"),s=n(i),a=e("../core-js/symbol"),o=n(a),u="function"==typeof o.default&&"symbol"==typeof s.default?function(e){return typeof e}:function(e){return e&&"function"==typeof o.default&&e.constructor===o.default&&e!==o.default.prototype?"symbol":typeof e};r.default="function"==typeof o.default&&"symbol"===u(s.default)?function(e){return void 0===e?"undefined":u(e)}:function(e){return e&&"function"==typeof o.default&&e.constructor===o.default&&e!==o.default.prototype?"symbol":void 0===e?"undefined":u(e)}},{"../core-js/symbol":122,"../core-js/symbol/iterator":124}],132:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t){e=(0,l.default)(e);var r=e,n=r.program;return t.length&&(0,m.default)(e,A,null,t),n.body.length>1?n.body:n.body[0]}r.__esModule=!0;var a=e("babel-runtime/core-js/symbol"),o=i(a);r.default=function(e,t){var r=void 0;try{throw new Error}catch(e){e.stack&&(r=e.stack.split("\n").slice(1).join("\n"))}t=(0,p.default)({allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,preserveComments:!1},t);var n=function(){var i=void 0;try{i=g.parse(e,t),i=m.default.removeProperties(i,{preserveComments:t.preserveComments}),m.default.cheap(i,function(e){e[x]=!0})}catch(e){throw e.stack=e.stack+"from\n"+r,e}return n=function(){return i},i};return function(){for(var e=arguments.length,t=Array(e),r=0;r=n.length)break;o=n[s++]}else{if(s=n.next(),s.done)break;o=s.value}if(e[o])return!0}return!1},e.prototype.create=function(e,t,r,n){return c.default.get({parentPath:this.parentPath,parent:e,container:t,key:r,listKey:n})},e.prototype.maybeQueue=function(e,t){if(this.trap)throw new Error("Infinite cycle detected");this.queue&&(t?this.queue.push(e):this.priorityQueue.push(e))},e.prototype.visitMultiple=function(e,t,r){if(0===e.length)return!1;for(var n=[],i=0;i=n.length)break;o=n[s++]}else{if(s=n.next(),s.done)break;o=s.value}var u=o;if(u.resync(),0!==u.contexts.length&&u.contexts[u.contexts.length-1]===this||u.pushContext(this),null!==u.key&&(f&&e.length>=1e4&&(this.trap=!0),!(t.indexOf(u.node)>=0))){if(t.push(u.node),u.visit()){r=!0;break}if(this.priorityQueue.length&&(r=this.visitQueue(this.priorityQueue),this.priorityQueue=[],this.queue=e,r))break}}for(var l=e,c=Array.isArray(l),p=0,l=c?l:(0,a.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if(p=l.next(),p.done)break;h=p.value}h.popContext()}return this.queue=null,r},e.prototype.visit=function(e,t){var r=e[t];return!!r&&(Array.isArray(r)?this.visitMultiple(r,e,t):this.visitSingle(e,t))},e}();r.default=d,t.exports=r.default}).call(this,e("_process"))},{"./path":143,_process:539,"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/classCallCheck":127,"babel-types":169}],135:[function(e,t,r){"use strict";r.__esModule=!0;var n=e("babel-runtime/helpers/classCallCheck"),i=function(e){return e&&e.__esModule?e:{default:e}}(n),s=function e(t,r){(0,i.default)(this,e),this.file=t,this.options=r};r.default=s,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":127}],136:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r,n,i){if(e){if(t||(t={}),!t.noScope&&!r&&"Program"!==e.type&&"File"!==e.type)throw new Error(g.get("traverseNeedsParent",e.type));m.explode(t),s.node(e,t,r,n,i)}}function a(e,t){e.node.type===t.type&&(t.has=!0,e.stop())}r.__esModule=!0,r.visitors=r.Hub=r.Scope=r.NodePath=void 0;var o=e("babel-runtime/core-js/get-iterator"),u=i(o),l=e("./path");Object.defineProperty(r,"NodePath",{enumerable:!0,get:function(){return i(l).default}});var c=e("./scope");Object.defineProperty(r,"Scope",{enumerable:!0,get:function(){return i(c).default}});var p=e("./hub");Object.defineProperty(r,"Hub",{enumerable:!0,get:function(){return i(p).default}}),r.default=s;var h=e("./context"),f=i(h),d=e("./visitors"),m=n(d),y=e("babel-messages"),g=n(y),b=e("lodash/includes"),v=i(b),x=e("babel-types"),E=n(x),A=e("./cache"),D=n(A);r.visitors=m,s.visitors=m,s.verify=m.verify,s.explode=m.explode,s.NodePath=e("./path"),s.Scope=e("./scope"),s.Hub=e("./hub"),s.cheap=function(e,t){return E.traverseFast(e,t)},s.node=function(e,t,r,n,i,s){var a=E.VISITOR_KEYS[e.type];if(a)for(var o=new f.default(r,t,n,i),l=a,c=Array.isArray(l),p=0,l=c?l:(0,u.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if(p=l.next(),p.done)break;h=p.value}var d=h;if((!s||!s[d])&&o.visit(e,d))return}},s.clearNode=function(e,t){E.removeProperties(e,t),D.path.delete(e)},s.removeProperties=function(e,t){return E.traverseFast(e,s.clearNode,t),e},s.hasType=function(e,t,r,n){if((0,v.default)(n,e.type))return!1;if(e.type===r)return!0;var i={has:!1,type:r};return s(e,{blacklist:n,enter:a},t,i),i.has},s.clearCache=function(){D.clear()},s.clearCache.clearPath=D.clearPath,s.clearCache.clearScope=D.clearScope,s.copyCache=function(e,t){D.path.has(e)&&D.path.set(t,D.path.get(e))}},{"./cache":133,"./context":134,"./hub":135,"./path":143,"./scope":155,"./visitors":157,"babel-messages":103,"babel-runtime/core-js/get-iterator":113,"babel-types":169,"lodash/includes":496}],137:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){for(var t=this;t=t.parentPath;)if(e(t))return t;return null}function s(e){var t=this;do{if(e(t))return t}while(t=t.parentPath);return null}function a(){return this.findParent(function(e){return e.isFunction()||e.isProgram()})}function o(){var e=this;do{if(Array.isArray(e.container))return e}while(e=e.parentPath)}function u(e){return this.getDeepestCommonAncestorFrom(e,function(e,t,r){for(var n=void 0,i=b.VISITOR_KEYS[e.type],s=r,a=Array.isArray(s),o=0,s=a?s:(0,y.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u,c=l[t+1];if(n)if(c.listKey&&n.listKey===c.listKey&&c.keyh&&(n=c)}else n=c}return n})}function l(e,t){var r=this;if(!e.length)return this;if(1===e.length)return e[0];var n=1/0,i=void 0,s=void 0,a=e.map(function(e){var t=[];do{t.unshift(e)}while((e=e.parentPath)&&e!==r);return t.length=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var d=f;if(d[u]!==l)break e}i=u,s=l}if(s)return t?t(s,i,a):s;throw new Error("Couldn't find intersection")}function c(){var e=this,t=[];do{t.push(e)}while(e=e.parentPath);return t}function p(e){return e.isDescendant(this)}function h(e){return!!this.findParent(function(t){return t===e})}function f(){for(var e=this;e;){for(var t=arguments,r=Array.isArray(t),n=0,t=r?t:(0,y.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;if(e.node.type===s)return!0}e=e.parentPath}return!1}function d(e){var t=this.isFunction()?this:this.findParent(function(e){return e.isFunction()});if(t){if(t.isFunctionExpression()||t.isFunctionDeclaration()){var r=t.node.shadow;if(r&&(!e||!1!==r[e]))return t}else if(t.isArrowFunctionExpression())return t;return null}}r.__esModule=!0;var m=e("babel-runtime/core-js/get-iterator"),y=n(m);r.findParent=i,r.find=s,r.getFunctionParent=a,r.getStatementParent=o,r.getEarliestCommonAncestorFrom=u,r.getDeepestCommonAncestorFrom=l,r.getAncestry=c,r.isAncestor=p,r.isDescendant=h,r.inType=f,r.inShadow=d;var g=e("babel-types"),b=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(g),v=e("./index");n(v)},{"./index":143,"babel-runtime/core-js/get-iterator":113,"babel-types":169}],138:[function(e,t,r){"use strict";function n(){if("string"!=typeof this.key){var e=this.node;if(e){var t=e.trailingComments,r=e.leadingComments;if(t||r){var n=this.getSibling(this.key-1),i=this.getSibling(this.key+1);n.node||(n=i),i.node||(i=n),n.addComments("trailing",r),i.addComments("leading",t)}}}}function i(e,t,r){this.addComments(e,[{type:r?"CommentLine":"CommentBlock",value:t}])}function s(e,t){if(t){var r=this.node;if(r){var n=e+"Comments";r[n]?r[n]=r[n].concat(t):r[n]=t}}}r.__esModule=!0,r.shareCommentsWithSiblings=n,r.addComment=i,r.addComments=s},{}],139:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=this.opts;return this.debug(function(){return e}),!(!this.node||!this._call(t[e]))||!!this.node&&this._call(t[this.node.type]&&t[this.node.type][e])}function s(e){if(!e)return!1;for(var t=e,r=Array.isArray(t),n=0,t=r?t:(0,S.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;if(s){var a=this.node;if(!a)return!0;if(s.call(this.state,this,this.state))throw new Error("Unexpected return value from visitor method "+s);if(this.node!==a)return!0;if(this.shouldStop||this.shouldSkip||this.removed)return!0}}return!1}function a(){var e=this.opts.blacklist;return e&&e.indexOf(this.node.type)>-1}function o(){return!!this.node&&(!this.isBlacklisted()&&((!this.opts.shouldSkip||!this.opts.shouldSkip(this))&&(this.call("enter")||this.shouldSkip?(this.debug(function(){return"Skip..."}),this.shouldStop):(this.debug(function(){return"Recursing into..."}),w.default.node(this.node,this.opts,this.scope,this.state,this,this.skipKeys),this.call("exit"),this.shouldStop))))}function u(){this.shouldSkip=!0}function l(e){this.skipKeys[e]=!0}function c(){this.shouldStop=!0,this.shouldSkip=!0}function p(){if(!this.opts||!this.opts.noScope){var e=this.context&&this.context.scope;if(!e)for(var t=this.parentPath;t&&!e;){if(t.opts&&t.opts.noScope)return;e=t.scope,t=t.parentPath}this.scope=this.getScope(e),this.scope&&this.scope.init()}}function h(e){return this.shouldSkip=!1,this.shouldStop=!1,this.removed=!1,this.skipKeys={},e&&(this.context=e,this.state=e.state,this.opts=e.opts),this.setScope(),this}function f(){this.removed||(this._resyncParent(),this._resyncList(),this._resyncKey())}function d(){this.parentPath&&(this.parent=this.parentPath.node)}function m(){if(this.container&&this.node!==this.container[this.key]){if(Array.isArray(this.container)){for(var e=0;e0&&void 0!==arguments[0]?arguments[0]:this;if(!e.removed)for(var t=this.contexts,r=t,n=Array.isArray(r),i=0,r=n?r:(0,S.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;a.maybeQueue(e)}}function D(){for(var e=this,t=this.contexts;!t.length;)e=e.parentPath,t=e.contexts;return t}r.__esModule=!0;var C=e("babel-runtime/core-js/get-iterator"),S=n(C);r.call=i,r._call=s,r.isBlacklisted=a,r.visit=o,r.skip=u,r.skipKey=l,r.stop=c,r.setScope=p,r.setContext=h,r.resync=f,r._resyncParent=d,r._resyncKey=m,r._resyncList=y,r._resyncRemoved=g,r.popContext=b,r.pushContext=v,r.setup=x,r.setKey=E,r.requeue=A,r._getQueueContexts=D;var _=e("../index"),w=n(_)},{"../index":136,"babel-runtime/core-js/get-iterator":113}],140:[function(e,t,r){"use strict";function n(){var e=this.node,t=void 0;if(this.isMemberExpression())t=e.property;else{if(!this.isProperty()&&!this.isMethod())throw new ReferenceError("todo");t=e.key}return e.computed||o.isIdentifier(t)&&(t=o.stringLiteral(t.name)),t}function i(){return o.ensureBlock(this.node)}function s(){if(this.isArrowFunctionExpression()){this.ensureBlock();var e=this.node;e.expression=!1,e.type="FunctionExpression",e.shadow=e.shadow||!0}}r.__esModule=!0,r.toComputedKey=n,r.ensureBlock=i,r.arrowFunctionToShadowed=s;var a=e("babel-types"),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(a)},{"babel-types":169}],141:[function(e,t,r){(function(t){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){var e=this.evaluate();if(e.confident)return!!e.value}function s(){function e(e){i&&(s=e,i=!1)}function r(t){var r=t.node;if(a.has(r)){var s=a.get(r);return s.resolved?s.value:void e(t)}var o={resolved:!1};a.set(r,o);var u=n(t);return i&&(o.resolved=!0,o.value=u),u}function n(n){if(i){var s=n.node;if(n.isSequenceExpression()){var a=n.get("expressions");return r(a[a.length-1])}if(n.isStringLiteral()||n.isNumericLiteral()||n.isBooleanLiteral())return s.value;if(n.isNullLiteral())return null;if(n.isTemplateLiteral()){for(var u="",c=0,p=n.get("expressions"),d=s.quasis,m=Array.isArray(d),y=0,d=m?d:(0,l.default)(d);;){var g;if(m){if(y>=d.length)break;g=d[y++]}else{if(y=d.next(),y.done)break;g=y.value}var b=g;if(!i)break;u+=b.value.cooked;var v=p[c++];v&&(u+=String(r(v)))}if(!i)return;return u}if(n.isConditionalExpression()){var x=r(n.get("test"));if(!i)return;return r(x?n.get("consequent"):n.get("alternate"))}if(n.isExpressionWrapper())return r(n.get("expression"));if(n.isMemberExpression()&&!n.parentPath.isCallExpression({callee:s})){var E=n.get("property"),A=n.get("object");if(A.isLiteral()&&E.isIdentifier()){var D=A.node.value,C=void 0===D?"undefined":(0,o.default)(D);if("number"===C||"string"===C)return D[E.node.name]}}if(n.isReferencedIdentifier()){var S=n.scope.getBinding(s.name);if(S&&S.constantViolations.length>0)return e(S.path);if(S&&n.node.start=P.length)break;j=P[O++]}else{if(O=P.next(),O.done)break;j=O.value}var N=j;if(N=N.evaluate(),!N.confident)return e(N);F.push(N.value)}return F}if(n.isObjectExpression()){for(var I={},L=n.get("properties"),M=L,R=Array.isArray(M),U=0,M=R?M:(0,l.default)(M);;){var V;if(R){if(U>=M.length)break;V=M[U++]}else{if(U=M.next(),U.done)break;V=U.value}var q=V;if(q.isObjectMethod()||q.isSpreadProperty())return e(q);var G=q.get("key"),X=G;if(q.node.computed){if(X=X.evaluate(),!X.confident)return e(G);X=X.value}else X=X.isIdentifier()?X.node.name:X.node.value;var J=q.get("value"),W=J.evaluate();if(!W.confident)return e(J);W=W.value,I[X]=W}return I}if(n.isLogicalExpression()){var K=i,z=r(n.get("left")),Y=i;i=K;var H=r(n.get("right")),$=i;switch(i=Y&&$,s.operator){case"||":if(z&&Y)return i=!0,z;if(!i)return;return z||H;case"&&":if((!z&&Y||!H&&$)&&(i=!0),!i)return;return z&&H}}if(n.isBinaryExpression()){var Q=r(n.get("left"));if(!i)return;var Z=r(n.get("right"));if(!i)return;switch(s.operator){case"-":return Q-Z;case"+":return Q+Z;case"/":return Q/Z;case"*":return Q*Z;case"%":return Q%Z;case"**":return Math.pow(Q,Z);case"<":return Q":return Q>Z;case"<=":return Q<=Z;case">=":return Q>=Z;case"==":return Q==Z;case"!=":return Q!=Z;case"===":return Q===Z;case"!==":return Q!==Z;case"|":return Q|Z;case"&":return Q&Z;case"^":return Q^Z;case"<<":return Q<>":return Q>>Z;case">>>":return Q>>>Z}}if(n.isCallExpression()){var ee=n.get("callee"),te=void 0,re=void 0;if(ee.isIdentifier()&&!n.scope.getBinding(ee.node.name,!0)&&h.indexOf(ee.node.name)>=0&&(re=t[s.callee.name]),ee.isMemberExpression()){var ne=ee.get("object"),ie=ee.get("property");if(ne.isIdentifier()&&ie.isIdentifier()&&h.indexOf(ne.node.name)>=0&&f.indexOf(ie.node.name)<0&&(te=t[ne.node.name],re=te[ie.node.name]),ne.isLiteral()&&ie.isIdentifier()){var se=(0,o.default)(ne.node.value);"string"!==se&&"number"!==se||(te=ne.node.value,re=te[ie.node.name])}}if(re){var ae=n.get("arguments").map(r);if(!i)return;return re.apply(te,ae)}}e(n)}}var i=!0,s=void 0,a=new p.default,u=r(this);return i||(u=void 0),{confident:i,deopt:s,value:u}}r.__esModule=!0;var a=e("babel-runtime/helpers/typeof"),o=n(a),u=e("babel-runtime/core-js/get-iterator"),l=n(u),c=e("babel-runtime/core-js/map"),p=n(c);r.evaluateTruthy=i,r.evaluate=s;var h=["String","Number","Math"],f=["random"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/map":115,"babel-runtime/helpers/typeof":131}],142:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){var e=this;do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement())break;e=e.parentPath}while(e);if(e&&(e.isProgram()||e.isFile()))throw new Error("File/Program node, we can't possibly find a statement parent to this");return e}function s(){return"left"===this.key?this.getSibling("right"):"right"===this.key?this.getSibling("left"):void 0}function a(){var e=[],t=function(t){t&&(e=e.concat(t.getCompletionRecords()))};if(this.isIfStatement())t(this.get("consequent")),t(this.get("alternate"));else if(this.isDoExpression()||this.isFor()||this.isWhile())t(this.get("body"));else if(this.isProgram()||this.isBlockStatement())t(this.get("body").pop());else{if(this.isFunction())return this.get("body").getCompletionRecords();this.isTryStatement()?(t(this.get("block")),t(this.get("handler")),t(this.get("finalizer"))):e.push(this)}return e}function o(e){return C.default.get({parentPath:this.parentPath,parent:this.parent,container:this.container,listKey:this.listKey,key:e})}function u(){return this.getSibling(this.key-1)}function l(){return this.getSibling(this.key+1)}function c(){for(var e=this.key,t=this.getSibling(++e),r=[];t.node;)r.push(t),t=this.getSibling(++e);return r}function p(){for(var e=this.key,t=this.getSibling(--e),r=[];t.node;)r.push(t),t=this.getSibling(--e);return r}function h(e,t){!0===t&&(t=this.context);var r=e.split(".");return 1===r.length?this._getKey(e,t):this._getPattern(r,t)}function f(e,t){var r=this,n=this.node,i=n[e];return Array.isArray(i)?i.map(function(s,a){return C.default.get({listKey:e,parentPath:r,parent:n,container:i,key:a}).setContext(t)}):C.default.get({parentPath:this,parent:n,container:n,key:e}).setContext(t)}function d(e,t){for(var r=this,n=e,i=Array.isArray(n),s=0,n=i?n:(0,A.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;r="."===o?r.parentPath:Array.isArray(r)?r[o]:r.get(o,t)}return r}function m(e){return _.getBindingIdentifiers(this.node,e)}function y(e){return _.getOuterBindingIdentifiers(this.node,e)}function g(){for(var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this,n=[].concat(r),i=(0,x.default)(null);n.length;){var s=n.shift();if(s&&s.node){var a=_.getBindingIdentifiers.keys[s.node.type];if(s.isIdentifier())if(e){var o=i[s.node.name]=i[s.node.name]||[];o.push(s)}else i[s.node.name]=s;else if(s.isExportDeclaration()){var u=s.get("declaration");u.isDeclaration()&&n.push(u)}else{if(t){if(s.isFunctionDeclaration()){n.push(s.get("id"));continue}if(s.isFunctionExpression())continue}if(a)for(var l=0;l1&&void 0!==arguments[1]?arguments[1]:SyntaxError;return this.hub.file.buildCodeFrameError(this.node,e,t)},e.prototype.traverse=function(e,t){(0,y.default)(this.node,e,this.scope,t,this)},e.prototype.mark=function(e,t){this.hub.file.metadata.marked.push({type:e,message:t,loc:this.node.loc})},e.prototype.set=function(e,t){A.validate(this.node,e,t),this.node[e]=t},e.prototype.getPathLocation=function(){var e=[],t=this;do{var r=t.key;t.inList&&(r=t.listKey+"["+r+"]"),e.unshift(r)}while(t=t.parentPath);return e.join(".")},e.prototype.debug=function(e){C.enabled&&C(this.getPathLocation()+" "+this.type+": "+e())},e}();r.default=S,(0,b.default)(S.prototype,e("./ancestry")),(0,b.default)(S.prototype,e("./inference")),(0,b.default)(S.prototype,e("./replacement")),(0,b.default)(S.prototype,e("./evaluation")),(0,b.default)(S.prototype,e("./conversion")),(0,b.default)(S.prototype,e("./introspection")),(0,b.default)(S.prototype,e("./context")),(0,b.default)(S.prototype,e("./removal")),(0,b.default)(S.prototype,e("./modification")),(0,b.default)(S.prototype,e("./family")),(0,b.default)(S.prototype,e("./comments"));for(var _=A.TYPES,w=Array.isArray(_),k=0,_=w?_:(0,a.default)(_);;){var F;if("break"===function(){if(w){if(k>=_.length)return"break";F=_[k++]}else{if(k=_.next(),k.done)return"break";F=k.value}var e=F,t="is"+e;S.prototype[t]=function(e){return A[t](this.node,e)},S.prototype["assert"+e]=function(r){if(!this[t](r))throw new TypeError("Expected node path of type "+e)}}())break}for(var T in c){(function(e){if("_"===e[0])return"continue";A.TYPES.indexOf(e)<0&&A.TYPES.push(e);var t=c[e];S.prototype["is"+e]=function(e){return t.checkPath(this,e)}})(T)}t.exports=r.default},{"../cache":133,"../index":136,"../scope":155,"./ancestry":137,"./comments":138,"./context":139,"./conversion":140,"./evaluation":141,"./family":142,"./inference":144,"./introspection":147,"./lib/virtual-types":150,"./modification":151,"./removal":152,"./replacement":153,"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/classCallCheck":127,"babel-types":169,debug:296,invariant:307,"lodash/assign":477}],144:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(){if(this.typeAnnotation)return this.typeAnnotation;var e=this._getTypeAnnotation()||y.anyTypeAnnotation();return y.isTypeAnnotation(e)&&(e=e.typeAnnotation),this.typeAnnotation=e}function s(){var e=this.node;{if(e){if(e.typeAnnotation)return e.typeAnnotation;var t=d[e.type];return t?t.call(this,e):(t=d[this.parentPath.type],t&&t.validParent?this.parentPath.getTypeAnnotation():void 0)}if("init"===this.key&&this.parentPath.isVariableDeclarator()){var r=this.parentPath.parentPath,n=r.parentPath;return"left"===r.key&&n.isForInStatement()?y.stringTypeAnnotation():"left"===r.key&&n.isForOfStatement()?y.anyTypeAnnotation():y.voidTypeAnnotation()}}}function a(e,t){return o(e,this.getTypeAnnotation(),t)}function o(e,t,r){if("string"===e)return y.isStringTypeAnnotation(t);if("number"===e)return y.isNumberTypeAnnotation(t);if("boolean"===e)return y.isBooleanTypeAnnotation(t);if("any"===e)return y.isAnyTypeAnnotation(t);if("mixed"===e)return y.isMixedTypeAnnotation(t);if("empty"===e)return y.isEmptyTypeAnnotation(t);if("void"===e)return y.isVoidTypeAnnotation(t);if(r)return!1;throw new Error("Unknown base type "+e)}function u(e){var t=this.getTypeAnnotation();if(y.isAnyTypeAnnotation(t))return!0;if(y.isUnionTypeAnnotation(t)){for(var r=t.types,n=Array.isArray(r),i=0,r=n?r:(0,h.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if(y.isAnyTypeAnnotation(a)||o(e,a,!0))return!0}return!1}return o(e,t,!0)}function l(e){var t=this.getTypeAnnotation();if(e=e.getTypeAnnotation(),!y.isAnyTypeAnnotation(t)&&y.isFlowBaseAnnotation(t))return e.type===t.type}function c(e){var t=this.getTypeAnnotation();return y.isGenericTypeAnnotation(t)&&y.isIdentifier(t.id,{name:e})}r.__esModule=!0;var p=e("babel-runtime/core-js/get-iterator"),h=function(e){return e&&e.__esModule?e:{default:e}}(p);r.getTypeAnnotation=i,r._getTypeAnnotation=s,r.isBaseType=a,r.couldBeBaseType=u,r.baseTypeStrictlyMatches=l,r.isGenericType=c;var f=e("./inferers"),d=n(f),m=e("babel-types"),y=n(m)},{"./inferers":146,"babel-runtime/core-js/get-iterator":113,"babel-types":169}],145:[function(e,t,r){"use strict";function n(e,t){var r=e.scope.getBinding(t),n=[];e.typeAnnotation=p.unionTypeAnnotation(n);var s=[],a=i(r,e,s),u=o(e,t);if(u&&function(){var e=i(r,u.ifStatement);a=a.filter(function(t){return e.indexOf(t)<0}),n.push(u.typeAnnotation)}(),a.length){a=a.concat(s);for(var c=a,h=Array.isArray(c),f=0,c=h?c:(0,l.default)(c);;){var d;if(h){if(f>=c.length)break;d=c[f++]}else{if(f=c.next(),f.done)break;d=f.value}var m=d;n.push(m.getTypeAnnotation())}}if(n.length)return p.createUnionTypeAnnotation(n)}function i(e,t,r){var n=e.constantViolations.slice();return n.unshift(e.path),n.filter(function(e){e=e.resolve();var n=e._guessExecutionStatusRelativeTo(t);return r&&"function"===n&&r.push(e),"before"===n})}function s(e,t){var r=t.node.operator,n=t.get("right").resolve(),i=t.get("left").resolve(),s=void 0;if(i.isIdentifier({name:e})?s=n:n.isIdentifier({name:e})&&(s=i),s)return"==="===r?s.getTypeAnnotation():p.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(r)>=0?p.numberTypeAnnotation():void 0;if("==="===r){var a=void 0,o=void 0;if(i.isUnaryExpression({operator:"typeof"})?(a=i,o=n):n.isUnaryExpression({operator:"typeof"})&&(a=n,o=i),(o||a)&&(o=o.resolve(),o.isLiteral())){if("string"==typeof o.node.value&&a.get("argument").isIdentifier({name:e}))return p.createTypeAnnotationBasedOnTypeof(o.node.value)}}}function a(e){for(var t=void 0;t=e.parentPath;){if(t.isIfStatement()||t.isConditionalExpression())return"test"===e.key?void 0:t;e=t}}function o(e,t){var r=a(e);if(r){var n=r.get("test"),i=[n],u=[];do{var l=i.shift().resolve();if(l.isLogicalExpression()&&(i.push(l.get("left")),i.push(l.get("right"))),l.isBinaryExpression()){var c=s(t,l);c&&u.push(c)}}while(i.length);return u.length?{typeAnnotation:p.createUnionTypeAnnotation(u),ifStatement:r}:o(r,t)}}r.__esModule=!0;var u=e("babel-runtime/core-js/get-iterator"),l=function(e){return e&&e.__esModule?e:{default:e}}(u);r.default=function(e){if(this.isReferenced()){var t=this.scope.getBinding(e.name);return t?t.identifier.typeAnnotation?t.identifier.typeAnnotation:n(this,e.name):"undefined"===e.name?p.voidTypeAnnotation():"NaN"===e.name||"Infinity"===e.name?p.numberTypeAnnotation():void e.name}};var c=e("babel-types"),p=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(c);t.exports=r.default},{"babel-runtime/core-js/get-iterator":113,"babel-types":169}],146:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(){return this.get("id").isIdentifier()?this.get("init").getTypeAnnotation():void 0}function s(e){return e.typeAnnotation}function a(e){if(this.get("callee").isIdentifier())return F.genericTypeAnnotation(e.callee)}function o(){return F.stringTypeAnnotation()}function u(e){var t=e.operator;return"void"===t?F.voidTypeAnnotation():F.NUMBER_UNARY_OPERATORS.indexOf(t)>=0?F.numberTypeAnnotation():F.STRING_UNARY_OPERATORS.indexOf(t)>=0?F.stringTypeAnnotation():F.BOOLEAN_UNARY_OPERATORS.indexOf(t)>=0?F.booleanTypeAnnotation():void 0}function l(e){var t=e.operator;if(F.NUMBER_BINARY_OPERATORS.indexOf(t)>=0)return F.numberTypeAnnotation();if(F.BOOLEAN_BINARY_OPERATORS.indexOf(t)>=0)return F.booleanTypeAnnotation();if("+"===t){var r=this.get("right"),n=this.get("left");return n.isBaseType("number")&&r.isBaseType("number")?F.numberTypeAnnotation():n.isBaseType("string")||r.isBaseType("string")?F.stringTypeAnnotation():F.unionTypeAnnotation([F.stringTypeAnnotation(),F.numberTypeAnnotation()])}}function c(){return F.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(),this.get("right").getTypeAnnotation()])}function p(){return F.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(),this.get("alternate").getTypeAnnotation()])}function h(){return this.get("expressions").pop().getTypeAnnotation()}function f(){return this.get("right").getTypeAnnotation()}function d(e){var t=e.operator;if("++"===t||"--"===t)return F.numberTypeAnnotation()}function m(){return F.stringTypeAnnotation()}function y(){return F.numberTypeAnnotation()}function g(){return F.booleanTypeAnnotation()}function b(){return F.nullLiteralTypeAnnotation()}function v(){return F.genericTypeAnnotation(F.identifier("RegExp"))}function x(){return F.genericTypeAnnotation(F.identifier("Object"))}function E(){return F.genericTypeAnnotation(F.identifier("Array"))}function A(){return E()}function D(){return F.genericTypeAnnotation(F.identifier("Function"))}function C(){return _(this.get("callee"))}function S(){return _(this.get("tag"))}function _(e){if(e=e.resolve(),e.isFunction()){if(e.is("async"))return e.is("generator")?F.genericTypeAnnotation(F.identifier("AsyncIterator")):F.genericTypeAnnotation(F.identifier("Promise"));if(e.node.returnType)return e.node.returnType}}r.__esModule=!0,r.ClassDeclaration=r.ClassExpression=r.FunctionDeclaration=r.ArrowFunctionExpression=r.FunctionExpression=r.Identifier=void 0;var w=e("./inferer-reference");Object.defineProperty(r,"Identifier",{enumerable:!0,get:function(){return n(w).default}}),r.VariableDeclarator=i, +r.TypeCastExpression=s,r.NewExpression=a,r.TemplateLiteral=o,r.UnaryExpression=u,r.BinaryExpression=l,r.LogicalExpression=c,r.ConditionalExpression=p,r.SequenceExpression=h,r.AssignmentExpression=f,r.UpdateExpression=d,r.StringLiteral=m,r.NumericLiteral=y,r.BooleanLiteral=g,r.NullLiteral=b,r.RegExpLiteral=v,r.ObjectExpression=x,r.ArrayExpression=E,r.RestElement=A,r.CallExpression=C,r.TaggedTemplateExpression=S;var k=e("babel-types"),F=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(k);s.validParent=!0,A.validParent=!0,r.FunctionExpression=D,r.ArrowFunctionExpression=D,r.FunctionDeclaration=D,r.ClassExpression=D,r.ClassDeclaration=D},{"./inferer-reference":145,"babel-types":169}],147:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){function r(e){var t=n[s];return"*"===t||e===t}if(!this.isMemberExpression())return!1;for(var n=e.split("."),i=[this.node],s=0;i.length;){var a=i.shift();if(t&&s===n.length)return!0;if(k.isIdentifier(a)){if(!r(a.name))return!1}else if(k.isLiteral(a)){if(!r(a.value))return!1}else{if(k.isMemberExpression(a)){if(a.computed&&!k.isLiteral(a.property))return!1;i.unshift(a.property),i.unshift(a.object);continue}if(!k.isThisExpression(a))return!1;if(!r("this"))return!1}if(++s>n.length)return!1}return s===n.length}function s(e){var t=this.node&&this.node[e];return t&&Array.isArray(t)?!!t.length:!!t}function a(){return this.scope.isStatic(this.node)}function o(e){return!this.has(e)}function u(e,t){return this.node[e]===t}function l(e){return k.isType(this.type,e)}function c(){return("init"===this.key||"left"===this.key)&&this.parentPath.isFor()}function p(e){return!("body"!==this.key||!this.parentPath.isArrowFunctionExpression())&&(this.isExpression()?k.isBlockStatement(e):!!this.isBlockStatement()&&k.isExpression(e))}function h(e){var t=this,r=!0;do{var n=t.container;if(t.isFunction()&&!r)return!!e;if(r=!1,Array.isArray(n)&&t.key!==n.length-1)return!1}while((t=t.parentPath)&&!t.isProgram());return!0}function f(){return!this.parentPath.isLabeledStatement()&&!k.isBlockStatement(this.container)&&(0,_.default)(k.STATEMENT_OR_BLOCK_KEYS,this.key)}function d(e,t){if(!this.isReferencedIdentifier())return!1;var r=this.scope.getBinding(this.node.name);if(!r||"module"!==r.kind)return!1;var n=r.path,i=n.parentPath;return!!i.isImportDeclaration()&&(i.node.source.value===e&&(!t||(!(!n.isImportDefaultSpecifier()||"default"!==t)||(!(!n.isImportNamespaceSpecifier()||"*"!==t)||!(!n.isImportSpecifier()||n.node.imported.name!==t)))))}function m(){var e=this.node;return e.end?this.hub.file.code.slice(e.start,e.end):""}function y(e){return"after"!==this._guessExecutionStatusRelativeTo(e)}function g(e){var t=e.scope.getFunctionParent(),r=this.scope.getFunctionParent();if(t.node!==r.node){var n=this._guessExecutionStatusRelativeToDifferentFunctions(t);if(n)return n;e=t.path}var i=e.getAncestry();if(i.indexOf(this)>=0)return"after";var s=this.getAncestry(),a=void 0,o=void 0,u=void 0;for(u=0;u=0){a=l;break}}if(!a)return"before";var c=i[o-1],p=s[u-1];return c&&p?c.listKey&&c.container===p.container?c.key>p.key?"before":"after":k.VISITOR_KEYS[c.type].indexOf(c.key)>k.VISITOR_KEYS[p.type].indexOf(p.key)?"before":"after":"before"}function b(e){var t=e.path;if(t.isFunctionDeclaration()){var r=t.scope.getBinding(t.node.id.name);if(!r.references)return"before";for(var n=r.referencePaths,i=n,s=Array.isArray(i),a=0,i=s?i:(0,C.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;if("callee"!==u.key||!u.parentPath.isCallExpression())return}for(var l=void 0,c=n,p=Array.isArray(c),h=0,c=p?c:(0,C.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var d=f;if(!!!d.find(function(e){return e.node===t.node})){var m=this._guessExecutionStatusRelativeTo(d);if(l){if(l!==m)return}else l=m}}return l}}function v(e,t){return this._resolve(e,t)||this}function x(e,t){var r=this;if(!(t&&t.indexOf(this)>=0))if(t=t||[],t.push(this),this.isVariableDeclarator()){if(this.get("id").isIdentifier())return this.get("init").resolve(e,t)}else if(this.isReferencedIdentifier()){var n=this.scope.getBinding(this.node.name);if(!n)return;if(!n.constant)return;if("module"===n.kind)return;if(n.path!==this){var i=function(){var i=n.path.resolve(e,t);return r.find(function(e){return e.node===i.node})?{v:void 0}:{v:i}}();if("object"===(void 0===i?"undefined":(0,A.default)(i)))return i.v}}else{if(this.isTypeCastExpression())return this.get("expression").resolve(e,t);if(e&&this.isMemberExpression()){var s=this.toComputedKey();if(!k.isLiteral(s))return;var a=s.value,o=this.get("object").resolve(e,t);if(o.isObjectExpression())for(var u=o.get("properties"),l=u,c=Array.isArray(l),p=0,l=c?l:(0,C.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if(p=l.next(),p.done)break;h=p.value}var f=h;if(f.isProperty()){var d=f.get("key"),m=f.isnt("computed")&&d.isIdentifier({name:a});if(m=m||d.isLiteral({value:a}))return f.get("value").resolve(e,t)}}else if(o.isArrayExpression()&&!isNaN(+a)){var y=o.get("elements"),g=y[a];if(g)return g.resolve(e,t)}}}}r.__esModule=!0,r.is=void 0;var E=e("babel-runtime/helpers/typeof"),A=n(E),D=e("babel-runtime/core-js/get-iterator"),C=n(D);r.matchesPattern=i,r.has=s,r.isStatic=a,r.isnt=o,r.equals=u,r.isNodeType=l,r.canHaveVariableDeclarationOrExpression=c,r.canSwapBetweenExpressionAndStatement=p,r.isCompletionRecord=h,r.isStatementOrBlock=f,r.referencesImport=d,r.getSource=m,r.willIMaybeExecuteBefore=y,r._guessExecutionStatusRelativeTo=g,r._guessExecutionStatusRelativeToDifferentFunctions=b,r.resolve=v,r._resolve=x;var S=e("lodash/includes"),_=n(S),w=e("babel-types"),k=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(w);r.is=s},{"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/typeof":131,"babel-types":169,"lodash/includes":496}],148:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/core-js/get-iterator"),s=n(i),a=e("babel-runtime/helpers/classCallCheck"),o=n(a),u=e("babel-types"),l=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(u),c={ReferencedIdentifier:function(e,t){if(!e.isJSXIdentifier()||!u.react.isCompatTag(e.node.name)||e.parentPath.isJSXMemberExpression()){if("this"===e.node.name){var r=e.scope;do{if(r.path.isFunction()&&!r.path.isArrowFunctionExpression())break}while(r=r.parent);r&&t.breakOnScopePaths.push(r.path)}var n=e.scope.getBinding(e.node.name);n&&n===t.scope.getBinding(e.node.name)&&(t.bindings[e.node.name]=n)}}},p=function(){function e(t,r){(0,o.default)(this,e),this.breakOnScopePaths=[],this.bindings={},this.scopes=[],this.scope=r,this.path=t,this.attachAfter=!1}return e.prototype.isCompatibleScope=function(e){for(var t in this.bindings){var r=this.bindings[t];if(!e.bindingIdentifierEquals(t,r.identifier))return!1}return!0},e.prototype.getCompatibleScopes=function(){var e=this.path.scope;do{if(!this.isCompatibleScope(e))break;if(this.scopes.push(e),this.breakOnScopePaths.indexOf(e.path)>=0)break}while(e=e.parent)},e.prototype.getAttachmentPath=function(){var e=this._getAttachmentPath();if(e){var t=e.scope;if(t.path===e&&(t=e.scope.parent),t.path.isProgram()||t.path.isFunction())for(var r in this.bindings)if(t.hasOwnBinding(r)){var n=this.bindings[r];if("param"!==n.kind&&this.getAttachmentParentForPath(n.path).key>e.key){this.attachAfter=!0,e=n.path;for(var i=n.constantViolations,a=Array.isArray(i),o=0,i=a?i:(0,s.default)(i);;){var u;if(a){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var l=u;this.getAttachmentParentForPath(l).key>e.key&&(e=l)}}}return e}},e.prototype._getAttachmentPath=function(){var e=this.scopes,t=e.pop();if(t){if(t.path.isFunction()){if(this.hasOwnParamBindings(t)){if(this.scope===t)return;return t.path.get("body").get("body")[0]}return this.getNextScopeAttachmentParent()}return t.path.isProgram()?this.getNextScopeAttachmentParent():void 0}},e.prototype.getNextScopeAttachmentParent=function(){var e=this.scopes.pop();if(e)return this.getAttachmentParentForPath(e.path)},e.prototype.getAttachmentParentForPath=function(e){do{if(!e.parentPath||Array.isArray(e.container)&&e.isStatement()||e.isVariableDeclarator()&&null!==e.parentPath.node&&e.parentPath.node.declarations.length>1)return e}while(e=e.parentPath)},e.prototype.hasOwnParamBindings=function(e){for(var t in this.bindings)if(e.hasOwnBinding(t)){var r=this.bindings[t];if("param"===r.kind&&r.constant)return!0}return!1},e.prototype.run=function(){var e=this.path.node;if(!e._hoisted){e._hoisted=!0,this.path.traverse(c,this),this.getCompatibleScopes();var t=this.getAttachmentPath();if(t&&t.getFunctionParent()!==this.path.getFunctionParent()){var r=t.scope.generateUidIdentifier("ref"),n=l.variableDeclarator(r,this.path.node);t[this.attachAfter?"insertAfter":"insertBefore"]([t.isVariableDeclarator()?n:l.variableDeclaration("var",[n])]);var i=this.path.parentPath;i.isJSXElement()&&this.path.container===i.node.children&&(r=l.JSXExpressionContainer(r)),this.path.replaceWith(r)}}},e}();r.default=p,t.exports=r.default},{"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/classCallCheck":127,"babel-types":169}],149:[function(e,t,r){"use strict";r.__esModule=!0;r.hooks=[function(e,t){if("test"===e.key&&(t.isWhile()||t.isSwitchCase())||"declaration"===e.key&&t.isExportDeclaration()||"body"===e.key&&t.isLabeledStatement()||"declarations"===e.listKey&&t.isVariableDeclaration()&&1===t.node.declarations.length||"expression"===e.key&&t.isExpressionStatement())return t.remove(),!0},function(e,t){if(t.isSequenceExpression()&&1===t.node.expressions.length)return t.replaceWith(t.node.expressions[0]),!0},function(e,t){if(t.isBinary())return"left"===e.key?t.replaceWith(t.node.right):t.replaceWith(t.node.left),!0},function(e,t){if(t.isIfStatement()&&("consequent"===e.key||"alternate"===e.key)||"body"===e.key&&(t.isLoop()||t.isArrowFunctionExpression()))return e.replaceWith({type:"BlockStatement",body:[]}),!0}]},{}],150:[function(e,t,r){"use strict";r.__esModule=!0,r.Flow=r.Pure=r.Generated=r.User=r.Var=r.BlockScoped=r.Referenced=r.Scope=r.Expression=r.Statement=r.BindingIdentifier=r.ReferencedMemberExpression=r.ReferencedIdentifier=void 0;var n=e("babel-types"),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(n);r.ReferencedIdentifier={types:["Identifier","JSXIdentifier"],checkPath:function(e,t){var r=e.node,s=e.parent;if(!i.isIdentifier(r,t)&&!i.isJSXMemberExpression(s,t)){if(!i.isJSXIdentifier(r,t))return!1;if(n.react.isCompatTag(r.name))return!1}return i.isReferenced(r,s)}},r.ReferencedMemberExpression={types:["MemberExpression"],checkPath:function(e){var t=e.node,r=e.parent;return i.isMemberExpression(t)&&i.isReferenced(t,r)}},r.BindingIdentifier={types:["Identifier"],checkPath:function(e){var t=e.node,r=e.parent;return i.isIdentifier(t)&&i.isBinding(t,r)}},r.Statement={types:["Statement"],checkPath:function(e){var t=e.node,r=e.parent;if(i.isStatement(t)){if(i.isVariableDeclaration(t)){if(i.isForXStatement(r,{left:t}))return!1;if(i.isForStatement(r,{init:t}))return!1}return!0}return!1}},r.Expression={types:["Expression"],checkPath:function(e){return e.isIdentifier()?e.isReferencedIdentifier():i.isExpression(e.node)}},r.Scope={types:["Scopable"],checkPath:function(e){return i.isScope(e.node,e.parent)}},r.Referenced={checkPath:function(e){return i.isReferenced(e.node,e.parent)}},r.BlockScoped={checkPath:function(e){return i.isBlockScoped(e.node)}},r.Var={types:["VariableDeclaration"],checkPath:function(e){return i.isVar(e.node)}},r.User={checkPath:function(e){return e.node&&!!e.node.loc}},r.Generated={checkPath:function(e){return!e.isUser()}},r.Pure={checkPath:function(e,t){return e.scope.isPure(e.node,t)}},r.Flow={types:["Flow","ImportDeclaration","ExportDeclaration","ImportSpecifier"],checkPath:function(e){var t=e.node;return!!i.isFlow(t)||(i.isImportDeclaration(t)?"type"===t.importKind||"typeof"===t.importKind:i.isExportDeclaration(t)?"type"===t.exportKind:!!i.isImportSpecifier(t)&&("type"===t.importKind||"typeof"===t.importKind))}}},{"babel-types":169}],151:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){if(this._assertUnremoved(),e=this._verifyNodeList(e),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertBefore(e);if(this.isNodeType("Expression")||this.parentPath.isForStatement()&&"init"===this.key)this.node&&e.push(this.node),this.replaceExpressionWithStatements(e);else{if(this._maybePopFromStatements(e),Array.isArray(this.container))return this._containerInsertBefore(e);if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&e.push(this.node),this._replaceWith(S.blockStatement(e))}return[this]}function s(e,t){this.updateSiblingKeys(e,t.length);for(var r=[],n=0;n=u.length)break;p=u[c++]}else{if(c=u.next(),c.done)break;p=c.value}var h=p;h.setScope(),h.debug(function(){return"Inserted."});for(var f=o,d=Array.isArray(f),m=0,f=d?f:(0,b.default)(f);;){var y;if(d){if(m>=f.length)break;y=f[m++]}else{if(m=f.next(),m.done)break;y=m.value}y.maybeQueue(h,!0)}}return r}function a(e){return this._containerInsert(this.key,e)}function o(e){return this._containerInsert(this.key+1,e)}function u(e){var t=e[e.length-1];(S.isIdentifier(t)||S.isExpressionStatement(t)&&S.isIdentifier(t.expression))&&!this.isCompletionRecord()&&e.pop()}function l(e){if(this._assertUnremoved(),e=this._verifyNodeList(e),this.parentPath.isExpressionStatement()||this.parentPath.isLabeledStatement())return this.parentPath.insertAfter(e);if(this.isNodeType("Expression")||this.parentPath.isForStatement()&&"init"===this.key){if(this.node){var t=this.scope.generateDeclaredUidIdentifier();e.unshift(S.expressionStatement(S.assignmentExpression("=",t,this.node))),e.push(S.expressionStatement(t))}this.replaceExpressionWithStatements(e)}else{if(this._maybePopFromStatements(e),Array.isArray(this.container))return this._containerInsertAfter(e);if(!this.isStatementOrBlock())throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?");this.node&&e.unshift(this.node),this._replaceWith(S.blockStatement(e))}return[this]}function c(e,t){if(this.parent)for(var r=v.path.get(this.parent),n=0;n=e&&(i.key+=t)}}function p(e){if(!e)return[];e.constructor!==Array&&(e=[e]);for(var t=0;t0&&void 0!==arguments[0]?arguments[0]:this.scope;return new E.default(this,e).run()}r.__esModule=!0;var m=e("babel-runtime/helpers/typeof"),y=n(m),g=e("babel-runtime/core-js/get-iterator"),b=n(g);r.insertBefore=i,r._containerInsert=s,r._containerInsertBefore=a,r._containerInsertAfter=o,r._maybePopFromStatements=u,r.insertAfter=l,r.updateSiblingKeys=c,r._verifyNodeList=p,r.unshiftContainer=h,r.pushContainer=f,r.hoist=d;var v=e("../cache"),x=e("./lib/hoister"),E=n(x),A=e("./index"),D=n(A),C=e("babel-types"),S=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(C)},{"../cache":133,"./index":143,"./lib/hoister":148,"babel-runtime/core-js/get-iterator":113,"babel-runtime/helpers/typeof":131,"babel-types":169}],152:[function(e,t,r){"use strict";function n(){if(this._assertUnremoved(),this.resync(),this._callRemovalHooks())return void this._markRemoved();this.shareCommentsWithSiblings(),this._remove(),this._markRemoved()}function i(){for(var e=c.hooks,t=Array.isArray(e),r=0,e=t?e:(0,l.default)(e);;){var n;if(t){if(r>=e.length)break;n=e[r++]}else{if(r=e.next(),r.done)break;n=r.value}if(n(this,this.parentPath))return!0}}function s(){Array.isArray(this.container)?(this.container.splice(this.key,1),this.updateSiblingKeys(this.key,-1)):this._replaceWith(null)}function a(){this.shouldSkip=!0,this.removed=!0,this.node=null}function o(){if(this.removed)throw this.buildCodeFrameError("NodePath has been removed so is read-only.")}r.__esModule=!0;var u=e("babel-runtime/core-js/get-iterator"),l=function(e){return e&&e.__esModule?e:{default:e}}(u);r.remove=n,r._callRemovalHooks=i,r._remove=s,r._markRemoved=a,r._assertUnremoved=o;var c=e("./lib/removal-hooks")},{"./lib/removal-hooks":149,"babel-runtime/core-js/get-iterator":113}],153:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){this.resync(),e=this._verifyNodeList(e),x.inheritLeadingComments(e[0],this.node),x.inheritTrailingComments(e[e.length-1],this.node),this.node=this.container[this.key]=null,this.insertAfter(e),this.node?this.requeue():this.remove()}function s(e){this.resync();try{e="("+e+")",e=(0,b.parse)(e)}catch(r){var t=r.loc;throw t&&(r.message+=" - make sure this is an expression.",r.message+="\n"+(0,f.default)(e,t.line,t.column+1)),r}return e=e.program.body[0].expression,m.default.removeProperties(e),this.replaceWith(e)}function a(e){if(this.resync(),this.removed)throw new Error("You can't replace this node, we've already removed it");if(e instanceof g.default&&(e=e.node),!e)throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");if(this.node!==e){if(this.isProgram()&&!x.isProgram(e))throw new Error("You can only replace a Program root node with another Program node");if(Array.isArray(e))throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");if("string"==typeof e)throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");if(this.isNodeType("Statement")&&x.isExpression(e)&&(this.canHaveVariableDeclarationOrExpression()||this.canSwapBetweenExpressionAndStatement(e)||(e=x.expressionStatement(e))),this.isNodeType("Expression")&&x.isStatement(e)&&!this.canHaveVariableDeclarationOrExpression()&&!this.canSwapBetweenExpressionAndStatement(e))return this.replaceExpressionWithStatements([e]);var t=this.node;t&&(x.inheritsComments(e,t),x.removeComments(t)),this._replaceWith(e),this.type=e.type,this.setScope(),this.requeue()}}function o(e){if(!this.container)throw new ReferenceError("Container is falsy");this.inList?x.validate(this.parent,this.key,[e]):x.validate(this.parent,this.key,e),this.debug(function(){return"Replace with "+(e&&e.type)}),this.node=this.container[this.key]=e}function u(e){this.resync();var t=x.toSequenceExpression(e,this.scope);if(x.isSequenceExpression(t)){var r=t.expressions;r.length>=2&&this.parentPath.isExpressionStatement()&&this._maybePopFromStatements(r),1===r.length?this.replaceWith(r[0]):this.replaceWith(t)}else{if(!t){var n=x.functionExpression(null,[],x.blockStatement(e));n.shadow=!0,this.replaceWith(x.callExpression(n,[])),this.traverse(E);for(var i=this.get("callee").getCompletionRecords(),s=i,a=Array.isArray(s),o=0,s=a?s:(0,p.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u;if(l.isExpressionStatement()){var c=l.findParent(function(e){return e.isLoop()});if(c){var h=c.getData("expressionReplacementReturnUid");if(h)h=x.identifier(h.name);else{var f=this.get("callee");h=f.scope.generateDeclaredUidIdentifier("ret"),f.get("body").pushContainer("body",x.returnStatement(h)),c.setData("expressionReplacementReturnUid",h)}l.get("expression").replaceWith(x.assignmentExpression("=",h,l.node.expression))}else l.replaceWith(x.returnStatement(l.node.expression))}}return this.node}this.replaceWith(t)}}function l(e){return this.resync(),Array.isArray(e)?Array.isArray(this.container)?(e=this._verifyNodeList(e),this._containerInsertAfter(e),this.remove()):this.replaceWithMultiple(e):this.replaceWith(e)}r.__esModule=!0;var c=e("babel-runtime/core-js/get-iterator"),p=n(c);r.replaceWithMultiple=i,r.replaceWithSourceString=s,r.replaceWith=a,r._replaceWith=o,r.replaceExpressionWithStatements=u,r.replaceInline=l;var h=e("babel-code-frame"),f=n(h),d=e("../index"),m=n(d),y=e("./index"),g=n(y),b=e("babylon"),v=e("babel-types"),x=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(v),E={Function:function(e){e.skip()},VariableDeclaration:function(e){if("var"===e.node.kind){var t=e.getBindingIdentifiers();for(var r in t)e.scope.push({id:t[r]});for(var n=[],i=e.node.declarations,s=Array.isArray(i),a=0,i=s?i:(0,p.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;u.init&&n.push(x.expressionStatement(x.assignmentExpression("=",u.id,u.init)))}e.replaceWithMultiple(n)}}}},{"../index":136,"./index":143,"babel-code-frame":23,"babel-runtime/core-js/get-iterator":113,"babel-types":169,babylon:177}],154:[function(e,t,r){"use strict";r.__esModule=!0;var n=e("babel-runtime/helpers/classCallCheck"),i=function(e){return e&&e.__esModule?e:{default:e}}(n),s=function(){function e(t){var r=t.existing,n=t.identifier,s=t.scope,a=t.path,o=t.kind;(0,i.default)(this,e),this.identifier=n,this.scope=s,this.path=a,this.kind=o,this.constantViolations=[],this.constant=!0,this.referencePaths=[],this.referenced=!1,this.references=0,this.clearValue(),r&&(this.constantViolations=[].concat(r.path,r.constantViolations,this.constantViolations))}return e.prototype.deoptValue=function(){this.clearValue(),this.hasDeoptedValue=!0},e.prototype.setValue=function(e){this.hasDeoptedValue||(this.hasValue=!0,this.value=e)},e.prototype.clearValue=function(){this.hasDeoptedValue=!1,this.hasValue=!1,this.value=null},e.prototype.reassign=function(e){this.constant=!1,-1===this.constantViolations.indexOf(e)&&this.constantViolations.push(e)},e.prototype.reference=function(e){-1===this.referencePaths.indexOf(e)&&(this.referenced=!0,this.references++,this.referencePaths.push(e))},e.prototype.dereference=function(){this.references--,this.referenced=!!this.references},e}();r.default=s,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":127}],155:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e,t,r){for(var n=N.scope.get(e.node)||[],i=n,s=Array.isArray(i),a=0,i=s?i:(0,y.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;if(u.parent===t&&u.path===e)return u}n.push(r),N.scope.has(e.node)||N.scope.set(e.node,n)}function a(e,t){if(j.isModuleDeclaration(e))if(e.source)a(e.source,t);else if(e.specifiers&&e.specifiers.length)for(var r=e.specifiers,n=Array.isArray(r),i=0,r=n?r:(0,y.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var o=s;a(o,t)}else e.declaration&&a(e.declaration,t);else if(j.isModuleSpecifier(e))a(e.local,t);else if(j.isMemberExpression(e))a(e.object,t),a(e.property,t);else if(j.isIdentifier(e))t.push(e.name);else if(j.isLiteral(e))t.push(e.value);else if(j.isCallExpression(e))a(e.callee,t);else if(j.isObjectExpression(e)||j.isObjectPattern(e))for(var u=e.properties,l=Array.isArray(u),c=0,u=l?u:(0,y.default)(u);;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if(c=u.next(),c.done)break;p=c.value}var h=p;a(h.key||h.argument,t)}}r.__esModule=!0;var o=e("babel-runtime/core-js/object/keys"),u=i(o),l=e("babel-runtime/core-js/object/create"),c=i(l),p=e("babel-runtime/core-js/map"),h=i(p),f=e("babel-runtime/helpers/classCallCheck"),d=i(f),m=e("babel-runtime/core-js/get-iterator"),y=i(m),g=e("lodash/includes"),b=i(g),v=e("lodash/repeat"),x=i(v),E=e("./lib/renamer"),A=i(E),D=e("../index"),C=i(D),S=e("lodash/defaults"),_=i(S),w=e("babel-messages"),k=n(w),F=e("./binding"),T=i(F),P=e("globals"),B=i(P),O=e("babel-types"),j=n(O),N=e("../cache"),I=0,L={For:function(e){for(var t=j.FOR_INIT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,y.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i,a=e.get(s);a.isVar()&&e.scope.getFunctionParent().registerBinding("var",a)}},Declaration:function(e){e.isBlockScoped()||e.isExportDeclaration()&&e.get("declaration").isDeclaration()||e.scope.getFunctionParent().registerDeclaration(e)},ReferencedIdentifier:function(e,t){t.references.push(e)},ForXStatement:function(e,t){var r=e.get("left");(r.isPattern()||r.isIdentifier())&&t.constantViolations.push(r)},ExportDeclaration:{exit:function(e){var t=e.node,r=e.scope,n=t.declaration;if(j.isClassDeclaration(n)||j.isFunctionDeclaration(n)){var i=n.id;if(!i)return;var s=r.getBinding(i.name);s&&s.reference(e)}else if(j.isVariableDeclaration(n))for(var a=n.declarations,o=Array.isArray(a),u=0,a=o?a:(0,y.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l,p=j.getBindingIdentifiers(c);for(var h in p){var f=r.getBinding(h);f&&f.reference(e)}}}},LabeledStatement:function(e){e.scope.getProgramParent().addGlobal(e.node),e.scope.getBlockParent().registerDeclaration(e)},AssignmentExpression:function(e,t){t.assignments.push(e)},UpdateExpression:function(e,t){t.constantViolations.push(e.get("argument"))},UnaryExpression:function(e,t){"delete"===e.node.operator&&t.constantViolations.push(e.get("argument"))},BlockScoped:function(e){var t=e.scope;t.path===e&&(t=t.parent),t.getBlockParent().registerDeclaration(e)},ClassDeclaration:function(e){var t=e.node.id;if(t){var r=t.name;e.scope.bindings[r]=e.scope.getBinding(r)}},Block:function(e){for(var t=e.get("body"),r=t,n=Array.isArray(r),i=0,r=n?r:(0,y.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;a.isFunctionDeclaration()&&e.scope.getBlockParent().registerDeclaration(a)}}},M=0,R=function(){function e(t,r){if((0,d.default)(this,e),r&&r.block===t.node)return r;var n=s(t,r,this);if(n)return n;this.uid=M++,this.parent=r,this.hub=t.hub,this.parentBlock=t.parent,this.block=t.node,this.path=t,this.labels=new h.default}return e.prototype.traverse=function(e,t,r){(0,C.default)(e,t,this,r,this.path)},e.prototype.generateDeclaredUidIdentifier=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp",t=this.generateUidIdentifier(e);return this.push({id:t}),t},e.prototype.generateUidIdentifier=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp";return j.identifier(this.generateUid(e))},e.prototype.generateUid=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp";e=j.toIdentifier(e).replace(/^_+/,"").replace(/[0-9]+$/g,"");var t=void 0,r=0;do{t=this._generateUid(e,r),r++}while(this.hasLabel(t)||this.hasBinding(t)||this.hasGlobal(t)||this.hasReference(t));var n=this.getProgramParent();return n.references[t]=!0,n.uids[t]=!0,t},e.prototype._generateUid=function(e,t){var r=e;return t>1&&(r+=t),"_"+r},e.prototype.generateUidIdentifierBasedOnNode=function(e,t){var r=e;j.isAssignmentExpression(e)?r=e.left:j.isVariableDeclarator(e)?r=e.id:(j.isObjectProperty(r)||j.isObjectMethod(r))&&(r=r.key);var n=[];a(r,n);var i=n.join("$");return i=i.replace(/^_/,"")||t||"ref",this.generateUidIdentifier(i.slice(0,20))},e.prototype.isStatic=function(e){if(j.isThisExpression(e)||j.isSuper(e))return!0;if(j.isIdentifier(e)){var t=this.getBinding(e.name);return t?t.constant:this.hasBinding(e.name)}return!1},e.prototype.maybeGenerateMemoised=function(e,t){if(this.isStatic(e))return null;var r=this.generateUidIdentifierBasedOnNode(e);return t||this.push({id:r}),r},e.prototype.checkBlockScopedCollisions=function(e,t,r,n){if("param"!==t&&("hoisted"!==t||"let"!==e.kind)){if("let"===t||"let"===e.kind||"const"===e.kind||"module"===e.kind||"param"===e.kind&&("let"===t||"const"===t))throw this.hub.file.buildCodeFrameError(n,k.get("scopeDuplicateDeclaration",r),TypeError)}},e.prototype.rename=function(e,t,r){var n=this.getBinding(e);if(n)return t=t||this.generateUidIdentifier(e).name,new A.default(n,e,t).rename(r)},e.prototype._renameFromMap=function(e,t,r,n){e[t]&&(e[r]=n,e[t]=null)},e.prototype.dump=function(){var e=(0,x.default)("-",60);console.log(e);var t=this;do{console.log("#",t.block.type);for(var r in t.bindings){var n=t.bindings[r];console.log(" -",r,{constant:n.constant,references:n.references,violations:n.constantViolations.length,kind:n.kind})}}while(t=t.parent);console.log(e)},e.prototype.toArray=function(e,t){var r=this.hub.file;if(j.isIdentifier(e)){var n=this.getBinding(e.name);if(n&&n.constant&&n.path.isGenericType("Array"))return e}if(j.isArrayExpression(e))return e;if(j.isIdentifier(e,{name:"arguments"}))return j.callExpression(j.memberExpression(j.memberExpression(j.memberExpression(j.identifier("Array"),j.identifier("prototype")),j.identifier("slice")),j.identifier("call")),[e]);var i="toArray",s=[e];return!0===t?i="toConsumableArray":t&&(s.push(j.numericLiteral(t)),i="slicedToArray"),j.callExpression(r.addHelper(i),s)},e.prototype.hasLabel=function(e){return!!this.getLabel(e)},e.prototype.getLabel=function(e){return this.labels.get(e)},e.prototype.registerLabel=function(e){this.labels.set(e.node.label.name,e)},e.prototype.registerDeclaration=function(e){if(e.isLabeledStatement())this.registerLabel(e);else if(e.isFunctionDeclaration())this.registerBinding("hoisted",e.get("id"),e);else if(e.isVariableDeclaration())for(var t=e.get("declarations"),r=t,n=Array.isArray(r),i=0,r=n?r:(0,y.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;this.registerBinding(e.node.kind,a)}else if(e.isClassDeclaration())this.registerBinding("let",e);else if(e.isImportDeclaration())for(var o=e.get("specifiers"),u=o,l=Array.isArray(u),c=0,u=l?u:(0,y.default)(u);;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if(c=u.next(),c.done)break;p=c.value}var h=p;this.registerBinding("module",h)}else if(e.isExportDeclaration()){var f=e.get("declaration");(f.isClassDeclaration()||f.isFunctionDeclaration()||f.isVariableDeclaration())&&this.registerDeclaration(f)}else this.registerBinding("unknown",e)},e.prototype.buildUndefinedNode=function(){return this.hasBinding("undefined")?j.unaryExpression("void",j.numericLiteral(0),!0):j.identifier("undefined")},e.prototype.registerConstantViolation=function(e){var t=e.getBindingIdentifiers();for(var r in t){var n=this.getBinding(r) +;n&&n.reassign(e)}},e.prototype.registerBinding=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t;if(!e)throw new ReferenceError("no `kind`");if(t.isVariableDeclaration())for(var n=t.get("declarations"),i=n,s=Array.isArray(i),a=0,i=s?i:(0,y.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o;this.registerBinding(e,u)}else{var l=this.getProgramParent(),c=t.getBindingIdentifiers(!0);for(var p in c)for(var h=c[p],f=Array.isArray(h),d=0,h=f?h:(0,y.default)(h);;){var m;if(f){if(d>=h.length)break;m=h[d++]}else{if(d=h.next(),d.done)break;m=d.value}var g=m,b=this.getOwnBinding(p);if(b){if(b.identifier===g)continue;this.checkBlockScopedCollisions(b,e,p,g)}b&&b.path.isFlow()&&(b=null),l.references[p]=!0,this.bindings[p]=new T.default({identifier:g,existing:b,scope:this,path:r,kind:e})}}},e.prototype.addGlobal=function(e){this.globals[e.name]=e},e.prototype.hasUid=function(e){var t=this;do{if(t.uids[e])return!0}while(t=t.parent);return!1},e.prototype.hasGlobal=function(e){var t=this;do{if(t.globals[e])return!0}while(t=t.parent);return!1},e.prototype.hasReference=function(e){var t=this;do{if(t.references[e])return!0}while(t=t.parent);return!1},e.prototype.isPure=function(e,t){if(j.isIdentifier(e)){var r=this.getBinding(e.name);return!!r&&(!t||r.constant)}if(j.isClass(e))return!(e.superClass&&!this.isPure(e.superClass,t))&&this.isPure(e.body,t);if(j.isClassBody(e)){for(var n=e.body,i=Array.isArray(n),s=0,n=i?n:(0,y.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;if(!this.isPure(o,t))return!1}return!0}if(j.isBinary(e))return this.isPure(e.left,t)&&this.isPure(e.right,t);if(j.isArrayExpression(e)){for(var u=e.elements,l=Array.isArray(u),c=0,u=l?u:(0,y.default)(u);;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if(c=u.next(),c.done)break;p=c.value}var h=p;if(!this.isPure(h,t))return!1}return!0}if(j.isObjectExpression(e)){for(var f=e.properties,d=Array.isArray(f),m=0,f=d?f:(0,y.default)(f);;){var g;if(d){if(m>=f.length)break;g=f[m++]}else{if(m=f.next(),m.done)break;g=m.value}var b=g;if(!this.isPure(b,t))return!1}return!0}return j.isClassMethod(e)?!(e.computed&&!this.isPure(e.key,t))&&("get"!==e.kind&&"set"!==e.kind):j.isClassProperty(e)||j.isObjectProperty(e)?!(e.computed&&!this.isPure(e.key,t))&&this.isPure(e.value,t):j.isUnaryExpression(e)?this.isPure(e.argument,t):j.isPureish(e)},e.prototype.setData=function(e,t){return this.data[e]=t},e.prototype.getData=function(e){var t=this;do{var r=t.data[e];if(null!=r)return r}while(t=t.parent)},e.prototype.removeData=function(e){var t=this;do{null!=t.data[e]&&(t.data[e]=null)}while(t=t.parent)},e.prototype.init=function(){this.references||this.crawl()},e.prototype.crawl=function(){I++,this._crawl(),I--},e.prototype._crawl=function(){var e=this.path;if(this.references=(0,c.default)(null),this.bindings=(0,c.default)(null),this.globals=(0,c.default)(null),this.uids=(0,c.default)(null),this.data=(0,c.default)(null),e.isLoop())for(var t=j.FOR_INIT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,y.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i,a=e.get(s);a.isBlockScoped()&&this.registerBinding(a.node.kind,a)}if(e.isFunctionExpression()&&e.has("id")&&(e.get("id").node[j.NOT_LOCAL_BINDING]||this.registerBinding("local",e.get("id"),e)),e.isClassExpression()&&e.has("id")&&(e.get("id").node[j.NOT_LOCAL_BINDING]||this.registerBinding("local",e)),e.isFunction())for(var o=e.get("params"),u=o,l=Array.isArray(u),p=0,u=l?u:(0,y.default)(u);;){var h;if(l){if(p>=u.length)break;h=u[p++]}else{if(p=u.next(),p.done)break;h=p.value}var f=h;this.registerBinding("param",f)}if(e.isCatchClause()&&this.registerBinding("let",e),!this.getProgramParent().crawling){var d={references:[],constantViolations:[],assignments:[]};this.crawling=!0,e.traverse(L,d),this.crawling=!1;for(var m=d.assignments,g=Array.isArray(m),b=0,m=g?m:(0,y.default)(m);;){var v;if(g){if(b>=m.length)break;v=m[b++]}else{if(b=m.next(),b.done)break;v=b.value}var x=v,E=x.getBindingIdentifiers(),A=void 0;for(var D in E)x.scope.getBinding(D)||(A=A||x.scope.getProgramParent(),A.addGlobal(E[D]));x.scope.registerConstantViolation(x)}for(var C=d.references,S=Array.isArray(C),_=0,C=S?C:(0,y.default)(C);;){var w;if(S){if(_>=C.length)break;w=C[_++]}else{if(_=C.next(),_.done)break;w=_.value}var k=w,F=k.scope.getBinding(k.node.name);F?F.reference(k):k.scope.getProgramParent().addGlobal(k.node)}for(var T=d.constantViolations,P=Array.isArray(T),B=0,T=P?T:(0,y.default)(T);;){var O;if(P){if(B>=T.length)break;O=T[B++]}else{if(B=T.next(),B.done)break;O=B.value}var N=O;N.scope.registerConstantViolation(N)}}},e.prototype.push=function(e){var t=this.path;t.isBlockStatement()||t.isProgram()||(t=this.getBlockParent().path),t.isSwitchStatement()&&(t=this.getFunctionParent().path),(t.isLoop()||t.isCatchClause()||t.isFunction())&&(j.ensureBlock(t.node),t=t.get("body"));var r=e.unique,n=e.kind||"var",i=null==e._blockHoist?2:e._blockHoist,s="declaration:"+n+":"+i,a=!r&&t.getData(s);if(!a){var o=j.variableDeclaration(n,[]);o._generated=!0,o._blockHoist=i;a=t.unshiftContainer("body",[o])[0],r||t.setData(s,a)}var u=j.variableDeclarator(e.id,e.init);a.node.declarations.push(u),this.registerBinding(n,a.get("declarations").pop())},e.prototype.getProgramParent=function(){var e=this;do{if(e.path.isProgram())return e}while(e=e.parent);throw new Error("We couldn't find a Function or Program...")},e.prototype.getFunctionParent=function(){var e=this;do{if(e.path.isFunctionParent())return e}while(e=e.parent);throw new Error("We couldn't find a Function or Program...")},e.prototype.getBlockParent=function(){var e=this;do{if(e.path.isBlockParent())return e}while(e=e.parent);throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program...")},e.prototype.getAllBindings=function(){var e=(0,c.default)(null),t=this;do{(0,_.default)(e,t.bindings),t=t.parent}while(t);return e},e.prototype.getAllBindingsOfKind=function(){for(var e=(0,c.default)(null),t=arguments,r=Array.isArray(t),n=0,t=r?t:(0,y.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i,a=this;do{for(var o in a.bindings){var u=a.bindings[o];u.kind===s&&(e[o]=u)}a=a.parent}while(a)}return e},e.prototype.bindingIdentifierEquals=function(e,t){return this.getBindingIdentifier(e)===t},e.prototype.warnOnFlowBinding=function(e){return 0===I&&e&&e.path.isFlow()&&console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 6.8. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "),e},e.prototype.getBinding=function(e){var t=this;do{var r=t.getOwnBinding(e);if(r)return this.warnOnFlowBinding(r)}while(t=t.parent)},e.prototype.getOwnBinding=function(e){return this.warnOnFlowBinding(this.bindings[e])},e.prototype.getBindingIdentifier=function(e){var t=this.getBinding(e);return t&&t.identifier},e.prototype.getOwnBindingIdentifier=function(e){var t=this.bindings[e];return t&&t.identifier},e.prototype.hasOwnBinding=function(e){return!!this.getOwnBinding(e)},e.prototype.hasBinding=function(t,r){return!!t&&(!!this.hasOwnBinding(t)||(!!this.parentHasBinding(t,r)||(!!this.hasUid(t)||(!(r||!(0,b.default)(e.globals,t))||!(r||!(0,b.default)(e.contextVariables,t))))))},e.prototype.parentHasBinding=function(e,t){return this.parent&&this.parent.hasBinding(e,t)},e.prototype.moveBindingTo=function(e,t){var r=this.getBinding(e);r&&(r.scope.removeOwnBinding(e),r.scope=t,t.bindings[e]=r)},e.prototype.removeOwnBinding=function(e){delete this.bindings[e]},e.prototype.removeBinding=function(e){var t=this.getBinding(e);t&&t.scope.removeOwnBinding(e);var r=this;do{r.uids[e]&&(r.uids[e]=!1)}while(r=r.parent)},e}();R.globals=(0,u.default)(B.default.builtin),R.contextVariables=["arguments","undefined","Infinity","NaN"],r.default=R,t.exports=r.default},{"../cache":133,"../index":136,"./binding":154,"./lib/renamer":156,"babel-messages":103,"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/map":115,"babel-runtime/core-js/object/create":118,"babel-runtime/core-js/object/keys":120,"babel-runtime/helpers/classCallCheck":127,"babel-types":169,globals:303,"lodash/defaults":484,"lodash/includes":496,"lodash/repeat":519}],156:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=e("babel-runtime/helpers/classCallCheck"),s=n(i),a=e("../binding"),o=(n(a),e("babel-types")),u=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(o),l={ReferencedIdentifier:function(e,t){var r=e.node;r.name===t.oldName&&(r.name=t.newName)},Scope:function(e,t){e.scope.bindingIdentifierEquals(t.oldName,t.binding.identifier)||e.skip()},"AssignmentExpression|Declaration":function(e,t){var r=e.getOuterBindingIdentifiers();for(var n in r)n===t.oldName&&(r[n].name=t.newName)}},c=function(){function e(t,r,n){(0,s.default)(this,e),this.newName=n,this.oldName=r,this.binding=t}return e.prototype.maybeConvertFromExportDeclaration=function(e){var t=e.parentPath.isExportDeclaration()&&e.parentPath;if(t){var r=t.isExportDefaultDeclaration();r&&(e.isFunctionDeclaration()||e.isClassDeclaration())&&!e.node.id&&(e.node.id=e.scope.generateUidIdentifier("default"));var n=e.getOuterBindingIdentifiers(),i=[];for(var s in n){var a=s===this.oldName?this.newName:s,o=r?"default":s;i.push(u.exportSpecifier(u.identifier(a),u.identifier(o)))}if(i.length){var l=u.exportNamedDeclaration(null,i);e.isFunctionDeclaration()&&(l._blockHoist=3),t.insertAfter(l),t.replaceWith(e.node)}}},e.prototype.maybeConvertFromClassFunctionDeclaration=function(e){},e.prototype.maybeConvertFromClassFunctionExpression=function(e){},e.prototype.rename=function(e){var t=this.binding,r=this.oldName,n=this.newName,i=t.scope,s=t.path,a=s.find(function(e){return e.isDeclaration()||e.isFunctionExpression()});a&&this.maybeConvertFromExportDeclaration(a),i.traverse(e||i.block,l,this),e||(i.removeOwnBinding(r),i.bindings[n]=t,this.binding.identifier.name=n),t.type,a&&(this.maybeConvertFromClassFunctionDeclaration(a),this.maybeConvertFromClassFunctionExpression(a))},e}();r.default=c,t.exports=r.default},{"../binding":154,"babel-runtime/helpers/classCallCheck":127,"babel-types":169}],157:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e){if(e._exploded)return e;e._exploded=!0;for(var t in e)if(!f(t)){var r=t.split("|");if(1!==r.length){var n=e[t];delete e[t];for(var i=r,s=Array.isArray(i),o=0,i=s?i:(0,x.default)(i);;){var u;if(s){if(o>=i.length)break;u=i[o++]}else{if(o=i.next(),o.done)break;u=o.value}var l=u;e[l]=n}}}a(e),delete e.__esModule,c(e),p(e);for(var m=(0,b.default)(e),y=Array.isArray(m),g=0,m=y?m:(0,x.default)(m);;){var v;if(y){if(g>=m.length)break;v=m[g++]}else{if(g=m.next(),g.done)break;v=g.value}var E=v;if(!f(E)){var D=A[E];if(D){var C=e[E];for(var S in C)C[S]=h(D,C[S]);if(delete e[E],D.types)for(var w=D.types,F=Array.isArray(w),T=0,w=F?w:(0,x.default)(w);;){var P;if(F){if(T>=w.length)break;P=w[T++]}else{if(T=w.next(),T.done)break;P=T.value}var B=P;e[B]?d(e[B],C):e[B]=C}else d(e,C)}}}for(var O in e)if(!f(O)){var j=e[O],N=_.FLIPPED_ALIAS_KEYS[O],I=_.DEPRECATED_KEYS[O];if(I&&(console.trace("Visitor defined for "+O+" but it has been renamed to "+I),N=[I]),N){delete e[O];for(var L=N,M=Array.isArray(L),R=0,L=M?L:(0,x.default)(L);;){var U;if(M){if(R>=L.length)break;U=L[R++]}else{if(R=L.next(),R.done)break;U=R.value}var V=U,q=e[V];q?d(q,j):e[V]=(0,k.default)(j)}}}for(var G in e)f(G)||p(e[G]);return e}function a(e){if(!e._verified){if("function"==typeof e)throw new Error(C.get("traverseVerifyRootFunction"));for(var t in e)if("enter"!==t&&"exit"!==t||o(t,e[t]),!f(t)){if(_.TYPES.indexOf(t)<0)throw new Error(C.get("traverseVerifyNodeType",t));var r=e[t];if("object"===(void 0===r?"undefined":(0,y.default)(r)))for(var n in r){if("enter"!==n&&"exit"!==n)throw new Error(C.get("traverseVerifyVisitorProperty",t,n));o(t+"."+n,r[n])}}e._verified=!0}}function o(e,t){for(var r=[].concat(t),n=r,i=Array.isArray(n),s=0,n=i?n:(0,x.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;if("function"!=typeof o)throw new TypeError("Non-function found defined in "+e+" with type "+(void 0===o?"undefined":(0,y.default)(o)))}}function u(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments[2],n={},i=0;i","<",">=","<="]),a=r.EQUALITY_BINARY_OPERATORS=["==","===","!=","!=="],o=r.COMPARISON_BINARY_OPERATORS=[].concat(a,["in","instanceof"]),u=r.BOOLEAN_BINARY_OPERATORS=[].concat(o,s),l=r.NUMBER_BINARY_OPERATORS=["-","/","%","*","**","&","|",">>",">>>","<<","^"],c=(r.BINARY_OPERATORS=["+"].concat(l,u),r.BOOLEAN_UNARY_OPERATORS=["delete","!"]),p=r.NUMBER_UNARY_OPERATORS=["+","-","++","--","~"],h=r.STRING_UNARY_OPERATORS=["typeof"];r.UNARY_OPERATORS=["void"].concat(c,p,h),r.INHERIT_KEYS={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]},r.BLOCK_SCOPED_SYMBOL=(0,i.default)("var used to be block scoped"),r.NOT_LOCAL_BINDING=(0,i.default)("should not be considered a local binding")},{"babel-runtime/core-js/symbol/for":123}],159:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.key||e.property;return e.computed||C.isIdentifier(t)&&(t=C.stringLiteral(t.name)),t}function s(e,t){function r(e){for(var s=!1,a=[],o=e,u=Array.isArray(o),l=0,o=u?o:(0,b.default)(o);;){var c;if(u){if(l>=o.length)break;c=o[l++]}else{if(l=o.next(),l.done)break;c=l.value}var p=c;if(C.isExpression(p))a.push(p);else if(C.isExpressionStatement(p))a.push(p.expression);else{if(C.isVariableDeclaration(p)){if("var"!==p.kind)return i=!0;for(var h=p.declarations,f=Array.isArray(h),d=0,h=f?h:(0,b.default)(h);;){var m;if(f){if(d>=h.length)break;m=h[d++]}else{if(d=h.next(),d.done)break;m=d.value}var y=m,g=C.getBindingIdentifiers(y);for(var v in g)n.push({kind:p.kind,id:g[v]});y.init&&a.push(C.assignmentExpression("=",y.id,y.init))}s=!0;continue}if(C.isIfStatement(p)){var x=p.consequent?r([p.consequent]):t.buildUndefinedNode(),E=p.alternate?r([p.alternate]):t.buildUndefinedNode();if(!x||!E)return i=!0;a.push(C.conditionalExpression(p.test,x,E))}else{if(!C.isBlockStatement(p)){if(C.isEmptyStatement(p)){s=!0;continue}return i=!0}a.push(r(p.body))}}s=!1}return(s||0===a.length)&&a.push(t.buildUndefinedNode()),1===a.length?a[0]:C.sequenceExpression(a)}if(e&&e.length){var n=[],i=!1,s=r(e);if(!i){for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:e.key,r=void 0;return"method"===e.kind?a.increment()+"":(r=C.isIdentifier(t)?t.name:C.isStringLiteral(t)?(0,y.default)(t.value):(0,y.default)(C.removePropertiesDeep(C.cloneDeep(t))),e.computed&&(r="["+r+"]"),e.static&&(r="static:"+r),r)}function o(e){return e+="",e=e.replace(/[^a-zA-Z0-9$_]/g,"-"),e=e.replace(/^[-0-9]+/,""),e=e.replace(/[-\s]+(.)?/g,function(e,t){return t?t.toUpperCase():""}),C.isValidIdentifier(e)||(e="_"+e),e||"_"}function u(e){return e=o(e),"eval"!==e&&"arguments"!==e||(e="_"+e),e}function l(e,t){if(C.isStatement(e))return e;var r=!1,n=void 0;if(C.isClass(e))r=!0,n="ClassDeclaration";else if(C.isFunction(e))r=!0,n="FunctionDeclaration";else if(C.isAssignmentExpression(e))return C.expressionStatement(e);if(r&&!e.id&&(n=!1),!n){if(t)return!1;throw new Error("cannot turn "+e.type+" to a statement")}return e.type=n,e}function c(e){if(C.isExpressionStatement(e)&&(e=e.expression),C.isExpression(e))return e;if(C.isClass(e)?e.type="ClassExpression":C.isFunction(e)&&(e.type="FunctionExpression"),!C.isExpression(e))throw new Error("cannot turn "+e.type+" to an expression");return e}function p(e,t){return C.isBlockStatement(e)?e:(C.isEmptyStatement(e)&&(e=[]),Array.isArray(e)||(C.isStatement(e)||(e=C.isFunction(t)?C.returnStatement(e):C.expressionStatement(e)),e=[e]),C.blockStatement(e))}function h(e){if(void 0===e)return C.identifier("undefined");if(!0===e||!1===e)return C.booleanLiteral(e);if(null===e)return C.nullLiteral();if("string"==typeof e)return C.stringLiteral(e);if("number"==typeof e)return C.numericLiteral(e);if((0,A.default)(e)){var t=e.source,r=e.toString().match(/\/([a-z]+|)$/)[1];return C.regExpLiteral(t,r)}if(Array.isArray(e))return C.arrayExpression(e.map(C.valueToNode));if((0,x.default)(e)){var n=[];for(var i in e){var s=void 0;s=C.isValidIdentifier(i)?C.identifier(i):C.stringLiteral(i),n.push(C.objectProperty(s,C.valueToNode(e[i])))}return C.objectExpression(n)}throw new Error("don't know how to turn this value into a node")}r.__esModule=!0;var f=e("babel-runtime/core-js/number/max-safe-integer"),d=n(f),m=e("babel-runtime/core-js/json/stringify"),y=n(m),g=e("babel-runtime/core-js/get-iterator"),b=n(g);r.toComputedKey=i,r.toSequenceExpression=s,r.toKeyAlias=a,r.toIdentifier=o,r.toBindingIdentifierName=u,r.toStatement=l,r.toExpression=c,r.toBlock=p,r.valueToNode=h;var v=e("lodash/isPlainObject"),x=n(v),E=e("lodash/isRegExp"),A=n(E),D=e("./index"),C=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(D);a.uid=0,a.increment=function(){return a.uid>=d.default?a.uid=0:a.uid++}},{"./index":169,"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/json/stringify":114,"babel-runtime/core-js/number/max-safe-integer":116,"lodash/isPlainObject":507,"lodash/isRegExp":508}],160:[function(e,t,r){"use strict";var n=e("../index"),i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(n),s=e("../constants"),a=e("./index"),o=function(e){return e&&e.__esModule?e:{default:e}}(a);(0,o.default)("ArrayExpression",{fields:{elements:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeOrValueType)("null","Expression","SpreadElement"))),default:[]}},visitor:["elements"],aliases:["Expression"]}),(0,o.default)("AssignmentExpression",{fields:{operator:{validate:(0,a.assertValueType)("string")},left:{validate:(0,a.assertNodeType)("LVal")},right:{validate:(0,a.assertNodeType)("Expression")}},builder:["operator","left","right"],visitor:["left","right"],aliases:["Expression"]}),(0,o.default)("BinaryExpression",{builder:["operator","left","right"],fields:{operator:{validate:a.assertOneOf.apply(void 0,s.BINARY_OPERATORS)},left:{validate:(0,a.assertNodeType)("Expression")},right:{validate:(0,a.assertNodeType)("Expression")}},visitor:["left","right"],aliases:["Binary","Expression"]}),(0,o.default)("Directive",{visitor:["value"],fields:{value:{validate:(0,a.assertNodeType)("DirectiveLiteral")}}}),(0,o.default)("DirectiveLiteral",{builder:["value"],fields:{value:{validate:(0,a.assertValueType)("string")}}}),(0,o.default)("BlockStatement",{builder:["body","directives"],visitor:["directives","body"],fields:{directives:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Directive"))),default:[]},body:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Statement")))}},aliases:["Scopable","BlockParent","Block","Statement"]}),(0,o.default)("BreakStatement",{visitor:["label"],fields:{label:{validate:(0,a.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),(0,o.default)("CallExpression",{visitor:["callee","arguments"],fields:{callee:{validate:(0,a.assertNodeType)("Expression")},arguments:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Expression","SpreadElement")))}},aliases:["Expression"]}),(0,o.default)("CatchClause",{visitor:["param","body"],fields:{param:{validate:(0,a.assertNodeType)("Identifier")},body:{validate:(0,a.assertNodeType)("BlockStatement")}},aliases:["Scopable"]}),(0,o.default)("ConditionalExpression",{visitor:["test","consequent","alternate"],fields:{test:{validate:(0,a.assertNodeType)("Expression")},consequent:{validate:(0,a.assertNodeType)("Expression")},alternate:{validate:(0,a.assertNodeType)("Expression")}},aliases:["Expression","Conditional"]}),(0,o.default)("ContinueStatement",{visitor:["label"],fields:{label:{validate:(0,a.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),(0,o.default)("DebuggerStatement",{aliases:["Statement"]}),(0,o.default)("DoWhileStatement",{visitor:["test","body"],fields:{test:{validate:(0,a.assertNodeType)("Expression")},body:{validate:(0,a.assertNodeType)("Statement")}},aliases:["Statement","BlockParent","Loop","While","Scopable"]}),(0,o.default)("EmptyStatement",{aliases:["Statement"]}),(0,o.default)("ExpressionStatement",{visitor:["expression"],fields:{expression:{validate:(0,a.assertNodeType)("Expression")}},aliases:["Statement","ExpressionWrapper"]}),(0,o.default)("File",{builder:["program","comments","tokens"],visitor:["program"],fields:{program:{validate:(0,a.assertNodeType)("Program")}}}),(0,o.default)("ForInStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,a.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,a.assertNodeType)("Expression")},body:{validate:(0,a.assertNodeType)("Statement")}}}),(0,o.default)("ForStatement",{visitor:["init","test","update","body"],aliases:["Scopable","Statement","For","BlockParent","Loop"],fields:{init:{validate:(0,a.assertNodeType)("VariableDeclaration","Expression"),optional:!0},test:{validate:(0,a.assertNodeType)("Expression"),optional:!0},update:{validate:(0,a.assertNodeType)("Expression"),optional:!0},body:{validate:(0,a.assertNodeType)("Statement")}}}),(0,o.default)("FunctionDeclaration",{builder:["id","params","body","generator","async"],visitor:["id","params","body","returnType","typeParameters"],fields:{id:{validate:(0,a.assertNodeType)("Identifier")},params:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("LVal")))},body:{validate:(0,a.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,a.assertValueType)("boolean")},async:{default:!1,validate:(0,a.assertValueType)("boolean")}},aliases:["Scopable","Function","BlockParent","FunctionParent","Statement","Pureish","Declaration"]}),(0,o.default)("FunctionExpression",{inherits:"FunctionDeclaration",aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{id:{validate:(0,a.assertNodeType)("Identifier"),optional:!0},params:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("LVal")))},body:{validate:(0,a.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,a.assertValueType)("boolean")},async:{default:!1,validate:(0,a.assertValueType)("boolean")}}}),(0,o.default)("Identifier",{builder:["name"],visitor:["typeAnnotation"],aliases:["Expression","LVal"],fields:{name:{validate:function(e,t,r){i.isValidIdentifier(r)}},decorators:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Decorator")))}}}),(0,o.default)("IfStatement",{visitor:["test","consequent","alternate"],aliases:["Statement","Conditional"],fields:{test:{validate:(0,a.assertNodeType)("Expression")},consequent:{validate:(0,a.assertNodeType)("Statement")},alternate:{optional:!0,validate:(0,a.assertNodeType)("Statement")}}}),(0,o.default)("LabeledStatement",{visitor:["label","body"],aliases:["Statement"],fields:{label:{validate:(0,a.assertNodeType)("Identifier")},body:{validate:(0,a.assertNodeType)("Statement")}}}),(0,o.default)("StringLiteral",{builder:["value"],fields:{value:{validate:(0,a.assertValueType)("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,o.default)("NumericLiteral",{builder:["value"],deprecatedAlias:"NumberLiteral",fields:{value:{validate:(0,a.assertValueType)("number")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,o.default)("NullLiteral",{aliases:["Expression","Pureish","Literal","Immutable"]}),(0,o.default)("BooleanLiteral",{builder:["value"],fields:{value:{validate:(0,a.assertValueType)("boolean")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,o.default)("RegExpLiteral",{builder:["pattern","flags"],deprecatedAlias:"RegexLiteral",aliases:["Expression","Literal"],fields:{pattern:{validate:(0,a.assertValueType)("string")},flags:{validate:(0,a.assertValueType)("string"),default:""}}}),(0,o.default)("LogicalExpression",{builder:["operator","left","right"],visitor:["left","right"],aliases:["Binary","Expression"],fields:{operator:{validate:a.assertOneOf.apply(void 0,s.LOGICAL_OPERATORS)},left:{validate:(0,a.assertNodeType)("Expression")},right:{validate:(0,a.assertNodeType)("Expression")}}}),(0,o.default)("MemberExpression",{builder:["object","property","computed"],visitor:["object","property"],aliases:["Expression","LVal"],fields:{object:{validate:(0,a.assertNodeType)("Expression")},property:{validate:function(e,t,r){var n=e.computed?"Expression":"Identifier";(0,a.assertNodeType)(n)(e,t,r)}},computed:{default:!1}}}),(0,o.default)("NewExpression",{visitor:["callee","arguments"],aliases:["Expression"],fields:{callee:{validate:(0,a.assertNodeType)("Expression")},arguments:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Expression","SpreadElement")))}}}),(0,o.default)("Program",{visitor:["directives","body"],builder:["body","directives"],fields:{directives:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Directive"))),default:[]},body:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Statement")))}},aliases:["Scopable","BlockParent","Block","FunctionParent"]}),(0,o.default)("ObjectExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("ObjectMethod","ObjectProperty","SpreadProperty")))}}}),(0,o.default)("ObjectMethod",{builder:["kind","key","params","body","computed"],fields:{kind:{validate:(0,a.chain)((0,a.assertValueType)("string"),(0,a.assertOneOf)("method","get","set")),default:"method"},computed:{validate:(0,a.assertValueType)("boolean"),default:!1},key:{validate:function(e,t,r){var n=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];a.assertNodeType.apply(void 0,n)(e,t,r)}},decorators:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Decorator")))},body:{validate:(0,a.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,a.assertValueType)("boolean")},async:{default:!1,validate:(0,a.assertValueType)("boolean")}},visitor:["key","params","body","decorators","returnType","typeParameters"],aliases:["UserWhitespacable","Function","Scopable","BlockParent","FunctionParent","Method","ObjectMember"]}),(0,o.default)("ObjectProperty",{builder:["key","value","computed","shorthand","decorators"],fields:{computed:{validate:(0,a.assertValueType)("boolean"),default:!1},key:{validate:function(e,t,r){var n=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];a.assertNodeType.apply(void 0,n)(e,t,r)}},value:{validate:(0,a.assertNodeType)("Expression")},shorthand:{validate:(0,a.assertValueType)("boolean"),default:!1},decorators:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Decorator"))),optional:!0}},visitor:["key","value","decorators"],aliases:["UserWhitespacable","Property","ObjectMember"]}),(0,o.default)("RestElement",{visitor:["argument","typeAnnotation"],aliases:["LVal"],fields:{argument:{validate:(0,a.assertNodeType)("LVal")},decorators:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Decorator")))}}}),(0,o.default)("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,a.assertNodeType)("Expression"),optional:!0}}}),(0,o.default)("SequenceExpression",{visitor:["expressions"],fields:{expressions:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Expression")))}},aliases:["Expression"]}),(0,o.default)("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:(0,a.assertNodeType)("Expression"),optional:!0},consequent:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("Statement")))}}}),(0,o.default)("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:(0,a.assertNodeType)("Expression")},cases:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("SwitchCase")))}}}),(0,o.default)("ThisExpression",{aliases:["Expression"]}),(0,o.default)("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,a.assertNodeType)("Expression")}}}),(0,o.default)("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{body:{validate:(0,a.assertNodeType)("BlockStatement")},handler:{optional:!0, +handler:(0,a.assertNodeType)("BlockStatement")},finalizer:{optional:!0,validate:(0,a.assertNodeType)("BlockStatement")}}}),(0,o.default)("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!0},argument:{validate:(0,a.assertNodeType)("Expression")},operator:{validate:a.assertOneOf.apply(void 0,s.UNARY_OPERATORS)}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),(0,o.default)("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!1},argument:{validate:(0,a.assertNodeType)("Expression")},operator:{validate:a.assertOneOf.apply(void 0,s.UPDATE_OPERATORS)}},visitor:["argument"],aliases:["Expression"]}),(0,o.default)("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{kind:{validate:(0,a.chain)((0,a.assertValueType)("string"),(0,a.assertOneOf)("var","let","const"))},declarations:{validate:(0,a.chain)((0,a.assertValueType)("array"),(0,a.assertEach)((0,a.assertNodeType)("VariableDeclarator")))}}}),(0,o.default)("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:(0,a.assertNodeType)("LVal")},init:{optional:!0,validate:(0,a.assertNodeType)("Expression")}}}),(0,o.default)("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:(0,a.assertNodeType)("Expression")},body:{validate:(0,a.assertNodeType)("BlockStatement","Statement")}}}),(0,o.default)("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{object:(0,a.assertNodeType)("Expression")},body:{validate:(0,a.assertNodeType)("BlockStatement","Statement")}}})},{"../constants":158,"../index":169,"./index":164}],161:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("AssignmentPattern",{visitor:["left","right"],aliases:["Pattern","LVal"],fields:{left:{validate:(0,n.assertNodeType)("Identifier")},right:{validate:(0,n.assertNodeType)("Expression")},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ArrayPattern",{visitor:["elements","typeAnnotation"],aliases:["Pattern","LVal"],fields:{elements:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Expression")))},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ArrowFunctionExpression",{builder:["params","body","async"],visitor:["params","body","returnType","typeParameters"],aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{params:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("LVal")))},body:{validate:(0,n.assertNodeType)("BlockStatement","Expression")},async:{validate:(0,n.assertValueType)("boolean"),default:!1}}}),(0,i.default)("ClassBody",{visitor:["body"],fields:{body:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("ClassMethod","ClassProperty")))}}}),(0,i.default)("ClassDeclaration",{builder:["id","superClass","body","decorators"],visitor:["id","body","superClass","mixins","typeParameters","superTypeParameters","implements","decorators"],aliases:["Scopable","Class","Statement","Declaration","Pureish"],fields:{id:{validate:(0,n.assertNodeType)("Identifier")},body:{validate:(0,n.assertNodeType)("ClassBody")},superClass:{optional:!0,validate:(0,n.assertNodeType)("Expression")},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ClassExpression",{inherits:"ClassDeclaration",aliases:["Scopable","Class","Expression","Pureish"],fields:{id:{optional:!0,validate:(0,n.assertNodeType)("Identifier")},body:{validate:(0,n.assertNodeType)("ClassBody")},superClass:{optional:!0,validate:(0,n.assertNodeType)("Expression")},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("ExportAllDeclaration",{visitor:["source"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{source:{validate:(0,n.assertNodeType)("StringLiteral")}}}),(0,i.default)("ExportDefaultDeclaration",{visitor:["declaration"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{declaration:{validate:(0,n.assertNodeType)("FunctionDeclaration","ClassDeclaration","Expression")}}}),(0,i.default)("ExportNamedDeclaration",{visitor:["declaration","specifiers","source"],aliases:["Statement","Declaration","ModuleDeclaration","ExportDeclaration"],fields:{declaration:{validate:(0,n.assertNodeType)("Declaration"),optional:!0},specifiers:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("ExportSpecifier")))},source:{validate:(0,n.assertNodeType)("StringLiteral"),optional:!0}}}),(0,i.default)("ExportSpecifier",{visitor:["local","exported"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")},exported:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ForOfStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,n.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,n.assertNodeType)("Expression")},body:{validate:(0,n.assertNodeType)("Statement")}}}),(0,i.default)("ImportDeclaration",{visitor:["specifiers","source"],aliases:["Statement","Declaration","ModuleDeclaration"],fields:{specifiers:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("ImportSpecifier","ImportDefaultSpecifier","ImportNamespaceSpecifier")))},source:{validate:(0,n.assertNodeType)("StringLiteral")}}}),(0,i.default)("ImportDefaultSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ImportNamespaceSpecifier",{visitor:["local"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ImportSpecifier",{visitor:["local","imported"],aliases:["ModuleSpecifier"],fields:{local:{validate:(0,n.assertNodeType)("Identifier")},imported:{validate:(0,n.assertNodeType)("Identifier")},importKind:{validate:(0,n.assertOneOf)(null,"type","typeof")}}}),(0,i.default)("MetaProperty",{visitor:["meta","property"],aliases:["Expression"],fields:{meta:{validate:(0,n.assertValueType)("string")},property:{validate:(0,n.assertValueType)("string")}}}),(0,i.default)("ClassMethod",{aliases:["Function","Scopable","BlockParent","FunctionParent","Method"],builder:["kind","key","params","body","computed","static"],visitor:["key","params","body","decorators","returnType","typeParameters"],fields:{kind:{validate:(0,n.chain)((0,n.assertValueType)("string"),(0,n.assertOneOf)("get","set","method","constructor")),default:"method"},computed:{default:!1,validate:(0,n.assertValueType)("boolean")},static:{default:!1,validate:(0,n.assertValueType)("boolean")},key:{validate:function(e,t,r){var i=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];n.assertNodeType.apply(void 0,i)(e,t,r)}},params:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("LVal")))},body:{validate:(0,n.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,n.assertValueType)("boolean")},async:{default:!1,validate:(0,n.assertValueType)("boolean")}}}),(0,i.default)("ObjectPattern",{visitor:["properties","typeAnnotation"],aliases:["Pattern","LVal"],fields:{properties:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("RestProperty","Property")))},decorators:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Decorator")))}}}),(0,i.default)("SpreadElement",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("Super",{aliases:["Expression"]}),(0,i.default)("TaggedTemplateExpression",{visitor:["tag","quasi"],aliases:["Expression"],fields:{tag:{validate:(0,n.assertNodeType)("Expression")},quasi:{validate:(0,n.assertNodeType)("TemplateLiteral")}}}),(0,i.default)("TemplateElement",{builder:["value","tail"],fields:{value:{},tail:{validate:(0,n.assertValueType)("boolean"),default:!1}}}),(0,i.default)("TemplateLiteral",{visitor:["quasis","expressions"],aliases:["Expression","Literal"],fields:{quasis:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("TemplateElement")))},expressions:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("Expression")))}}}),(0,i.default)("YieldExpression",{builder:["argument","delegate"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{delegate:{validate:(0,n.assertValueType)("boolean"),default:!1},argument:{optional:!0,validate:(0,n.assertNodeType)("Expression")}}})},{"./index":164}],162:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("AwaitExpression",{builder:["argument"],visitor:["argument"],aliases:["Expression","Terminatorless"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("ForAwaitStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,n.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,n.assertNodeType)("Expression")},body:{validate:(0,n.assertNodeType)("Statement")}}}),(0,i.default)("BindExpression",{visitor:["object","callee"],aliases:["Expression"],fields:{}}),(0,i.default)("Import",{aliases:["Expression"]}),(0,i.default)("Decorator",{visitor:["expression"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("DoExpression",{visitor:["body"],aliases:["Expression"],fields:{body:{validate:(0,n.assertNodeType)("BlockStatement")}}}),(0,i.default)("ExportDefaultSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("ExportNamespaceSpecifier",{visitor:["exported"],aliases:["ModuleSpecifier"],fields:{exported:{validate:(0,n.assertNodeType)("Identifier")}}}),(0,i.default)("RestProperty",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:(0,n.assertNodeType)("LVal")}}}),(0,i.default)("SpreadProperty",{visitor:["argument"],aliases:["UnaryLike"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}})},{"./index":164}],163:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("AnyTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("ArrayTypeAnnotation",{visitor:["elementType"],aliases:["Flow"],fields:{}}),(0,i.default)("BooleanTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("BooleanLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),(0,i.default)("NullLiteralTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("ClassImplements",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),(0,i.default)("ClassProperty",{visitor:["key","value","typeAnnotation","decorators"],builder:["key","value","typeAnnotation","decorators","computed"],aliases:["Property"],fields:{computed:{validate:(0,n.assertValueType)("boolean"),default:!1}}}),(0,i.default)("DeclareClass",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareFunction",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareInterface",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareModule",{visitor:["id","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareModuleExports",{visitor:["typeAnnotation"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareTypeAlias",{visitor:["id","typeParameters","right"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareVariable",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("ExistentialTypeParam",{aliases:["Flow"]}),(0,i.default)("FunctionTypeAnnotation",{visitor:["typeParameters","params","rest","returnType"],aliases:["Flow"],fields:{}}),(0,i.default)("FunctionTypeParam",{visitor:["name","typeAnnotation"],aliases:["Flow"],fields:{}}),(0,i.default)("GenericTypeAnnotation",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),(0,i.default)("InterfaceExtends",{visitor:["id","typeParameters"],aliases:["Flow"],fields:{}}),(0,i.default)("InterfaceDeclaration",{visitor:["id","typeParameters","extends","body"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("IntersectionTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),(0,i.default)("MixedTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"]}),(0,i.default)("EmptyTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"]}),(0,i.default)("NullableTypeAnnotation",{visitor:["typeAnnotation"],aliases:["Flow"],fields:{}}),(0,i.default)("NumericLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),(0,i.default)("NumberTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("StringLiteralTypeAnnotation",{aliases:["Flow"],fields:{}}),(0,i.default)("StringTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("ThisTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}}),(0,i.default)("TupleTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeofTypeAnnotation",{visitor:["argument"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeAlias",{visitor:["id","typeParameters","right"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("TypeAnnotation",{visitor:["typeAnnotation"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeCastExpression",{visitor:["expression","typeAnnotation"],aliases:["Flow","ExpressionWrapper","Expression"],fields:{}}),(0,i.default)("TypeParameter",{visitor:["bound"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeParameterDeclaration",{visitor:["params"],aliases:["Flow"],fields:{}}),(0,i.default)("TypeParameterInstantiation",{visitor:["params"],aliases:["Flow"],fields:{}}),(0,i.default)("ObjectTypeAnnotation",{visitor:["properties","indexers","callProperties"],aliases:["Flow"],fields:{}}),(0,i.default)("ObjectTypeCallProperty",{visitor:["value"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("ObjectTypeIndexer",{visitor:["id","key","value"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("ObjectTypeProperty",{visitor:["key","value"],aliases:["Flow","UserWhitespacable"],fields:{}}),(0,i.default)("QualifiedTypeIdentifier",{visitor:["id","qualification"],aliases:["Flow"],fields:{}}),(0,i.default)("UnionTypeAnnotation",{visitor:["types"],aliases:["Flow"],fields:{}}),(0,i.default)("VoidTypeAnnotation",{aliases:["Flow","FlowBaseAnnotation"],fields:{}})},{"./index":164}],164:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){return Array.isArray(e)?"array":null===e?"null":void 0===e?"undefined":void 0===e?"undefined":(0,g.default)(e)}function s(e){function t(t,r,n){if(Array.isArray(n))for(var i=0;i=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u;if(v.is(l,n)){i=!0;break}}if(!i)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,m.default)(r)+" but instead got "+(0,m.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;if(i(n)===c||v.is(c,n)){s=!0;break}}if(!s)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,m.default)(r)+" but instead got "+(0,m.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=e.length)break;i=e[n++]}else{if(n=e.next(),n.done)break;i=n.value}i.apply(void 0,arguments)}}for(var t=arguments.length,r=Array(t),n=0;n1&&void 0!==arguments[1]?arguments[1]:{},r=t.inherits&&S[t.inherits]||{};t.fields=t.fields||r.fields||{},t.visitor=t.visitor||r.visitor||[],t.aliases=t.aliases||r.aliases||[],t.builder=t.builder||r.builder||t.visitor||[],t.deprecatedAlias&&(C[t.deprecatedAlias]=e);for(var n=t.visitor.concat(t.builder),s=Array.isArray(n),a=0,n=s?n:(0,f.default)(n);;){var o;if(s){if(a>=n.length)break;o=n[a++]}else{if(a=n.next(),a.done)break;o=a.value}var u=o;t.fields[u]=t.fields[u]||{}}for(var c in t.fields){var p=t.fields[c];-1===t.builder.indexOf(c)&&(p.optional=!0),void 0===p.default?p.default=null:p.validate||(p.validate=l(i(p.default)))}x[e]=t.visitor,D[e]=t.builder,A[e]=t.fields,E[e]=t.aliases,S[e]=t}r.__esModule=!0,r.DEPRECATED_KEYS=r.BUILDER_KEYS=r.NODE_FIELDS=r.ALIAS_KEYS=r.VISITOR_KEYS=void 0;var h=e("babel-runtime/core-js/get-iterator"),f=n(h),d=e("babel-runtime/core-js/json/stringify"),m=n(d),y=e("babel-runtime/helpers/typeof"),g=n(y);r.assertEach=s,r.assertOneOf=a,r.assertNodeType=o,r.assertNodeOrValueType=u,r.assertValueType=l,r.chain=c,r.default=p;var b=e("../index"),v=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(b),x=r.VISITOR_KEYS={},E=r.ALIAS_KEYS={},A=r.NODE_FIELDS={},D=r.BUILDER_KEYS={},C=r.DEPRECATED_KEYS={},S={}},{"../index":169,"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/json/stringify":114,"babel-runtime/helpers/typeof":131}],165:[function(e,t,r){"use strict";e("./index"),e("./core"),e("./es2015"),e("./flow"),e("./jsx"),e("./misc"),e("./experimental")},{"./core":160,"./es2015":161,"./experimental":162,"./flow":163,"./index":164,"./jsx":166,"./misc":167}],166:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("JSXAttribute",{visitor:["name","value"],aliases:["JSX","Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXNamespacedName")},value:{optional:!0,validate:(0,n.assertNodeType)("JSXElement","StringLiteral","JSXExpressionContainer")}}}),(0,i.default)("JSXClosingElement",{visitor:["name"],aliases:["JSX","Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXMemberExpression")}}}),(0,i.default)("JSXElement",{builder:["openingElement","closingElement","children","selfClosing"],visitor:["openingElement","children","closingElement"],aliases:["JSX","Immutable","Expression"],fields:{openingElement:{validate:(0,n.assertNodeType)("JSXOpeningElement")},closingElement:{optional:!0,validate:(0,n.assertNodeType)("JSXClosingElement")},children:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("JSXText","JSXExpressionContainer","JSXSpreadChild","JSXElement")))}}}),(0,i.default)("JSXEmptyExpression",{aliases:["JSX","Expression"]}),(0,i.default)("JSXExpressionContainer",{visitor:["expression"],aliases:["JSX","Immutable"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("JSXSpreadChild",{visitor:["expression"],aliases:["JSX","Immutable"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("JSXIdentifier",{builder:["name"],aliases:["JSX","Expression"],fields:{name:{validate:(0,n.assertValueType)("string")}}}),(0,i.default)("JSXMemberExpression",{visitor:["object","property"],aliases:["JSX","Expression"],fields:{object:{validate:(0,n.assertNodeType)("JSXMemberExpression","JSXIdentifier")},property:{validate:(0,n.assertNodeType)("JSXIdentifier")}}}),(0,i.default)("JSXNamespacedName",{visitor:["namespace","name"],aliases:["JSX"],fields:{namespace:{validate:(0,n.assertNodeType)("JSXIdentifier")},name:{validate:(0,n.assertNodeType)("JSXIdentifier")}}}),(0,i.default)("JSXOpeningElement",{builder:["name","attributes","selfClosing"],visitor:["name","attributes"],aliases:["JSX","Immutable"],fields:{name:{validate:(0,n.assertNodeType)("JSXIdentifier","JSXMemberExpression")},selfClosing:{default:!1,validate:(0,n.assertValueType)("boolean")},attributes:{validate:(0,n.chain)((0,n.assertValueType)("array"),(0,n.assertEach)((0,n.assertNodeType)("JSXAttribute","JSXSpreadAttribute")))}}}),(0,i.default)("JSXSpreadAttribute",{visitor:["argument"],aliases:["JSX"],fields:{argument:{validate:(0,n.assertNodeType)("Expression")}}}),(0,i.default)("JSXText",{aliases:["JSX","Immutable"],builder:["value"],fields:{value:{validate:(0,n.assertValueType)("string")}}})},{"./index":164}],167:[function(e,t,r){"use strict";var n=e("./index"),i=function(e){return e&&e.__esModule?e:{default:e}}(n);(0,i.default)("Noop",{visitor:[]}),(0,i.default)("ParenthesizedExpression",{visitor:["expression"],aliases:["Expression","ExpressionWrapper"],fields:{expression:{validate:(0,n.assertNodeType)("Expression")}}})},{"./index":164}],168:[function(e,t,r){"use strict";function n(e){var t=i(e);return 1===t.length?t[0]:o.unionTypeAnnotation(t)}function i(e){for(var t={},r={},n=[],s=[],a=0;a=0)){if(o.isAnyTypeAnnotation(u))return[u];if(o.isFlowBaseAnnotation(u))r[u.type]=u;else if(o.isUnionTypeAnnotation(u))n.indexOf(u.types)<0&&(e=e.concat(u.types),n.push(u.types));else if(o.isGenericTypeAnnotation(u)){var l=u.id.name;if(t[l]){var c=t[l];c.typeParameters?u.typeParameters&&(c.typeParameters.params=i(c.typeParameters.params.concat(u.typeParameters.params))):c=u.typeParameters}else t[l]=u}else s.push(u)}}for(var p in r)s.push(r[p]);for(var h in t)s.push(t[h]);return s}function s(e){if("string"===e)return o.stringTypeAnnotation();if("number"===e)return o.numberTypeAnnotation();if("undefined"===e)return o.voidTypeAnnotation();if("boolean"===e)return o.booleanTypeAnnotation();if("function"===e)return o.genericTypeAnnotation(o.identifier("Function"));if("object"===e)return o.genericTypeAnnotation(o.identifier("Object"));if("symbol"===e)return o.genericTypeAnnotation(o.identifier("Symbol"));throw new Error("Invalid typeof value")}r.__esModule=!0,r.createUnionTypeAnnotation=n,r.removeTypeDuplicates=i,r.createTypeAnnotationBasedOnTypeof=s;var a=e("./index"),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(a)},{"./index":169}],169:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=H["is"+e];t||(t=H["is"+e]=function(t,r){return H.is(e,t,r)}),H["assert"+e]=function(r,n){if(n=n||{},!t(r,n))throw new Error("Expected type "+(0,N.default)(e)+" with option "+(0,N.default)(n))}}function s(e,t,r){return!!t&&(!!a(t.type,e)&&(void 0===r||H.shallowEqual(t,r)))}function a(e,t){if(e===t)return!0;if(H.ALIAS_KEYS[t])return!1;var r=H.FLIPPED_ALIAS_KEYS[t];if(r){if(r[0]===e)return!0;for(var n=r,i=Array.isArray(n),s=0,n=i?n:(0,P.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}if(e===a)return!0}}return!1}function o(e,t,r){if(e){var n=H.NODE_FIELDS[e.type];if(n){var i=n[t];i&&i.validate&&(i.optional&&null==r||i.validate(e,t,r))}}}function u(e,t){for(var r=(0,O.default)(t),n=r,i=Array.isArray(n),s=0,n=i?n:(0,P.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;if(e[o]!==t[o])return!1}return!0}function l(e,t,r){return e.object=H.memberExpression(e.object,e.property,e.computed),e.property=t,e.computed=!!r,e}function c(e,t){return e.object=H.memberExpression(t,e.object),e}function p(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"body";return e[t]=H.toBlock(e[t],e)}function h(e){if(!e)return e;var t={};for(var r in e)"_"!==r[0]&&(t[r]=e[r]);return t}function f(e){var t=h(e);return delete t.loc,t}function d(e){if(!e)return e;var t={};for(var r in e)if("_"!==r[0]){var n=e[r];n&&(n.type?n=H.cloneDeep(n):Array.isArray(n)&&(n=n.map(H.cloneDeep))),t[r]=n}return t}function m(e,t){var r=e.split(".");return function(e){if(!H.isMemberExpression(e))return!1;for(var n=[e],i=0;n.length;){var s=n.shift();if(t&&i===r.length)return!0;if(H.isIdentifier(s)){if(r[i]!==s.name)return!1}else{if(!H.isStringLiteral(s)){if(H.isMemberExpression(s)){if(s.computed&&!H.isStringLiteral(s.property))return!1;n.push(s.object),n.push(s.property);continue}return!1}if(r[i]!==s.value)return!1}if(++i>r.length)return!1}return!0}}function y(e){for(var t=H.COMMENT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,P.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}delete e[i]}return e}function g(e,t){return b(e,t),v(e,t),x(e,t),e}function b(e,t){E("trailingComments",e,t)}function v(e,t){E("leadingComments",e,t)}function x(e,t){E("innerComments",e,t)}function E(e,t,r){t&&r&&(t[e]=(0,W.default)([].concat(t[e],r[e]).filter(Boolean)))}function A(e,t){if(!e||!t)return e;for(var r=H.INHERIT_KEYS.optional,n=Array.isArray(r),i=0,r=n?r:(0,P.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;null==e[a]&&(e[a]=t[a])}for(var o in t)"_"===o[0]&&(e[o]=t[o]);for(var u=H.INHERIT_KEYS.force,l=Array.isArray(u),c=0,u=l?u:(0,P.default)(u);;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if(c=u.next(),c.done)break;p=c.value}var h=p;e[h]=t[h]}return H.inheritsComments(e,t),e}function D(e){if(!C(e))throw new TypeError("Not a valid node "+(e&&e.type))}function C(e){return!(!e||!K.VISITOR_KEYS[e.type])}function S(e,t,r){if(e){var n=H.VISITOR_KEYS[e.type];if(n){r=r||{},t(e,r);for(var i=n,s=Array.isArray(i),a=0,i=s?i:(0,P.default)(i);;){var o;if(s){if(a>=i.length)break;o=i[a++]}else{if(a=i.next(),a.done)break;o=a.value}var u=o,l=e[u];if(Array.isArray(l))for(var c=l,p=Array.isArray(c),h=0,c=p?c:(0,P.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var d=f;S(d,t,r)}else S(l,t,r)}}}}function _(e,t){t=t||{};for(var r=t.preserveComments?Z:ee,n=r,i=Array.isArray(n),s=0,n=i?n:(0,P.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;null!=e[o]&&(e[o]=void 0)}for(var u in e)"_"===u[0]&&null!=e[u]&&(e[u]=void 0);for(var l=(0,F.default)(e),c=l,p=Array.isArray(c),h=0,c=p?c:(0,P.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}e[f]=null}}function w(e,t){return S(e,_,t),e}r.__esModule=!0,r.createTypeAnnotationBasedOnTypeof=r.removeTypeDuplicates=r.createUnionTypeAnnotation=r.valueToNode=r.toBlock=r.toExpression=r.toStatement=r.toBindingIdentifierName=r.toIdentifier=r.toKeyAlias=r.toSequenceExpression=r.toComputedKey=r.isNodesEquivalent=r.isImmutable=r.isScope=r.isSpecifierDefault=r.isVar=r.isBlockScoped=r.isLet=r.isValidIdentifier=r.isReferenced=r.isBinding=r.getOuterBindingIdentifiers=r.getBindingIdentifiers=r.TYPES=r.react=r.DEPRECATED_KEYS=r.BUILDER_KEYS=r.NODE_FIELDS=r.ALIAS_KEYS=r.VISITOR_KEYS=r.NOT_LOCAL_BINDING=r.BLOCK_SCOPED_SYMBOL=r.INHERIT_KEYS=r.UNARY_OPERATORS=r.STRING_UNARY_OPERATORS=r.NUMBER_UNARY_OPERATORS=r.BOOLEAN_UNARY_OPERATORS=r.BINARY_OPERATORS=r.NUMBER_BINARY_OPERATORS=r.BOOLEAN_BINARY_OPERATORS=r.COMPARISON_BINARY_OPERATORS=r.EQUALITY_BINARY_OPERATORS=r.BOOLEAN_NUMBER_BINARY_OPERATORS=r.UPDATE_OPERATORS=r.LOGICAL_OPERATORS=r.COMMENT_KEYS=r.FOR_INIT_KEYS=r.FLATTENABLE_KEYS=r.STATEMENT_OR_BLOCK_KEYS=void 0;var k=e("babel-runtime/core-js/object/get-own-property-symbols"),F=n(k),T=e("babel-runtime/core-js/get-iterator"),P=n(T),B=e("babel-runtime/core-js/object/keys"),O=n(B),j=e("babel-runtime/core-js/json/stringify"),N=n(j),I=e("./constants");Object.defineProperty(r,"STATEMENT_OR_BLOCK_KEYS",{enumerable:!0,get:function(){return I.STATEMENT_OR_BLOCK_KEYS}}),Object.defineProperty(r,"FLATTENABLE_KEYS",{enumerable:!0,get:function(){return I.FLATTENABLE_KEYS}}),Object.defineProperty(r,"FOR_INIT_KEYS",{enumerable:!0,get:function(){return I.FOR_INIT_KEYS}}),Object.defineProperty(r,"COMMENT_KEYS",{enumerable:!0,get:function(){return I.COMMENT_KEYS}}),Object.defineProperty(r,"LOGICAL_OPERATORS",{enumerable:!0,get:function(){return I.LOGICAL_OPERATORS}}),Object.defineProperty(r,"UPDATE_OPERATORS",{enumerable:!0,get:function(){return I.UPDATE_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return I.BOOLEAN_NUMBER_BINARY_OPERATORS}}),Object.defineProperty(r,"EQUALITY_BINARY_OPERATORS",{enumerable:!0,get:function(){return I.EQUALITY_BINARY_OPERATORS}}),Object.defineProperty(r,"COMPARISON_BINARY_OPERATORS",{enumerable:!0,get:function(){return I.COMPARISON_BINARY_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_BINARY_OPERATORS",{enumerable:!0,get:function(){return I.BOOLEAN_BINARY_OPERATORS}}),Object.defineProperty(r,"NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return I.NUMBER_BINARY_OPERATORS}}),Object.defineProperty(r,"BINARY_OPERATORS",{enumerable:!0,get:function(){return I.BINARY_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_UNARY_OPERATORS",{enumerable:!0,get:function(){return I.BOOLEAN_UNARY_OPERATORS}}),Object.defineProperty(r,"NUMBER_UNARY_OPERATORS",{enumerable:!0,get:function(){return I.NUMBER_UNARY_OPERATORS}}),Object.defineProperty(r,"STRING_UNARY_OPERATORS",{enumerable:!0,get:function(){return I.STRING_UNARY_OPERATORS}}),Object.defineProperty(r,"UNARY_OPERATORS",{enumerable:!0,get:function(){return I.UNARY_OPERATORS}}),Object.defineProperty(r,"INHERIT_KEYS",{enumerable:!0,get:function(){return I.INHERIT_KEYS}}),Object.defineProperty(r,"BLOCK_SCOPED_SYMBOL",{enumerable:!0,get:function(){return I.BLOCK_SCOPED_SYMBOL}}),Object.defineProperty(r,"NOT_LOCAL_BINDING",{enumerable:!0,get:function(){return I.NOT_LOCAL_BINDING}}),r.is=s,r.isType=a,r.validate=o,r.shallowEqual=u,r.appendToMemberExpression=l,r.prependToMemberExpression=c,r.ensureBlock=p,r.clone=h,r.cloneWithoutLoc=f,r.cloneDeep=d,r.buildMatchMemberExpression=m,r.removeComments=y,r.inheritsComments=g,r.inheritTrailingComments=b,r.inheritLeadingComments=v,r.inheritInnerComments=x,r.inherits=A,r.assertNode=D,r.isNode=C,r.traverseFast=S,r.removeProperties=_,r.removePropertiesDeep=w;var L=e("./retrievers");Object.defineProperty(r,"getBindingIdentifiers",{enumerable:!0,get:function(){return L.getBindingIdentifiers}}),Object.defineProperty(r,"getOuterBindingIdentifiers",{enumerable:!0,get:function(){return L.getOuterBindingIdentifiers}});var M=e("./validators");Object.defineProperty(r,"isBinding",{enumerable:!0,get:function(){return M.isBinding}}),Object.defineProperty(r,"isReferenced",{enumerable:!0,get:function(){return M.isReferenced}}), +Object.defineProperty(r,"isValidIdentifier",{enumerable:!0,get:function(){return M.isValidIdentifier}}),Object.defineProperty(r,"isLet",{enumerable:!0,get:function(){return M.isLet}}),Object.defineProperty(r,"isBlockScoped",{enumerable:!0,get:function(){return M.isBlockScoped}}),Object.defineProperty(r,"isVar",{enumerable:!0,get:function(){return M.isVar}}),Object.defineProperty(r,"isSpecifierDefault",{enumerable:!0,get:function(){return M.isSpecifierDefault}}),Object.defineProperty(r,"isScope",{enumerable:!0,get:function(){return M.isScope}}),Object.defineProperty(r,"isImmutable",{enumerable:!0,get:function(){return M.isImmutable}}),Object.defineProperty(r,"isNodesEquivalent",{enumerable:!0,get:function(){return M.isNodesEquivalent}});var R=e("./converters");Object.defineProperty(r,"toComputedKey",{enumerable:!0,get:function(){return R.toComputedKey}}),Object.defineProperty(r,"toSequenceExpression",{enumerable:!0,get:function(){return R.toSequenceExpression}}),Object.defineProperty(r,"toKeyAlias",{enumerable:!0,get:function(){return R.toKeyAlias}}),Object.defineProperty(r,"toIdentifier",{enumerable:!0,get:function(){return R.toIdentifier}}),Object.defineProperty(r,"toBindingIdentifierName",{enumerable:!0,get:function(){return R.toBindingIdentifierName}}),Object.defineProperty(r,"toStatement",{enumerable:!0,get:function(){return R.toStatement}}),Object.defineProperty(r,"toExpression",{enumerable:!0,get:function(){return R.toExpression}}),Object.defineProperty(r,"toBlock",{enumerable:!0,get:function(){return R.toBlock}}),Object.defineProperty(r,"valueToNode",{enumerable:!0,get:function(){return R.valueToNode}});var U=e("./flow");Object.defineProperty(r,"createUnionTypeAnnotation",{enumerable:!0,get:function(){return U.createUnionTypeAnnotation}}),Object.defineProperty(r,"removeTypeDuplicates",{enumerable:!0,get:function(){return U.removeTypeDuplicates}}),Object.defineProperty(r,"createTypeAnnotationBasedOnTypeof",{enumerable:!0,get:function(){return U.createTypeAnnotationBasedOnTypeof}});var V=e("to-fast-properties"),q=n(V),G=e("lodash/clone"),X=n(G),J=e("lodash/uniq"),W=n(J);e("./definitions/init");var K=e("./definitions"),z=e("./react"),Y=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(z),H=r;r.VISITOR_KEYS=K.VISITOR_KEYS,r.ALIAS_KEYS=K.ALIAS_KEYS,r.NODE_FIELDS=K.NODE_FIELDS,r.BUILDER_KEYS=K.BUILDER_KEYS,r.DEPRECATED_KEYS=K.DEPRECATED_KEYS,r.react=Y;for(var $ in H.VISITOR_KEYS)i($);H.FLIPPED_ALIAS_KEYS={},(0,O.default)(H.ALIAS_KEYS).forEach(function(e){H.ALIAS_KEYS[e].forEach(function(t){(H.FLIPPED_ALIAS_KEYS[t]=H.FLIPPED_ALIAS_KEYS[t]||[]).push(e)})}),(0,O.default)(H.FLIPPED_ALIAS_KEYS).forEach(function(e){H[e.toUpperCase()+"_TYPES"]=H.FLIPPED_ALIAS_KEYS[e],i(e)});r.TYPES=(0,O.default)(H.VISITOR_KEYS).concat((0,O.default)(H.FLIPPED_ALIAS_KEYS)).concat((0,O.default)(H.DEPRECATED_KEYS));(0,O.default)(H.BUILDER_KEYS).forEach(function(e){function t(){if(arguments.length>r.length)throw new Error("t."+e+": Too many arguments passed. Received "+arguments.length+" but can receive no more than "+r.length);var t={};t.type=e;for(var n=0,i=r,s=Array.isArray(i),a=0,i=s?i:(0,P.default)(i);;){var u;if(s){if(a>=i.length)break;u=i[a++]}else{if(a=i.next(),a.done)break;u=a.value}var l=u,c=H.NODE_FIELDS[e][l],p=arguments[n++];void 0===p&&(p=(0,X.default)(c.default)),t[l]=p}for(var h in t)o(t,h,t[h]);return t}var r=H.BUILDER_KEYS[e];H[e]=t,H[e[0].toLowerCase()+e.slice(1)]=t});for(var Q in H.DEPRECATED_KEYS)!function(e){function t(t){return function(){return console.trace("The node type "+e+" has been renamed to "+r),t.apply(this,arguments)}}var r=H.DEPRECATED_KEYS[e];H[e]=H[e[0].toLowerCase()+e.slice(1)]=t(H[r]),H["is"+e]=t(H["is"+r]),H["assert"+e]=t(H["assert"+r])}(Q);(0,q.default)(H),(0,q.default)(H.VISITOR_KEYS);var Z=["tokens","start","end","loc","raw","rawValue"],ee=H.COMMENT_KEYS.concat(["comments"]).concat(Z)},{"./constants":158,"./converters":159,"./definitions":164,"./definitions/init":165,"./flow":168,"./react":170,"./retrievers":171,"./validators":172,"babel-runtime/core-js/get-iterator":113,"babel-runtime/core-js/json/stringify":114,"babel-runtime/core-js/object/get-own-property-symbols":119,"babel-runtime/core-js/object/keys":120,"lodash/clone":480,"lodash/uniq":529,"to-fast-properties":595}],170:[function(e,t,r){"use strict";function n(e){return!!e&&/^[a-z]|\-/.test(e)}function i(e,t){for(var r=e.value.split(/\r\n|\n|\r/),n=0,i=0;i=0)return!0}else if(s===e)return!0}return!1}function s(e,t){switch(t.type){case"BindExpression":return t.object===e||t.callee===e;case"MemberExpression":case"JSXMemberExpression":return!(t.property!==e||!t.computed)||t.object===e;case"MetaProperty":return!1;case"ObjectProperty":if(t.key===e)return t.computed;case"VariableDeclarator":return t.id!==e;case"ArrowFunctionExpression":case"FunctionDeclaration":case"FunctionExpression":for(var r=t.params,n=Array.isArray(r),i=0,r=n?r:(0,v.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}if(s===e)return!1}return t.id!==e;case"ExportSpecifier":return!t.source&&t.local===e;case"ExportNamespaceSpecifier":case"ExportDefaultSpecifier":return!1;case"JSXAttribute":return t.name!==e;case"ClassProperty":return t.key===e?t.computed:t.value===e;case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"ImportSpecifier":return!1;case"ClassDeclaration":case"ClassExpression":return t.id!==e;case"ClassMethod":case"ObjectMethod":return t.key===e&&t.computed;case"LabeledStatement":return!1;case"CatchClause":return t.param!==e;case"RestElement":return!1;case"AssignmentExpression":case"AssignmentPattern":return t.right===e;case"ObjectPattern":case"ArrayPattern":return!1}return!0}function a(e){return"string"==typeof e&&!A.default.keyword.isReservedWordES6(e,!0)&&A.default.keyword.isIdentifierNameES6(e)}function o(e){return C.isVariableDeclaration(e)&&("var"!==e.kind||e[S.BLOCK_SCOPED_SYMBOL])}function u(e){return C.isFunctionDeclaration(e)||C.isClassDeclaration(e)||C.isLet(e)}function l(e){return C.isVariableDeclaration(e,{kind:"var"})&&!e[S.BLOCK_SCOPED_SYMBOL]}function c(e){return C.isImportDefaultSpecifier(e)||C.isIdentifier(e.imported||e.exported,{name:"default"})}function p(e,t){return(!C.isBlockStatement(e)||!C.isFunction(t,{body:e}))&&C.isScopable(e)}function h(e){return!!C.isType(e.type,"Immutable")||!!C.isIdentifier(e)&&"undefined"===e.name}function f(e,t){if("object"!==(void 0===e?"undefined":(0,g.default)(e))||"object"!==(void 0===e?"undefined":(0,g.default)(e))||null==e||null==t)return e===t;if(e.type!==t.type)return!1;for(var r=(0,m.default)(C.NODE_FIELDS[e.type]||e.type),n=r,i=Array.isArray(n),s=0,n=i?n:(0,v.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;if((0,g.default)(e[o])!==(0,g.default)(t[o]))return!1;if(Array.isArray(e[o])){if(!Array.isArray(t[o]))return!1;if(e[o].length!==t[o].length)return!1;for(var u=0;u=0}}function i(e,t){for(var r=65536,n=0;ne)return!1;if((r+=t[n+1])>=e)return!0}}function s(e){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&E.test(String.fromCharCode(e)):i(e,D)))}function a(e){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&A.test(String.fromCharCode(e)):i(e,D)||i(e,C))))}function o(e){var t={};for(var r in S)t[r]=e&&r in e?e[r]:S[r];return t}function u(e){return 10===e||13===e||8232===e||8233===e}function l(e,t){for(var r=1,n=0;;){L.lastIndex=n;var i=L.exec(e);if(!(i&&i.index>10),56320+(e-65536&1023))}function p(e,t,r,n){return e.type=t,e.end=r,e.loc.end=n,this.processComment(e),e}function h(e){return e[e.length-1]}function f(e){return e&&"Property"===e.type&&"init"===e.kind&&!1===e.method}function d(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?d(e.object)+"."+d(e.property):void 0}function m(e,t){return new z(t,e).parse()}function y(e,t){var r=new z(t,e);return r.options.strictMode&&(r.state.strict=!0),r.getExpression()}Object.defineProperty(r,"__esModule",{value:!0});var g={6:n("enum await"),strict:n("implements interface let package private protected public static yield"),strictBind:n("eval arguments")},b=n("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this let const class extends export import yield super"),v="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",x="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",E=new RegExp("["+v+"]"),A=new RegExp("["+v+x+"]");v=x=null;var D=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541],C=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239],S={sourceType:"script",sourceFilename:void 0,startLine:1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null},_="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},w=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},k=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},F=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},T=!0,P=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};w(this,e),this.label=t,this.keyword=r.keyword,this.beforeExpr=!!r.beforeExpr,this.startsExpr=!!r.startsExpr,this.rightAssociative=!!r.rightAssociative,this.isLoop=!!r.isLoop,this.isAssign=!!r.isAssign,this.prefix=!!r.prefix,this.postfix=!!r.postfix,this.binop=r.binop||null,this.updateContext=null},B=function(e){function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return w(this,t),n.keyword=r,F(this,e.call(this,r,n))}return k(t,e),t}(P),O=function(e){function t(r,n){return w(this,t),F(this,e.call(this,r,{beforeExpr:T,binop:n}))}return k(t,e),t}(P),j={num:new P("num",{startsExpr:!0}),regexp:new P("regexp",{startsExpr:!0}),string:new P("string",{startsExpr:!0}),name:new P("name",{startsExpr:!0}),eof:new P("eof"),bracketL:new P("[",{beforeExpr:T,startsExpr:!0}),bracketR:new P("]"),braceL:new P("{",{beforeExpr:T,startsExpr:!0}),braceBarL:new P("{|",{beforeExpr:T,startsExpr:!0}),braceR:new P("}"),braceBarR:new P("|}"),parenL:new P("(",{beforeExpr:T,startsExpr:!0}),parenR:new P(")"),comma:new P(",",{beforeExpr:T}),semi:new P(";",{beforeExpr:T}),colon:new P(":",{beforeExpr:T}),doubleColon:new P("::",{beforeExpr:T}),dot:new P("."),question:new P("?",{beforeExpr:T}),arrow:new P("=>",{beforeExpr:T}),template:new P("template"),ellipsis:new P("...",{beforeExpr:T}),backQuote:new P("`",{startsExpr:!0}),dollarBraceL:new P("${",{beforeExpr:T,startsExpr:!0}),at:new P("@"),eq:new P("=",{beforeExpr:T,isAssign:!0}),assign:new P("_=",{beforeExpr:T,isAssign:!0}),incDec:new P("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new P("prefix",{beforeExpr:T,prefix:!0,startsExpr:!0}),logicalOR:new O("||",1),logicalAND:new O("&&",2),bitwiseOR:new O("|",3),bitwiseXOR:new O("^",4),bitwiseAND:new O("&",5),equality:new O("==/!=",6),relational:new O("",7),bitShift:new O("<>",8),plusMin:new P("+/-",{beforeExpr:T,binop:9,prefix:!0,startsExpr:!0}),modulo:new O("%",10),star:new O("*",10),slash:new O("/",10),exponent:new P("**",{beforeExpr:T,binop:11,rightAssociative:!0})},N={break:new B("break"),case:new B("case",{beforeExpr:T}),catch:new B("catch"),continue:new B("continue"),debugger:new B("debugger"),default:new B("default",{beforeExpr:T}),do:new B("do",{isLoop:!0,beforeExpr:T}),else:new B("else",{beforeExpr:T}),finally:new B("finally"),for:new B("for",{isLoop:!0}),function:new B("function",{startsExpr:!0}),if:new B("if"),return:new B("return",{beforeExpr:T}),switch:new B("switch"),throw:new B("throw",{beforeExpr:T}),try:new B("try"),var:new B("var"),let:new B("let"),const:new B("const"),while:new B("while",{isLoop:!0}),with:new B("with"),new:new B("new",{beforeExpr:T,startsExpr:!0}),this:new B("this",{startsExpr:!0}),super:new B("super",{startsExpr:!0}),class:new B("class"),extends:new B("extends",{beforeExpr:T}),export:new B("export"),import:new B("import"),yield:new B("yield",{beforeExpr:T,startsExpr:!0}),null:new B("null",{startsExpr:!0}),true:new B("true",{startsExpr:!0}),false:new B("false",{startsExpr:!0}),in:new B("in",{beforeExpr:T,binop:7}),instanceof:new B("instanceof",{beforeExpr:T,binop:7}),typeof:new B("typeof",{beforeExpr:T,prefix:!0,startsExpr:!0}),void:new B("void",{beforeExpr:T,prefix:!0,startsExpr:!0}),delete:new B("delete",{beforeExpr:T,prefix:!0,startsExpr:!0})};Object.keys(N).forEach(function(e){j["_"+e]=N[e]});var I=/\r\n?|\n|\u2028|\u2029/,L=new RegExp(I.source,"g"),M=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,R=function e(t,r,n,i){w(this,e),this.token=t,this.isExpr=!!r,this.preserveSpace=!!n,this.override=i},U={braceStatement:new R("{",!1),braceExpression:new R("{",!0),templateQuasi:new R("${",!0),parenStatement:new R("(",!1),parenExpression:new R("(",!0),template:new R("`",!0,!0,function(e){return e.readTmplToken()}),functionExpression:new R("function",!0)};j.parenR.updateContext=j.braceR.updateContext=function(){if(1===this.state.context.length)return void(this.state.exprAllowed=!0);var e=this.state.context.pop();e===U.braceStatement&&this.curContext()===U.functionExpression?(this.state.context.pop(),this.state.exprAllowed=!1):e===U.templateQuasi?this.state.exprAllowed=!0:this.state.exprAllowed=!e.isExpr},j.name.updateContext=function(e){this.state.exprAllowed=!1,e!==j._let&&e!==j._const&&e!==j._var||I.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0)},j.braceL.updateContext=function(e){this.state.context.push(this.braceIsBlock(e)?U.braceStatement:U.braceExpression),this.state.exprAllowed=!0},j.dollarBraceL.updateContext=function(){this.state.context.push(U.templateQuasi),this.state.exprAllowed=!0},j.parenL.updateContext=function(e){var t=e===j._if||e===j._for||e===j._with||e===j._while;this.state.context.push(t?U.parenStatement:U.parenExpression),this.state.exprAllowed=!0},j.incDec.updateContext=function(){},j._function.updateContext=function(){this.curContext()!==U.braceStatement&&this.state.context.push(U.functionExpression),this.state.exprAllowed=!1},j.backQuote.updateContext=function(){this.curContext()===U.template?this.state.context.pop():this.state.context.push(U.template),this.state.exprAllowed=!1};var V=function e(t,r){w(this,e),this.line=t,this.column=r},q=function e(t,r){w(this,e),this.start=t,this.end=r},G=function(){function e(){w(this,e)}return e.prototype.init=function(e,t){return this.strict=!1!==e.strictMode&&"module"===e.sourceType,this.input=t,this.potentialArrowAt=-1,this.inMethod=this.inFunction=this.inGenerator=this.inAsync=this.inPropertyName=this.inType=this.noAnonFunctionType=!1,this.labels=[],this.decorators=[],this.tokens=[],this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.pos=this.lineStart=0,this.curLine=e.startLine,this.type=j.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=[U.braceStatement],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this.exportedIdentifiers=[],this},e.prototype.curPosition=function(){return new V(this.curLine,this.pos-this.lineStart)},e.prototype.clone=function(t){var r=new e;for(var n in this){var i=this[n];t&&"context"!==n||!Array.isArray(i)||(i=i.slice()),r[n]=i}return r},e}(),X=function e(t){w(this,e),this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new q(t.startLoc,t.endLoc)},J=function(){function e(t,r){w(this,e),this.state=new G,this.state.init(t,r)}return e.prototype.next=function(){this.isLookahead||this.state.tokens.push(new X(this.state)),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()},e.prototype.eat=function(e){return!!this.match(e)&&(this.next(),!0)},e.prototype.match=function(e){return this.state.type===e},e.prototype.isKeyword=function(e){return b(e)},e.prototype.lookahead=function(){var e=this.state;this.state=e.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;var t=this.state.clone(!0);return this.state=e,t},e.prototype.setStrict=function(e){if(this.state.strict=e,this.match(j.num)||this.match(j.string)){for(this.state.pos=this.state.start;this.state.pos=this.input.length?this.finishToken(j.eof):e.override?e.override(this):this.readToken(this.fullCharCodeAtPos())},e.prototype.readToken=function(e){return s(e)||92===e?this.readWord():this.getTokenFromCode(e)},e.prototype.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.state.pos);return e<=55295||e>=57344?e:(e<<10)+this.input.charCodeAt(this.state.pos+1)-56613888},e.prototype.pushComment=function(e,t,r,n,i,s){var a={type:e?"CommentBlock":"CommentLine",value:t,start:r,end:n,loc:new q(i,s)};this.isLookahead||(this.state.tokens.push(a),this.state.comments.push(a),this.addComment(a))},e.prototype.skipBlockComment=function(){var e=this.state.curPosition(),t=this.state.pos,r=this.input.indexOf("*/",this.state.pos+=2);-1===r&&this.raise(this.state.pos-2,"Unterminated comment"),this.state.pos=r+2,L.lastIndex=t;for(var n=void 0;(n=L.exec(this.input))&&n.index8&&e<14||e>=5760&&M.test(String.fromCharCode(e))))break e;++this.state.pos}}},e.prototype.finishToken=function(e,t){this.state.end=this.state.pos,this.state.endLoc=this.state.curPosition();var r=this.state.type;this.state.type=e,this.state.value=t,this.updateContext(r)},e.prototype.readToken_dot=function(){var e=this.input.charCodeAt(this.state.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.state.pos+2);return 46===e&&46===t?(this.state.pos+=3,this.finishToken(j.ellipsis)):(++this.state.pos,this.finishToken(j.dot))},e.prototype.readToken_slash=function(){return this.state.exprAllowed?(++this.state.pos,this.readRegexp()):61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(j.assign,2):this.finishOp(j.slash,1)},e.prototype.readToken_mult_modulo=function(e){var t=42===e?j.star:j.modulo,r=1,n=this.input.charCodeAt(this.state.pos+1);return 42===n&&(r++,n=this.input.charCodeAt(this.state.pos+2),t=j.exponent),61===n&&(r++,t=j.assign),this.finishOp(t,r)},e.prototype.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.state.pos+1);return t===e?this.finishOp(124===e?j.logicalOR:j.logicalAND,2):61===t?this.finishOp(j.assign,2):124===e&&125===t&&this.hasPlugin("flow")?this.finishOp(j.braceBarR,2):this.finishOp(124===e?j.bitwiseOR:j.bitwiseAND,1)},e.prototype.readToken_caret=function(){return 61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(j.assign,2):this.finishOp(j.bitwiseXOR,1)},e.prototype.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.state.pos+1);return t===e?45===t&&62===this.input.charCodeAt(this.state.pos+2)&&I.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(j.incDec,2):61===t?this.finishOp(j.assign,2):this.finishOp(j.plusMin,1)},e.prototype.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.state.pos+1),r=1;return t===e?(r=62===e&&62===this.input.charCodeAt(this.state.pos+2)?3:2,61===this.input.charCodeAt(this.state.pos+r)?this.finishOp(j.assign,r+1):this.finishOp(j.bitShift,r)):33===t&&60===e&&45===this.input.charCodeAt(this.state.pos+2)&&45===this.input.charCodeAt(this.state.pos+3)?(this.inModule&&this.unexpected(),this.skipLineComment(4),this.skipSpace(),this.nextToken()):(61===t&&(r=2),this.finishOp(j.relational,r))},e.prototype.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(j.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2):61===e&&62===t?(this.state.pos+=2,this.finishToken(j.arrow)):this.finishOp(61===e?j.eq:j.prefix,1)},e.prototype.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.state.pos,this.finishToken(j.parenL);case 41:return++this.state.pos,this.finishToken(j.parenR);case 59:return++this.state.pos,this.finishToken(j.semi);case 44:return++this.state.pos,this.finishToken(j.comma);case 91:return++this.state.pos,this.finishToken(j.bracketL);case 93:return++this.state.pos,this.finishToken(j.bracketR);case 123:return this.hasPlugin("flow")&&124===this.input.charCodeAt(this.state.pos+1)?this.finishOp(j.braceBarL,2):(++this.state.pos,this.finishToken(j.braceL));case 125:return++this.state.pos,this.finishToken(j.braceR);case 58:return this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(j.doubleColon,2):(++this.state.pos,this.finishToken(j.colon));case 63:return++this.state.pos,this.finishToken(j.question);case 64:return++this.state.pos,this.finishToken(j.at);case 96:return++this.state.pos,this.finishToken(j.backQuote);case 48:var t=this.input.charCodeAt(this.state.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2);case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 126:return this.finishOp(j.prefix,1)}this.raise(this.state.pos,"Unexpected character '"+c(e)+"'")},e.prototype.finishOp=function(e,t){var r=this.input.slice(this.state.pos,this.state.pos+t);return this.state.pos+=t,this.finishToken(e,r)},e.prototype.readRegexp=function(){for(var e=this.state.pos,t=void 0,r=void 0;;){this.state.pos>=this.input.length&&this.raise(e,"Unterminated regular expression");var n=this.input.charAt(this.state.pos);if(I.test(n)&&this.raise(e,"Unterminated regular expression"),t)t=!1;else{if("["===n)r=!0;else if("]"===n&&r)r=!1;else if("/"===n&&!r)break;t="\\"===n}++this.state.pos}var i=this.input.slice(e,this.state.pos);++this.state.pos;var s=this.readWord1();if(s){/^[gmsiyu]*$/.test(s)||this.raise(e,"Invalid regular expression flag")}return this.finishToken(j.regexp,{pattern:i,flags:s})},e.prototype.readInt=function(e,t){for(var r=this.state.pos,n=0,i=0,s=null==t?1/0:t;i=97?a-97+10:a>=65?a-65+10:a>=48&&a<=57?a-48:1/0)>=e)break;++this.state.pos,n=n*e+o}return this.state.pos===r||null!=t&&this.state.pos-r!==t?null:n},e.prototype.readRadixNumber=function(e){this.state.pos+=2;var t=this.readInt(e) +;return null==t&&this.raise(this.state.start+2,"Expected number in radix "+e),s(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number"),this.finishToken(j.num,t)},e.prototype.readNumber=function(e){var t=this.state.pos,r=48===this.input.charCodeAt(this.state.pos),n=!1;e||null!==this.readInt(10)||this.raise(t,"Invalid number");var i=this.input.charCodeAt(this.state.pos);46===i&&(++this.state.pos,this.readInt(10),n=!0,i=this.input.charCodeAt(this.state.pos)),69!==i&&101!==i||(i=this.input.charCodeAt(++this.state.pos),43!==i&&45!==i||++this.state.pos,null===this.readInt(10)&&this.raise(t,"Invalid number"),n=!0),s(this.fullCharCodeAtPos())&&this.raise(this.state.pos,"Identifier directly after number");var a=this.input.slice(t,this.state.pos),o=void 0;return n?o=parseFloat(a):r&&1!==a.length?/[89]/.test(a)||this.state.strict?this.raise(t,"Invalid number"):o=parseInt(a,8):o=parseInt(a,10),this.finishToken(j.num,o)},e.prototype.readCodePoint=function(){var e=this.input.charCodeAt(this.state.pos),t=void 0;if(123===e){var r=++this.state.pos;t=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos),++this.state.pos,t>1114111&&this.raise(r,"Code point out of bounds")}else t=this.readHexChar(4);return t},e.prototype.readString=function(e){for(var t="",r=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var n=this.input.charCodeAt(this.state.pos);if(n===e)break;92===n?(t+=this.input.slice(r,this.state.pos),t+=this.readEscapedChar(!1),r=this.state.pos):(u(n)&&this.raise(this.state.start,"Unterminated string constant"),++this.state.pos)}return t+=this.input.slice(r,this.state.pos++),this.finishToken(j.string,t)},e.prototype.readTmplToken=function(){for(var e="",t=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var r=this.input.charCodeAt(this.state.pos);if(96===r||36===r&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(j.template)?36===r?(this.state.pos+=2,this.finishToken(j.dollarBraceL)):(++this.state.pos,this.finishToken(j.backQuote)):(e+=this.input.slice(t,this.state.pos),this.finishToken(j.template,e));if(92===r)e+=this.input.slice(t,this.state.pos),e+=this.readEscapedChar(!0),t=this.state.pos;else if(u(r)){switch(e+=this.input.slice(t,this.state.pos),++this.state.pos,r){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(r)}++this.state.curLine,this.state.lineStart=this.state.pos,t=this.state.pos}else++this.state.pos}},e.prototype.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,t){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return c(this.readCodePoint());case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:return this.state.lineStart=this.state.pos,++this.state.curLine,"";default:if(t>=48&&t<=55){var r=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(r,8);return n>255&&(r=r.slice(0,-1),n=parseInt(r,8)),n>0&&(this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=this.state.pos-2),(this.state.strict||e)&&this.raise(this.state.pos-2,"Octal literal in strict mode")),this.state.pos+=r.length-1,String.fromCharCode(n)}return String.fromCharCode(t)}},e.prototype.readHexChar=function(e){var t=this.state.pos,r=this.readInt(16,e);return null===r&&this.raise(t,"Bad character escape sequence"),r},e.prototype.readWord1=function(){this.state.containsEsc=!1;for(var e="",t=!0,r=this.state.pos;this.state.pos-1)||!!this.plugins[e]},t.prototype.extend=function(e,t){this[e]=t(this[e])},t.prototype.loadAllPlugins=function(){var e=this,t=Object.keys(W).filter(function(e){return"flow"!==e&&"estree"!==e});t.push("flow"),t.forEach(function(t){var r=W[t];r&&r(e)})},t.prototype.loadPlugins=function(e){if(e.indexOf("*")>=0)return this.loadAllPlugins(),{"*":!0};var t={};e.indexOf("flow")>=0&&(e=e.filter(function(e){return"flow"!==e}),e.push("flow")),e.indexOf("estree")>=0&&(e=e.filter(function(e){return"estree"!==e}),e.unshift("estree"));for(var r=e,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if(!t[a]){t[a]=!0;var o=W[a];o&&o(this)}}return t},t.prototype.parse=function(){var e=this.startNode(),t=this.startNode();return this.nextToken(),this.parseTopLevel(e,t)},t}(J),Y=z.prototype;Y.addExtra=function(e,t,r){if(e){(e.extra=e.extra||{})[t]=r}},Y.isRelational=function(e){return this.match(j.relational)&&this.state.value===e},Y.expectRelational=function(e){this.isRelational(e)?this.next():this.unexpected(null,j.relational)},Y.isContextual=function(e){return this.match(j.name)&&this.state.value===e},Y.eatContextual=function(e){return this.state.value===e&&this.eat(j.name)},Y.expectContextual=function(e,t){this.eatContextual(e)||this.unexpected(null,t)},Y.canInsertSemicolon=function(){return this.match(j.eof)||this.match(j.braceR)||I.test(this.input.slice(this.state.lastTokEnd,this.state.start))},Y.isLineTerminator=function(){return this.eat(j.semi)||this.canInsertSemicolon()},Y.semicolon=function(){this.isLineTerminator()||this.unexpected(null,j.semi)},Y.expect=function(e,t){return this.eat(e)||this.unexpected(t,e)},Y.unexpected=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Unexpected token";t&&"object"===(void 0===t?"undefined":_(t))&&t.label&&(t="Unexpected token, expected "+t.label),this.raise(null!=e?e:this.state.start,t)};var H=z.prototype;H.parseTopLevel=function(e,t){return t.sourceType=this.options.sourceType,this.parseBlockBody(t,!0,!0,j.eof),e.program=this.finishNode(t,"Program"),e.comments=this.state.comments,e.tokens=this.state.tokens,this.finishNode(e,"File")};var $={kind:"loop"},Q={kind:"switch"};H.stmtToDirective=function(e){var t=e.expression,r=this.startNodeAt(t.start,t.loc.start),n=this.startNodeAt(e.start,e.loc.start),i=this.input.slice(t.start,t.end),s=r.value=i.slice(1,-1);return this.addExtra(r,"raw",i),this.addExtra(r,"rawValue",s),n.value=this.finishNodeAt(r,"DirectiveLiteral",t.end,t.loc.end),this.finishNodeAt(n,"Directive",e.end,e.loc.end)},H.parseStatement=function(e,t){this.match(j.at)&&this.parseDecorators(!0);var r=this.state.type,n=this.startNode();switch(r){case j._break:case j._continue:return this.parseBreakContinueStatement(n,r.keyword);case j._debugger:return this.parseDebuggerStatement(n);case j._do:return this.parseDoStatement(n);case j._for:return this.parseForStatement(n);case j._function:return e||this.unexpected(),this.parseFunctionStatement(n);case j._class:return e||this.unexpected(),this.parseClass(n,!0);case j._if:return this.parseIfStatement(n);case j._return:return this.parseReturnStatement(n);case j._switch:return this.parseSwitchStatement(n);case j._throw:return this.parseThrowStatement(n);case j._try:return this.parseTryStatement(n);case j._let:case j._const:e||this.unexpected();case j._var:return this.parseVarStatement(n,r);case j._while:return this.parseWhileStatement(n);case j._with:return this.parseWithStatement(n);case j.braceL:return this.parseBlock();case j.semi:return this.parseEmptyStatement(n);case j._export:case j._import:if(this.hasPlugin("dynamicImport")&&this.lookahead().type===j.parenL)break;return this.options.allowImportExportEverywhere||(t||this.raise(this.state.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.state.start,"'import' and 'export' may appear only with 'sourceType: module'")),r===j._import?this.parseImport(n):this.parseExport(n);case j.name:if("async"===this.state.value){var i=this.state.clone();if(this.next(),this.match(j._function)&&!this.canInsertSemicolon())return this.expect(j._function),this.parseFunction(n,!0,!1,!0);this.state=i}}var s=this.state.value,a=this.parseExpression();return r===j.name&&"Identifier"===a.type&&this.eat(j.colon)?this.parseLabeledStatement(n,s,a):this.parseExpressionStatement(n,a)},H.takeDecorators=function(e){this.state.decorators.length&&(e.decorators=this.state.decorators,this.state.decorators=[])},H.parseDecorators=function(e){for(;this.match(j.at);){var t=this.parseDecorator();this.state.decorators.push(t)}e&&this.match(j._export)||this.match(j._class)||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},H.parseDecorator=function(){this.hasPlugin("decorators")||this.unexpected();var e=this.startNode();return this.next(),e.expression=this.parseMaybeAssign(),this.finishNode(e,"Decorator")},H.parseBreakContinueStatement=function(e,t){var r="break"===t;this.next(),this.isLineTerminator()?e.label=null:this.match(j.name)?(e.label=this.parseIdentifier(),this.semicolon()):this.unexpected();var n=void 0;for(n=0;n=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}a.name===t&&this.raise(r.start,"Label '"+t+"' is already declared")}for(var o=this.state.type.isLoop?"loop":this.match(j._switch)?"switch":null,u=this.state.labels.length-1;u>=0;u--){var l=this.state.labels[u];if(l.statementStart!==e.start)break;l.statementStart=this.state.start,l.kind=o}return this.state.labels.push({name:t,kind:o,statementStart:this.state.start}),e.body=this.parseStatement(!0),this.state.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")},H.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},H.parseBlock=function(e){var t=this.startNode();return this.expect(j.braceL),this.parseBlockBody(t,e,!1,j.braceR),this.finishNode(t,"BlockStatement")},H.isValidDirective=function(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized},H.parseBlockBody=function(e,t,r,n){e.body=[],e.directives=[];for(var i=!1,s=void 0,a=void 0;!this.eat(n);){i||!this.state.containsOctal||a||(a=this.state.octalPosition);var o=this.parseStatement(!0,r);if(t&&!i&&this.isValidDirective(o)){var u=this.stmtToDirective(o);e.directives.push(u),void 0===s&&"use strict"===u.value.value&&(s=this.state.strict,this.setStrict(!0),a&&this.raise(a,"Octal literal in strict mode"))}else i=!0,e.body.push(o)}!1===s&&this.setStrict(!1)},H.parseFor=function(e,t){return e.init=t,this.expect(j.semi),e.test=this.match(j.semi)?null:this.parseExpression(),this.expect(j.semi),e.update=this.match(j.parenR)?null:this.parseExpression(),this.expect(j.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,"ForStatement")},H.parseForIn=function(e,t,r){var n=void 0;return r?(this.eatContextual("of"),n="ForAwaitStatement"):(n=this.match(j._in)?"ForInStatement":"ForOfStatement",this.next()),e.left=t,e.right=this.parseExpression(),this.expect(j.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,n)},H.parseVar=function(e,t,r){for(e.declarations=[],e.kind=r.keyword;;){var n=this.startNode();if(this.parseVarHead(n),this.eat(j.eq)?n.init=this.parseMaybeAssign(t):r!==j._const||this.match(j._in)||this.isContextual("of")?"Identifier"===n.id.type||t&&(this.match(j._in)||this.isContextual("of"))?n.init=null:this.raise(this.state.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(j.comma))break}return e},H.parseVarHead=function(e){e.id=this.parseBindingAtom(),this.checkLVal(e.id,!0,void 0,"variable declaration")},H.parseFunction=function(e,t,r,n,i){var s=this.state.inMethod;return this.state.inMethod=!1,this.initFunction(e,n),this.match(j.star)&&(e.async&&!this.hasPlugin("asyncGenerators")?this.unexpected():(e.generator=!0,this.next())),!t||i||this.match(j.name)||this.match(j._yield)||this.unexpected(),(this.match(j.name)||this.match(j._yield))&&(e.id=this.parseBindingIdentifier()),this.parseFunctionParams(e),this.parseFunctionBody(e,r),this.state.inMethod=s,this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression")},H.parseFunctionParams=function(e){this.expect(j.parenL),e.params=this.parseBindingList(j.parenR)},H.parseClass=function(e,t,r){return this.next(),this.takeDecorators(e),this.parseClassId(e,t,r),this.parseClassSuper(e),this.parseClassBody(e),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},H.isClassProperty=function(){return this.match(j.eq)||this.isLineTerminator()},H.isClassMutatorStarter=function(){return!1},H.parseClassBody=function(e){var t=this.state.strict;this.state.strict=!0;var r=!1,n=!1,i=[],s=this.startNode();for(s.body=[],this.expect(j.braceL);!this.eat(j.braceR);)if(this.eat(j.semi))i.length>0&&this.raise(this.state.lastTokEnd,"Decorators must not be followed by a semicolon");else if(this.match(j.at))i.push(this.parseDecorator());else{var a=this.startNode();i.length&&(a.decorators=i,i=[]);var o=!1,u=this.match(j.name)&&"static"===this.state.value,l=this.eat(j.star),c=!1,p=!1;if(this.parsePropertyName(a),a.static=u&&!this.match(j.parenL),a.static&&(l=this.eat(j.star),this.parsePropertyName(a)),!l){if(this.isClassProperty()){s.body.push(this.parseClassProperty(a));continue}"Identifier"===a.key.type&&!a.computed&&this.hasPlugin("classConstructorCall")&&"call"===a.key.name&&this.match(j.name)&&"constructor"===this.state.value&&(o=!0,this.parsePropertyName(a))}var h=!this.match(j.parenL)&&!a.computed&&"Identifier"===a.key.type&&"async"===a.key.name;if(h&&(this.hasPlugin("asyncGenerators")&&this.eat(j.star)&&(l=!0),p=!0,this.parsePropertyName(a)),a.kind="method",!a.computed){var f=a.key;p||l||this.isClassMutatorStarter()||"Identifier"!==f.type||this.match(j.parenL)||"get"!==f.name&&"set"!==f.name||(c=!0,a.kind=f.name,f=this.parsePropertyName(a));var d=!(o||a.static||"constructor"!==f.name&&"constructor"!==f.value);d&&(n&&this.raise(f.start,"Duplicate constructor in the same class"),c&&this.raise(f.start,"Constructor can't have get/set modifier"),l&&this.raise(f.start,"Constructor can't be a generator"),p&&this.raise(f.start,"Constructor can't be an async function"),a.kind="constructor",n=!0);var m=a.static&&("prototype"===f.name||"prototype"===f.value);m&&this.raise(f.start,"Classes may not have static property named prototype")}o&&(r&&this.raise(a.start,"Duplicate constructor call in the same class"),a.kind="constructorCall",r=!0),"constructor"!==a.kind&&"constructorCall"!==a.kind||!a.decorators||this.raise(a.start,"You can't attach decorators to a class constructor"),this.parseClassMethod(s,a,l,p),c&&this.checkGetterSetterParamCount(a)}i.length&&this.raise(this.state.start,"You have trailing decorators with no method"),e.body=this.finishNode(s,"ClassBody"),this.state.strict=t},H.parseClassProperty=function(e){return this.match(j.eq)?(this.hasPlugin("classProperties")||this.unexpected(),this.next(),e.value=this.parseMaybeAssign()):e.value=null,this.semicolon(),this.finishNode(e,"ClassProperty")},H.parseClassMethod=function(e,t,r,n){this.parseMethod(t,r,n),e.body.push(this.finishNode(t,"ClassMethod"))},H.parseClassId=function(e,t,r){this.match(j.name)?e.id=this.parseIdentifier():r||!t?e.id=null:this.unexpected()},H.parseClassSuper=function(e){e.superClass=this.eat(j._extends)?this.parseExprSubscripts():null},H.parseExport=function(e){if(this.next(),this.match(j.star)){var t=this.startNode();if(this.next(),!this.hasPlugin("exportExtensions")||!this.eatContextual("as"))return this.parseExportFrom(e,!0),this.finishNode(e,"ExportAllDeclaration");t.exported=this.parseIdentifier(),e.specifiers=[this.finishNode(t,"ExportNamespaceSpecifier")],this.parseExportSpecifiersMaybe(e),this.parseExportFrom(e,!0)}else if(this.hasPlugin("exportExtensions")&&this.isExportDefaultSpecifier()){var r=this.startNode();if(r.exported=this.parseIdentifier(!0),e.specifiers=[this.finishNode(r,"ExportDefaultSpecifier")],this.match(j.comma)&&this.lookahead().type===j.star){this.expect(j.comma);var n=this.startNode();this.expect(j.star),this.expectContextual("as"),n.exported=this.parseIdentifier(),e.specifiers.push(this.finishNode(n,"ExportNamespaceSpecifier"))}else this.parseExportSpecifiersMaybe(e);this.parseExportFrom(e,!0)}else{if(this.eat(j._default)){var i=this.startNode(),s=!1;return this.eat(j._function)?i=this.parseFunction(i,!0,!1,!1,!0):this.match(j._class)?i=this.parseClass(i,!0,!0):(s=!0,i=this.parseMaybeAssign()),e.declaration=i,s&&this.semicolon(),this.checkExport(e,!0,!0),this.finishNode(e,"ExportDefaultDeclaration")}this.shouldParseExportDeclaration()?(e.specifiers=[],e.source=null,e.declaration=this.parseExportDeclaration(e)):(e.declaration=null,e.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(e))}return this.checkExport(e,!0),this.finishNode(e,"ExportNamedDeclaration")},H.parseExportDeclaration=function(){return this.parseStatement(!0)},H.isExportDefaultSpecifier=function(){if(this.match(j.name))return"type"!==this.state.value&&"async"!==this.state.value&&"interface"!==this.state.value;if(!this.match(j._default))return!1;var e=this.lookahead();return e.type===j.comma||e.type===j.name&&"from"===e.value},H.parseExportSpecifiersMaybe=function(e){this.eat(j.comma)&&(e.specifiers=e.specifiers.concat(this.parseExportSpecifiers()))},H.parseExportFrom=function(e,t){this.eatContextual("from")?(e.source=this.match(j.string)?this.parseExprAtom():this.unexpected(),this.checkExport(e)):t?this.unexpected():e.source=null,this.semicolon()},H.shouldParseExportDeclaration=function(){return"var"===this.state.type.keyword||"const"===this.state.type.keyword||"let"===this.state.type.keyword||"function"===this.state.type.keyword||"class"===this.state.type.keyword||this.isContextual("async")},H.checkExport=function(e,t,r){if(t)if(r)this.checkDuplicateExports(e,"default");else if(e.specifiers&&e.specifiers.length)for(var n=e.specifiers,i=Array.isArray(n),s=0,n=i?n:n[Symbol.iterator]();;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;this.checkDuplicateExports(o,o.exported.name)}else if(e.declaration)if("FunctionDeclaration"===e.declaration.type||"ClassDeclaration"===e.declaration.type)this.checkDuplicateExports(e,e.declaration.id.name);else if("VariableDeclaration"===e.declaration.type)for(var u=e.declaration.declarations,l=Array.isArray(u),c=0,u=l?u:u[Symbol.iterator]();;){var p;if(l){if(c>=u.length)break;p=u[c++]}else{if(c=u.next(),c.done)break;p=c.value}var h=p;this.checkDeclaration(h.id)}if(this.state.decorators.length){var f=e.declaration&&("ClassDeclaration"===e.declaration.type||"ClassExpression"===e.declaration.type);e.declaration&&f||this.raise(e.start,"You can only use decorators on an export when exporting a class"),this.takeDecorators(e.declaration)}},H.checkDeclaration=function(e){if("ObjectPattern"===e.type)for(var t=e.properties,r=Array.isArray(t),n=0,t=r?t:t[Symbol.iterator]();;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if(n=t.next(),n.done)break;i=n.value}var s=i;this.checkDeclaration(s)}else if("ArrayPattern"===e.type)for(var a=e.elements,o=Array.isArray(a),u=0,a=o?a:a[Symbol.iterator]();;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;c&&this.checkDeclaration(c)}else"ObjectProperty"===e.type?this.checkDeclaration(e.value):"RestElement"===e.type||"RestProperty"===e.type?this.checkDeclaration(e.argument):"Identifier"===e.type&&this.checkDuplicateExports(e,e.name)},H.checkDuplicateExports=function(e,t){this.state.exportedIdentifiers.indexOf(t)>-1&&this.raiseDuplicateExportError(e,t),this.state.exportedIdentifiers.push(t)},H.raiseDuplicateExportError=function(e,t){this.raise(e.start,"default"===t?"Only one default export allowed per module.":"`"+t+"` has already been exported. Exported identifiers must be unique.")},H.parseExportSpecifiers=function(){var e=[],t=!0,r=void 0;for(this.expect(j.braceL);!this.eat(j.braceR);){if(t)t=!1;else if(this.expect(j.comma),this.eat(j.braceR))break;var n=this.match(j._default);n&&!r&&(r=!0);var i=this.startNode();i.local=this.parseIdentifier(n),i.exported=this.eatContextual("as")?this.parseIdentifier(!0):i.local.__clone(),e.push(this.finishNode(i,"ExportSpecifier"))}return r&&!this.isContextual("from")&&this.unexpected(),e},H.parseImport=function(e){return this.eat(j._import),this.match(j.string)?(e.specifiers=[],e.source=this.parseExprAtom()):(e.specifiers=[],this.parseImportSpecifiers(e),this.expectContextual("from"),e.source=this.match(j.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},H.parseImportSpecifiers=function(e){var t=!0;if(this.match(j.name)){var r=this.state.start,n=this.state.startLoc;if(e.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(),r,n)),!this.eat(j.comma))return}if(this.match(j.star)){var i=this.startNode();return this.next(),this.expectContextual("as"),i.local=this.parseIdentifier(),this.checkLVal(i.local,!0,void 0,"import namespace specifier"),void e.specifiers.push(this.finishNode(i,"ImportNamespaceSpecifier"))}for(this.expect(j.braceL);!this.eat(j.braceR);){if(t)t=!1;else if(this.eat(j.colon)&&this.unexpected(null,"ES2015 named imports do not destructure. Use another statement for destructuring after the import."),this.expect(j.comma),this.eat(j.braceR))break;this.parseImportSpecifier(e)}},H.parseImportSpecifier=function(e){var t=this.startNode();t.imported=this.parseIdentifier(!0),this.eatContextual("as")?t.local=this.parseIdentifier():(this.checkReservedWord(t.imported.name,t.start,!0,!0),t.local=t.imported.__clone()),this.checkLVal(t.local,!0,void 0,"import specifier"),e.specifiers.push(this.finishNode(t,"ImportSpecifier"))},H.parseImportSpecifierDefault=function(e,t,r){var n=this.startNodeAt(t,r);return n.local=e,this.checkLVal(n.local,!0,void 0,"default import specifier"),this.finishNode(n,"ImportDefaultSpecifier")};var ee=z.prototype;ee.toAssignable=function(e,t,r){if(e)switch(e.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":e.type="ObjectPattern";for(var n=e.properties,i=Array.isArray(n),s=0,n=i?n:n[Symbol.iterator]();;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if(s=n.next(),s.done)break;a=s.value}var o=a;"ObjectMethod"===o.type?"get"===o.kind||"set"===o.kind?this.raise(o.key.start,"Object pattern can't contain getter or setter"):this.raise(o.key.start,"Object pattern can't contain methods"):this.toAssignable(o,t,"object destructuring pattern")}break;case"ObjectProperty":this.toAssignable(e.value,t,r);break;case"SpreadProperty":e.type="RestProperty";break;case"ArrayExpression":e.type="ArrayPattern",this.toAssignableList(e.elements,t,r);break;case"AssignmentExpression":"="===e.operator?(e.type="AssignmentPattern",delete e.operator):this.raise(e.left.end,"Only '=' operator can be used for specifying default value.");break;case"MemberExpression":if(!t)break;default:var u="Invalid left-hand side"+(r?" in "+r:"expression");this.raise(e.start,u)}return e},ee.toAssignableList=function(e,t,r){var n=e.length;if(n){var i=e[n-1];if(i&&"RestElement"===i.type)--n;else if(i&&"SpreadElement"===i.type){i.type="RestElement";var s=i.argument;this.toAssignable(s,t,r),"Identifier"!==s.type&&"MemberExpression"!==s.type&&"ArrayPattern"!==s.type&&this.unexpected(s.start),--n}}for(var a=0;a=s.length)break;u=s[o++]}else{if(o=s.next(),o.done)break;u=o.value}var l=u +;"ObjectProperty"===l.type&&(l=l.value),this.checkLVal(l,t,r,"object destructuring pattern")}break;case"ArrayPattern":for(var c=e.elements,p=Array.isArray(c),h=0,c=p?c:c[Symbol.iterator]();;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if(h=c.next(),h.done)break;f=h.value}var d=f;d&&this.checkLVal(d,t,r,"array destructuring pattern")}break;case"AssignmentPattern":this.checkLVal(e.left,t,r,"assignment pattern");break;case"RestProperty":this.checkLVal(e.argument,t,r,"rest property");break;case"RestElement":this.checkLVal(e.argument,t,r,"rest element");break;default:var m=(t?"Binding invalid":"Invalid")+" left-hand side"+(n?" in "+n:"expression");this.raise(e.start,m)}};var te=z.prototype;te.checkPropClash=function(e,t){if(!e.computed&&!e.kind){var r=e.key;"__proto__"===("Identifier"===r.type?r.name:String(r.value))&&(t.proto&&this.raise(r.start,"Redefinition of __proto__ property"),t.proto=!0)}},te.getExpression=function(){this.nextToken();var e=this.parseExpression();return this.match(j.eof)||this.unexpected(),e},te.parseExpression=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeAssign(e,t);if(this.match(j.comma)){var s=this.startNodeAt(r,n);for(s.expressions=[i];this.eat(j.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return i},te.parseMaybeAssign=function(e,t,r,n){var i=this.state.start,s=this.state.startLoc;if(this.match(j._yield)&&this.state.inGenerator){var a=this.parseYield();return r&&(a=r.call(this,a,i,s)),a}var o=void 0;t?o=!1:(t={start:0},o=!0),(this.match(j.parenL)||this.match(j.name))&&(this.state.potentialArrowAt=this.state.start);var u=this.parseMaybeConditional(e,t,n);if(r&&(u=r.call(this,u,i,s)),this.state.type.isAssign){var l=this.startNodeAt(i,s);if(l.operator=this.state.value,l.left=this.match(j.eq)?this.toAssignable(u,void 0,"assignment expression"):u,t.start=0,this.checkLVal(u,void 0,void 0,"assignment expression"),u.extra&&u.extra.parenthesized){var c=void 0;"ObjectPattern"===u.type?c="`({a}) = 0` use `({a} = 0)`":"ArrayPattern"===u.type&&(c="`([a]) = 0` use `([a] = 0)`"),c&&this.raise(u.start,"You're trying to assign to a parenthesized expression, eg. instead of "+c)}return this.next(),l.right=this.parseMaybeAssign(e),this.finishNode(l,"AssignmentExpression")}return o&&t.start&&this.unexpected(t.start),u},te.parseMaybeConditional=function(e,t,r){var n=this.state.start,i=this.state.startLoc,s=this.parseExprOps(e,t);return t&&t.start?s:this.parseConditional(s,e,n,i,r)},te.parseConditional=function(e,t,r,n){if(this.eat(j.question)){var i=this.startNodeAt(r,n);return i.test=e,i.consequent=this.parseMaybeAssign(),this.expect(j.colon),i.alternate=this.parseMaybeAssign(t),this.finishNode(i,"ConditionalExpression")}return e},te.parseExprOps=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeUnary(t);return t&&t.start?i:this.parseExprOp(i,r,n,-1,e)},te.parseExprOp=function(e,t,r,n,i){var s=this.state.type.binop;if(!(null==s||i&&this.match(j._in))&&s>n){var a=this.startNodeAt(t,r);a.left=e,a.operator=this.state.value,"**"!==a.operator||"UnaryExpression"!==e.type||!e.extra||e.extra.parenthesizedArgument||e.extra.parenthesized||this.raise(e.argument.start,"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");var o=this.state.type;this.next();var u=this.state.start,l=this.state.startLoc;return a.right=this.parseExprOp(this.parseMaybeUnary(),u,l,o.rightAssociative?s-1:s,i),this.finishNode(a,o===j.logicalOR||o===j.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(a,t,r,n,i)}return e},te.parseMaybeUnary=function(e){if(this.state.type.prefix){var t=this.startNode(),r=this.match(j.incDec);t.operator=this.state.value,t.prefix=!0,this.next();var n=this.state.type;return t.argument=this.parseMaybeUnary(),this.addExtra(t,"parenthesizedArgument",!(n!==j.parenL||t.argument.extra&&t.argument.extra.parenthesized)),e&&e.start&&this.unexpected(e.start),r?this.checkLVal(t.argument,void 0,void 0,"prefix operation"):this.state.strict&&"delete"===t.operator&&"Identifier"===t.argument.type&&this.raise(t.start,"Deleting local variable in strict mode"),this.finishNode(t,r?"UpdateExpression":"UnaryExpression")}var i=this.state.start,s=this.state.startLoc,a=this.parseExprSubscripts(e);if(e&&e.start)return a;for(;this.state.type.postfix&&!this.canInsertSemicolon();){var o=this.startNodeAt(i,s);o.operator=this.state.value,o.prefix=!1,o.argument=a,this.checkLVal(a,void 0,void 0,"postfix operation"),this.next(),a=this.finishNode(o,"UpdateExpression")}return a},te.parseExprSubscripts=function(e){var t=this.state.start,r=this.state.startLoc,n=this.state.potentialArrowAt,i=this.parseExprAtom(e);return"ArrowFunctionExpression"===i.type&&i.start===n?i:e&&e.start?i:this.parseSubscripts(i,t,r)},te.parseSubscripts=function(e,t,r,n){for(;;){if(!n&&this.eat(j.doubleColon)){var i=this.startNodeAt(t,r);return i.object=e,i.callee=this.parseNoCallExpr(),this.parseSubscripts(this.finishNode(i,"BindExpression"),t,r,n)}if(this.eat(j.dot)){var s=this.startNodeAt(t,r);s.object=e,s.property=this.parseIdentifier(!0),s.computed=!1,e=this.finishNode(s,"MemberExpression")}else if(this.eat(j.bracketL)){var a=this.startNodeAt(t,r);a.object=e,a.property=this.parseExpression(),a.computed=!0,this.expect(j.bracketR),e=this.finishNode(a,"MemberExpression")}else if(!n&&this.match(j.parenL)){var o=this.state.potentialArrowAt===e.start&&"Identifier"===e.type&&"async"===e.name&&!this.canInsertSemicolon();this.next();var u=this.startNodeAt(t,r);if(u.callee=e,u.arguments=this.parseCallExpressionArguments(j.parenR,o),"Import"===u.callee.type&&1!==u.arguments.length&&this.raise(u.start,"import() requires exactly one argument"),e=this.finishNode(u,"CallExpression"),o&&this.shouldParseAsyncArrow())return this.parseAsyncArrowFromCallExpression(this.startNodeAt(t,r),u);this.toReferencedList(u.arguments)}else{if(!this.match(j.backQuote))return e;var l=this.startNodeAt(t,r);l.tag=e,l.quasi=this.parseTemplate(),e=this.finishNode(l,"TaggedTemplateExpression")}}},te.parseCallExpressionArguments=function(e,t){for(var r=[],n=void 0,i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(j.comma),this.eat(e))break;this.match(j.parenL)&&!n&&(n=this.state.start),r.push(this.parseExprListItem(!1,t?{start:0}:void 0,t?{start:0}:void 0))}return t&&n&&this.shouldParseAsyncArrow()&&this.unexpected(),r},te.shouldParseAsyncArrow=function(){return this.match(j.arrow)},te.parseAsyncArrowFromCallExpression=function(e,t){return this.expect(j.arrow),this.parseArrowExpression(e,t.arguments,!0)},te.parseNoCallExpr=function(){var e=this.state.start,t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),e,t,!0)},te.parseExprAtom=function(e){var t=this.state.potentialArrowAt===this.state.start,r=void 0;switch(this.state.type){case j._super:return this.state.inMethod||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"'super' outside of function or class"),r=this.startNode(),this.next(),this.match(j.parenL)||this.match(j.bracketL)||this.match(j.dot)||this.unexpected(),this.match(j.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(r.start,"super() outside of class constructor"),this.finishNode(r,"Super");case j._import:return this.hasPlugin("dynamicImport")||this.unexpected(),r=this.startNode(),this.next(),this.match(j.parenL)||this.unexpected(null,j.parenL),this.finishNode(r,"Import");case j._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case j._yield:this.state.inGenerator&&this.unexpected();case j.name:r=this.startNode();var n="await"===this.state.value&&this.state.inAsync,i=this.shouldAllowYieldIdentifier(),s=this.parseIdentifier(n||i);if("await"===s.name){if(this.state.inAsync||this.inModule)return this.parseAwait(r)}else{if("async"===s.name&&this.match(j._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(r,!1,!1,!0);if(t&&"async"===s.name&&this.match(j.name)){var a=[this.parseIdentifier()];return this.expect(j.arrow),this.parseArrowExpression(r,a,!0)}}return t&&!this.canInsertSemicolon()&&this.eat(j.arrow)?this.parseArrowExpression(r,[s]):s;case j._do:if(this.hasPlugin("doExpressions")){var o=this.startNode();this.next();var u=this.state.inFunction,l=this.state.labels;return this.state.labels=[],this.state.inFunction=!1,o.body=this.parseBlock(!1,!0),this.state.inFunction=u,this.state.labels=l,this.finishNode(o,"DoExpression")}case j.regexp:var c=this.state.value;return r=this.parseLiteral(c.value,"RegExpLiteral"),r.pattern=c.pattern,r.flags=c.flags,r;case j.num:return this.parseLiteral(this.state.value,"NumericLiteral");case j.string:return this.parseLiteral(this.state.value,"StringLiteral");case j._null:return r=this.startNode(),this.next(),this.finishNode(r,"NullLiteral");case j._true:case j._false:return r=this.startNode(),r.value=this.match(j._true),this.next(),this.finishNode(r,"BooleanLiteral");case j.parenL:return this.parseParenAndDistinguishExpression(null,null,t);case j.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(j.bracketR,!0,e),this.toReferencedList(r.elements),this.finishNode(r,"ArrayExpression");case j.braceL:return this.parseObj(!1,e);case j._function:return this.parseFunctionExpression();case j.at:this.parseDecorators();case j._class:return r=this.startNode(),this.takeDecorators(r),this.parseClass(r,!1);case j._new:return this.parseNew();case j.backQuote:return this.parseTemplate();case j.doubleColon:r=this.startNode(),this.next(),r.object=null;var p=r.callee=this.parseNoCallExpr();if("MemberExpression"===p.type)return this.finishNode(r,"BindExpression");this.raise(p.start,"Binding should be performed on object property.");default:this.unexpected()}},te.parseFunctionExpression=function(){var e=this.startNode(),t=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(j.dot)&&this.hasPlugin("functionSent")?this.parseMetaProperty(e,t,"sent"):this.parseFunction(e,!1)},te.parseMetaProperty=function(e,t,r){return e.meta=t,e.property=this.parseIdentifier(!0),e.property.name!==r&&this.raise(e.property.start,"The only valid meta property for new is "+t.name+"."+r),this.finishNode(e,"MetaProperty")},te.parseLiteral=function(e,t,r,n){r=r||this.state.start,n=n||this.state.startLoc;var i=this.startNodeAt(r,n);return this.addExtra(i,"rawValue",e),this.addExtra(i,"raw",this.input.slice(r,this.state.end)),i.value=e,this.next(),this.finishNode(i,t)},te.parseParenExpression=function(){this.expect(j.parenL);var e=this.parseExpression();return this.expect(j.parenR),e},te.parseParenAndDistinguishExpression=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;var n=void 0;this.expect(j.parenL);for(var i=this.state.start,s=this.state.startLoc,a=[],o={start:0},u={start:0},l=!0,c=void 0,p=void 0;!this.match(j.parenR);){if(l)l=!1;else if(this.expect(j.comma,u.start||null),this.match(j.parenR)){p=this.state.start;break}if(this.match(j.ellipsis)){var h=this.state.start,f=this.state.startLoc;c=this.state.start,a.push(this.parseParenItem(this.parseRest(),f,h));break}a.push(this.parseMaybeAssign(!1,o,this.parseParenItem,u))}var d=this.state.start,m=this.state.startLoc;this.expect(j.parenR);var y=this.startNodeAt(e,t);if(r&&this.shouldParseArrow()&&(y=this.parseArrow(y))){for(var g=a,b=Array.isArray(g),v=0,g=b?g:g[Symbol.iterator]();;){var x;if(b){if(v>=g.length)break;x=g[v++]}else{if(v=g.next(),v.done)break;x=v.value}var E=x;E.extra&&E.extra.parenthesized&&this.unexpected(E.extra.parenStart)}return this.parseArrowExpression(y,a)}return a.length||this.unexpected(this.state.lastTokStart),p&&this.unexpected(p),c&&this.unexpected(c),o.start&&this.unexpected(o.start),u.start&&this.unexpected(u.start),a.length>1?(n=this.startNodeAt(i,s),n.expressions=a,this.toReferencedList(n.expressions),this.finishNodeAt(n,"SequenceExpression",d,m)):n=a[0],this.addExtra(n,"parenthesized",!0),this.addExtra(n,"parenStart",e),n},te.shouldParseArrow=function(){return!this.canInsertSemicolon()},te.parseArrow=function(e){if(this.eat(j.arrow))return e},te.parseParenItem=function(e){return e},te.parseNew=function(){var e=this.startNode(),t=this.parseIdentifier(!0);return this.eat(j.dot)?this.parseMetaProperty(e,t,"target"):(e.callee=this.parseNoCallExpr(),this.eat(j.parenL)?(e.arguments=this.parseExprList(j.parenR),this.toReferencedList(e.arguments)):e.arguments=[],this.finishNode(e,"NewExpression"))},te.parseTemplateElement=function(){var e=this.startNode();return e.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),e.tail=this.match(j.backQuote),this.finishNode(e,"TemplateElement")},te.parseTemplate=function(){var e=this.startNode();this.next(),e.expressions=[];var t=this.parseTemplateElement();for(e.quasis=[t];!t.tail;)this.expect(j.dollarBraceL),e.expressions.push(this.parseExpression()),this.expect(j.braceR),e.quasis.push(t=this.parseTemplateElement());return this.next(),this.finishNode(e,"TemplateLiteral")},te.parseObj=function(e,t){var r=[],n=Object.create(null),i=!0,s=this.startNode();s.properties=[],this.next();for(var a=null;!this.eat(j.braceR);){if(i)i=!1;else if(this.expect(j.comma),this.eat(j.braceR))break;for(;this.match(j.at);)r.push(this.parseDecorator());var o=this.startNode(),u=!1,l=!1,c=void 0,p=void 0;if(r.length&&(o.decorators=r,r=[]),this.hasPlugin("objectRestSpread")&&this.match(j.ellipsis)){if(o=this.parseSpread(e?{start:0}:void 0),o.type=e?"RestProperty":"SpreadProperty",e&&this.toAssignable(o.argument,!0,"object pattern"),s.properties.push(o),!e)continue;var h=this.state.start;if(null===a){if(this.eat(j.braceR))break;if(this.match(j.comma)&&this.lookahead().type===j.braceR)continue;a=h;continue}this.unexpected(a,"Cannot have multiple rest elements when destructuring")}if(o.method=!1,o.shorthand=!1,(e||t)&&(c=this.state.start,p=this.state.startLoc),e||(u=this.eat(j.star)),!e&&this.isContextual("async")){u&&this.unexpected();var f=this.parseIdentifier();this.match(j.colon)||this.match(j.parenL)||this.match(j.braceR)||this.match(j.eq)||this.match(j.comma)?(o.key=f,o.computed=!1):(l=!0,this.hasPlugin("asyncGenerators")&&(u=this.eat(j.star)),this.parsePropertyName(o))}else this.parsePropertyName(o);this.parseObjPropValue(o,c,p,u,l,e,t),this.checkPropClash(o,n),o.shorthand&&this.addExtra(o,"shorthand",!0),s.properties.push(o)}return null!==a&&this.unexpected(a,"The rest element has to be the last element when destructuring"),r.length&&this.raise(this.state.start,"You have trailing decorators with no property"),this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},te.isGetterOrSetterMethod=function(e,t){return!t&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&(this.match(j.string)||this.match(j.num)||this.match(j.bracketL)||this.match(j.name)||this.state.type.keyword)},te.checkGetterSetterParamCount=function(e){var t="get"===e.kind?0:1;if(e.params.length!==t){var r=e.start;"get"===e.kind?this.raise(r,"getter should have no params"):this.raise(r,"setter should have exactly one param")}},te.parseObjectMethod=function(e,t,r,n){return r||t||this.match(j.parenL)?(n&&this.unexpected(),e.kind="method",e.method=!0,this.parseMethod(e,t,r),this.finishNode(e,"ObjectMethod")):this.isGetterOrSetterMethod(e,n)?((t||r)&&this.unexpected(),e.kind=e.key.name,this.parsePropertyName(e),this.parseMethod(e),this.checkGetterSetterParamCount(e),this.finishNode(e,"ObjectMethod")):void 0},te.parseObjectProperty=function(e,t,r,n,i){return this.eat(j.colon)?(e.value=n?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,i),this.finishNode(e,"ObjectProperty")):e.computed||"Identifier"!==e.key.type?void 0:(n?(this.checkReservedWord(e.key.name,e.key.start,!0,!0),e.value=this.parseMaybeDefault(t,r,e.key.__clone())):this.match(j.eq)&&i?(i.start||(i.start=this.state.start),e.value=this.parseMaybeDefault(t,r,e.key.__clone())):e.value=e.key.__clone(),e.shorthand=!0,this.finishNode(e,"ObjectProperty"))},te.parseObjPropValue=function(e,t,r,n,i,s,a){var o=this.parseObjectMethod(e,n,i,s)||this.parseObjectProperty(e,t,r,s,a);return o||this.unexpected(),o},te.parsePropertyName=function(e){if(this.eat(j.bracketL))e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(j.bracketR);else{e.computed=!1;var t=this.state.inPropertyName;this.state.inPropertyName=!0,e.key=this.match(j.num)||this.match(j.string)?this.parseExprAtom():this.parseIdentifier(!0),this.state.inPropertyName=t}return e.key},te.initFunction=function(e,t){e.id=null,e.generator=!1,e.expression=!1,e.async=!!t},te.parseMethod=function(e,t,r){var n=this.state.inMethod;return this.state.inMethod=e.kind||!0,this.initFunction(e,r),this.expect(j.parenL),e.params=this.parseBindingList(j.parenR),e.generator=!!t,this.parseFunctionBody(e),this.state.inMethod=n,e},te.parseArrowExpression=function(e,t,r){return this.initFunction(e,r),e.params=this.toAssignableList(t,!0,"arrow function parameters"),this.parseFunctionBody(e,!0),this.finishNode(e,"ArrowFunctionExpression")},te.isStrictBody=function(e,t){if(!t&&e.body.directives.length)for(var r=e.body.directives,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if("use strict"===a.value.value)return!0}return!1},te.parseFunctionBody=function(e,t){var r=t&&!this.match(j.braceL),n=this.state.inAsync;if(this.state.inAsync=e.async,r)e.body=this.parseMaybeAssign(),e.expression=!0;else{var i=this.state.inFunction,s=this.state.inGenerator,a=this.state.labels;this.state.inFunction=!0,this.state.inGenerator=e.generator,this.state.labels=[],e.body=this.parseBlock(!0),e.expression=!1,this.state.inFunction=i,this.state.inGenerator=s,this.state.labels=a}this.state.inAsync=n;var o=this.isStrictBody(e,r),u=this.state.strict||t||o;if(o&&e.id&&"Identifier"===e.id.type&&"yield"===e.id.name&&this.raise(e.id.start,"Binding yield in strict mode"),u){var l=Object.create(null),c=this.state.strict;o&&(this.state.strict=!0),e.id&&this.checkLVal(e.id,!0,void 0,"function name");for(var p=e.params,h=Array.isArray(p),f=0,p=h?p:p[Symbol.iterator]();;){var d;if(h){if(f>=p.length)break;d=p[f++]}else{if(f=p.next(),f.done)break;d=f.value}var m=d;o&&"Identifier"!==m.type&&this.raise(m.start,"Non-simple parameter in strict mode"),this.checkLVal(m,!0,l,"function parameter list")}this.state.strict=c}},te.parseExprList=function(e,t,r){for(var n=[],i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(j.comma),this.eat(e))break;n.push(this.parseExprListItem(t,r))}return n},te.parseExprListItem=function(e,t,r){return e&&this.match(j.comma)?null:this.match(j.ellipsis)?this.parseSpread(t):this.parseMaybeAssign(!1,t,this.parseParenItem,r)},te.parseIdentifier=function(e){var t=this.startNode();return e||this.checkReservedWord(this.state.value,this.state.start,!!this.state.type.keyword,!1),this.match(j.name)?t.name=this.state.value:this.state.type.keyword?t.name=this.state.type.keyword:this.unexpected(),!e&&"await"===t.name&&this.state.inAsync&&this.raise(t.start,"invalid use of await inside of an async function"),t.loc.identifierName=t.name,this.next(),this.finishNode(t,"Identifier")},te.checkReservedWord=function(e,t,r,n){(this.isReservedWord(e)||r&&this.isKeyword(e))&&this.raise(t,e+" is a reserved word"),this.state.strict&&(g.strict(e)||n&&g.strictBind(e))&&this.raise(t,e+" is a reserved word in strict mode")},te.parseAwait=function(e){return this.state.inAsync||this.unexpected(),this.match(j.star)&&this.raise(e.start,"await* has been removed from the async functions proposal. Use Promise.all() instead."),e.argument=this.parseMaybeUnary(),this.finishNode(e,"AwaitExpression")},te.parseYield=function(){var e=this.startNode();return this.next(),this.match(j.semi)||this.canInsertSemicolon()||!this.match(j.star)&&!this.state.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(j.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")};var re=z.prototype,ne=["leadingComments","trailingComments","innerComments"],ie=function(){function e(t,r,n){w(this,e),this.type="",this.start=t,this.end=0,this.loc=new q(r),n&&(this.loc.filename=n)}return e.prototype.__clone=function(){var t=new e;for(var r in this)ne.indexOf(r)<0&&(t[r]=this[r]);return t},e}();re.startNode=function(){return new ie(this.state.start,this.state.startLoc,this.filename)},re.startNodeAt=function(e,t){return new ie(e,t,this.filename)},re.finishNode=function(e,t){return p.call(this,e,t,this.state.lastTokEnd,this.state.lastTokEndLoc)},re.finishNodeAt=function(e,t,r,n){return p.call(this,e,t,r,n)},z.prototype.raise=function(e,t){var r=l(this.input,e);t+=" ("+r.line+":"+r.column+")";var n=new SyntaxError(t);throw n.pos=e,n.loc=r,n};var se=z.prototype;se.addComment=function(e){this.filename&&(e.loc.filename=this.filename),this.state.trailingComments.push(e),this.state.leadingComments.push(e)},se.processComment=function(e){if(!("Program"===e.type&&e.body.length>0)){var t=this.state.commentStack,r=void 0,n=void 0,i=void 0,s=void 0;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=e.end?(n=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else{var a=h(t);t.length>0&&a.trailingComments&&a.trailingComments[0].start>=e.end&&(n=a.trailingComments,a.trailingComments=null)}for(;t.length>0&&h(t).start>=e.start;)r=t.pop();if(r){if(r.leadingComments)if(r!==e&&h(r.leadingComments).end<=e.start)e.leadingComments=r.leadingComments,r.leadingComments=null;else for(i=r.leadingComments.length-2;i>=0;--i)if(r.leadingComments[i].end<=e.start){e.leadingComments=r.leadingComments.splice(0,i+1);break}}else if(this.state.leadingComments.length>0)if(h(this.state.leadingComments).end<=e.start){if(this.state.commentPreviousNode)for(s=0;s0&&(e.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(i=0;ie.start);i++);e.leadingComments=this.state.leadingComments.slice(0,i),0===e.leadingComments.length&&(e.leadingComments=null),n=this.state.leadingComments.slice(i),0===n.length&&(n=null)}this.state.commentPreviousNode=e,n&&(n.length&&n[0].start>=e.start&&h(n).end<=e.end?e.innerComments=n:e.trailingComments=n),t.push(e)}};var ae=z.prototype;ae.estreeParseRegExpLiteral=function(e){var t=e.pattern,r=e.flags,n=null;try{n=new RegExp(t,r)}catch(e){}var i=this.estreeParseLiteral(n);return i.regex={pattern:t,flags:r},i},ae.estreeParseLiteral=function(e){return this.parseLiteral(e,"Literal")},ae.directiveToStmt=function(e){var t=e.value,r=this.startNodeAt(e.start,e.loc.start),n=this.startNodeAt(t.start,t.loc.start);return n.value=t.value,n.raw=t.extra.raw,r.expression=this.finishNodeAt(n,"Literal",t.end,t.loc.end),r.directive=t.extra.raw.slice(1,-1),this.finishNodeAt(r,"ExpressionStatement",e.end,e.loc.end)};var oe=function(e){e.extend("checkDeclaration",function(e){return function(t){f(t)?this.checkDeclaration(t.value):e.call(this,t)}}),e.extend("checkGetterSetterParamCount",function(){return function(e){var t="get"===e.kind?0:1;if(e.value.params.length!==t){var r=e.start;"get"===e.kind?this.raise(r,"getter should have no params"):this.raise(r,"setter should have exactly one param")}}}),e.extend("checkLVal",function(e){return function(t,r,n){var i=this;switch(t.type){case"ObjectPattern":t.properties.forEach(function(e){i.checkLVal("Property"===e.type?e.value:e,r,n,"object destructuring pattern")});break;default:for(var s=arguments.length,a=Array(s>3?s-3:0),o=3;o0)for(var r=e.body.body,n=Array.isArray(r),i=0,r=n?r:r[Symbol.iterator]();;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if(i=r.next(),i.done)break;s=i.value}var a=s;if("ExpressionStatement"!==a.type||"Literal"!==a.expression.type)break;if("use strict"===a.expression.value)return!0}return!1}}),e.extend("isValidDirective",function(){return function(e){return!("ExpressionStatement"!==e.type||"Literal"!==e.expression.type||"string"!=typeof e.expression.value||e.expression.extra&&e.expression.extra.parenthesized)}}),e.extend("parseBlockBody",function(e){return function(t){for(var r=this,n=arguments.length,i=Array(n>1?n-1:0),s=1;s1?r-1:0),i=1;i1?n-1:0),s=1;s2?n-2:0),s=2;s=a.length)break;l=a[u++]}else{if(u=a.next(),u.done)break;l=u.value}var c=l;"get"===c.kind||"set"===c.kind?this.raise(c.key.start,"Object pattern can't contain getter or setter"):c.method?this.raise(c.key.start,"Object pattern can't contain methods"):this.toAssignable(c,r,"object destructuring pattern")}return t}return e.call.apply(e,[this,t,r].concat(i))}})},ue=["any","mixed","empty","bool","boolean","number","string","void","null"],le=z.prototype;le.flowParseTypeInitialiser=function(e){var t=this.state.inType;this.state.inType=!0,this.expect(e||j.colon);var r=this.flowParseType();return this.state.inType=t,r},le.flowParsePredicate=function(){var e=this.startNode(),t=this.state.startLoc,r=this.state.start;this.expect(j.modulo);var n=this.state.startLoc;return this.expectContextual("checks"),t.line===n.line&&t.column===n.column-1||this.raise(r,"Spaces between ´%´ and ´checks´ are not allowed here."),this.eat(j.parenL)?(e.expression=this.parseExpression(),this.expect(j.parenR),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")},le.flowParseTypeAndPredicateInitialiser=function(){var e=this.state.inType;this.state.inType=!0,this.expect(j.colon);var t=null,r=null;return this.match(j.modulo)?(this.state.inType=e,r=this.flowParsePredicate()):(t=this.flowParseType(),this.state.inType=e,this.match(j.modulo)&&(r=this.flowParsePredicate())),[t,r]},le.flowParseDeclareClass=function(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},le.flowParseDeclareFunction=function(e){this.next();var t=e.id=this.parseIdentifier(),r=this.startNode(),n=this.startNode();this.isRelational("<")?r.typeParameters=this.flowParseTypeParameterDeclaration():r.typeParameters=null,this.expect(j.parenL);var i=this.flowParseFunctionTypeParams();r.params=i.params,r.rest=i.rest,this.expect(j.parenR);var s=null,a=this.flowParseTypeAndPredicateInitialiser();return r.returnType=a[0],s=a[1],n.typeAnnotation=this.finishNode(r,"FunctionTypeAnnotation"),n.predicate=s,t.typeAnnotation=this.finishNode(n,"TypeAnnotation"),this.finishNode(t,t.type),this.semicolon(),this.finishNode(e,"DeclareFunction")},le.flowParseDeclare=function(e){return this.match(j._class)?this.flowParseDeclareClass(e):this.match(j._function)?this.flowParseDeclareFunction(e):this.match(j._var)?this.flowParseDeclareVariable(e):this.isContextual("module")?this.lookahead().type===j.dot?this.flowParseDeclareModuleExports(e):this.flowParseDeclareModule(e):this.isContextual("type")?this.flowParseDeclareTypeAlias(e):this.isContextual("interface")?this.flowParseDeclareInterface(e):void this.unexpected()},le.flowParseDeclareVariable=function(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(e,"DeclareVariable")},le.flowParseDeclareModule=function(e){this.next(),this.match(j.string)?e.id=this.parseExprAtom():e.id=this.parseIdentifier();var t=e.body=this.startNode(),r=t.body=[];for(this.expect(j.braceL);!this.match(j.braceR);){var n=this.startNode();if(this.match(j._import)){var i=this.lookahead();"type"!==i.value&&"typeof"!==i.value&&this.unexpected(null,"Imports within a `declare module` body must always be `import type` or `import typeof`"),this.parseImport(n)}else this.expectContextual("declare","Only declares and type imports are allowed inside declare module"),n=this.flowParseDeclare(n,!0);r.push(n)}return this.expect(j.braceR),this.finishNode(t,"BlockStatement"),this.finishNode(e,"DeclareModule")},le.flowParseDeclareModuleExports=function(e){return this.expectContextual("module"),this.expect(j.dot),this.expectContextual("exports"),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")},le.flowParseDeclareTypeAlias=function(e){return this.next(),this.flowParseTypeAlias(e),this.finishNode(e,"DeclareTypeAlias")},le.flowParseDeclareInterface=function(e){return this.next(),this.flowParseInterfaceish(e),this.finishNode(e,"DeclareInterface")},le.flowParseInterfaceish=function(e,t){if(e.id=this.parseIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],e.mixins=[],this.eat(j._extends))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(j.comma));if(this.isContextual("mixins")){this.next();do{e.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(j.comma))}e.body=this.flowParseObjectType(t)},le.flowParseInterfaceExtends=function(){var e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")},le.flowParseInterface=function(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},le.flowParseRestrictedIdentifier=function(e){ +return ue.indexOf(this.state.value)>-1&&this.raise(this.state.start,"Cannot overwrite primitive type "+this.state.value),this.parseIdentifier(e)},le.flowParseTypeAlias=function(e){return e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(j.eq),this.semicolon(),this.finishNode(e,"TypeAlias")},le.flowParseTypeParameter=function(){var e=this.startNode(),t=this.flowParseVariance(),r=this.flowParseTypeAnnotatableIdentifier();return e.name=r.name,e.variance=t,e.bound=r.typeAnnotation,this.match(j.eq)&&(this.eat(j.eq),e.default=this.flowParseType()),this.finishNode(e,"TypeParameter")},le.flowParseTypeParameterDeclaration=function(){var e=this.state.inType,t=this.startNode();t.params=[],this.state.inType=!0,this.isRelational("<")||this.match(j.jsxTagStart)?this.next():this.unexpected();do{t.params.push(this.flowParseTypeParameter()),this.isRelational(">")||this.expect(j.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterDeclaration")},le.flowParseTypeParameterInstantiation=function(){var e=this.startNode(),t=this.state.inType;for(e.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)e.params.push(this.flowParseType()),this.isRelational(">")||this.expect(j.comma);return this.expectRelational(">"),this.state.inType=t,this.finishNode(e,"TypeParameterInstantiation")},le.flowParseObjectPropertyKey=function(){return this.match(j.num)||this.match(j.string)?this.parseExprAtom():this.parseIdentifier(!0)},le.flowParseObjectTypeIndexer=function(e,t,r){return e.static=t,this.expect(j.bracketL),this.lookahead().type===j.colon?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(j.bracketR),e.value=this.flowParseTypeInitialiser(),e.variance=r,this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeIndexer")},le.flowParseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(j.parenL);this.match(j.name);)e.params.push(this.flowParseFunctionTypeParam()),this.match(j.parenR)||this.expect(j.comma);return this.eat(j.ellipsis)&&(e.rest=this.flowParseFunctionTypeParam()),this.expect(j.parenR),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")},le.flowParseObjectTypeMethod=function(e,t,r,n){var i=this.startNodeAt(e,t);return i.value=this.flowParseObjectTypeMethodish(this.startNodeAt(e,t)),i.static=r,i.key=n,i.optional=!1,this.flowObjectTypeSemicolon(),this.finishNode(i,"ObjectTypeProperty")},le.flowParseObjectTypeCallProperty=function(e,t){var r=this.startNode();return e.static=t,e.value=this.flowParseObjectTypeMethodish(r),this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeCallProperty")},le.flowParseObjectType=function(e,t){var r=this.state.inType;this.state.inType=!0;var n=this.startNode(),i=void 0,s=void 0,a=!1;n.callProperties=[],n.properties=[],n.indexers=[];var o=void 0,u=void 0;for(t&&this.match(j.braceBarL)?(this.expect(j.braceBarL),o=j.braceBarR,u=!0):(this.expect(j.braceL),o=j.braceR,u=!1),n.exact=u;!this.match(o);){var l=!1,c=this.state.start,p=this.state.startLoc;i=this.startNode(),e&&this.isContextual("static")&&this.lookahead().type!==j.colon&&(this.next(),a=!0);var h=this.state.start,f=this.flowParseVariance();this.match(j.bracketL)?n.indexers.push(this.flowParseObjectTypeIndexer(i,a,f)):this.match(j.parenL)||this.isRelational("<")?(f&&this.unexpected(h),n.callProperties.push(this.flowParseObjectTypeCallProperty(i,a))):(s=this.flowParseObjectPropertyKey(),this.isRelational("<")||this.match(j.parenL)?(f&&this.unexpected(h),n.properties.push(this.flowParseObjectTypeMethod(c,p,a,s))):(this.eat(j.question)&&(l=!0),i.key=s,i.value=this.flowParseTypeInitialiser(),i.optional=l,i.static=a,i.variance=f,this.flowObjectTypeSemicolon(),n.properties.push(this.finishNode(i,"ObjectTypeProperty")))),a=!1}this.expect(o);var d=this.finishNode(n,"ObjectTypeAnnotation");return this.state.inType=r,d},le.flowObjectTypeSemicolon=function(){this.eat(j.semi)||this.eat(j.comma)||this.match(j.braceR)||this.match(j.braceBarR)||this.unexpected()},le.flowParseQualifiedTypeIdentifier=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;for(var n=r||this.parseIdentifier();this.eat(j.dot);){var i=this.startNodeAt(e,t);i.qualification=n,i.id=this.parseIdentifier(),n=this.finishNode(i,"QualifiedTypeIdentifier")}return n},le.flowParseGenericType=function(e,t,r){var n=this.startNodeAt(e,t);return n.typeParameters=null,n.id=this.flowParseQualifiedTypeIdentifier(e,t,r),this.isRelational("<")&&(n.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(n,"GenericTypeAnnotation")},le.flowParseTypeofType=function(){var e=this.startNode();return this.expect(j._typeof),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},le.flowParseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(j.bracketL);this.state.pos0&&void 0!==arguments[0]?arguments[0]:[],t={params:e,rest:null};!this.match(j.parenR)&&!this.match(j.ellipsis);)t.params.push(this.flowParseFunctionTypeParam()),this.match(j.parenR)||this.expect(j.comma);return this.eat(j.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),t},le.flowIdentToTypeAnnotation=function(e,t,r,n){switch(n.name){case"any":return this.finishNode(r,"AnyTypeAnnotation");case"void":return this.finishNode(r,"VoidTypeAnnotation");case"bool":case"boolean":return this.finishNode(r,"BooleanTypeAnnotation");case"mixed":return this.finishNode(r,"MixedTypeAnnotation");case"empty":return this.finishNode(r,"EmptyTypeAnnotation");case"number":return this.finishNode(r,"NumberTypeAnnotation");case"string":return this.finishNode(r,"StringTypeAnnotation");default:return this.flowParseGenericType(e,t,n)}},le.flowParsePrimaryType=function(){var e=this.state.start,t=this.state.startLoc,r=this.startNode(),n=void 0,i=void 0,s=!1,a=this.state.noAnonFunctionType;switch(this.state.type){case j.name:return this.flowIdentToTypeAnnotation(e,t,r,this.parseIdentifier());case j.braceL:return this.flowParseObjectType(!1,!1);case j.braceBarL:return this.flowParseObjectType(!1,!0);case j.bracketL:return this.flowParseTupleType();case j.relational:if("<"===this.state.value)return r.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(j.parenL),n=this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(j.parenR),this.expect(j.arrow),r.returnType=this.flowParseType(),this.finishNode(r,"FunctionTypeAnnotation");break;case j.parenL:if(this.next(),!this.match(j.parenR)&&!this.match(j.ellipsis))if(this.match(j.name)){var o=this.lookahead().type;s=o!==j.question&&o!==j.colon}else s=!0;if(s){if(this.state.noAnonFunctionType=!1,i=this.flowParseType(),this.state.noAnonFunctionType=a,this.state.noAnonFunctionType||!(this.match(j.comma)||this.match(j.parenR)&&this.lookahead().type===j.arrow))return this.expect(j.parenR),i;this.eat(j.comma)}return n=i?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(i)]):this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(j.parenR),this.expect(j.arrow),r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation");case j.string:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case j._true:case j._false:return r.value=this.match(j._true),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case j.plusMin:if("-"===this.state.value)return this.next(),this.match(j.num)||this.unexpected(null,"Unexpected token, expected number"),this.parseLiteral(-this.state.value,"NumericLiteralTypeAnnotation",r.start,r.loc.start);this.unexpected();case j.num:return this.parseLiteral(this.state.value,"NumericLiteralTypeAnnotation");case j._null:return r.value=this.match(j._null),this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case j._this:return r.value=this.match(j._this),this.next(),this.finishNode(r,"ThisTypeAnnotation");case j.star:return this.next(),this.finishNode(r,"ExistentialTypeParam");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}this.unexpected()},le.flowParsePostfixType=function(){for(var e=this.state.start,t=this.state.startLoc,r=this.flowParsePrimaryType();!this.canInsertSemicolon()&&this.match(j.bracketL);){var n=this.startNodeAt(e,t);n.elementType=r,this.expect(j.bracketL),this.expect(j.bracketR),r=this.finishNode(n,"ArrayTypeAnnotation")}return r},le.flowParsePrefixType=function(){var e=this.startNode();return this.eat(j.question)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()},le.flowParseAnonFunctionWithoutParens=function(){var e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(j.arrow)){var t=this.startNodeAt(e.start,e.loc);return t.params=[this.reinterpretTypeAsFunctionTypeParam(e)],t.rest=null,t.returnType=this.flowParseType(),t.typeParameters=null,this.finishNode(t,"FunctionTypeAnnotation")}return e},le.flowParseIntersectionType=function(){var e=this.startNode();this.eat(j.bitwiseAND);var t=this.flowParseAnonFunctionWithoutParens();for(e.types=[t];this.eat(j.bitwiseAND);)e.types.push(this.flowParseAnonFunctionWithoutParens());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")},le.flowParseUnionType=function(){var e=this.startNode();this.eat(j.bitwiseOR);var t=this.flowParseIntersectionType();for(e.types=[t];this.eat(j.bitwiseOR);)e.types.push(this.flowParseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")},le.flowParseType=function(){var e=this.state.inType;this.state.inType=!0;var t=this.flowParseUnionType();return this.state.inType=e,t},le.flowParseTypeAnnotation=function(){var e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")},le.flowParseTypeAndPredicateAnnotation=function(){var e=this.startNode(),t=this.flowParseTypeAndPredicateInitialiser();return e.typeAnnotation=t[0],e.predicate=t[1],this.finishNode(e,"TypeAnnotation")},le.flowParseTypeAnnotatableIdentifier=function(){var e=this.flowParseRestrictedIdentifier();return this.match(j.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e,e.type)),e},le.typeCastToParameter=function(e){return e.expression.typeAnnotation=e.typeAnnotation,this.finishNodeAt(e.expression,e.expression.type,e.typeAnnotation.end,e.typeAnnotation.loc.end)},le.flowParseVariance=function(){var e=null;return this.match(j.plusMin)&&("+"===this.state.value?e="plus":"-"===this.state.value&&(e="minus"),this.next()),e};var ce=function(e){e.extend("parseFunctionBody",function(e){return function(t,r){return this.match(j.colon)&&!r&&(t.returnType=this.flowParseTypeAndPredicateAnnotation()),e.call(this,t,r)}}),e.extend("parseStatement",function(e){return function(t,r){if(this.state.strict&&this.match(j.name)&&"interface"===this.state.value){var n=this.startNode();return this.next(),this.flowParseInterface(n)}return e.call(this,t,r)}}),e.extend("parseExpressionStatement",function(e){return function(t,r){if("Identifier"===r.type)if("declare"===r.name){if(this.match(j._class)||this.match(j.name)||this.match(j._function)||this.match(j._var))return this.flowParseDeclare(t)}else if(this.match(j.name)){if("interface"===r.name)return this.flowParseInterface(t);if("type"===r.name)return this.flowParseTypeAlias(t)}return e.call(this,t,r)}}),e.extend("shouldParseExportDeclaration",function(e){return function(){return this.isContextual("type")||this.isContextual("interface")||e.call(this)}}),e.extend("parseConditional",function(e){return function(t,r,n,i,s){if(s&&this.match(j.question)){var a=this.state.clone();try{return e.call(this,t,r,n,i)}catch(e){if(e instanceof SyntaxError)return this.state=a,s.start=e.pos||this.state.start,t;throw e}}return e.call(this,t,r,n,i)}}),e.extend("parseParenItem",function(e){return function(t,r,n){if(t=e.call(this,t,r,n),this.eat(j.question)&&(t.optional=!0),this.match(j.colon)){var i=this.startNodeAt(r,n);return i.expression=t,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return t}}),e.extend("parseExport",function(e){return function(t){return t=e.call(this,t),"ExportNamedDeclaration"===t.type&&(t.exportKind=t.exportKind||"value"),t}}),e.extend("parseExportDeclaration",function(e){return function(t){if(this.isContextual("type")){t.exportKind="type";var r=this.startNode();return this.next(),this.match(j.braceL)?(t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t),null):this.flowParseTypeAlias(r)}if(this.isContextual("interface")){t.exportKind="type";var n=this.startNode();return this.next(),this.flowParseInterface(n)}return e.call(this,t)}}),e.extend("parseClassId",function(e){return function(t){e.apply(this,arguments),this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration())}}),e.extend("isKeyword",function(e){return function(t){return(!this.state.inType||"void"!==t)&&e.call(this,t)}}),e.extend("readToken",function(e){return function(t){return!this.state.inType||62!==t&&60!==t?e.call(this,t):this.finishOp(j.relational,1)}}),e.extend("jsx_readToken",function(e){return function(){if(!this.state.inType)return e.call(this)}}),e.extend("toAssignable",function(e){return function(t,r,n){return"TypeCastExpression"===t.type?e.call(this,this.typeCastToParameter(t),r,n):e.call(this,t,r,n)}}),e.extend("toAssignableList",function(e){return function(t,r,n){for(var i=0;i2?n-2:0),s=2;s1114111||fe(a)!=a)throw RangeError("Invalid code point: "+a);a<=65535?e.push(a):(a-=65536,t=55296+(a>>10),r=a%1024+56320,e.push(t,r)),(n+1==i||e.length>16384)&&(s+=he.apply(null,e),e.length=0)}return s}}var de=pe,me={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},ye=/^[\da-fA-F]+$/,ge=/^\d+$/;U.j_oTag=new R("...",!0,!0),j.jsxName=new P("jsxName"),j.jsxText=new P("jsxText",{beforeExpr:!0}),j.jsxTagStart=new P("jsxTagStart",{startsExpr:!0}),j.jsxTagEnd=new P("jsxTagEnd"),j.jsxTagStart.updateContext=function(){this.state.context.push(U.j_expr),this.state.context.push(U.j_oTag),this.state.exprAllowed=!1},j.jsxTagEnd.updateContext=function(e){var t=this.state.context.pop();t===U.j_oTag&&e===j.slash||t===U.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===U.j_expr):this.state.exprAllowed=!0};var be=z.prototype;be.jsxReadToken=function(){for(var e="",t=this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated JSX contents");var r=this.input.charCodeAt(this.state.pos);switch(r){case 60:case 123:return this.state.pos===this.state.start?60===r&&this.state.exprAllowed?(++this.state.pos,this.finishToken(j.jsxTagStart)):this.getTokenFromCode(r):(e+=this.input.slice(t,this.state.pos),this.finishToken(j.jsxText,e));case 38:e+=this.input.slice(t,this.state.pos),e+=this.jsxReadEntity(),t=this.state.pos;break;default:u(r)?(e+=this.input.slice(t,this.state.pos),e+=this.jsxReadNewLine(!0),t=this.state.pos):++this.state.pos}}},be.jsxReadNewLine=function(e){var t=this.input.charCodeAt(this.state.pos),r=void 0;return++this.state.pos,13===t&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,r=e?"\n":"\r\n"):r=String.fromCharCode(t),++this.state.curLine,this.state.lineStart=this.state.pos,r},be.jsxReadString=function(e){for(var t="",r=++this.state.pos;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated string constant");var n=this.input.charCodeAt(this.state.pos);if(n===e)break;38===n?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadEntity(),r=this.state.pos):u(n)?(t+=this.input.slice(r,this.state.pos),t+=this.jsxReadNewLine(!1),r=this.state.pos):++this.state.pos}return t+=this.input.slice(r,this.state.pos++),this.finishToken(j.string,t)},be.jsxReadEntity=function(){for(var e="",t=0,r=void 0,n=this.input[this.state.pos],i=++this.state.pos;this.state.pos")}return r.openingElement=i,r.closingElement=s,r.children=n,this.match(j.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(r,"JSXElement")},be.jsxParseElement=function(){var e=this.state.start,t=this.state.startLoc;return this.next(),this.jsxParseElementAt(e,t)};var ve=function(e){e.extend("parseExprAtom",function(e){return function(t){if(this.match(j.jsxText)){var r=this.parseLiteral(this.state.value,"JSXText");return r.extra=null,r}return this.match(j.jsxTagStart)?this.jsxParseElement():e.call(this,t)}}),e.extend("readToken",function(e){return function(t){if(this.state.inPropertyName)return e.call(this,t);var r=this.curContext();if(r===U.j_expr)return this.jsxReadToken();if(r===U.j_oTag||r===U.j_cTag){if(s(t))return this.jsxReadWord();if(62===t)return++this.state.pos,this.finishToken(j.jsxTagEnd);if((34===t||39===t)&&r===U.j_oTag)return this.jsxReadString(t)}return 60===t&&this.state.exprAllowed?(++this.state.pos,this.finishToken(j.jsxTagStart)):e.call(this,t)}}),e.extend("updateContext",function(e){return function(t){if(this.match(j.braceL)){var r=this.curContext();r===U.j_oTag?this.state.context.push(U.braceExpression):r===U.j_expr?this.state.context.push(U.templateQuasi):e.call(this,t),this.state.exprAllowed=!0}else{if(!this.match(j.slash)||t!==j.jsxTagStart)return e.call(this,t);this.state.context.length-=2,this.state.context.push(U.j_cTag),this.state.exprAllowed=!1}}})};W.estree=oe,W.flow=ce,W.jsx=ve,r.parse=m,r.parseExpression=y,r.tokTypes=j},{}],178:[function(e,t,r){function n(e,t,r){e instanceof RegExp&&(e=i(e,r)),t instanceof RegExp&&(t=i(t,r));var n=s(e,t,r);return n&&{start:n[0],end:n[1],pre:r.slice(0,n[0]),body:r.slice(n[0]+e.length,n[1]),post:r.slice(n[1]+t.length)}}function i(e,t){var r=t.match(e);return r?r[0]:null}function s(e,t,r){var n,i,s,a,o,u=r.indexOf(e),l=r.indexOf(t,u+1),c=u;if(u>=0&&l>0){for(n=[],s=r.length;c>=0&&!o;)c==u?(n.push(c), +u=r.indexOf(e,c+1)):1==n.length?o=[n.pop(),l]:(i=n.pop(),i=0?u:l;n.length&&(o=[s,a])}return o}t.exports=n,n.range=s},{}],179:[function(e,t,r){"use strict";function n(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function i(e){return 3*e.length/4-n(e)}function s(e){var t,r,i,s,a,o,u=e.length;a=n(e),o=new p(3*u/4-a),i=a>0?u-4:u;var l=0;for(t=0,r=0;t>16&255,o[l++]=s>>8&255,o[l++]=255&s;return 2===a?(s=c[e.charCodeAt(t)]<<2|c[e.charCodeAt(t+1)]>>4,o[l++]=255&s):1===a&&(s=c[e.charCodeAt(t)]<<10|c[e.charCodeAt(t+1)]<<4|c[e.charCodeAt(t+2)]>>2,o[l++]=s>>8&255,o[l++]=255&s),o}function a(e){return l[e>>18&63]+l[e>>12&63]+l[e>>6&63]+l[63&e]}function o(e,t,r){for(var n,i=[],s=t;su?u:a+16383));return 1===n?(t=e[r-1],i+=l[t>>2],i+=l[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=l[t>>10],i+=l[t>>4&63],i+=l[t<<2&63],i+="="),s.push(i),s.join("")}r.byteLength=i,r.toByteArray=s,r.fromByteArray=u;for(var l=[],c=[],p="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=0,d=h.length;f=t}function h(e,t){var r=[],i=d("{","}",e);if(!i||/\$$/.test(i.pre))return[e];var s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),o=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),m=s||o,y=/^(.*,)+(.+)?$/.test(i.body);if(!m&&!y)return i.post.match(/,.*\}/)?(e=i.pre+"{"+i.body+g+i.post,h(e)):[e];var b;if(m)b=i.body.split(/\.\./);else if(b=a(i.body),1===b.length&&(b=h(b[0],!1).map(u),1===b.length)){var v=i.post.length?h(i.post,!1):[""];return v.map(function(e){return i.pre+b[0]+e})}var x,E=i.pre,v=i.post.length?h(i.post,!1):[""];if(m){var A=n(b[0]),D=n(b[1]),C=Math.max(b[0].length,b[1].length),S=3==b.length?Math.abs(n(b[2])):1,_=c;D0){var P=new Array(T+1).join("0");F=k<0?"-"+P+F.slice(1):P+F}}x.push(F)}}else x=f(b,function(e){return h(e,!1)});for(var B=0;Ba)throw new RangeError("size is too large");var n=r,s=t;void 0===s&&(n=void 0,s=0);var o=new i(e);if("string"==typeof s)for(var u=new i(s,n),l=u.length,c=-1;++ca)throw new RangeError("size is too large");return new i(e)},r.from=function(e,r,n){if("function"==typeof i.from&&(!t.Uint8Array||Uint8Array.from!==i.from))return i.from(e,r,n);if("number"==typeof e)throw new TypeError('"value" argument must not be a number');if("string"==typeof e)return new i(e,r);if("undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer){var s=r;if(1===arguments.length)return new i(e);void 0===s&&(s=0);var a=n;if(void 0===a&&(a=e.byteLength-s),s>=e.byteLength)throw new RangeError("'offset' is out of bounds");if(a>e.byteLength-s)throw new RangeError("'length' is out of bounds");return new i(e.slice(s,s+a))}if(i.isBuffer(e)){var o=new i(e.length);return e.copy(o,0,0,e.length),o}if(e){if(Array.isArray(e)||"undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return new i(e);if("Buffer"===e.type&&Array.isArray(e.data))return new i(e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},r.allocUnsafeSlow=function(e){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(e);if("number"!=typeof e)throw new TypeError("size must be a number");if(e>=a)throw new RangeError("size is too large");return new s(e)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{buffer:184}],184:[function(e,t,r){"use strict";function n(e){if(e>Y)throw new RangeError("Invalid typed array length");var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return u(e)}return s(e,t,r)}function s(e,t,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return e instanceof ArrayBuffer?p(e,t,r):"string"==typeof e?l(e,t):h(e)}function a(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function o(e,t,r){return a(e),e<=0?n(e):void 0!==t?"string"==typeof r?n(e).fill(t,r):n(e).fill(t):n(e)}function u(e){return a(e),n(e<0?0:0|f(e))}function l(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError('"encoding" must be a valid string encoding');var r=0|m(e,t),s=n(r),a=s.write(e,t);return a!==r&&(s=s.slice(0,a)),s}function c(e){for(var t=e.length<0?0:0|f(e.length),r=n(t),i=0;i=Y)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Y.toString(16)+" bytes");return 0|e}function d(e){return+e!=e&&(e=0),i.alloc(+e)}function m(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return X(e).length;default:if(n)return V(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,r);case"utf8":case"utf-8":return w(this,t,r);case"ascii":return F(this,t,r);case"latin1":case"binary":return T(this,t,r);case"base64":return _(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function b(e,t,r,n,s){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=s?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(s)return-1;r=e.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof t&&(t=i.from(t,n)),i.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):v(e,[t],r,n,s);throw new TypeError("val must be string, number or Buffer")}function v(e,t,r,n,i){function s(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,o=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,o/=2,u/=2,r/=2}var l;if(i){var c=-1;for(l=r;lo&&(r=o-u),l=r;l>=0;l--){for(var p=!0,h=0;hi&&(n=i):n=i;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var a=0;a239?4:s>223?3:s>191?2:1;if(i+o<=r){var u,l,c,p;switch(o){case 1:s<128&&(a=s);break;case 2:u=e[i+1],128==(192&u)&&(p=(31&s)<<6|63&u)>127&&(a=p);break;case 3:u=e[i+1],l=e[i+2],128==(192&u)&&128==(192&l)&&(p=(15&s)<<12|(63&u)<<6|63&l)>2047&&(p<55296||p>57343)&&(a=p);break;case 4:u=e[i+1],l=e[i+2],c=e[i+3],128==(192&u)&&128==(192&l)&&128==(192&c)&&(p=(15&s)<<18|(63&u)<<12|(63&l)<<6|63&c)>65535&&p<1114112&&(a=p)}}null===a?(a=65533,o=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=o}return k(n)}function k(e){var t=e.length;if(t<=H)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var i="",s=t;sr)throw new RangeError("Trying to access beyond buffer length")}function j(e,t,r,n,s,a){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||te.length)throw new RangeError("Index out of range")}function N(e,t,r,n,i,s){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function I(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),z.write(e,t,r,n,23,4),r+4}function L(e,t,r,n,i){return t=+t,r>>>=0,i||N(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),z.write(e,t,r,n,52,8),r+8}function M(e){if(e=R(e).replace($,""),e.length<2)return"";for(;e.length%4!=0;)e+="=";return e}function R(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function U(e){return e<16?"0"+e.toString(16):e.toString(16)}function V(e,t){t=t||1/0;for(var r,n=e.length,i=null,s=[],a=0;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function q(e){for(var t=[],r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function X(e){return K.toByteArray(M(e))}function J(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function W(e){return e!==e}var K=e("base64-js"),z=e("ieee754");r.Buffer=i,r.SlowBuffer=d,r.INSPECT_MAX_BYTES=50;var Y=2147483647;r.kMaxLength=Y,i.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,r){return s(e,t,r)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,r){return o(e,t,r)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer},i.compare=function(e,t){if(!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,s=0,a=Math.min(r,n);s0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},i.prototype.compare=function(e,t,r,n,s){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===s&&(s=this.length),t<0||r>e.length||n<0||s>this.length)throw new RangeError("out of range index");if(n>=s&&t>=r)return 0;if(n>=s)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,s>>>=0,this===e)return 0;for(var a=s-n,o=r-t,u=Math.min(a,o),l=this.slice(n,s),c=e.slice(t,r),p=0;p>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var s=!1;;)switch(n){case"hex":return x(this,e,t,r);case"utf8":case"utf-8":return E(this,e,t,r);case"ascii":return A(this,e,t,r);case"latin1":case"binary":return D(this,e,t,r);case"base64":return C(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var H=4096;i.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||O(e,t,this.length);for(var n=this[e],i=1,s=0;++s>>=0,t>>>=0,r||O(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},i.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);for(var n=this[e],i=1,s=0;++s=i&&(n-=Math.pow(2,8*t)),n},i.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);for(var n=t,i=1,s=this[e+--n];n>0&&(i*=256);)s+=this[e+--n]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),z.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),z.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),z.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),z.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){j(this,e,t,r,Math.pow(2,8*r)-1,0)}var i=1,s=0;for(this[t]=255&e;++s>>=0,r>>>=0,!n){j(this,e,t,r,Math.pow(2,8*r)-1,0)}var i=r-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+r},i.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var s=0,a=1,o=0;for(this[t]=255&e;++s>0)-o&255;return t+r},i.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);j(this,e,t,r,i-1,-i)}var s=r-1,a=1,o=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===o&&0!==this[t+s+1]&&(o=1),this[t+s]=(e/a>>0)-o&255;return t+r},i.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||j(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,r){return I(this,e,t,!0,r)},i.prototype.writeFloatBE=function(e,t,r){return I(this,e,t,!1,r)},i.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},i.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},i.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=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),e.length-t=0;--i)e[i+t]=this[i+r];else if(s<1e3)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var a;if("number"==typeof e)for(a=t;a1)for(var n=1;n0;i--)if(t=n[i],~t.indexOf("sourceMappingURL=data:"))return r.fromComment(t)}var u=e("fs"),l=e("path"),c=/^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+;)?base64,(.*)$/gm,p=/(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/gm;a.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)},a.prototype.toBase64=function(){var e=this.toJSON();return new t(e).toString("base64")},a.prototype.toComment=function(e){var t=this.toBase64(),r="sourceMappingURL=data:application/json;base64,"+t;return e&&e.multiline?"/*# "+r+" */":"//# "+r},a.prototype.toObject=function(){return JSON.parse(this.toJSON())},a.prototype.addProperty=function(e,t){if(this.sourcemap.hasOwnProperty(e))throw new Error("property %s already exists on the sourcemap, use set property instead");return this.setProperty(e,t)},a.prototype.setProperty=function(e,t){return this.sourcemap[e]=t,this},a.prototype.getProperty=function(e){return this.sourcemap[e]},r.fromObject=function(e){return new a(e)},r.fromJSON=function(e){return new a(e,{isJSON:!0})},r.fromBase64=function(e){return new a(e,{isEncoded:!0})},r.fromComment=function(e){return e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,""),new a(e,{isEncoded:!0,hasComment:!0})},r.fromMapFileComment=function(e,t){return new a(e,{commentFileDir:t,isFileComment:!0,isJSON:!0})},r.fromSource=function(e,t){if(t){var n=o(e);return n||null}var i=e.match(c);return c.lastIndex=0,i?r.fromComment(i.pop()):null},r.fromMapFileSource=function(e,t){var n=e.match(p);return p.lastIndex=0,n?r.fromMapFileComment(n.pop(),t):null},r.removeComments=function(e){return c.lastIndex=0,e.replace(c,"")},r.removeMapFileComments=function(e){return p.lastIndex=0,e.replace(p,"")},Object.defineProperty(r,"commentRegex",{get:function(){return c.lastIndex=0,c}}),Object.defineProperty(r,"mapFileCommentRegex",{get:function(){return p.lastIndex=0,p}})}).call(this,e("buffer").Buffer)},{buffer:184,fs:182,path:535}],188:[function(e,t,r){e("../modules/web.dom.iterable"),e("../modules/es6.string.iterator"),t.exports=e("../modules/core.get-iterator")},{"../modules/core.get-iterator":277,"../modules/es6.string.iterator":286,"../modules/web.dom.iterable":293}],189:[function(e,t,r){var n=e("../../modules/_core"),i=n.JSON||(n.JSON={stringify:JSON.stringify});t.exports=function(e){return i.stringify.apply(i,arguments)}},{"../../modules/_core":217}],190:[function(e,t,r){e("../modules/es6.object.to-string"),e("../modules/es6.string.iterator"),e("../modules/web.dom.iterable"),e("../modules/es6.map"),e("../modules/es7.map.to-json"),t.exports=e("../modules/_core").Map},{"../modules/_core":217,"../modules/es6.map":279,"../modules/es6.object.to-string":285,"../modules/es6.string.iterator":286,"../modules/es7.map.to-json":290,"../modules/web.dom.iterable":293}],191:[function(e,t,r){e("../../modules/es6.number.max-safe-integer"),t.exports=9007199254740991},{"../../modules/es6.number.max-safe-integer":280}],192:[function(e,t,r){e("../../modules/es6.object.assign"),t.exports=e("../../modules/_core").Object.assign},{"../../modules/_core":217,"../../modules/es6.object.assign":281}],193:[function(e,t,r){e("../../modules/es6.object.create");var n=e("../../modules/_core").Object;t.exports=function(e,t){return n.create(e,t)}},{"../../modules/_core":217,"../../modules/es6.object.create":282}],194:[function(e,t,r){e("../../modules/es6.symbol"),t.exports=e("../../modules/_core").Object.getOwnPropertySymbols},{"../../modules/_core":217,"../../modules/es6.symbol":287}],195:[function(e,t,r){e("../../modules/es6.object.keys"),t.exports=e("../../modules/_core").Object.keys},{"../../modules/_core":217,"../../modules/es6.object.keys":283}],196:[function(e,t,r){e("../../modules/es6.object.set-prototype-of"),t.exports=e("../../modules/_core").Object.setPrototypeOf},{"../../modules/_core":217,"../../modules/es6.object.set-prototype-of":284}],197:[function(e,t,r){e("../../modules/es6.symbol"),t.exports=e("../../modules/_core").Symbol.for},{"../../modules/_core":217,"../../modules/es6.symbol":287}],198:[function(e,t,r){e("../../modules/es6.symbol"),e("../../modules/es6.object.to-string"),e("../../modules/es7.symbol.async-iterator"),e("../../modules/es7.symbol.observable"),t.exports=e("../../modules/_core").Symbol},{"../../modules/_core":217,"../../modules/es6.object.to-string":285,"../../modules/es6.symbol":287,"../../modules/es7.symbol.async-iterator":291,"../../modules/es7.symbol.observable":292}],199:[function(e,t,r){e("../../modules/es6.string.iterator"),e("../../modules/web.dom.iterable"),t.exports=e("../../modules/_wks-ext").f("iterator")},{"../../modules/_wks-ext":274,"../../modules/es6.string.iterator":286,"../../modules/web.dom.iterable":293}],200:[function(e,t,r){e("../modules/es6.object.to-string"),e("../modules/web.dom.iterable"),e("../modules/es6.weak-map"),t.exports=e("../modules/_core").WeakMap},{"../modules/_core":217,"../modules/es6.object.to-string":285,"../modules/es6.weak-map":288,"../modules/web.dom.iterable":293}],201:[function(e,t,r){e("../modules/es6.object.to-string"),e("../modules/web.dom.iterable"),e("../modules/es6.weak-set"), +t.exports=e("../modules/_core").WeakSet},{"../modules/_core":217,"../modules/es6.object.to-string":285,"../modules/es6.weak-set":289,"../modules/web.dom.iterable":293}],202:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},{}],203:[function(e,t,r){t.exports=function(){}},{}],204:[function(e,t,r){t.exports=function(e,t,r,n){if(!(e instanceof t)||void 0!==n&&n in e)throw TypeError(r+": incorrect invocation!");return e}},{}],205:[function(e,t,r){var n=e("./_is-object");t.exports=function(e){if(!n(e))throw TypeError(e+" is not an object!");return e}},{"./_is-object":235}],206:[function(e,t,r){var n=e("./_for-of");t.exports=function(e,t){var r=[];return n(e,!1,r.push,r,t),r}},{"./_for-of":226}],207:[function(e,t,r){var n=e("./_to-iobject"),i=e("./_to-length"),s=e("./_to-index");t.exports=function(e){return function(t,r,a){var o,u=n(t),l=i(u.length),c=s(a,l);if(e&&r!=r){for(;l>c;)if((o=u[c++])!=o)return!0}else for(;l>c;c++)if((e||c in u)&&u[c]===r)return e||c||0;return!e&&-1}}},{"./_to-index":266,"./_to-iobject":268,"./_to-length":269}],208:[function(e,t,r){var n=e("./_ctx"),i=e("./_iobject"),s=e("./_to-object"),a=e("./_to-length"),o=e("./_array-species-create");t.exports=function(e,t){var r=1==e,u=2==e,l=3==e,c=4==e,p=6==e,h=5==e||p,f=t||o;return function(t,o,d){for(var m,y,g=s(t),b=i(g),v=n(o,d,3),x=a(b.length),E=0,A=r?f(t,x):u?f(t,0):void 0;x>E;E++)if((h||E in b)&&(m=b[E],y=v(m,E,g),e))if(r)A[E]=y;else if(y)switch(e){case 3:return!0;case 5:return m;case 6:return E;case 2:A.push(m)}else if(c)return!1;return p?-1:l||c?c:A}}},{"./_array-species-create":210,"./_ctx":218,"./_iobject":232,"./_to-length":269,"./_to-object":270}],209:[function(e,t,r){var n=e("./_is-object"),i=e("./_is-array"),s=e("./_wks")("species");t.exports=function(e){var t;return i(e)&&(t=e.constructor,"function"!=typeof t||t!==Array&&!i(t.prototype)||(t=void 0),n(t)&&null===(t=t[s])&&(t=void 0)),void 0===t?Array:t}},{"./_is-array":234,"./_is-object":235,"./_wks":275}],210:[function(e,t,r){var n=e("./_array-species-constructor");t.exports=function(e,t){return new(n(e))(t)}},{"./_array-species-constructor":209}],211:[function(e,t,r){var n=e("./_cof"),i=e("./_wks")("toStringTag"),s="Arguments"==n(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(e){}};t.exports=function(e){var t,r,o;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=a(t=Object(e),i))?r:s?n(t):"Object"==(o=n(t))&&"function"==typeof t.callee?"Arguments":o}},{"./_cof":212,"./_wks":275}],212:[function(e,t,r){var n={}.toString;t.exports=function(e){return n.call(e).slice(8,-1)}},{}],213:[function(e,t,r){"use strict";var n=e("./_object-dp").f,i=e("./_object-create"),s=e("./_redefine-all"),a=e("./_ctx"),o=e("./_an-instance"),u=e("./_defined"),l=e("./_for-of"),c=e("./_iter-define"),p=e("./_iter-step"),h=e("./_set-species"),f=e("./_descriptors"),d=e("./_meta").fastKey,m=f?"_s":"size",y=function(e,t){var r,n=d(t);if("F"!==n)return e._i[n];for(r=e._f;r;r=r.n)if(r.k==t)return r};t.exports={getConstructor:function(e,t,r,c){var p=e(function(e,n){o(e,p,t,"_i"),e._i=i(null),e._f=void 0,e._l=void 0,e[m]=0,void 0!=n&&l(n,r,e[c],e)});return s(p.prototype,{clear:function(){for(var e=this,t=e._i,r=e._f;r;r=r.n)r.r=!0,r.p&&(r.p=r.p.n=void 0),delete t[r.i];e._f=e._l=void 0,e[m]=0},delete:function(e){var t=this,r=y(t,e);if(r){var n=r.n,i=r.p;delete t._i[r.i],r.r=!0,i&&(i.n=n),n&&(n.p=i),t._f==r&&(t._f=n),t._l==r&&(t._l=i),t[m]--}return!!r},forEach:function(e){o(this,p,"forEach");for(var t,r=a(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.n:this._f;)for(r(t.v,t.k,this);t&&t.r;)t=t.p},has:function(e){return!!y(this,e)}}),f&&n(p.prototype,"size",{get:function(){return u(this[m])}}),p},def:function(e,t,r){var n,i,s=y(e,t);return s?s.v=r:(e._l=s={i:i=d(t,!0),k:t,v:r,p:n=e._l,n:void 0,r:!1},e._f||(e._f=s),n&&(n.n=s),e[m]++,"F"!==i&&(e._i[i]=s)),e},getEntry:y,setStrong:function(e,t,r){c(e,t,function(e,t){this._t=e,this._k=t,this._l=void 0},function(){for(var e=this,t=e._k,r=e._l;r&&r.r;)r=r.p;return e._t&&(e._l=r=r?r.n:e._t._f)?"keys"==t?p(0,r.k):"values"==t?p(0,r.v):p(0,[r.k,r.v]):(e._t=void 0,p(1))},r?"entries":"values",!r,!0),h(t)}}},{"./_an-instance":204,"./_ctx":218,"./_defined":219,"./_descriptors":220,"./_for-of":226,"./_iter-define":238,"./_iter-step":239,"./_meta":243,"./_object-create":245,"./_object-dp":246,"./_redefine-all":258,"./_set-species":261}],214:[function(e,t,r){var n=e("./_classof"),i=e("./_array-from-iterable");t.exports=function(e){return function(){if(n(this)!=e)throw TypeError(e+"#toJSON isn't generic");return i(this)}}},{"./_array-from-iterable":206,"./_classof":211}],215:[function(e,t,r){"use strict";var n=e("./_redefine-all"),i=e("./_meta").getWeak,s=e("./_an-object"),a=e("./_is-object"),o=e("./_an-instance"),u=e("./_for-of"),l=e("./_array-methods"),c=e("./_has"),p=l(5),h=l(6),f=0,d=function(e){return e._l||(e._l=new m)},m=function(){this.a=[]},y=function(e,t){return p(e.a,function(e){return e[0]===t})};m.prototype={get:function(e){var t=y(this,e);if(t)return t[1]},has:function(e){return!!y(this,e)},set:function(e,t){var r=y(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=h(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}},t.exports={getConstructor:function(e,t,r,s){var l=e(function(e,n){o(e,l,t,"_i"),e._i=f++,e._l=void 0,void 0!=n&&u(n,r,e[s],e)});return n(l.prototype,{delete:function(e){if(!a(e))return!1;var t=i(e);return!0===t?d(this).delete(e):t&&c(t,this._i)&&delete t[this._i]},has:function(e){if(!a(e))return!1;var t=i(e);return!0===t?d(this).has(e):t&&c(t,this._i)}}),l},def:function(e,t,r){var n=i(s(t),!0);return!0===n?d(e).set(t,r):n[e._i]=r,e},ufstore:d}},{"./_an-instance":204,"./_an-object":205,"./_array-methods":208,"./_for-of":226,"./_has":228,"./_is-object":235,"./_meta":243,"./_redefine-all":258}],216:[function(e,t,r){"use strict";var n=e("./_global"),i=e("./_export"),s=e("./_meta"),a=e("./_fails"),o=e("./_hide"),u=e("./_redefine-all"),l=e("./_for-of"),c=e("./_an-instance"),p=e("./_is-object"),h=e("./_set-to-string-tag"),f=e("./_object-dp").f,d=e("./_array-methods")(0),m=e("./_descriptors");t.exports=function(e,t,r,y,g,b){var v=n[e],x=v,E=g?"set":"add",A=x&&x.prototype,D={};return m&&"function"==typeof x&&(b||A.forEach&&!a(function(){(new x).entries().next()}))?(x=t(function(t,r){c(t,x,e,"_c"),t._c=new v,void 0!=r&&l(r,g,t[E],t)}),d("add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON".split(","),function(e){var t="add"==e||"set"==e;e in A&&(!b||"clear"!=e)&&o(x.prototype,e,function(r,n){if(c(this,x,e),!t&&b&&!p(r))return"get"==e&&void 0;var i=this._c[e](0===r?0:r,n);return t?this:i})}),"size"in A&&f(x.prototype,"size",{get:function(){return this._c.size}})):(x=y.getConstructor(t,e,g,E),u(x.prototype,r),s.NEED=!0),h(x,e),D[e]=x,i(i.G+i.W+i.F,D),b||y.setStrong(x,e,g),x}},{"./_an-instance":204,"./_array-methods":208,"./_descriptors":220,"./_export":224,"./_fails":225,"./_for-of":226,"./_global":227,"./_hide":229,"./_is-object":235,"./_meta":243,"./_object-dp":246,"./_redefine-all":258,"./_set-to-string-tag":262}],217:[function(e,t,r){var n=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},{}],218:[function(e,t,r){var n=e("./_a-function");t.exports=function(e,t,r){if(n(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,n){return e.call(t,r,n)};case 3:return function(r,n,i){return e.call(t,r,n,i)}}return function(){return e.apply(t,arguments)}}},{"./_a-function":202}],219:[function(e,t,r){t.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},{}],220:[function(e,t,r){t.exports=!e("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":225}],221:[function(e,t,r){var n=e("./_is-object"),i=e("./_global").document,s=n(i)&&n(i.createElement);t.exports=function(e){return s?i.createElement(e):{}}},{"./_global":227,"./_is-object":235}],222:[function(e,t,r){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},{}],223:[function(e,t,r){var n=e("./_object-keys"),i=e("./_object-gops"),s=e("./_object-pie");t.exports=function(e){var t=n(e),r=i.f;if(r)for(var a,o=r(e),u=s.f,l=0;o.length>l;)u.call(e,a=o[l++])&&t.push(a);return t}},{"./_object-gops":251,"./_object-keys":254,"./_object-pie":255}],224:[function(e,t,r){var n=e("./_global"),i=e("./_core"),s=e("./_ctx"),a=e("./_hide"),o=function(e,t,r){var u,l,c,p=e&o.F,h=e&o.G,f=e&o.S,d=e&o.P,m=e&o.B,y=e&o.W,g=h?i:i[t]||(i[t]={}),b=g.prototype,v=h?n:f?n[t]:(n[t]||{}).prototype;h&&(r=t);for(u in r)(l=!p&&v&&void 0!==v[u])&&u in g||(c=l?v[u]:r[u],g[u]=h&&"function"!=typeof v[u]?r[u]:m&&l?s(c,n):y&&v[u]==c?function(e){var t=function(t,r,n){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,r)}return new e(t,r,n)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(c):d&&"function"==typeof c?s(Function.call,c):c,d&&((g.virtual||(g.virtual={}))[u]=c,e&o.R&&b&&!b[u]&&a(b,u,c)))};o.F=1,o.G=2,o.S=4,o.P=8,o.B=16,o.W=32,o.U=64,o.R=128,t.exports=o},{"./_core":217,"./_ctx":218,"./_global":227,"./_hide":229}],225:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],226:[function(e,t,r){var n=e("./_ctx"),i=e("./_iter-call"),s=e("./_is-array-iter"),a=e("./_an-object"),o=e("./_to-length"),u=e("./core.get-iterator-method"),l={},c={},r=t.exports=function(e,t,r,p,h){var f,d,m,y,g=h?function(){return e}:u(e),b=n(r,p,t?2:1),v=0;if("function"!=typeof g)throw TypeError(e+" is not iterable!");if(s(g)){for(f=o(e.length);f>v;v++)if((y=t?b(a(d=e[v])[0],d[1]):b(e[v]))===l||y===c)return y}else for(m=g.call(e);!(d=m.next()).done;)if((y=i(m,b,d.value,t))===l||y===c)return y};r.BREAK=l,r.RETURN=c},{"./_an-object":205,"./_ctx":218,"./_is-array-iter":233,"./_iter-call":236,"./_to-length":269,"./core.get-iterator-method":276}],227:[function(e,t,r){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},{}],228:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],229:[function(e,t,r){var n=e("./_object-dp"),i=e("./_property-desc");t.exports=e("./_descriptors")?function(e,t,r){return n.f(e,t,i(1,r))}:function(e,t,r){return e[t]=r,e}},{"./_descriptors":220,"./_object-dp":246,"./_property-desc":257}],230:[function(e,t,r){t.exports=e("./_global").document&&document.documentElement},{"./_global":227}],231:[function(e,t,r){t.exports=!e("./_descriptors")&&!e("./_fails")(function(){return 7!=Object.defineProperty(e("./_dom-create")("div"),"a",{get:function(){return 7}}).a})},{"./_descriptors":220,"./_dom-create":221,"./_fails":225}],232:[function(e,t,r){var n=e("./_cof");t.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==n(e)?e.split(""):Object(e)}},{"./_cof":212}],233:[function(e,t,r){var n=e("./_iterators"),i=e("./_wks")("iterator"),s=Array.prototype;t.exports=function(e){return void 0!==e&&(n.Array===e||s[i]===e)}},{"./_iterators":240,"./_wks":275}],234:[function(e,t,r){var n=e("./_cof");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"./_cof":212}],235:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],236:[function(e,t,r){var n=e("./_an-object");t.exports=function(e,t,r,i){try{return i?t(n(r)[0],r[1]):t(r)}catch(t){var s=e.return;throw void 0!==s&&n(s.call(e)),t}}},{"./_an-object":205}],237:[function(e,t,r){"use strict";var n=e("./_object-create"),i=e("./_property-desc"),s=e("./_set-to-string-tag"),a={};e("./_hide")(a,e("./_wks")("iterator"),function(){return this}),t.exports=function(e,t,r){e.prototype=n(a,{next:i(1,r)}),s(e,t+" Iterator")}},{"./_hide":229,"./_object-create":245,"./_property-desc":257,"./_set-to-string-tag":262,"./_wks":275}],238:[function(e,t,r){"use strict";var n=e("./_library"),i=e("./_export"),s=e("./_redefine"),a=e("./_hide"),o=e("./_has"),u=e("./_iterators"),l=e("./_iter-create"),c=e("./_set-to-string-tag"),p=e("./_object-gpo"),h=e("./_wks")("iterator"),f=!([].keys&&"next"in[].keys()),d=function(){return this};t.exports=function(e,t,r,m,y,g,b){l(r,t,m);var v,x,E,A=function(e){if(!f&&e in _)return _[e];switch(e){case"keys":case"values":return function(){return new r(this,e)}}return function(){return new r(this,e)}},D=t+" Iterator",C="values"==y,S=!1,_=e.prototype,w=_[h]||_["@@iterator"]||y&&_[y],k=w||A(y),F=y?C?A("entries"):k:void 0,T="Array"==t?_.entries||w:w;if(T&&(E=p(T.call(new e)))!==Object.prototype&&(c(E,D,!0),n||o(E,h)||a(E,h,d)),C&&w&&"values"!==w.name&&(S=!0,k=function(){return w.call(this)}),n&&!b||!f&&!S&&_[h]||a(_,h,k),u[t]=k,u[D]=d,y)if(v={values:C?k:A("values"),keys:g?k:A("keys"),entries:F},b)for(x in v)x in _||s(_,x,v[x]);else i(i.P+i.F*(f||S),t,v);return v}},{"./_export":224,"./_has":228,"./_hide":229,"./_iter-create":237,"./_iterators":240,"./_library":242,"./_object-gpo":252,"./_redefine":259,"./_set-to-string-tag":262,"./_wks":275}],239:[function(e,t,r){t.exports=function(e,t){return{value:t,done:!!e}}},{}],240:[function(e,t,r){t.exports={}},{}],241:[function(e,t,r){var n=e("./_object-keys"),i=e("./_to-iobject");t.exports=function(e,t){for(var r,s=i(e),a=n(s),o=a.length,u=0;o>u;)if(s[r=a[u++]]===t)return r}},{"./_object-keys":254,"./_to-iobject":268}],242:[function(e,t,r){t.exports=!0},{}],243:[function(e,t,r){var n=e("./_uid")("meta"),i=e("./_is-object"),s=e("./_has"),a=e("./_object-dp").f,o=0,u=Object.isExtensible||function(){return!0},l=!e("./_fails")(function(){return u(Object.preventExtensions({}))}),c=function(e){a(e,n,{value:{i:"O"+ ++o,w:{}}})},p=function(e,t){if(!i(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!s(e,n)){if(!u(e))return"F";if(!t)return"E";c(e)}return e[n].i},h=function(e,t){if(!s(e,n)){if(!u(e))return!0;if(!t)return!1;c(e)}return e[n].w},f=function(e){return l&&d.NEED&&u(e)&&!s(e,n)&&c(e),e},d=t.exports={KEY:n,NEED:!1,fastKey:p,getWeak:h,onFreeze:f}},{"./_fails":225,"./_has":228,"./_is-object":235,"./_object-dp":246,"./_uid":272}],244:[function(e,t,r){"use strict";var n=e("./_object-keys"),i=e("./_object-gops"),s=e("./_object-pie"),a=e("./_to-object"),o=e("./_iobject"),u=Object.assign;t.exports=!u||e("./_fails")(function(){var e={},t={},r=Symbol(),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(e){t[e]=e}),7!=u({},e)[r]||Object.keys(u({},t)).join("")!=n})?function(e,t){for(var r=a(e),u=arguments.length,l=1,c=i.f,p=s.f;u>l;)for(var h,f=o(arguments[l++]),d=c?n(f).concat(c(f)):n(f),m=d.length,y=0;m>y;)p.call(f,h=d[y++])&&(r[h]=f[h]);return r}:u},{"./_fails":225,"./_iobject":232,"./_object-gops":251,"./_object-keys":254,"./_object-pie":255,"./_to-object":270}],245:[function(e,t,r){var n=e("./_an-object"),i=e("./_object-dps"),s=e("./_enum-bug-keys"),a=e("./_shared-key")("IE_PROTO"),o=function(){},u=function(){var t,r=e("./_dom-create")("iframe"),n=s.length;for(r.style.display="none",e("./_html").appendChild(r),r.src="javascript:",t=r.contentWindow.document,t.open(),t.write(""),t.close(),u=t.F;n--;)delete u.prototype[s[n]];return u()};t.exports=Object.create||function(e,t){var r;return null!==e?(o.prototype=n(e),r=new o,o.prototype=null,r[a]=e):r=u(),void 0===t?r:i(r,t)}},{"./_an-object":205,"./_dom-create":221,"./_enum-bug-keys":222,"./_html":230,"./_object-dps":247,"./_shared-key":263}],246:[function(e,t,r){var n=e("./_an-object"),i=e("./_ie8-dom-define"),s=e("./_to-primitive"),a=Object.defineProperty;r.f=e("./_descriptors")?Object.defineProperty:function(e,t,r){if(n(e),t=s(t,!0),n(r),i)try{return a(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(e[t]=r.value),e}},{"./_an-object":205,"./_descriptors":220,"./_ie8-dom-define":231,"./_to-primitive":271}],247:[function(e,t,r){var n=e("./_object-dp"),i=e("./_an-object"),s=e("./_object-keys");t.exports=e("./_descriptors")?Object.defineProperties:function(e,t){i(e);for(var r,a=s(t),o=a.length,u=0;o>u;)n.f(e,r=a[u++],t[r]);return e}},{"./_an-object":205,"./_descriptors":220,"./_object-dp":246,"./_object-keys":254}],248:[function(e,t,r){var n=e("./_object-pie"),i=e("./_property-desc"),s=e("./_to-iobject"),a=e("./_to-primitive"),o=e("./_has"),u=e("./_ie8-dom-define"),l=Object.getOwnPropertyDescriptor;r.f=e("./_descriptors")?l:function(e,t){if(e=s(e),t=a(t,!0),u)try{return l(e,t)}catch(e){}if(o(e,t))return i(!n.f.call(e,t),e[t])}},{"./_descriptors":220,"./_has":228,"./_ie8-dom-define":231,"./_object-pie":255,"./_property-desc":257,"./_to-iobject":268,"./_to-primitive":271}],249:[function(e,t,r){var n=e("./_to-iobject"),i=e("./_object-gopn").f,s={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],o=function(e){try{return i(e)}catch(e){return a.slice()}};t.exports.f=function(e){return a&&"[object Window]"==s.call(e)?o(e):i(n(e))}},{"./_object-gopn":250,"./_to-iobject":268}],250:[function(e,t,r){var n=e("./_object-keys-internal"),i=e("./_enum-bug-keys").concat("length","prototype");r.f=Object.getOwnPropertyNames||function(e){return n(e,i)}},{"./_enum-bug-keys":222,"./_object-keys-internal":253}],251:[function(e,t,r){r.f=Object.getOwnPropertySymbols},{}],252:[function(e,t,r){var n=e("./_has"),i=e("./_to-object"),s=e("./_shared-key")("IE_PROTO"),a=Object.prototype;t.exports=Object.getPrototypeOf||function(e){return e=i(e),n(e,s)?e[s]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},{"./_has":228,"./_shared-key":263,"./_to-object":270}],253:[function(e,t,r){var n=e("./_has"),i=e("./_to-iobject"),s=e("./_array-includes")(!1),a=e("./_shared-key")("IE_PROTO");t.exports=function(e,t){var r,o=i(e),u=0,l=[];for(r in o)r!=a&&n(o,r)&&l.push(r);for(;t.length>u;)n(o,r=t[u++])&&(~s(l,r)||l.push(r));return l}},{"./_array-includes":207,"./_has":228,"./_shared-key":263,"./_to-iobject":268}],254:[function(e,t,r){var n=e("./_object-keys-internal"),i=e("./_enum-bug-keys");t.exports=Object.keys||function(e){return n(e,i)}},{"./_enum-bug-keys":222,"./_object-keys-internal":253}],255:[function(e,t,r){r.f={}.propertyIsEnumerable},{}],256:[function(e,t,r){var n=e("./_export"),i=e("./_core"),s=e("./_fails");t.exports=function(e,t){var r=(i.Object||{})[e]||Object[e],a={};a[e]=t(r),n(n.S+n.F*s(function(){r(1)}),"Object",a)}},{"./_core":217,"./_export":224,"./_fails":225}],257:[function(e,t,r){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],258:[function(e,t,r){var n=e("./_hide");t.exports=function(e,t,r){for(var i in t)r&&e[i]?e[i]=t[i]:n(e,i,t[i]);return e}},{"./_hide":229}],259:[function(e,t,r){t.exports=e("./_hide")},{"./_hide":229}],260:[function(e,t,r){var n=e("./_is-object"),i=e("./_an-object"),s=function(e,t){if(i(e),!n(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,r,n){try{n=e("./_ctx")(Function.call,e("./_object-gopd").f(Object.prototype,"__proto__").set,2),n(t,[]),r=!(t instanceof Array)}catch(e){r=!0}return function(e,t){return s(e,t),r?e.__proto__=t:n(e,t),e}}({},!1):void 0),check:s}},{"./_an-object":205,"./_ctx":218,"./_is-object":235,"./_object-gopd":248}],261:[function(e,t,r){"use strict";var n=e("./_global"),i=e("./_core"),s=e("./_object-dp"),a=e("./_descriptors"),o=e("./_wks")("species");t.exports=function(e){var t="function"==typeof i[e]?i[e]:n[e];a&&t&&!t[o]&&s.f(t,o,{configurable:!0,get:function(){return this}})}},{"./_core":217,"./_descriptors":220,"./_global":227,"./_object-dp":246,"./_wks":275}],262:[function(e,t,r){var n=e("./_object-dp").f,i=e("./_has"),s=e("./_wks")("toStringTag");t.exports=function(e,t,r){e&&!i(e=r?e:e.prototype,s)&&n(e,s,{configurable:!0,value:t})}},{"./_has":228,"./_object-dp":246,"./_wks":275}],263:[function(e,t,r){var n=e("./_shared")("keys"),i=e("./_uid");t.exports=function(e){return n[e]||(n[e]=i(e))}},{"./_shared":264,"./_uid":272}],264:[function(e,t,r){var n=e("./_global"),i=n["__core-js_shared__"]||(n["__core-js_shared__"]={});t.exports=function(e){return i[e]||(i[e]={})}},{"./_global":227}],265:[function(e,t,r){var n=e("./_to-integer"),i=e("./_defined");t.exports=function(e){return function(t,r){var s,a,o=String(i(t)),u=n(r),l=o.length;return u<0||u>=l?e?"":void 0:(s=o.charCodeAt(u),s<55296||s>56319||u+1===l||(a=o.charCodeAt(u+1))<56320||a>57343?e?o.charAt(u):s:e?o.slice(u,u+2):a-56320+(s-55296<<10)+65536)}}},{"./_defined":219,"./_to-integer":267}],266:[function(e,t,r){var n=e("./_to-integer"),i=Math.max,s=Math.min;t.exports=function(e,t){return e=n(e),e<0?i(e+t,0):s(e,t)}},{"./_to-integer":267}],267:[function(e,t,r){var n=Math.ceil,i=Math.floor;t.exports=function(e){return isNaN(e=+e)?0:(e>0?i:n)(e)}},{}],268:[function(e,t,r){var n=e("./_iobject"),i=e("./_defined");t.exports=function(e){return n(i(e))}},{"./_defined":219,"./_iobject":232}],269:[function(e,t,r){var n=e("./_to-integer"),i=Math.min;t.exports=function(e){return e>0?i(n(e),9007199254740991):0}},{"./_to-integer":267}],270:[function(e,t,r){var n=e("./_defined");t.exports=function(e){return Object(n(e))}},{"./_defined":219}],271:[function(e,t,r){var n=e("./_is-object");t.exports=function(e,t){if(!n(e))return e;var r,i;if(t&&"function"==typeof(r=e.toString)&&!n(i=r.call(e)))return i;if("function"==typeof(r=e.valueOf)&&!n(i=r.call(e)))return i;if(!t&&"function"==typeof(r=e.toString)&&!n(i=r.call(e)))return i;throw TypeError("Can't convert object to primitive value")}},{"./_is-object":235}],272:[function(e,t,r){var n=0,i=Math.random();t.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+i).toString(36))}},{}],273:[function(e,t,r){var n=e("./_global"),i=e("./_core"),s=e("./_library"),a=e("./_wks-ext"),o=e("./_object-dp").f;t.exports=function(e){var t=i.Symbol||(i.Symbol=s?{}:n.Symbol||{});"_"==e.charAt(0)||e in t||o(t,e,{value:a.f(e)})}},{"./_core":217,"./_global":227,"./_library":242,"./_object-dp":246,"./_wks-ext":274}],274:[function(e,t,r){r.f=e("./_wks")},{"./_wks":275}],275:[function(e,t,r){var n=e("./_shared")("wks"),i=e("./_uid"),s=e("./_global").Symbol,a="function"==typeof s;(t.exports=function(e){return n[e]||(n[e]=a&&s[e]||(a?s:i)("Symbol."+e))}).store=n},{"./_global":227,"./_shared":264,"./_uid":272}],276:[function(e,t,r){var n=e("./_classof"),i=e("./_wks")("iterator"),s=e("./_iterators");t.exports=e("./_core").getIteratorMethod=function(e){if(void 0!=e)return e[i]||e["@@iterator"]||s[n(e)]}},{"./_classof":211,"./_core":217,"./_iterators":240,"./_wks":275}],277:[function(e,t,r){var n=e("./_an-object"),i=e("./core.get-iterator-method");t.exports=e("./_core").getIterator=function(e){var t=i(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return n(t.call(e))}},{"./_an-object":205,"./_core":217,"./core.get-iterator-method":276}],278:[function(e,t,r){"use strict";var n=e("./_add-to-unscopables"),i=e("./_iter-step"),s=e("./_iterators"),a=e("./_to-iobject");t.exports=e("./_iter-define")(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,r=this._i++;return!e||r>=e.length?(this._t=void 0,i(1)):"keys"==t?i(0,r):"values"==t?i(0,e[r]):i(0,[r,e[r]])},"values"),s.Arguments=s.Array,n("keys"),n("values"),n("entries")},{"./_add-to-unscopables":203,"./_iter-define":238,"./_iter-step":239,"./_iterators":240,"./_to-iobject":268}],279:[function(e,t,r){"use strict";var n=e("./_collection-strong");t.exports=e("./_collection")("Map",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{get:function(e){var t=n.getEntry(this,e);return t&&t.v},set:function(e,t){return n.def(this,0===e?0:e,t)}},n,!0)},{"./_collection":216,"./_collection-strong":213}],280:[function(e,t,r){var n=e("./_export");n(n.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},{"./_export":224}],281:[function(e,t,r){var n=e("./_export");n(n.S+n.F,"Object",{assign:e("./_object-assign")})},{"./_export":224,"./_object-assign":244}],282:[function(e,t,r){var n=e("./_export");n(n.S,"Object",{create:e("./_object-create")})},{"./_export":224,"./_object-create":245}],283:[function(e,t,r){var n=e("./_to-object"),i=e("./_object-keys");e("./_object-sap")("keys",function(){return function(e){return i(n(e))}})},{"./_object-keys":254,"./_object-sap":256,"./_to-object":270}],284:[function(e,t,r){var n=e("./_export");n(n.S,"Object",{setPrototypeOf:e("./_set-proto").set})},{"./_export":224,"./_set-proto":260}],285:[function(e,t,r){arguments[4][181][0].apply(r,arguments)},{dup:181}],286:[function(e,t,r){"use strict";var n=e("./_string-at")(!0);e("./_iter-define")(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,r=this._i;return r>=t.length?{value:void 0,done:!0}:(e=n(t,r),this._i+=e.length,{value:e,done:!1})})},{"./_iter-define":238,"./_string-at":265}],287:[function(e,t,r){"use strict";var n=e("./_global"),i=e("./_has"),s=e("./_descriptors"),a=e("./_export"),o=e("./_redefine"),u=e("./_meta").KEY,l=e("./_fails"),c=e("./_shared"),p=e("./_set-to-string-tag"),h=e("./_uid"),f=e("./_wks"),d=e("./_wks-ext"),m=e("./_wks-define"),y=e("./_keyof"),g=e("./_enum-keys"),b=e("./_is-array"),v=e("./_an-object"),x=e("./_to-iobject"),E=e("./_to-primitive"),A=e("./_property-desc"),D=e("./_object-create"),C=e("./_object-gopn-ext"),S=e("./_object-gopd"),_=e("./_object-dp"),w=e("./_object-keys"),k=S.f,F=_.f,T=C.f,P=n.Symbol,B=n.JSON,O=B&&B.stringify,j=f("_hidden"),N=f("toPrimitive"),I={}.propertyIsEnumerable,L=c("symbol-registry"),M=c("symbols"),R=c("op-symbols"),U=Object.prototype,V="function"==typeof P,q=n.QObject,G=!q||!q.prototype||!q.prototype.findChild,X=s&&l(function(){return 7!=D(F({},"a",{get:function(){return F(this,"a",{value:7}).a}})).a})?function(e,t,r){var n=k(U,t);n&&delete U[t],F(e,t,r),n&&e!==U&&F(U,t,n)}:F,J=function(e){var t=M[e]=D(P.prototype);return t._k=e,t},W=V&&"symbol"==typeof P.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof P},K=function(e,t,r){return e===U&&K(R,t,r),v(e),t=E(t,!0),v(r),i(M,t)?(r.enumerable?(i(e,j)&&e[j][t]&&(e[j][t]=!1),r=D(r,{enumerable:A(0,!1)})):(i(e,j)||F(e,j,A(1,{})),e[j][t]=!0),X(e,t,r)):F(e,t,r)},z=function(e,t){v(e);for(var r,n=g(t=x(t)),i=0,s=n.length;s>i;)K(e,r=n[i++],t[r]);return e},Y=function(e,t){return void 0===t?D(e):z(D(e),t)},H=function(e){var t=I.call(this,e=E(e,!0));return!(this===U&&i(M,e)&&!i(R,e))&&(!(t||!i(this,e)||!i(M,e)||i(this,j)&&this[j][e])||t)},$=function(e,t){if(e=x(e),t=E(t,!0),e!==U||!i(M,t)||i(R,t)){var r=k(e,t);return!r||!i(M,t)||i(e,j)&&e[j][t]||(r.enumerable=!0),r}},Q=function(e){for(var t,r=T(x(e)),n=[],s=0;r.length>s;)i(M,t=r[s++])||t==j||t==u||n.push(t);return n},Z=function(e){for(var t,r=e===U,n=T(r?R:x(e)),s=[],a=0;n.length>a;)!i(M,t=n[a++])||r&&!i(U,t)||s.push(M[t]);return s};V||(P=function(){if(this instanceof P)throw TypeError("Symbol is not a constructor!");var e=h(arguments.length>0?arguments[0]:void 0),t=function(r){this===U&&t.call(R,r),i(this,j)&&i(this[j],e)&&(this[j][e]=!1),X(this,e,A(1,r))};return s&&G&&X(U,e,{configurable:!0,set:t}),J(e)},o(P.prototype,"toString",function(){return this._k}),S.f=$,_.f=K,e("./_object-gopn").f=C.f=Q,e("./_object-pie").f=H,e("./_object-gops").f=Z,s&&!e("./_library")&&o(U,"propertyIsEnumerable",H,!0),d.f=function(e){return J(f(e))}),a(a.G+a.W+a.F*!V,{Symbol:P});for(var ee="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),te=0;ee.length>te;)f(ee[te++]);for(var ee=w(f.store),te=0;ee.length>te;)m(ee[te++]);a(a.S+a.F*!V,"Symbol",{for:function(e){return i(L,e+="")?L[e]:L[e]=P(e)},keyFor:function(e){if(W(e))return y(L,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){G=!0},useSimple:function(){G=!1}}),a(a.S+a.F*!V,"Object",{create:Y,defineProperty:K,defineProperties:z,getOwnPropertyDescriptor:$,getOwnPropertyNames:Q,getOwnPropertySymbols:Z}),B&&a(a.S+a.F*(!V||l(function(){var e=P();return"[null]"!=O([e])||"{}"!=O({a:e})||"{}"!=O(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!W(e)){for(var t,r,n=[e],i=1;arguments.length>i;)n.push(arguments[i++]);return t=n[1],"function"==typeof t&&(r=t),!r&&b(t)||(t=function(e,t){if(r&&(t=r.call(this,e,t)),!W(t))return t}),n[1]=t,O.apply(B,n)}}}),P.prototype[N]||e("./_hide")(P.prototype,N,P.prototype.valueOf),p(P,"Symbol"),p(Math,"Math",!0),p(n.JSON,"JSON",!0)},{"./_an-object":205,"./_descriptors":220,"./_enum-keys":223,"./_export":224,"./_fails":225,"./_global":227,"./_has":228,"./_hide":229,"./_is-array":234,"./_keyof":241,"./_library":242,"./_meta":243,"./_object-create":245,"./_object-dp":246,"./_object-gopd":248,"./_object-gopn":250,"./_object-gopn-ext":249,"./_object-gops":251,"./_object-keys":254,"./_object-pie":255,"./_property-desc":257,"./_redefine":259,"./_set-to-string-tag":262,"./_shared":264,"./_to-iobject":268,"./_to-primitive":271,"./_uid":272,"./_wks":275,"./_wks-define":273,"./_wks-ext":274}],288:[function(e,t,r){"use strict";var n,i=e("./_array-methods")(0),s=e("./_redefine"),a=e("./_meta"),o=e("./_object-assign"),u=e("./_collection-weak"),l=e("./_is-object"),c=a.getWeak,p=Object.isExtensible,h=u.ufstore,f={},d=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},m={get:function(e){if(l(e)){var t=c(e);return!0===t?h(this).get(e):t?t[this._i]:void 0}},set:function(e,t){return u.def(this,e,t)}},y=t.exports=e("./_collection")("WeakMap",d,m,u,!0,!0);7!=(new y).set((Object.freeze||Object)(f),7).get(f)&&(n=u.getConstructor(d),o(n.prototype,m),a.NEED=!0,i(["delete","has","get","set"],function(e){var t=y.prototype,r=t[e];s(t,e,function(t,i){if(l(t)&&!p(t)){this._f||(this._f=new n);var s=this._f[e](t,i);return"set"==e?this:s}return r.call(this,t,i)})}))},{"./_array-methods":208,"./_collection":216,"./_collection-weak":215,"./_is-object":235,"./_meta":243,"./_object-assign":244,"./_redefine":259}],289:[function(e,t,r){"use strict";var n=e("./_collection-weak");e("./_collection")("WeakSet",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return n.def(this,e,!0)}},n,!1,!0)},{"./_collection":216,"./_collection-weak":215}],290:[function(e,t,r){var n=e("./_export");n(n.P+n.R,"Map",{toJSON:e("./_collection-to-json")("Map")})},{"./_collection-to-json":214,"./_export":224}],291:[function(e,t,r){e("./_wks-define")("asyncIterator")},{"./_wks-define":273}],292:[function(e,t,r){e("./_wks-define")("observable")},{"./_wks-define":273}],293:[function(e,t,r){e("./es6.array.iterator");for(var n=e("./_global"),i=e("./_hide"),s=e("./_iterators"),a=e("./_wks")("toStringTag"),o=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],u=0;u<5;u++){var l=o[u],c=n[l],p=c&&c.prototype;p&&!p[a]&&i(p,a,l),s[l]=s.Array}},{"./_global":227,"./_hide":229,"./_iterators":240,"./_wks":275,"./es6.array.iterator":278}],294:[function(e,t,r){(function(e){function t(e){return Array.isArray?Array.isArray(e):"[object Array]"===y(e)}function n(e){return"boolean"==typeof e}function i(e){return null===e}function s(e){return null==e}function a(e){return"number"==typeof e}function o(e){return"string"==typeof e}function u(e){return"symbol"==typeof e}function l(e){return void 0===e}function c(e){return"[object RegExp]"===y(e)}function p(e){return"object"==typeof e&&null!==e}function h(e){return"[object Date]"===y(e)}function f(e){return"[object Error]"===y(e)||e instanceof Error}function d(e){return"function"==typeof e}function m(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e}function y(e){return Object.prototype.toString.call(e)}r.isArray=t,r.isBoolean=n,r.isNull=i,r.isNullOrUndefined=s,r.isNumber=a,r.isString=o,r.isSymbol=u,r.isUndefined=l,r.isRegExp=c,r.isObject=p,r.isDate=h,r.isError=f,r.isFunction=d,r.isPrimitive=m, +r.isBuffer=e.isBuffer}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":308}],295:[function(e,t,r){t.exports=e("./src/node")},{"./src/node":298}],296:[function(e,t,r){(function(n){function i(){return!("undefined"==typeof window||!window||void 0===window.process||"renderer"!==window.process.type)||("undefined"!=typeof document&&document&&"WebkitAppearance"in document.documentElement.style||"undefined"!=typeof window&&window&&window.console&&(console.firebug||console.exception&&console.table)||"undefined"!=typeof navigator&&navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function s(e){var t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+r.humanize(this.diff),t){var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,s=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(s=i))}),e.splice(s,0,n)}}function a(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function o(e){try{null==e?r.storage.removeItem("debug"):r.storage.debug=e}catch(e){}}function u(){var e;try{e=r.storage.debug}catch(e){}return!e&&void 0!==n&&"env"in n&&(e=n.env.DEBUG),e}r=t.exports=e("./debug"),r.log=a,r.formatArgs=s,r.save=o,r.load=u,r.useColors=i,r.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],r.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},r.enable(u())}).call(this,e("_process"))},{"./debug":297,_process:539}],297:[function(e,t,r){function n(e){var t,n=0;for(t in e)n=(n<<5)-n+e.charCodeAt(t),n|=0;return r.colors[Math.abs(n)%r.colors.length]}function i(e){function t(){if(t.enabled){var e=t,n=+new Date,i=n-(l||n);e.diff=i,e.prev=l,e.curr=n,l=n;for(var s=new Array(arguments.length),a=0;ar||a===r&&o>n)&&(r=a,n=o,t=Number(i))}return t}var i=e("repeating");t.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");var t,r,s=0,a=0,o=0,u={};e.split(/\n/g).forEach(function(e){if(e){var n,i=e.match(/^(?:( )+|\t+)/);i?(n=i[0].length,i[1]?a++:s++):n=0;var l=n-o;o=n,l?(r=l>0,t=u[r?l:-l],t?t[0]++:t=u[l]=[1,0]):t&&(t[1]+=Number(r))}});var l,c,p=n(u);return p?a>=s?(l="space",c=i(" ",p)):(l="tab",c=i("\t",p)):(l=null,c=""),{amount:p,type:l,indent:c}}},{repeating:588}],300:[function(e,t,r){"use strict";t.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&")}},{}],301:[function(e,t,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function s(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}t.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!s(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},n.prototype.emit=function(e){var t,r,n,s,u,l;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(r=this._events[e],o(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),r.apply(this,s)}else if(a(r))for(s=Array.prototype.slice.call(arguments,1),l=r.slice(),n=l.length,u=0;u0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function r(){this.removeListener(e,r),n||(n=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var n=!1;return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,t){var r,n,s,o;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=this._events[e],s=r.length,n=-1,r===t||i(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(r)){for(o=s;o-- >0;)if(r[o]===t||r[o].listener&&r[o].listener===t){n=o;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[e],i(r))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},{}],302:[function(e,t,r){t.exports={builtin:{Array:!1,ArrayBuffer:!1,Boolean:!1,constructor:!1,DataView:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,escape:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Map:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,Promise:!1,propertyIsEnumerable:!1,Proxy:!1,RangeError:!1,ReferenceError:!1,Reflect:!1,RegExp:!1,Set:!1,String:!1,Symbol:!1,SyntaxError:!1,System:!1,toLocaleString:!1,toString:!1,TypeError:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1,undefined:!1,unescape:!1,URIError:!1,valueOf:!1,WeakMap:!1,WeakSet:!1},es5:{Array:!1,Boolean:!1,constructor:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,escape:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,propertyIsEnumerable:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,toLocaleString:!1,toString:!1,TypeError:!1,undefined:!1,unescape:!1,URIError:!1,valueOf:!1},es6:{Array:!1,ArrayBuffer:!1,Boolean:!1,constructor:!1,DataView:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,escape:!1,eval:!1,EvalError:!1,Float32Array:!1,Float64Array:!1,Function:!1,hasOwnProperty:!1,Infinity:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,isFinite:!1,isNaN:!1,isPrototypeOf:!1,JSON:!1,Map:!1,Math:!1,NaN:!1,Number:!1,Object:!1,parseFloat:!1,parseInt:!1,Promise:!1,propertyIsEnumerable:!1,Proxy:!1,RangeError:!1,ReferenceError:!1,Reflect:!1,RegExp:!1,Set:!1,String:!1,Symbol:!1,SyntaxError:!1,System:!1,toLocaleString:!1,toString:!1,TypeError:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1,undefined:!1,unescape:!1,URIError:!1,valueOf:!1,WeakMap:!1,WeakSet:!1},browser:{addEventListener:!1,alert:!1,AnalyserNode:!1,Animation:!1,AnimationEffectReadOnly:!1,AnimationEffectTiming:!1,AnimationEffectTimingReadOnly:!1,AnimationEvent:!1,AnimationPlaybackEvent:!1,AnimationTimeline:!1,applicationCache:!1,ApplicationCache:!1,ApplicationCacheErrorEvent:!1,atob:!1,Attr:!1,Audio:!1,AudioBuffer:!1,AudioBufferSourceNode:!1,AudioContext:!1,AudioDestinationNode:!1,AudioListener:!1,AudioNode:!1,AudioParam:!1,AudioProcessingEvent:!1,AutocompleteErrorEvent:!1,BarProp:!1,BatteryManager:!1,BeforeUnloadEvent:!1,BiquadFilterNode:!1,Blob:!1,blur:!1,btoa:!1,Cache:!1,caches:!1,CacheStorage:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CDATASection:!1,ChannelMergerNode:!1,ChannelSplitterNode:!1,CharacterData:!1,clearInterval:!1,clearTimeout:!1,clientInformation:!1,ClientRect:!1,ClientRectList:!1,ClipboardEvent:!1,close:!1,closed:!1,CloseEvent:!1,Comment:!1,CompositionEvent:!1,confirm:!1,console:!1,ConvolverNode:!1,Credential:!1,CredentialsContainer:!1,crypto:!1,Crypto:!1,CryptoKey:!1,CSS:!1,CSSAnimation:!1,CSSFontFaceRule:!1,CSSImportRule:!1,CSSKeyframeRule:!1,CSSKeyframesRule:!1,CSSMediaRule:!1,CSSPageRule:!1,CSSRule:!1,CSSRuleList:!1,CSSStyleDeclaration:!1,CSSStyleRule:!1,CSSStyleSheet:!1,CSSSupportsRule:!1,CSSTransition:!1,CSSUnknownRule:!1,CSSViewportRule:!1,customElements:!1,CustomEvent:!1,DataTransfer:!1,DataTransferItem:!1,DataTransferItemList:!1,Debug:!1,defaultStatus:!1,defaultstatus:!1,DelayNode:!1,DeviceMotionEvent:!1,DeviceOrientationEvent:!1,devicePixelRatio:!1,dispatchEvent:!1,document:!1,Document:!1,DocumentFragment:!1,DocumentTimeline:!1,DocumentType:!1,DOMError:!1,DOMException:!1,DOMImplementation:!1,DOMParser:!1,DOMSettableTokenList:!1,DOMStringList:!1,DOMStringMap:!1,DOMTokenList:!1,DragEvent:!1,DynamicsCompressorNode:!1,Element:!1,ElementTimeControl:!1,ErrorEvent:!1,event:!1,Event:!1,EventSource:!1,EventTarget:!1,external:!1,FederatedCredential:!1,fetch:!1,File:!1,FileError:!1,FileList:!1,FileReader:!1,find:!1,focus:!1,FocusEvent:!1,FontFace:!1,FormData:!1,frameElement:!1,frames:!1,GainNode:!1,Gamepad:!1,GamepadButton:!1,GamepadEvent:!1,getComputedStyle:!1,getSelection:!1,HashChangeEvent:!1,Headers:!1,history:!1,History:!1,HTMLAllCollection:!1,HTMLAnchorElement:!1,HTMLAppletElement:!1,HTMLAreaElement:!1,HTMLAudioElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLContentElement:!1,HTMLDataListElement:!1,HTMLDetailsElement:!1,HTMLDialogElement:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLDocument:!1,HTMLElement:!1,HTMLEmbedElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormControlsCollection:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLKeygenElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMarqueeElement:!1,HTMLMediaElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLMeterElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLOptionsCollection:!1,HTMLOutputElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPictureElement:!1,HTMLPreElement:!1,HTMLProgressElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLShadowElement:!1,HTMLSourceElement:!1,HTMLSpanElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLTrackElement:!1,HTMLUListElement:!1,HTMLUnknownElement:!1,HTMLVideoElement:!1,IDBCursor:!1,IDBCursorWithValue:!1,IDBDatabase:!1,IDBEnvironment:!1,IDBFactory:!1,IDBIndex:!1,IDBKeyRange:!1,IDBObjectStore:!1,IDBOpenDBRequest:!1,IDBRequest:!1,IDBTransaction:!1,IDBVersionChangeEvent:!1,Image:!1,ImageBitmap:!1,ImageData:!1,indexedDB:!1,innerHeight:!1,innerWidth:!1,InputEvent:!1,InputMethodContext:!1,IntersectionObserver:!1,IntersectionObserverEntry:!1,Intl:!1,KeyboardEvent:!1,KeyframeEffect:!1,KeyframeEffectReadOnly:!1,length:!1,localStorage:!1,location:!1,Location:!1,locationbar:!1,matchMedia:!1,MediaElementAudioSourceNode:!1,MediaEncryptedEvent:!1,MediaError:!1,MediaKeyError:!1,MediaKeyEvent:!1,MediaKeyMessageEvent:!1,MediaKeys:!1,MediaKeySession:!1,MediaKeyStatusMap:!1,MediaKeySystemAccess:!1,MediaList:!1,MediaQueryList:!1,MediaQueryListEvent:!1,MediaSource:!1,MediaRecorder:!1,MediaStream:!1,MediaStreamAudioDestinationNode:!1,MediaStreamAudioSourceNode:!1,MediaStreamEvent:!1,MediaStreamTrack:!1,menubar:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MIDIAccess:!1,MIDIConnectionEvent:!1,MIDIInput:!1,MIDIInputMap:!1,MIDIMessageEvent:!1,MIDIOutput:!1,MIDIOutputMap:!1,MIDIPort:!1,MimeType:!1,MimeTypeArray:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationEvent:!1,MutationObserver:!1,MutationRecord:!1,name:!1,NamedNodeMap:!1,navigator:!1,Navigator:!1,Node:!1,NodeFilter:!1,NodeIterator:!1,NodeList:!1,Notification:!1,OfflineAudioCompletionEvent:!1,OfflineAudioContext:!1,offscreenBuffering:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,opera:!1,Option:!1,OscillatorNode:!1,outerHeight:!1,outerWidth:!1,PageTransitionEvent:!1,pageXOffset:!1,pageYOffset:!1,parent:!1,PasswordCredential:!1,Path2D:!1,performance:!1,Performance:!1,PerformanceEntry:!1,PerformanceMark:!1,PerformanceMeasure:!1,PerformanceNavigation:!1,PerformanceResourceTiming:!1,PerformanceTiming:!1,PeriodicWave:!1,Permissions:!1,PermissionStatus:!1,personalbar:!1,Plugin:!1,PluginArray:!1,PopStateEvent:!1,postMessage:!1,print:!1,ProcessingInstruction:!1,ProgressEvent:!1,PromiseRejectionEvent:!1,prompt:!1,PushManager:!1,PushSubscription:!1,RadioNodeList:!1,Range:!1,ReadableByteStream:!1,ReadableStream:!1,removeEventListener:!1,Request:!1,requestAnimationFrame:!1,requestIdleCallback:!1,resizeBy:!1,resizeTo:!1,Response:!1,RTCIceCandidate:!1,RTCSessionDescription:!1,RTCPeerConnection:!1,screen:!1,Screen:!1,screenLeft:!1,ScreenOrientation:!1,screenTop:!1,screenX:!1,screenY:!1,ScriptProcessorNode:!1,scroll:!1,scrollbars:!1,scrollBy:!1,scrollTo:!1,scrollX:!1,scrollY:!1,SecurityPolicyViolationEvent:!1,Selection:!1,self:!1,ServiceWorker:!1,ServiceWorkerContainer:!1,ServiceWorkerRegistration:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,ShadowRoot:!1,SharedKeyframeList:!1,SharedWorker:!1,showModalDialog:!1,SiteBoundCredential:!1,speechSynthesis:!1,SpeechSynthesisEvent:!1,SpeechSynthesisUtterance:!1,status:!1,statusbar:!1,stop:!1,Storage:!1,StorageEvent:!1,styleMedia:!1,StyleSheet:!1,StyleSheetList:!1,SubtleCrypto:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimationElement:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCSSRule:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDiscardElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGEvent:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEDropShadowElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGeometryElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGGraphicsElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLinearGradientElement:!1,SVGLineElement:!1,SVGLocatable:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGMPathElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSVGElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformable:!1,SVGTransformList:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGUnitTypes:!1,SVGURIReference:!1,SVGUseElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGVKernElement:!1,SVGZoomAndPan:!1,SVGZoomEvent:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TextEvent:!1,TextMetrics:!1,TextTrack:!1,TextTrackCue:!1,TextTrackCueList:!1,TextTrackList:!1,TimeEvent:!1,TimeRanges:!1,toolbar:!1,top:!1,Touch:!1,TouchEvent:!1,TouchList:!1,TrackEvent:!1,TransitionEvent:!1,TreeWalker:!1,UIEvent:!1,URL:!1,URLSearchParams:!1,ValidityState:!1,VTTCue:!1,WaveShaperNode:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,WheelEvent:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLDocument:!1,XMLHttpRequest:!1,XMLHttpRequestEventTarget:!1,XMLHttpRequestProgressEvent:!1,XMLHttpRequestUpload:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1,XSLTProcessor:!1},worker:{applicationCache:!1,atob:!1,Blob:!1,BroadcastChannel:!1,btoa:!1,Cache:!1,caches:!1,clearInterval:!1,clearTimeout:!1,close:!0,console:!1,fetch:!1,FileReaderSync:!1,FormData:!1,Headers:!1,IDBCursor:!1,IDBCursorWithValue:!1,IDBDatabase:!1,IDBFactory:!1,IDBIndex:!1,IDBKeyRange:!1,IDBObjectStore:!1,IDBOpenDBRequest:!1,IDBRequest:!1,IDBTransaction:!1,IDBVersionChangeEvent:!1,ImageData:!1,importScripts:!0,indexedDB:!1,location:!1,MessageChannel:!1,MessagePort:!1,name:!1,navigator:!1,Notification:!1,onclose:!0,onconnect:!0,onerror:!0,onlanguagechange:!0,onmessage:!0,onoffline:!0,ononline:!0,onrejectionhandled:!0,onunhandledrejection:!0,performance:!1,Performance:!1,PerformanceEntry:!1,PerformanceMark:!1,PerformanceMeasure:!1,PerformanceNavigation:!1,PerformanceResourceTiming:!1,PerformanceTiming:!1,postMessage:!0,Promise:!1,Request:!1,Response:!1,self:!0,ServiceWorkerRegistration:!1,setInterval:!1,setTimeout:!1,TextDecoder:!1,TextEncoder:!1,URL:!1,URLSearchParams:!1,WebSocket:!1,Worker:!1,XMLHttpRequest:!1},node:{__dirname:!1,__filename:!1,arguments:!1,Buffer:!1,clearImmediate:!1,clearInterval:!1,clearTimeout:!1,console:!1,exports:!0,GLOBAL:!1,global:!1,Intl:!1,module:!1,process:!1,require:!1,root:!1,setImmediate:!1,setInterval:!1,setTimeout:!1},commonjs:{exports:!0,module:!1,require:!1,global:!1},amd:{define:!1,require:!1},mocha:{after:!1,afterEach:!1,before:!1,beforeEach:!1,context:!1,describe:!1,it:!1,mocha:!1,run:!1,setup:!1,specify:!1,suite:!1,suiteSetup:!1,suiteTeardown:!1,teardown:!1,test:!1,xcontext:!1,xdescribe:!1,xit:!1,xspecify:!1},jasmine:{afterAll:!1,afterEach:!1,beforeAll:!1,beforeEach:!1,describe:!1,expect:!1,fail:!1,fdescribe:!1,fit:!1,it:!1,jasmine:!1,pending:!1,runs:!1,spyOn:!1,waits:!1,waitsFor:!1,xdescribe:!1,xit:!1},jest:{afterAll:!1,afterEach:!1,beforeAll:!1,beforeEach:!1,check:!1,describe:!1,expect:!1,gen:!1,it:!1,fdescribe:!1,fit:!1,jest:!1,pit:!1,require:!1,test:!1,xdescribe:!1,xit:!1,xtest:!1},qunit:{asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notOk:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,throws:!1},phantomjs:{console:!0,exports:!0,phantom:!0,require:!0,WebPage:!0},couch:{emit:!1,exports:!1,getRow:!1,log:!1,module:!1,provides:!1,require:!1,respond:!1,send:!1,start:!1,sum:!1},rhino:{defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},nashorn:{__DIR__:!1,__FILE__:!1,__LINE__:!1,com:!1,edu:!1,exit:!1,Java:!1,java:!1,javafx:!1,JavaImporter:!1,javax:!1,JSAdapter:!1,load:!1,loadWithNewGlobal:!1,org:!1,Packages:!1,print:!1,quit:!1},wsh:{ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WScript:!0,WSH:!0,XDomainRequest:!0},jquery:{$:!1,jQuery:!1},yui:{Y:!1,YUI:!1,YUI_config:!1},shelljs:{cat:!1,cd:!1,chmod:!1,config:!1,cp:!1,dirs:!1,echo:!1,env:!1,error:!1,exec:!1,exit:!1,find:!1,grep:!1,ls:!1,ln:!1,mkdir:!1,mv:!1,popd:!1,pushd:!1,pwd:!1,rm:!1,sed:!1,set:!1,target:!1,tempdir:!1,test:!1,touch:!1,which:!1},prototypejs:{$:!1,$$:!1,$A:!1,$break:!1,$continue:!1,$F:!1,$H:!1,$R:!1,$w:!1,Abstract:!1,Ajax:!1,Autocompleter:!1,Builder:!1,Class:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Element:!1,Enumerable:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Scriptaculous:!1,Selector:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Template:!1,Toggle:!1,Try:!1},meteor:{$:!1,_:!1,Accounts:!1,AccountsClient:!1,AccountsServer:!1,AccountsCommon:!1,App:!1,Assets:!1,Blaze:!1,check:!1,Cordova:!1,DDP:!1,DDPServer:!1,DDPRateLimiter:!1,Deps:!1,EJSON:!1,Email:!1,HTTP:!1,Log:!1,Match:!1,Meteor:!1,Mongo:!1,MongoInternals:!1,Npm:!1,Package:!1,Plugin:!1,process:!1,Random:!1,ReactiveDict:!1,ReactiveVar:!1,Router:!1,ServiceConfiguration:!1,Session:!1,share:!1,Spacebars:!1,Template:!1,Tinytest:!1,Tracker:!1,UI:!1,Utils:!1,WebApp:!1,WebAppInternals:!1},mongo:{_isWindows:!1,_rand:!1,BulkWriteResult:!1,cat:!1,cd:!1,connect:!1,db:!1,getHostName:!1,getMemInfo:!1,hostname:!1,ISODate:!1,listFiles:!1,load:!1,ls:!1,md5sumFile:!1,mkdir:!1,Mongo:!1,NumberInt:!1,NumberLong:!1,ObjectId:!1,PlanCache:!1,print:!1,printjson:!1,pwd:!1,quit:!1,removeFile:!1,rs:!1,sh:!1,UUID:!1,version:!1,WriteResult:!1},applescript:{$:!1,Application:!1,Automation:!1,console:!1,delay:!1,Library:!1,ObjC:!1,ObjectSpecifier:!1,Path:!1,Progress:!1,Ref:!1},serviceworker:{caches:!1,Cache:!1,CacheStorage:!1,Client:!1,clients:!1,Clients:!1,ExtendableEvent:!1,ExtendableMessageEvent:!1,FetchEvent:!1,importScripts:!1,registration:!1,self:!1,ServiceWorker:!1,ServiceWorkerContainer:!1,ServiceWorkerGlobalScope:!1,ServiceWorkerMessageEvent:!1,ServiceWorkerRegistration:!1,skipWaiting:!1,WindowClient:!1},atomtest:{advanceClock:!1,fakeClearInterval:!1,fakeClearTimeout:!1,fakeSetInterval:!1,fakeSetTimeout:!1,resetTimeouts:!1,waitsForPromise:!1},embertest:{andThen:!1,click:!1,currentPath:!1,currentRouteName:!1,currentURL:!1,fillIn:!1,find:!1,findWithAssert:!1,keyEvent:!1,pauseTest:!1,resumeTest:!1,triggerEvent:!1,visit:!1},protractor:{$:!1,$$:!1,browser:!1,By:!1,by:!1,DartObject:!1,element:!1,protractor:!1},"shared-node-browser":{clearInterval:!1,clearTimeout:!1,console:!1,setInterval:!1,setTimeout:!1},webextensions:{browser:!1,chrome:!1,opr:!1},greasemonkey:{GM_addStyle:!1,GM_deleteValue:!1,GM_getResourceText:!1,GM_getResourceURL:!1,GM_getValue:!1,GM_info:!1,GM_listValues:!1,GM_log:!1,GM_openInTab:!1,GM_registerMenuCommand:!1,GM_setClipboard:!1,GM_setValue:!1,GM_xmlhttpRequest:!1,unsafeWindow:!1}}},{}],303:[function(e,t,r){t.exports=e("./globals.json")},{"./globals.json":302}],304:[function(e,t,r){"use strict";var n=e("ansi-regex"),i=new RegExp(n().source);t.exports=i.test.bind(i)},{"ansi-regex":1}],305:[function(e,t,r){r.read=function(e,t,r,n,i){var s,a,o=8*i-n-1,u=(1<>1,c=-7,p=r?i-1:0,h=r?-1:1,f=e[t+p];for(p+=h,s=f&(1<<-c)-1,f>>=-c,c+=o;c>0;s=256*s+e[t+p],p+=h,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+e[t+p],p+=h,c-=8);if(0===s)s=1-l;else{if(s===u)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=l}return(f?-1:1)*a*Math.pow(2,s-n)},r.write=function(e,t,r,n,i,s){var a,o,u,l=8*s-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+p>=1?h/u:h*Math.pow(2,1-p),t*u>=2&&(a++,u/=2),a+p>=c?(o=0,a=c):a+p>=1?(o=(t*u-1)*Math.pow(2,i),a+=p):(o=t*Math.pow(2,p-1)*Math.pow(2,i),a=0));i>=8;e[r+f]=255&o,f+=d,o/=256,i-=8);for(a=a<0;e[r+f]=255&a,f+=d,a/=256,l-=8);e[r+f-d]|=128*m}},{}],306:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],307:[function(e,t,r){"use strict";var n=function(e,t,r,n,i,s,a,o){if(void 0===t)throw new Error("invariant requires an error message argument");if(!e){var u;if(void 0===t)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,i,s,a,o],c=0;u=new Error(t.replace(/%s/g,function(){return l[c++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}};t.exports=n},{}],308:[function(e,t,r){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function i(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}t.exports=function(e){return null!=e&&(n(e)||i(e)||!!e._isBuffer)}},{}],309:[function(e,t,r){"use strict";var n=e("number-is-nan");t.exports=Number.isFinite||function(e){return!("number"!=typeof e||n(e)||e===1/0||e===-1/0)}},{"number-is-nan":533}],310:[function(e,t,r){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],311:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0}), +r.default=/((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyu]{1,5}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g,r.matchToToken=function(e){var t={type:"invalid",value:e[0]};return e[1]?(t.type="string",t.closed=!(!e[3]&&!e[4])):e[5]?t.type="comment":e[6]?(t.type="comment",t.closed=!!e[7]):e[8]?t.type="regex":e[9]?t.type="number":e[10]?t.type="name":e[11]?t.type="punctuator":e[12]&&(t.type="whitespace"),t}},{}],312:[function(e,t,r){(function(e){!function(n){var i="object"==typeof r&&r,s="object"==typeof t&&t&&t.exports==i&&t,a="object"==typeof e&&e;a.global!==a&&a.window!==a||(n=a);var o={},u=o.hasOwnProperty,l=function(e,t){var r;for(r in e)u.call(e,r)&&t(r,e[r])},c=function(e,t){return t?(l(t,function(t,r){e[t]=r}),e):e},p=function(e,t){for(var r=e.length,n=-1;++n=55296&&j<=56319&&R>M+1&&(N=L.charCodeAt(M+1))>=56320&&N<=57343){I=1024*(j-55296)+N-56320+65536;var V=I.toString(16);u||(V=V.toUpperCase()),i+="\\u{"+V+"}",M++}else{if(!t.escapeEverything){if(D.test(U)){i+=U;continue}if('"'==U){i+=s==U?'\\"':U;continue}if("'"==U){i+=s==U?"\\'":U;continue}}if("\0"!=U||n||A.test(L.charAt(M+1)))if(E.test(U))i+=x[U];else{var q=U.charCodeAt(0),V=q.toString(16);u||(V=V.toUpperCase());var G=V.length>2||n,X="\\"+(G?"u":"x")+("0000"+V).slice(G?-4:-2);i+=X}else i+="\\0"}}return t.wrap&&(i=s+i+s),t.escapeEtago?i.replace(/<\/(script|style)/gi,"<\\/$1"):i};C.version="1.3.0","function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return C}):i&&!i.nodeType?s?s.exports=C:i.jsesc=C:n.jsesc=C}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],313:[function(e,t,r){var n="object"==typeof r?r:{};n.parse=function(){"use strict";var e,t,r,n,i,s,a={"'":"'",'"':'"',"\\":"\\","/":"/","\n":"",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},o=[" ","\t","\r","\n","\v","\f"," ","\ufeff"],u=function(e){return""===e?"EOF":"'"+e+"'"},l=function(n){var s=new SyntaxError;throw s.message=n+" at line "+t+" column "+r+" of the JSON5 data. Still to read: "+JSON.stringify(i.substring(e-1,e+19)),s.at=e,s.lineNumber=t,s.columnNumber=r,s},c=function(s){return s&&s!==n&&l("Expected "+u(s)+" instead of "+u(n)),n=i.charAt(e),e++,r++,("\n"===n||"\r"===n&&"\n"!==p())&&(t++,r=0),n},p=function(){return i.charAt(e)},h=function(){var e=n;for("_"!==n&&"$"!==n&&(n<"a"||n>"z")&&(n<"A"||n>"Z")&&l("Bad identifier as unquoted key");c()&&("_"===n||"$"===n||n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9");)e+=n;return e},f=function(){var e,t="",r="",i=10;if("-"!==n&&"+"!==n||(t=n,c(n)),"I"===n)return e=v(),("number"!=typeof e||isNaN(e))&&l("Unexpected word for number"),"-"===t?-e:e;if("N"===n)return e=v(),isNaN(e)||l("expected word to be NaN"),e;switch("0"===n&&(r+=n,c(),"x"===n||"X"===n?(r+=n,c(),i=16):n>="0"&&n<="9"&&l("Octal literal")),i){case 10:for(;n>="0"&&n<="9";)r+=n,c();if("."===n)for(r+=".";c()&&n>="0"&&n<="9";)r+=n;if("e"===n||"E"===n)for(r+=n,c(),"-"!==n&&"+"!==n||(r+=n,c());n>="0"&&n<="9";)r+=n,c();break;case 16:for(;n>="0"&&n<="9"||n>="A"&&n<="F"||n>="a"&&n<="f";)r+=n,c()}if(e="-"===t?-r:+r,isFinite(e))return e;l("Bad number")},d=function(){var e,t,r,i,s="";if('"'===n||"'"===n)for(r=n;c();){if(n===r)return c(),s;if("\\"===n)if(c(),"u"===n){for(i=0,t=0;t<4&&(e=parseInt(c(),16),isFinite(e));t+=1)i=16*i+e;s+=String.fromCharCode(i)}else if("\r"===n)"\n"===p()&&c();else{if("string"!=typeof a[n])break;s+=a[n]}else{if("\n"===n)break;s+=n}}l("Bad string")},m=function(){"/"!==n&&l("Not an inline comment");do{if(c(),"\n"===n||"\r"===n)return void c()}while(n)},y=function(){"*"!==n&&l("Not a block comment");do{for(c();"*"===n;)if(c("*"),"/"===n)return void c("/")}while(n);l("Unterminated block comment")},g=function(){"/"!==n&&l("Not a comment"),c("/"),"/"===n?m():"*"===n?y():l("Unrecognized comment")},b=function(){for(;n;)if("/"===n)g();else{if(!(o.indexOf(n)>=0))return;c()}},v=function(){switch(n){case"t":return c("t"),c("r"),c("u"),c("e"),!0;case"f":return c("f"),c("a"),c("l"),c("s"),c("e"),!1;case"n":return c("n"),c("u"),c("l"),c("l"),null;case"I":return c("I"),c("n"),c("f"),c("i"),c("n"),c("i"),c("t"),c("y"),1/0;case"N":return c("N"),c("a"),c("N"),NaN}l("Unexpected "+u(n))},x=function(){var e=[];if("["===n)for(c("["),b();n;){if("]"===n)return c("]"),e;if(","===n?l("Missing array element"):e.push(s()),b(),","!==n)return c("]"),e;c(","),b()}l("Bad array")},E=function(){var e,t={};if("{"===n)for(c("{"),b();n;){if("}"===n)return c("}"),t;if(e='"'===n||"'"===n?d():h(),b(),c(":"),t[e]=s(),b(),","!==n)return c("}"),t;c(","),b()}l("Bad object")};return s=function(){switch(b(),n){case"{":return E();case"[":return x();case'"':case"'":return d();case"-":case"+":case".":return f();default:return n>="0"&&n<="9"?f():v()}},function(a,o){var u;return i=String(a),e=0,t=1,r=1,n=" ",u=s(),b(),n&&l("Syntax error"),"function"==typeof o?function e(t,r){var n,i,s=t[r];if(s&&"object"==typeof s)for(n in s)Object.prototype.hasOwnProperty.call(s,n)&&(i=e(s,n),void 0!==i?s[n]=i:delete s[n]);return o.call(t,r,s)}({"":u},""):u}}(),n.stringify=function(e,t,r){function i(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e>="0"&&e<="9"||"_"===e||"$"===e}function s(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||"_"===e||"$"===e}function a(e){if("string"!=typeof e)return!1;if(!s(e[0]))return!1;for(var t=1,r=e.length;t10&&(e=e.substring(0,10));for(var n=r?"":"\n",i=0;i=0?i:void 0:i};n.isWord=a;var d,m=[];r&&("string"==typeof r?d=r:"number"==typeof r&&r>=0&&(d=c(" ",r,!0)));var y=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,g={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},b={"":e};return void 0===e?f(b,"",!0):h(b,"",!0)}},{}],314:[function(e,t,r){var n=e("./_getNative"),i=e("./_root"),s=n(i,"DataView");t.exports=s},{"./_getNative":418,"./_root":462}],315:[function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t-1}var i=e("./_baseIndexOf");t.exports=n},{"./_baseIndexOf":357}],332:[function(e,t,r){function n(e,t,r){for(var n=-1,i=null==e?0:e.length;++n=t?e:t)),e}t.exports=n},{}],345:[function(e,t,r){function n(e,t,r,P,B,O){var j,N=t&D,I=t&C,L=t&S;if(r&&(j=B?r(e,P,B,O):r(e)),void 0!==j)return j;if(!E(e))return e;var M=v(e);if(M){if(j=y(e),!N)return c(e,j)}else{var R=m(e),U=R==w||R==k;if(x(e))return l(e,N);if(R==F||R==_||U&&!B){if(j=I||U?{}:b(e),!N)return I?h(e,u(j,e)):p(e,o(j,e))}else{if(!T[R])return B?e:{};j=g(e,R,n,N)}}O||(O=new i);var V=O.get(e);if(V)return V;O.set(e,j);var q=L?I?d:f:I?keysIn:A,G=M?void 0:q(e);return s(G||e,function(i,s){G&&(s=i,i=e[s]),a(j,s,n(i,t,r,s,e,O))}),j}var i=e("./_Stack"),s=e("./_arrayEach"),a=e("./_assignValue"),o=e("./_baseAssign"),u=e("./_baseAssignIn"),l=e("./_cloneBuffer"),c=e("./_copyArray"),p=e("./_copySymbols"),h=e("./_copySymbolsIn"),f=e("./_getAllKeys"),d=e("./_getAllKeysIn"),m=e("./_getTag"),y=e("./_initCloneArray"),g=e("./_initCloneByTag"),b=e("./_initCloneObject"),v=e("./isArray"),x=e("./isBuffer"),E=e("./isObject"),A=e("./keys"),D=1,C=2,S=4,_="[object Arguments]",w="[object Function]",k="[object GeneratorFunction]",F="[object Object]",T={};T[_]=T["[object Array]"]=T["[object ArrayBuffer]"]=T["[object DataView]"]=T["[object Boolean]"]=T["[object Date]"]=T["[object Float32Array]"]=T["[object Float64Array]"]=T["[object Int8Array]"]=T["[object Int16Array]"]=T["[object Int32Array]"]=T["[object Map]"]=T["[object Number]"]=T[F]=T["[object RegExp]"]=T["[object Set]"]=T["[object String]"]=T["[object Symbol]"]=T["[object Uint8Array]"]=T["[object Uint8ClampedArray]"]=T["[object Uint16Array]"]=T["[object Uint32Array]"]=!0,T["[object Error]"]=T[w]=T["[object WeakMap]"]=!1,t.exports=n},{"./_Stack":322,"./_arrayEach":329,"./_assignValue":339,"./_baseAssign":341,"./_baseAssignIn":342,"./_cloneBuffer":389,"./_copyArray":398,"./_copySymbols":400,"./_copySymbolsIn":401,"./_getAllKeys":414,"./_getAllKeysIn":415,"./_getTag":423,"./_initCloneArray":431,"./_initCloneByTag":432,"./_initCloneObject":433,"./isArray":498,"./isBuffer":501,"./isObject":505,"./keys":512}],346:[function(e,t,r){var n=e("./isObject"),i=Object.create,s=function(){function e(){}return function(t){if(!n(t))return{};if(i)return i(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();t.exports=s},{"./isObject":505}],347:[function(e,t,r){var n=e("./_baseForOwn"),i=e("./_createBaseEach"),s=i(n);t.exports=s},{"./_baseForOwn":351,"./_createBaseEach":404}],348:[function(e,t,r){function n(e,t,r,n){for(var i=e.length,s=r+(n?1:-1);n?s--:++s0&&r(c)?t>1?n(c,t-1,r,a,o):i(o,c):a||(o[o.length]=c)}return o}var i=e("./_arrayPush"),s=e("./_isFlattenable");t.exports=n},{"./_arrayPush":335,"./_isFlattenable":434}],350:[function(e,t,r){var n=e("./_createBaseFor"),i=n();t.exports=i},{"./_createBaseFor":405}],351:[function(e,t,r){function n(e,t){return e&&i(e,t,s)}var i=e("./_baseFor"),s=e("./keys");t.exports=n},{"./_baseFor":350,"./keys":512}],352:[function(e,t,r){function n(e,t){t=i(t,e);for(var r=0,n=t.length;null!=e&&ri)return r;do{t%2&&(r+=e),(t=s(t/2))&&(e+=e)}while(t);return r}var i=9007199254740991,s=Math.floor;t.exports=n},{}],378:[function(e,t,r){function n(e,t){return a(s(e,t,i),e+"")}var i=e("./identity"),s=e("./_overRest"),a=e("./_setToString");t.exports=n},{"./_overRest":461,"./_setToString":466,"./identity":495}],379:[function(e,t,r){var n=e("./constant"),i=e("./_defineProperty"),s=e("./identity"),a=i?function(e,t){return i(e,"toString",{configurable:!0,enumerable:!1,value:n(t),writable:!0})}:s;t.exports=a},{"./_defineProperty":409,"./constant":483,"./identity":495}],380:[function(e,t,r){function n(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}t.exports=n},{}],381:[function(e,t,r){function n(e,t){for(var r=-1,n=Array(e);++r=c){var y=t?null:u(e);if(y)return l(y);f=!1,p=o,m=new i}else m=t?[]:d;e:for(;++nt||a&&o&&l&&!u&&!c||n&&o&&l||!r&&l||!s)return 1;if(!n&&!a&&!c&&e=u)return l;return l*("desc"==r[n]?-1:1)}}return e.index-t.index}var i=e("./_compareAscending");t.exports=n},{"./_compareAscending":396}],398:[function(e,t,r){function n(e,t){var r=-1,n=e.length +;for(t||(t=Array(n));++r1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(a=e.length>3&&"function"==typeof a?(i--,a):void 0,o&&s(r[0],r[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++n-1?o[u?t[l]:l]:void 0}}var i=e("./_baseIteratee"),s=e("./isArrayLike"),a=e("./keys");t.exports=n},{"./_baseIteratee":366,"./isArrayLike":499,"./keys":512}],407:[function(e,t,r){var n=e("./_Set"),i=e("./noop"),s=e("./_setToArray"),a=n&&1/s(new n([,-0]))[1]==1/0?function(e){return new n(e)}:i;t.exports=a},{"./_Set":320,"./_setToArray":465,"./noop":517}],408:[function(e,t,r){function n(e,t,r,n){return void 0===e||i(e,s[r])&&!a.call(n,r)?t:e}var i=e("./eq"),s=Object.prototype,a=s.hasOwnProperty;t.exports=n},{"./eq":485}],409:[function(e,t,r){var n=e("./_getNative"),i=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();t.exports=i},{"./_getNative":418}],410:[function(e,t,r){function n(e,t,r,n,l,c){var p=r&o,h=e.length,f=t.length;if(h!=f&&!(p&&f>h))return!1;var d=c.get(e);if(d&&c.get(t))return d==t;var m=-1,y=!0,g=r&u?new i:void 0;for(c.set(e,t),c.set(t,e);++m-1&&e%1==0&&e-1}var i=e("./_assocIndexOf");t.exports=n},{"./_assocIndexOf":340}],446:[function(e,t,r){function n(e,t){var r=this.__data__,n=i(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var i=e("./_assocIndexOf");t.exports=n},{"./_assocIndexOf":340}],447:[function(e,t,r){function n(){this.size=0,this.__data__={hash:new i,map:new(a||s),string:new i}}var i=e("./_Hash"),s=e("./_ListCache"),a=e("./_Map");t.exports=n},{"./_Hash":315,"./_ListCache":316,"./_Map":317}],448:[function(e,t,r){function n(e){var t=i(this,e).delete(e);return this.size-=t?1:0,t}var i=e("./_getMapData");t.exports=n},{"./_getMapData":416}],449:[function(e,t,r){function n(e){return i(this,e).get(e)}var i=e("./_getMapData");t.exports=n},{"./_getMapData":416}],450:[function(e,t,r){function n(e){return i(this,e).has(e)}var i=e("./_getMapData");t.exports=n},{"./_getMapData":416}],451:[function(e,t,r){function n(e,t){var r=i(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var i=e("./_getMapData");t.exports=n},{"./_getMapData":416}],452:[function(e,t,r){function n(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}t.exports=n},{}],453:[function(e,t,r){function n(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}}t.exports=n},{}],454:[function(e,t,r){function n(e){var t=i(e,function(e){return r.size===s&&r.clear(),e}),r=t.cache;return t}var i=e("./memoize"),s=500;t.exports=n},{"./memoize":515}],455:[function(e,t,r){var n=e("./_getNative"),i=n(Object,"create");t.exports=i},{"./_getNative":418}],456:[function(e,t,r){var n=e("./_overArg"),i=n(Object.keys,Object);t.exports=i},{"./_overArg":460}],457:[function(e,t,r){function n(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}t.exports=n},{}],458:[function(e,t,r){var n=e("./_freeGlobal"),i="object"==typeof r&&r&&!r.nodeType&&r,s=i&&"object"==typeof t&&t&&!t.nodeType&&t,a=s&&s.exports===i,o=a&&n.process,u=function(){try{return o&&o.binding&&o.binding("util")}catch(e){}}();t.exports=u},{"./_freeGlobal":413}],459:[function(e,t,r){function n(e){return s.call(e)}var i=Object.prototype,s=i.toString;t.exports=n},{}],460:[function(e,t,r){function n(e,t){return function(r){return e(t(r))}}t.exports=n},{}],461:[function(e,t,r){function n(e,t,r){return t=s(void 0===t?e.length-1:t,0),function(){for(var n=arguments,a=-1,o=s(n.length-t,0),u=Array(o);++a0){if(++t>=i)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var i=800,s=16,a=Date.now;t.exports=n},{}],468:[function(e,t,r){function n(){this.__data__=new i,this.size=0}var i=e("./_ListCache");t.exports=n},{"./_ListCache":316}],469:[function(e,t,r){function n(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}t.exports=n},{}],470:[function(e,t,r){function n(e){return this.__data__.get(e)}t.exports=n},{}],471:[function(e,t,r){function n(e){return this.__data__.has(e)}t.exports=n},{}],472:[function(e,t,r){function n(e,t){var r=this.__data__;if(r instanceof i){var n=r.__data__;if(!s||n.length-1:!!c&&i(e,t,r)>-1}var i=e("./_baseIndexOf"),s=e("./isArrayLike"),a=e("./isString"),o=e("./toInteger"),u=e("./values"),l=Math.max;t.exports=n},{"./_baseIndexOf":357,"./isArrayLike":499,"./isString":509,"./toInteger":525,"./values":530}],497:[function(e,t,r){var n=e("./_baseIsArguments"),i=e("./isObjectLike"),s=Object.prototype,a=s.hasOwnProperty,o=s.propertyIsEnumerable,u=n(function(){return arguments}())?n:function(e){return i(e)&&a.call(e,"callee")&&!o.call(e,"callee")};t.exports=u},{"./_baseIsArguments":358,"./isObjectLike":506}],498:[function(e,t,r){var n=Array.isArray;t.exports=n},{}],499:[function(e,t,r){function n(e){return null!=e&&s(e.length)&&!i(e)}var i=e("./isFunction"),s=e("./isLength");t.exports=n},{"./isFunction":502,"./isLength":504}],500:[function(e,t,r){function n(e){return s(e)&&i(e)}var i=e("./isArrayLike"),s=e("./isObjectLike");t.exports=n},{"./isArrayLike":499,"./isObjectLike":506}],501:[function(e,t,r){var n=e("./_root"),i=e("./stubFalse"),s="object"==typeof r&&r&&!r.nodeType&&r,a=s&&"object"==typeof t&&t&&!t.nodeType&&t,o=a&&a.exports===s,u=o?n.Buffer:void 0,l=u?u.isBuffer:void 0,c=l||i;t.exports=c},{"./_root":462,"./stubFalse":523}],502:[function(e,t,r){function n(e){if(!s(e))return!1;var t=i(e);return t==o||t==u||t==a||t==l}var i=e("./_baseGetTag"),s=e("./isObject"),a="[object AsyncFunction]",o="[object Function]",u="[object GeneratorFunction]",l="[object Proxy]";t.exports=n},{"./_baseGetTag":354,"./isObject":505}],503:[function(e,t,r){function n(e){return"number"==typeof e&&e==i(e)}var i=e("./toInteger");t.exports=n},{"./toInteger":525}],504:[function(e,t,r){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}var i=9007199254740991;t.exports=n},{}],505:[function(e,t,r){function n(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}t.exports=n},{}],506:[function(e,t,r){function n(e){return null!=e&&"object"==typeof e}t.exports=n},{}],507:[function(e,t,r){function n(e){if(!a(e)||i(e)!=o)return!1;var t=s(e);if(null===t)return!0;var r=p.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&c.call(r)==h}var i=e("./_baseGetTag"),s=e("./_getPrototype"),a=e("./isObjectLike"),o="[object Object]",u=Function.prototype,l=Object.prototype,c=u.toString,p=l.hasOwnProperty,h=c.call(Object);t.exports=n},{"./_baseGetTag":354,"./_getPrototype":419,"./isObjectLike":506}],508:[function(e,t,r){var n=e("./_baseIsRegExp"),i=e("./_baseUnary"),s=e("./_nodeUtil"),a=s&&s.isRegExp,o=a?i(a):n;t.exports=o},{"./_baseIsRegExp":364,"./_baseUnary":383,"./_nodeUtil":458}],509:[function(e,t,r){function n(e){return"string"==typeof e||!s(e)&&a(e)&&i(e)==o}var i=e("./_baseGetTag"),s=e("./isArray"),a=e("./isObjectLike"),o="[object String]";t.exports=n},{"./_baseGetTag":354,"./isArray":498,"./isObjectLike":506}],510:[function(e,t,r){function n(e){return"symbol"==typeof e||s(e)&&i(e)==a}var i=e("./_baseGetTag"),s=e("./isObjectLike"),a="[object Symbol]";t.exports=n},{"./_baseGetTag":354,"./isObjectLike":506}],511:[function(e,t,r){var n=e("./_baseIsTypedArray"),i=e("./_baseUnary"),s=e("./_nodeUtil"),a=s&&s.isTypedArray,o=a?i(a):n;t.exports=o},{"./_baseIsTypedArray":365,"./_baseUnary":383,"./_nodeUtil":458}],512:[function(e,t,r){function n(e){return a(e)?i(e):s(e)}var i=e("./_arrayLikeKeys"),s=e("./_baseKeys"),a=e("./isArrayLike");t.exports=n},{"./_arrayLikeKeys":333,"./_baseKeys":367,"./isArrayLike":499}],513:[function(e,t,r){function n(e){return a(e)?i(e,!0):s(e)}var i=e("./_arrayLikeKeys"),s=e("./_baseKeysIn"),a=e("./isArrayLike");t.exports=n},{"./_arrayLikeKeys":333,"./_baseKeysIn":368,"./isArrayLike":499}],514:[function(e,t,r){function n(e,t){return(o(e)?i:a)(e,s(t,3))}var i=e("./_arrayMap"),s=e("./_baseIteratee"),a=e("./_baseMap"),o=e("./isArray");t.exports=n},{"./_arrayMap":334,"./_baseIteratee":366,"./_baseMap":369,"./isArray":498}],515:[function(e,t,r){function n(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(s);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],s=r.cache;if(s.has(i))return s.get(i);var a=e.apply(this,n);return r.cache=s.set(i,a)||s,a};return r.cache=new(n.Cache||i),r}var i=e("./_MapCache"),s="Expected a function";n.Cache=i,t.exports=n},{"./_MapCache":318}],516:[function(e,t,r){var n=e("./_baseMerge"),i=e("./_createAssigner"),s=i(function(e,t,r,i){n(e,t,r,i)});t.exports=s},{"./_baseMerge":372,"./_createAssigner":403}],517:[function(e,t,r){function n(){}t.exports=n},{}],518:[function(e,t,r){function n(e){return a(e)?i(o(e)):s(e)}var i=e("./_baseProperty"),s=e("./_basePropertyDeep"),a=e("./_isKey"),o=e("./_toKey");t.exports=n},{"./_baseProperty":375,"./_basePropertyDeep":376,"./_isKey":437,"./_toKey":475}],519:[function(e,t,r){function n(e,t,r){return t=(r?s(e,t,r):void 0===t)?1:a(t),i(o(e),t)}var i=e("./_baseRepeat"),s=e("./_isIterateeCall"),a=e("./toInteger"),o=e("./toString");t.exports=n},{"./_baseRepeat":377,"./_isIterateeCall":436,"./toInteger":525,"./toString":528}],520:[function(e,t,r){var n=e("./_baseFlatten"),i=e("./_baseOrderBy"),s=e("./_baseRest"),a=e("./_isIterateeCall"),o=s(function(e,t){if(null==e)return[];var r=t.length;return r>1&&a(e,t[0],t[1])?t=[]:r>2&&a(t[0],t[1],t[2])&&(t=[t[0]]),i(e,n(t,1),[])});t.exports=o},{"./_baseFlatten":349,"./_baseOrderBy":374,"./_baseRest":378,"./_isIterateeCall":436}],521:[function(e,t,r){function n(e,t,r){return e=o(e),r=null==r?0:i(a(r),0,e.length),t=s(t),e.slice(r,r+t.length)==t}var i=e("./_baseClamp"),s=e("./_baseToString"),a=e("./toInteger"),o=e("./toString");t.exports=n},{"./_baseClamp":344,"./_baseToString":382,"./toInteger":525,"./toString":528}],522:[function(e,t,r){function n(){return[]}t.exports=n},{}],523:[function(e,t,r){function n(){return!1}t.exports=n},{}],524:[function(e,t,r){function n(e){if(!e)return 0===e?e:0;if((e=i(e))===s||e===-s){return(e<0?-1:1)*a}return e===e?e:0}var i=e("./toNumber"),s=1/0,a=1.7976931348623157e308;t.exports=n},{"./toNumber":526}],525:[function(e,t,r){function n(e){var t=i(e),r=t%1;return t===t?r?t-r:t:0}var i=e("./toFinite");t.exports=n},{"./toFinite":524}],526:[function(e,t,r){function n(e){if("number"==typeof e)return e;if(s(e))return a;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(o,"");var r=l.test(e);return r||c.test(e)?p(e.slice(2),r?2:8):u.test(e)?a:+e}var i=e("./isObject"),s=e("./isSymbol"),a=NaN,o=/^\s+|\s+$/g,u=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,c=/^0o[0-7]+$/i,p=parseInt;t.exports=n},{"./isObject":505,"./isSymbol":510}],527:[function(e,t,r){function n(e){return i(e,s(e))}var i=e("./_copyObject"),s=e("./keysIn");t.exports=n},{"./_copyObject":399,"./keysIn":513}],528:[function(e,t,r){function n(e){return null==e?"":i(e)}var i=e("./_baseToString");t.exports=n},{"./_baseToString":382}],529:[function(e,t,r){function n(e){return e&&e.length?i(e):[]}var i=e("./_baseUniq");t.exports=n},{"./_baseUniq":384}],530:[function(e,t,r){function n(e){return null==e?[]:i(e,s(e))}var i=e("./_baseValues"),s=e("./keys");t.exports=n},{"./_baseValues":385,"./keys":512}],531:[function(e,t,r){function n(e,t){return t=t||{},function(r,n,i){return s(r,e,t)}}function i(e,t){e=e||{},t=t||{};var r={};return Object.keys(t).forEach(function(e){r[e]=t[e]}),Object.keys(e).forEach(function(t){r[t]=e[t]}),r}function s(e,t,r){if("string"!=typeof t)throw new TypeError("glob pattern string required");return r||(r={}),!(!r.nocomment&&"#"===t.charAt(0))&&(""===t.trim()?""===e:new a(t,r).match(e))}function a(e,t){if(!(this instanceof a))return new a(e,t);if("string"!=typeof e)throw new TypeError("glob pattern string required");t||(t={}),e=e.trim(),"/"!==m.sep&&(e=e.split(m.sep).join("/")),this.options=t,this.set=[],this.pattern=e,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.make()}function o(){if(!this._made){var e=this.pattern,t=this.options;if(!t.nocomment&&"#"===e.charAt(0))return void(this.comment=!0);if(!e)return void(this.empty=!0);this.parseNegate();var r=this.globSet=this.braceExpand();t.debug&&(this.debug=console.error),this.debug(this.pattern,r),r=this.globParts=r.map(function(e){return e.split(C)}),this.debug(this.pattern,r),r=r.map(function(e,t,r){return e.map(this.parse,this)},this),this.debug(this.pattern,r),r=r.filter(function(e){return-1===e.indexOf(!1)}),this.debug(this.pattern,r),this.set=r}}function u(){var e=this.pattern,t=!1,r=this.options,n=0;if(!r.nonegate){for(var i=0,s=e.length;i65536)throw new TypeError("pattern is too long");var n=this.options;if(!n.noglobstar&&"**"===e)return y;if(""===e)return"";for(var i,s,a="",o=!!n.nocase,u=!1,l=[],c=[],p=!1,h=-1,d=-1,m="."===e.charAt(0)?"":n.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",g=this,E=0,A=e.length;E-1;P--){ +var B=c[P],O=a.slice(0,B.reStart),j=a.slice(B.reStart,B.reEnd-8),N=a.slice(B.reEnd-8,B.reEnd),I=a.slice(B.reEnd);N+=I;var L=O.split("(").length-1,M=I;for(E=0;E=0&&!(i=e[s]);s--);for(s=0;s>> no match, partial?",e,c,t,p),c!==a))}var f;if("string"==typeof u?(f=n.nocase?l.toLowerCase()===u.toLowerCase():l===u,this.debug("string match",u,l,f)):(f=l.match(u),this.debug("pattern match",u,l,f)),!f)return!1}if(i===a&&s===o)return!0;if(i===a)return r;if(s===o){return i===a-1&&""===e[i]}throw new Error("wtf?")}},{"brace-expansion":180,path:535}],532:[function(e,t,r){function n(e){if(e=String(e),!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*p;case"days":case"day":case"d":return r*c;case"hours":case"hour":case"hrs":case"hr":case"h":return r*l;case"minutes":case"minute":case"mins":case"min":case"m":return r*u;case"seconds":case"second":case"secs":case"sec":case"s":return r*o;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function i(e){return e>=c?Math.round(e/c)+"d":e>=l?Math.round(e/l)+"h":e>=u?Math.round(e/u)+"m":e>=o?Math.round(e/o)+"s":e+"ms"}function s(e){return a(e,c,"day")||a(e,l,"hour")||a(e,u,"minute")||a(e,o,"second")||e+" ms"}function a(e,t,r){if(!(e0)return n(e);if("number"===r&&!1===isNaN(e))return t.long?s(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],533:[function(e,t,r){"use strict";t.exports=Number.isNaN||function(e){return e!==e}},{}],534:[function(e,t,r){r.endianness=function(){return"LE"},r.hostname=function(){return"undefined"!=typeof location?location.hostname:""},r.loadavg=function(){return[]},r.uptime=function(){return 0},r.freemem=function(){return Number.MAX_VALUE},r.totalmem=function(){return Number.MAX_VALUE},r.cpus=function(){return[]},r.type=function(){return"Browser"},r.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},r.networkInterfaces=r.getNetworkInterfaces=function(){return{}},r.arch=function(){return"javascript"},r.platform=function(){return"browser"},r.tmpdir=r.tmpDir=function(){return"/tmp"},r.EOL="\n"},{}],535:[function(e,t,r){(function(e){function t(e,t){for(var r=0,n=e.length-1;n>=0;n--){var i=e[n];"."===i?e.splice(n,1):".."===i?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n=-1&&!i;s--){var a=s>=0?arguments[s]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(r=a+"/"+r,i="/"===a.charAt(0))}return r=t(n(r.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(e){var i=r.isAbsolute(e),s="/"===a(e,-1);return e=t(n(e.split("/"),function(e){return!!e}),!i).join("/"),e||i||(e="."),e&&s&&(e+="/"),(i?"/":"")+e},r.isAbsolute=function(e){return"/"===e.charAt(0)},r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(n(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},r.relative=function(e,t){function n(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=r.resolve(e).substr(1),t=r.resolve(t).substr(1);for(var i=n(e.split("/")),s=n(t.split("/")),a=Math.min(i.length,s.length),o=a,u=0;un&&(t[n]=t[r]),++n);return t.length=n,t},r.makeAccessor=l},{}],538:[function(e,t,r){(function(e){"use strict";function r(t,r,n,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,a,o=arguments.length;switch(o){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,r)});case 3:return e.nextTick(function(){t.call(null,r,n)});case 4:return e.nextTick(function(){t.call(null,r,n,i)});default:for(s=new Array(o-1),a=0;a1)for(var r=1;r0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var u=new Error("stream.unshift() after end event");e.emit("error",u)}else{var l;!t.decoder||i||n||(r=t.decoder.write(r),l=!t.objectMode&&0===r.length),i||(t.reading=!1),l||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&h(e))),d(e,t)}else i||(t.reading=!1);return o(t)}function o(e){return!e.ended&&(e.needReadable||e.length=V?e=V:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function l(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=u(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function c(e,t){var r=null;return j.isBuffer(t)||"string"==typeof t||null===t||void 0===t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk")),r}function p(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,h(e)}}function h(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(M("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?T(f,e):f(e))}function f(e){M("emit readable"),e.emit("readable"),x(e)}function d(e,t){t.readingMore||(t.readingMore=!0,T(m,e,t))}function m(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=A(e,t.buffer,t.decoder),r}function A(e,t,r){var n;return es.length?s.length:e;if(a===s.length?i+=s:i+=s.slice(0,e),0===(e-=a)){a===s.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=s.slice(a));break}++n}return t.length-=n,i}function C(e,t){var r=N.allocUnsafe(e),n=t.head,i=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var s=n.data,a=e>s.length?s.length:e;if(s.copy(r,r.length-e,0,a),0===(e-=a)){a===s.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=s.slice(a));break}++i}return t.length-=i,r}function S(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,T(_,t,e))}function _(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function w(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return M("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?S(this):h(this),null;if(0===(e=l(e,t))&&t.ended)return 0===t.length&&S(this),null;var n=t.needReadable;M("need readable",n),(0===t.length||t.length-e0?E(e,t):null,null===i?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&S(this)),null!==i&&this.emit("data",i),i},s.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},s.prototype.pipe=function(e,t){function i(e){M("onunpipe"),e===h&&a()}function s(){M("onend"),e.end()}function a(){M("cleanup"),e.removeListener("close",l),e.removeListener("finish",c),e.removeListener("drain",g),e.removeListener("error",u),e.removeListener("unpipe",i),h.removeListener("end",s),h.removeListener("end",a),h.removeListener("data",o),b=!0,!f.awaitDrain||e._writableState&&!e._writableState.needDrain||g()}function o(t){M("ondata"),v=!1,!1!==e.write(t)||v||((1===f.pipesCount&&f.pipes===e||f.pipesCount>1&&-1!==k(f.pipes,e))&&!b&&(M("false write response, pause",h._readableState.awaitDrain),h._readableState.awaitDrain++,v=!0),h.pause())}function u(t){M("onerror",t),p(),e.removeListener("error",u),0===O(e,"error")&&e.emit("error",t)}function l(){e.removeListener("finish",c),p()}function c(){M("onfinish"),e.removeListener("close",l),p()}function p(){M("unpipe"),h.unpipe(e)}var h=this,f=this._readableState;switch(f.pipesCount){case 0:f.pipes=e;break;case 1:f.pipes=[f.pipes,e];break;default:f.pipes.push(e)}f.pipesCount+=1,M("pipe count=%d opts=%j",f.pipesCount,t);var d=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr,m=d?s:a;f.endEmitted?T(m):h.once("end",m),e.on("unpipe",i);var g=y(h);e.on("drain",g);var b=!1,v=!1;return h.on("data",o),n(e,"error",u),e.once("close",l),e.once("finish",c),e.emit("pipe",h),f.flowing||(M("pipe resume"),h.resume()),e},s.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this),this);if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:C;a.WritableState=s;var _=e("core-util-is");_.inherits=e("inherits");var w,k={deprecate:e("util-deprecate")};!function(){try{w=e("stream")}catch(e){}finally{w||(w=e("events").EventEmitter)}}();var F=e("buffer").Buffer,T=e("buffer-shims");_.inherits(a,w),s.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(s.prototype,"buffer",{get:k.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(e){}}();var P;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(P=Function.prototype[Symbol.hasInstance],Object.defineProperty(a,Symbol.hasInstance,{value:function(e){return!!P.call(this,e)||e&&e._writableState instanceof s}})):P=function(e){return e instanceof this},a.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},a.prototype.write=function(e,t,r){var i=this._writableState,s=!1,a=F.isBuffer(e);return"function"==typeof t&&(r=t,t=null),a?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=n),i.ended?o(this,r):(a||u(this,i,e,r))&&(i.pendingcb++,s=c(this,i,a,e,t,r)),s},a.prototype.cork=function(){this._writableState.corked++},a.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||g(this,e))},a.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},a.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},a.prototype._writev=null,a.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||E(this,n,r)}}).call(this,e("_process"))},{"./_stream_duplex":541,_process:539,buffer:184,"buffer-shims":183,"core-util-is":294,events:301,inherits:306,"process-nextick-args":538,"util-deprecate":598}],546:[function(e,t,r){"use strict";function n(){this.head=null,this.tail=null,this.length=0}var i=(e("buffer").Buffer,e("buffer-shims"));t.exports=n,n.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},n.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},n.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},n.prototype.clear=function(){this.head=this.tail=null,this.length=0},n.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},n.prototype.concat=function(e){if(0===this.length)return i.alloc(0) +;if(1===this.length)return this.head.data;for(var t=i.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t}},{buffer:184,"buffer-shims":183}],547:[function(e,t,r){t.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":542}],548:[function(e,t,r){(function(n){var i=function(){try{return e("stream")}catch(e){}}();r=t.exports=e("./lib/_stream_readable.js"),r.Stream=i||r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js"),!n.browser&&"disable"===n.env.READABLE_STREAM&&i&&(t.exports=i)}).call(this,e("_process"))},{"./lib/_stream_duplex.js":541,"./lib/_stream_passthrough.js":542,"./lib/_stream_readable.js":543,"./lib/_stream_transform.js":544,"./lib/_stream_writable.js":545,_process:539}],549:[function(e,t,r){t.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":544}],550:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":545}],551:[function(e,t,r){function n(e,t,r){if(e){if(x.fixFaultyLocations(e,t),r){if(d.Node.check(e)&&d.SourceLocation.check(e.loc)){for(var i=r.length-1;i>=0&&!(E(r[i].loc.end,e.loc.start)<=0);--i);return void r.splice(i+1,0,e)}}else if(e[A])return e[A];var s;if(m.check(e))s=Object.keys(e);else{if(!y.check(e))return;s=f.getFieldNames(e)}r||Object.defineProperty(e,A,{value:r=[],enumerable:!1});for(var i=0,a=s.length;i>1,l=s[u];if(E(l.loc.start,t.loc.start)<=0&&E(t.loc.end,l.loc.end)<=0)return void i(t.enclosingNode=l,t,r);if(E(l.loc.end,t.loc.start)<=0){var c=l;a=u+1}else{if(!(E(t.loc.end,l.loc.start)<=0))throw new Error("Comment location overlaps with node location");var p=l;o=u}}c&&(t.precedingNode=c),p&&(t.followingNode=p)}function s(e,t){var r=e.length;if(0!==r){for(var n=e[0].precedingNode,i=e[0].followingNode,s=i.loc.start,a=r;a>0;--a){var u=e[a-1];h.strictEqual(u.precedingNode,n),h.strictEqual(u.followingNode,i);var c=t.sliceString(u.loc.end,s);if(/\S/.test(c))break;s=u.loc.start}for(;a<=r&&(u=e[a])&&("Line"===u.type||"CommentLine"===u.type)&&u.loc.start.column>i.loc.start.column;)++a;e.forEach(function(e,t){t0){var d=n[f-1];h.strictEqual(d.precedingNode===e.precedingNode,d.followingNode===e.followingNode),d.followingNode!==e.followingNode&&s(n,r)}n.push(e)}else if(a)s(n,r),l(a,e);else if(p)s(n,r),o(p,e);else{if(!c)throw new Error("AST contains no nodes at all?");s(n,r),u(c,e)}}),s(n,r),e.forEach(function(e){delete e.precedingNode,delete e.enclosingNode,delete e.followingNode})}},r.printComments=function(e,t){var r=e.getValue(),n=t(e),i=d.Node.check(r)&&f.getFieldValue(r,"comments");if(!i||0===i.length)return n;var s=[],a=[n];return e.each(function(e){var n=e.getValue(),i=f.getFieldValue(n,"leading"),o=f.getFieldValue(n,"trailing");i||o&&!d.Statement.check(r)&&"Block"!==n.type&&"CommentBlock"!==n.type?s.push(c(e,t)):o&&a.push(p(e,t))},"comments"),s.push.apply(s,a),v(s)}},{"./lines":553,"./types":559,"./util":560,assert:3,private:537}],552:[function(e,t,r){function n(e){o.ok(this instanceof n),this.stack=[e]}function i(e,t){for(var r=e.stack,n=r.length-1;n>=0;n-=2){var i=r[n];if(l.Node.check(i)&&--t<0)return i}return null}function s(e){return l.BinaryExpression.check(e)||l.LogicalExpression.check(e)}function a(e){return!!l.CallExpression.check(e)||(c.check(e)?e.some(a):!!l.Node.check(e)&&u.someField(e,function(e,t){return a(t)}))}var o=e("assert"),u=e("./types"),l=u.namedTypes,c=(l.Node,u.builtInTypes.array),p=u.builtInTypes.number,h=n.prototype;t.exports=n,n.from=function(e){if(e instanceof n)return e.copy();if(e instanceof u.NodePath){for(var t,r=Object.create(n.prototype),i=[e.value];t=e.parentPath;e=t)i.push(e.name,t.value);return r.stack=i.reverse(),r}return new n(e)},h.copy=function(){var e=Object.create(n.prototype);return e.stack=this.stack.slice(0),e},h.getName=function(){var e=this.stack,t=e.length;return t>1?e[t-2]:null},h.getValue=function(){var e=this.stack;return e[e.length-1]},h.getNode=function(e){return i(this,~~e)},h.getParentNode=function(e){return i(this,1+~~e)},h.getRootValue=function(){var e=this.stack;return e.length%2==0?e[1]:e[0]},h.call=function(e){for(var t=this.stack,r=t.length,n=t[r-1],i=arguments.length,s=1;sh)return!0;if(u===h&&"right"===r)return o.strictEqual(t.right,n),!0;default:return!1}case"SequenceExpression":switch(t.type){case"ReturnStatement":case"ForStatement":return!1;case"ExpressionStatement":return"expression"!==r;default:return!0}case"YieldExpression":switch(t.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return!0;default:return!1}case"IntersectionTypeAnnotation":case"UnionTypeAnnotation":return"NullableTypeAnnotation"===t.type;case"Literal":return"MemberExpression"===t.type&&p.check(n.value)&&"object"===r&&t.object===n;case"AssignmentExpression":case"ConditionalExpression":switch(t.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return!0;case"CallExpression":return"callee"===r&&t.callee===n;case"ConditionalExpression":return"test"===r&&t.test===n;case"MemberExpression":return"object"===r&&t.object===n;default:return!1}case"ArrowFunctionExpression":return!(!l.CallExpression.check(t)||"callee"!==r)||(!(!l.MemberExpression.check(t)||"object"!==r)||s(t));case"ObjectExpression":if("ArrowFunctionExpression"===t.type&&"body"===r)return!0;default:if("NewExpression"===t.type&&"callee"===r&&t.callee===n)return a(n)}return!(!0===e||this.canBeFirstInStatement()||!this.firstInStatement())};var f={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%","**"]].forEach(function(e,t){e.forEach(function(e){f[e]=t})}),h.canBeFirstInStatement=function(){var e=this.getNode();return!l.FunctionExpression.check(e)&&!l.ObjectExpression.check(e)},h.firstInStatement=function(){for(var e,t,r,n,i=this.stack,a=i.length-1;a>=0;a-=2)if(l.Node.check(i[a])&&(r=e,n=t,e=i[a-1],t=i[a]),t&&n){if(l.BlockStatement.check(t)&&"body"===e&&0===r)return o.strictEqual(t.body[0],n),!0;if(l.ExpressionStatement.check(t)&&"expression"===r)return o.strictEqual(t.expression,n),!0;if(l.SequenceExpression.check(t)&&"expressions"===e&&0===r)o.strictEqual(t.expressions[0],n);else if(l.CallExpression.check(t)&&"callee"===r)o.strictEqual(t.callee,n);else if(l.MemberExpression.check(t)&&"object"===r)o.strictEqual(t.object,n);else if(l.ConditionalExpression.check(t)&&"test"===r)o.strictEqual(t.test,n);else if(s(t)&&"left"===r)o.strictEqual(t.left,n);else{if(!l.UnaryExpression.check(t)||t.prefix||"argument"!==r)return!1;o.strictEqual(t.argument,n)}}return!0}},{"./types":559,assert:3}],553:[function(e,t,r){function n(e){return e[f]}function i(e,t){c.ok(this instanceof i),c.ok(e.length>0),t?m.assert(t):t=null,Object.defineProperty(this,f,{value:{infos:e,mappings:[],name:t,cachedSourceMap:null}}),t&&n(this).mappings.push(new g(this,{start:this.firstPos(),end:this.lastPos()}))}function s(e){return{line:e.line,indent:e.indent,locked:e.locked,sliceStart:e.sliceStart,sliceEnd:e.sliceEnd}}function a(e,t){for(var r=0,n=e.length,i=0;i0);var s=Math.ceil(r/t)*t;s===r?r+=t:r=s;break;case 11:case 12:case 13:case 65279:break;case 32:default:r+=1}return r}function o(e,t){if(e instanceof i)return e;e+="";var r=t&&t.tabWidth,n=e.indexOf("\t")<0,s=!(!t||!t.locked),o=!t&&n&&e.length<=E;if(c.ok(r||n,"No tab width specified but encountered tabs in string\n"+e),o&&x.call(v,e))return v[e];var u=new i(e.split(D).map(function(e){var t=A.exec(e)[0];return{line:e,indent:a(t,r),locked:s,sliceStart:t.length,sliceEnd:e.length}}),h(t).sourceFileName);return o&&(v[e]=u),u}function u(e){return!/\S/.test(e)}function l(e,t,r){var n=e.sliceStart,i=e.sliceEnd,s=Math.max(e.indent,0),a=s+i-n;return void 0===r&&(r=a),t=Math.max(t,0),r=Math.min(r,a),r=Math.max(r,t),r=0),c.ok(n<=i),c.strictEqual(a,s+i-n),e.indent===s&&e.sliceStart===n&&e.sliceEnd===i?e:{line:e.line,indent:s,locked:!1,sliceStart:n,sliceEnd:i}}var c=e("assert"),p=e("source-map"),h=e("./options").normalize,f=e("private").makeUniqueKey(),d=e("./types"),m=d.builtInTypes.string,y=e("./util").comparePos,g=e("./mapping");r.Lines=i;var b=i.prototype;Object.defineProperties(b,{length:{get:function(){return n(this).infos.length}},name:{get:function(){return n(this).name}}});var v={},x=v.hasOwnProperty,E=10;r.countSpaces=a;var A=/^\s*/,D=/\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/;r.fromString=o,b.toString=function(e){return this.sliceString(this.firstPos(),this.lastPos(),e)},b.getSourceMap=function(e,t){function r(r){return r=r||{},m.assert(e),r.file=e,t&&(m.assert(t),r.sourceRoot=t),r}if(!e)return null;var i=this,s=n(i);if(s.cachedSourceMap)return r(s.cachedSourceMap.toJSON());var a=new p.SourceMapGenerator(r()),o={};return s.mappings.forEach(function(e){for(var t=e.sourceLines.skipSpaces(e.sourceLoc.start)||e.sourceLines.lastPos(),r=i.skipSpaces(e.targetLoc.start)||i.lastPos();y(t,e.sourceLoc.end)<0&&y(r,e.targetLoc.end)<0;){var n=e.sourceLines.charAt(t),s=i.charAt(r);c.strictEqual(n,s);var u=e.sourceLines.name;if(a.addMapping({source:u,original:{line:t.line,column:t.column},generated:{line:r.line,column:r.column}}),!x.call(o,u)){var l=e.sourceLines.toString();a.setSourceContent(u,l),o[u]=l}i.nextPos(r,!0),e.sourceLines.nextPos(t,!0)}}),s.cachedSourceMap=a,a.toJSON()},b.bootstrapCharAt=function(e){c.strictEqual(typeof e,"object"),c.strictEqual(typeof e.line,"number"),c.strictEqual(typeof e.column,"number");var t=e.line,r=e.column,n=this.toString().split(D),i=n[t-1];return void 0===i?"":r===i.length&&t=i.length?"":i.charAt(r)},b.charAt=function(e){c.strictEqual(typeof e,"object"),c.strictEqual(typeof e.line,"number"),c.strictEqual(typeof e.column,"number");var t=e.line,r=e.column,i=n(this),s=i.infos,a=s[t-1],o=r;if(void 0===a||o<0)return"";var u=this.getIndentAt(t);return o=a.sliceEnd?"":a.line.charAt(o))},b.stripMargin=function(e,t){if(0===e)return this;if(c.ok(e>0,"negative margin: "+e),t&&1===this.length)return this;var r=n(this),a=new i(r.infos.map(function(r,n){return r.line&&(n>0||!t)&&(r=s(r),r.indent=Math.max(0,r.indent-e)),r}));if(r.mappings.length>0){var o=n(a).mappings;c.strictEqual(o.length,0),r.mappings.forEach(function(r){o.push(r.indent(e,t,!0))})}return a},b.indent=function(e){if(0===e)return this;var t=n(this),r=new i(t.infos.map(function(t){return t.line&&!t.locked&&(t=s(t),t.indent+=e),t}));if(t.mappings.length>0){var a=n(r).mappings;c.strictEqual(a.length,0),t.mappings.forEach(function(t){a.push(t.indent(e))})}return r},b.indentTail=function(e){if(0===e)return this;if(this.length<2)return this;var t=n(this),r=new i(t.infos.map(function(t,r){return r>0&&t.line&&!t.locked&&(t=s(t),t.indent+=e),t}));if(t.mappings.length>0){var a=n(r).mappings;c.strictEqual(a.length,0),t.mappings.forEach(function(t){a.push(t.indent(e,!0))})}return r},b.lockIndentTail=function(){return this.length<2?this:new i(n(this).infos.map(function(e,t){return e=s(e),e.locked=t>0,e}))},b.getIndentAt=function(e){c.ok(e>=1,"no line "+e+" (line numbers start from 1)");var t=n(this),r=t.infos[e-1];return Math.max(r.indent,0)},b.guessTabWidth=function(){var e=n(this);if(x.call(e,"cachedTabWidth"))return e.cachedTabWidth;for(var t=[],r=0,i=1,s=this.length;i<=s;++i){var a=e.infos[i-1];if(!u(a.line.slice(a.sliceStart,a.sliceEnd))){var o=Math.abs(a.indent-r);t[o]=1+~~t[o],r=a.indent}}for(var l=-1,c=2,p=1;pl&&(l=t[p],c=p);return e.cachedTabWidth=c},b.startsWithComment=function(){var e=n(this);if(0===e.infos.length)return!1;var t=e.infos[0],r=t.sliceStart,i=t.sliceEnd,s=t.line.slice(r,i).trim();return 0===s.length||"//"===s.slice(0,2)||"/*"===s.slice(0,2)},b.isOnlyWhitespace=function(){return u(this.toString())},b.isPrecededOnlyByWhitespace=function(e){var t=n(this),r=t.infos[e.line-1],i=Math.max(r.indent,0),s=e.column-i;if(s<=0)return!0;var a=r.sliceStart,o=Math.min(a+s,r.sliceEnd);return u(r.line.slice(a,o))},b.getLineLength=function(e){var t=n(this),r=t.infos[e-1];return this.getIndentAt(e)+r.sliceEnd-r.sliceStart},b.nextPos=function(e,t){var r=Math.max(e.line,0);return Math.max(e.column,0)0){var o=n(a).mappings;c.strictEqual(o.length,0),r.mappings.forEach(function(r){var n=r.slice(this,e,t);n&&o.push(n)},this)}return a},b.bootstrapSliceString=function(e,t,r){return this.slice(e,t).toString(r)},b.sliceString=function(e,t,r){if(!t){if(!e)return this;t=this.lastPos()}r=h(r);for(var i=n(this).infos,s=[],o=r.tabWidth,c=e.line;c<=t.line;++c){var p=i[c-1];c===e.line?p=c===t.line?l(p,e.column,t.column):l(p,e.column):c===t.line&&(p=l(p,0,t.column));var f=Math.max(p.indent,0),d=p.line.slice(0,p.sliceStart);if(r.reuseWhitespace&&u(d)&&a(d,r.tabWidth)===f)s.push(p.line.slice(0,p.sliceEnd));else{var m=0,y=f;r.useTabs&&(m=Math.floor(f/o),y-=m*o);var g="";m>0&&(g+=new Array(m+1).join("\t")),y>0&&(g+=new Array(y+1).join(" ")),g+=p.line.slice(p.sliceStart,p.sliceEnd),s.push(g)}}return s.join(r.lineTerminator)},b.isEmpty=function(){return this.length<2&&this.getLineLength(1)<1},b.join=function(e){function t(e){if(null!==e){if(a){var t=e.infos[0],r=new Array(t.indent+1).join(" "),n=c.length,i=Math.max(a.indent,0)+a.sliceEnd-a.sliceStart;a.line=a.line.slice(0,a.sliceEnd)+r+t.line.slice(t.sliceStart,t.sliceEnd),a.locked=a.locked||t.locked,a.sliceEnd=a.line.length,e.mappings.length>0&&e.mappings.forEach(function(e){p.push(e.add(n,i))})}else e.mappings.length>0&&p.push.apply(p,e.mappings);e.infos.forEach(function(e,t){(!a||t>0)&&(a=s(e),c.push(a))})}}function r(e,r){r>0&&t(l),t(e)}var a,u=this,l=n(u),c=[],p=[];if(e.map(function(e){var t=o(e);return t.isEmpty()?null:n(t)}).forEach(u.isEmpty()?t:r),c.length<1)return C;var h=new i(c);return n(h).mappings=p,h},r.concat=function(e){return C.join(e)},b.concat=function(e){var t=arguments,r=[this];return r.push.apply(r,t),c.strictEqual(r.length,t.length+1),C.join(r)};var C=o("")},{"./mapping":554,"./options":555,"./types":559,"./util":560,assert:3,private:537,"source-map":573}],554:[function(e,t,r){function n(e,t,r){o.ok(this instanceof n),o.ok(e instanceof h.Lines),c.assert(t),r?o.ok(l.check(r.start.line)&&l.check(r.start.column)&&l.check(r.end.line)&&l.check(r.end.column)):r=t,Object.defineProperties(this,{sourceLines:{value:e},sourceLoc:{value:t},targetLoc:{value:r}})}function i(e,t,r){return{line:e.line+t-1,column:1===e.line?e.column+r:e.column}}function s(e,t,r){return{line:e.line-t+1,column:e.line===t?e.column-r:e.column}}function a(e,t,r,n,i){o.ok(e instanceof h.Lines),o.ok(r instanceof h.Lines),p.assert(t),p.assert(n),p.assert(i);var s=f(n,i);if(0===s)return t;if(s<0){var a=e.skipSpaces(t),u=r.skipSpaces(n),l=i.line-u.line;for(a.line+=l,u.line+=l,l>0?(a.column=0,u.column=0):o.strictEqual(l,0);f(u,i)<0&&r.nextPos(u,!0);)o.ok(e.nextPos(a,!0)),o.strictEqual(e.charAt(a),r.charAt(u))}else{var a=e.skipSpaces(t,!0),u=r.skipSpaces(n,!0),l=i.line-u.line;for(a.line+=l,u.line+=l,l<0?(a.column=e.getLineLength(a.line),u.column=r.getLineLength(u.line)):o.strictEqual(l,0);f(i,u)<0&&r.prevPos(u,!0);)o.ok(e.prevPos(a,!0)),o.strictEqual(e.charAt(a),r.charAt(u))}return a}var o=e("assert"),u=e("./types"),l=(u.builtInTypes.string,u.builtInTypes.number),c=u.namedTypes.SourceLocation,p=u.namedTypes.Position,h=e("./lines"),f=e("./util").comparePos,d=n.prototype;t.exports=n,d.slice=function(e,t,r){function i(n){var i=l[n],s=c[n],p=t;return"end"===n?p=r:o.strictEqual(n,"start"),a(u,i,e,s,p)}o.ok(e instanceof h.Lines),p.assert(t),r?p.assert(r):r=e.lastPos();var u=this.sourceLines,l=this.sourceLoc,c=this.targetLoc;if(f(t,c.start)<=0)if(f(c.end,r)<=0)c={start:s(c.start,t.line,t.column),end:s(c.end,t.line,t.column)};else{if(f(r,c.start)<=0)return null;l={start:l.start,end:i("end")},c={start:s(c.start,t.line,t.column),end:s(r,t.line,t.column)}}else{if(f(c.end,t)<=0)return null;f(c.end,r)<=0?(l={start:i("start"),end:l.end},c={start:{line:1,column:0},end:s(c.end,t.line,t.column)}):(l={start:i("start"),end:i("end")},c={start:{line:1,column:0},end:s(r,t.line,t.column)})}return new n(this.sourceLines,l,c)},d.add=function(e,t){return new n(this.sourceLines,this.sourceLoc,{start:i(this.targetLoc.start,e,t),end:i(this.targetLoc.end,e,t)})},d.subtract=function(e,t){return new n(this.sourceLines,this.sourceLoc,{start:s(this.targetLoc.start,e,t),end:s(this.targetLoc.end,e,t)})},d.indent=function(e,t,r){if(0===e)return this;var i=this.targetLoc,s=i.start.line,a=i.end.line;if(t&&1===s&&1===a)return this;if(i={start:i.start,end:i.end},!t||s>1){var o=i.start.column+e;i.start={line:s,column:r?Math.max(0,o):o}}if(!t||a>1){var u=i.end.column+e;i.end={line:a,column:r?Math.max(0,u):u}}return new n(this.sourceLines,this.sourceLoc,i)}},{"./lines":553,"./types":559,"./util":560,assert:3}],555:[function(e,t,r){var n={parser:e("esprima"),tabWidth:4,useTabs:!1,reuseWhitespace:!0,lineTerminator:e("os").EOL,wrapColumn:74,sourceFileName:null,sourceMapName:null,sourceRoot:null,inputSourceMap:null,range:!1,tolerant:!0,quote:null,trailingComma:!1,arrayBracketSpacing:!1,objectCurlySpacing:!0,arrowParensAlways:!1,flowObjectCommas:!0},i=n.hasOwnProperty;r.normalize=function(e){function t(t){return i.call(e,t)?e[t]:n[t]}return e=e||n,{tabWidth:+t("tabWidth"),useTabs:!!t("useTabs"),reuseWhitespace:!!t("reuseWhitespace"),lineTerminator:t("lineTerminator"),wrapColumn:Math.max(t("wrapColumn"),0),sourceFileName:t("sourceFileName"),sourceMapName:t("sourceMapName"),sourceRoot:t("sourceRoot"),inputSourceMap:t("inputSourceMap"),parser:t("esprima")||t("parser"),range:t("range"),tolerant:t("tolerant"),quote:t("quote"),trailingComma:t("trailingComma"),arrayBracketSpacing:t("arrayBracketSpacing"),objectCurlySpacing:t("objectCurlySpacing"),arrowParensAlways:t("arrowParensAlways"),flowObjectCommas:t("flowObjectCommas")}}},{esprima:562,os:534}],556:[function(e,t,r){function n(e){i.ok(this instanceof n),this.lines=e,this.indent=0}var i=e("assert"),s=e("./types"),a=(s.namedTypes,s.builders),o=s.builtInTypes.object,u=s.builtInTypes.array,l=(s.builtInTypes.function,e("./patcher").Patcher,e("./options").normalize),c=e("./lines").fromString,p=e("./comments").attach,h=e("./util");r.parse=function(e,t){t=l(t);var r=c(e,t),i=r.toString({tabWidth:t.tabWidth,reuseWhitespace:!1,useTabs:!1}),s=[],o=t.parser.parse(i,{jsx:!0,loc:!0,locations:!0,range:t.range,comment:!0,onComment:s,tolerant:t.tolerant,ecmaVersion:6,sourceType:"module"});h.fixFaultyLocations(o,r),o.loc=o.loc||{start:r.firstPos(),end:r.lastPos()},o.loc.lines=r,o.loc.indent=0;var u=h.getTrueLoc(o,r);o.loc.start=u.start,o.loc.end=u.end,o.comments&&(s=o.comments,delete o.comments);var f=o;if("Program"===f.type){var f=a.file(o,t.sourceFileName||null);f.loc={lines:r,indent:0,start:r.firstPos(),end:r.lastPos()}}else"File"===f.type&&(o=f.program);return p(s,o.body.length?f.program:f,r),new n(r).copy(f)},n.prototype.copy=function(e){if(u.check(e))return e.map(this.copy,this);if(!o.check(e))return e;h.fixFaultyLocations(e,this.lines);var t=Object.create(Object.getPrototypeOf(e),{original:{value:e,configurable:!1,enumerable:!1,writable:!0}}),r=e.loc,n=this.indent,i=n;r&&(("Block"===e.type||"Line"===e.type||"CommentBlock"===e.type||"CommentLine"===e.type||this.lines.isPrecededOnlyByWhitespace(r.start))&&(i=this.indent=r.start.column),r.lines=this.lines,r.indent=i);for(var s=Object.keys(e),a=s.length,l=0;l0||(n(i,e.start),s.push(e.lines),i=e.end)}),n(i,t.end),y.concat(s)}}function i(e){var t=[];return e.comments&&e.comments.length>0&&e.comments.forEach(function(e){(e.leading||e.trailing)&&t.push(e)}),t}function s(e,t,r){var n=A.copyPos(t.start),i=e.prevPos(n)&&e.charAt(n),s=r.charAt(r.firstPos());return i&&k.test(i)&&s&&k.test(s)}function a(e,t,r){var n=e.charAt(t.end),i=r.lastPos(),s=r.prevPos(i)&&r.charAt(i);return s&&k.test(s)&&n&&k.test(n)}function o(e,t){var r=e.getValue();b.assert(r);var n=r.original;if(b.assert(n),m.deepEqual(t,[]),r.type!==n.type)return!1;var i=new C(n),s=d(e,i,t);return s||(t.length=0),s}function u(e,t,r){var n=e.getValue();return n===t.getValue()||(_.check(n)?l(e,t,r):!!S.check(n)&&c(e,t,r))}function l(e,t,r){var n=e.getValue(),i=t.getValue();_.assert(n);var s=n.length;if(!_.check(i)||i.length!==s)return!1;for(var a=0;aa)}var m=e("assert"),y=e("./lines"),g=e("./types"),b=(g.getFieldValue,g.namedTypes.Printable),v=g.namedTypes.Expression,x=g.namedTypes.ReturnStatement,E=g.namedTypes.SourceLocation,A=e("./util"),D=A.comparePos,C=e("./fast-path"),S=g.builtInTypes.object,_=g.builtInTypes.array,w=g.builtInTypes.string,k=/[0-9a-z_$]/i;r.Patcher=n;var F=n.prototype;F.tryToReprintComments=function(e,t,r){var n=this;if(!e.comments&&!t.comments)return!0;var s=C.from(e),a=C.from(t);s.stack.push("comments",i(e)),a.stack.push("comments",i(t));var o=[],u=l(s,a,o);return u&&o.length>0&&o.forEach(function(e){var t=e.oldPath.getValue();m.ok(t.leading||t.trailing),n.replace(t.loc,r(e.newPath).indentTail(t.loc.indent))}),u},F.deleteComments=function(e){if(e.comments){var t=this;e.comments.forEach(function(r){r.leading?t.replace({start:r.loc.start,end:e.loc.lines.skipSpaces(r.loc.end,!1,!1)},""):r.trailing&&t.replace({start:e.loc.lines.skipSpaces(r.loc.start,!0,!1),end:r.loc.end},"")})}},r.getReprinter=function(e){m.ok(e instanceof C);var t=e.getValue();if(b.check(t)){var r=t.original,i=r&&r.loc,u=i&&i.lines,l=[];if(u&&o(e,l))return function(e){var t=new n(u);return l.forEach(function(r){var n=r.newPath.getValue(),i=r.oldPath.getValue();E.assert(i.loc,!0);var o=!t.tryToReprintComments(n,i,e);o&&t.deleteComments(i);var l=e(r.newPath,o).indentTail(i.loc.indent),c=s(u,i.loc,l),p=a(u,i.loc,l);if(c||p){var h=[];c&&h.push(" "),h.push(l),p&&h.push(" "),l=y.concat(h)}t.replace(i.loc,l)}),t.get(i).indentTail(-r.loc.indent)}}};var T={line:1,column:0},P=/\S/},{"./fast-path":552,"./lines":553,"./types":559,"./util":560,assert:3}],558:[function(e,t,r){function n(e,t){D.ok(this instanceof n),B.assert(e),this.code=e,t&&(O.assert(t),this.map=t)}function i(e){function t(e){return D.ok(e instanceof j),C(e,r)}function r(e,r){if(r)return t(e);if(D.ok(e instanceof j),!c){var n=p.tabWidth,i=e.getNode().loc;if(i&&i.lines&&i.lines.guessTabWidth){p.tabWidth=i.lines.guessTabWidth();var s=o(e);return p.tabWidth=n,s}}return o(e)}function o(e){var t=F(e);return t?s(e,t(r)):u(e)}function u(e,r){return r?C(e,u):a(e,p,t)}function l(e){return a(e,p,l)}D.ok(this instanceof i);var c=e&&e.tabWidth,p=k(e);D.notStrictEqual(p,e),p.sourceFileName=null,this.print=function(e){if(!e)return M;var t=r(j.from(e),!0);return new n(t.toString(p),N.composeSourceMaps(p.inputSourceMap,t.getSourceMap(p.sourceMapName,p.sourceRoot)))},this.printGenerically=function(e){if(!e)return M;var t=j.from(e),r=p.reuseWhitespace;p.reuseWhitespace=!1;var i=new n(l(t).toString(p));return p.reuseWhitespace=r,i}}function s(e,t){return e.needsParens()?w(["(",t,")"]):t}function a(e,t,r){D.ok(e instanceof j);var n=e.getValue(),i=[],s=!1,a=o(e,t,r);return!n||a.isEmpty()?a:(n.decorators&&n.decorators.length>0&&!N.getParentExportDeclaration(e)?e.each(function(e){i.push(r(e),"\n")},"decorators"):N.isExportDeclaration(n)&&n.declaration&&n.declaration.decorators?e.each(function(e){i.push(r(e),"\n")},"declaration","decorators"):s=e.needsParens(),s&&i.unshift("("),i.push(a),s&&i.push(")"),w(i))}function o(e,t,r){var n=e.getValue();if(!n)return _("");if("string"==typeof n)return _(n,t);P.Printable.assert(n);var i=[];switch(n.type){case"File":return e.call(r,"program");case"Program":return n.directives&&e.each(function(e){i.push(r(e),";\n")},"directives"),i.push(e.call(function(e){return u(e,t,r)},"body")),w(i);case"Noop":case"EmptyStatement":return _("");case"ExpressionStatement":return w([e.call(r,"expression"),";"]);case"ParenthesizedExpression":return w(["(",e.call(r,"expression"),")"]);case"BinaryExpression":case"LogicalExpression":case"AssignmentExpression":return _(" ").join([e.call(r,"left"),n.operator,e.call(r,"right")]);case"AssignmentPattern":return w([e.call(r,"left")," = ",e.call(r,"right")]);case"MemberExpression":i.push(e.call(r,"object"));var s=e.call(r,"property");return n.computed?i.push("[",s,"]"):i.push(".",s),w(i);case"MetaProperty":return w([e.call(r,"meta"),".",e.call(r,"property")]);case"BindExpression":return n.object&&i.push(e.call(r,"object")),i.push("::",e.call(r,"callee")),w(i);case"Path":return _(".").join(n.body);case"Identifier":return w([_(n.name,t),e.call(r,"typeAnnotation")]);case"SpreadElement":case"SpreadElementPattern":case"RestProperty":case"SpreadProperty":case"SpreadPropertyPattern":case"RestElement":return w(["...",e.call(r,"argument")]);case"FunctionDeclaration":case"FunctionExpression":return n.async&&i.push("async "),i.push("function"),n.generator&&i.push("*"),n.id&&i.push(" ",e.call(r,"id"),e.call(r,"typeParameters")),i.push("(",f(e,t,r),")",e.call(r,"returnType")," ",e.call(r,"body")),w(i);case"ArrowFunctionExpression":return n.async&&i.push("async "),n.typeParameters&&i.push(e.call(r,"typeParameters")),t.arrowParensAlways||1!==n.params.length||n.rest||"Identifier"!==n.params[0].type||n.params[0].typeAnnotation||n.returnType?i.push("(",f(e,t,r),")",e.call(r,"returnType")):i.push(e.call(r,"params",0)),i.push(" => ",e.call(r,"body")),w(i);case"MethodDefinition": +return n.static&&i.push("static "),i.push(c(e,t,r)),w(i);case"YieldExpression":return i.push("yield"),n.delegate&&i.push("*"),n.argument&&i.push(" ",e.call(r,"argument")),w(i);case"AwaitExpression":return i.push("await"),n.all&&i.push("*"),n.argument&&i.push(" ",e.call(r,"argument")),w(i);case"ModuleDeclaration":return i.push("module",e.call(r,"id")),n.source?(D.ok(!n.body),i.push("from",e.call(r,"source"))):i.push(e.call(r,"body")),_(" ").join(i);case"ImportSpecifier":return n.imported?(i.push(e.call(r,"imported")),n.local&&n.local.name!==n.imported.name&&i.push(" as ",e.call(r,"local"))):n.id&&(i.push(e.call(r,"id")),n.name&&i.push(" as ",e.call(r,"name"))),w(i);case"ExportSpecifier":return n.local?(i.push(e.call(r,"local")),n.exported&&n.exported.name!==n.local.name&&i.push(" as ",e.call(r,"exported"))):n.id&&(i.push(e.call(r,"id")),n.name&&i.push(" as ",e.call(r,"name"))),w(i);case"ExportBatchSpecifier":return _("*");case"ImportNamespaceSpecifier":return i.push("* as "),n.local?i.push(e.call(r,"local")):n.id&&i.push(e.call(r,"id")),w(i);case"ImportDefaultSpecifier":return n.local?e.call(r,"local"):e.call(r,"id");case"ExportDeclaration":case"ExportDefaultDeclaration":case"ExportNamedDeclaration":return m(e,t,r);case"ExportAllDeclaration":return i.push("export *"),n.exported&&i.push(" as ",e.call(r,"exported")),i.push(" from ",e.call(r,"source")),w(i);case"ExportNamespaceSpecifier":return w(["* as ",e.call(r,"exported")]);case"ExportDefaultSpecifier":return e.call(r,"exported");case"Import":return _("import",t);case"ImportDeclaration":if(i.push("import "),n.importKind&&"value"!==n.importKind&&i.push(n.importKind+" "),n.specifiers&&n.specifiers.length>0){var a=!1;e.each(function(e){e.getName()>0&&i.push(", ");var n=e.getValue();P.ImportDefaultSpecifier.check(n)||P.ImportNamespaceSpecifier.check(n)?D.strictEqual(a,!1):(P.ImportSpecifier.assert(n),a||(a=!0,i.push(t.objectCurlySpacing?"{ ":"{"))),i.push(r(e))},"specifiers"),a&&i.push(t.objectCurlySpacing?" }":"}"),i.push(" from ")}return i.push(e.call(r,"source"),";"),w(i);case"BlockStatement":var o=e.call(function(e){return u(e,t,r)},"body");return!o.isEmpty()||n.directives&&0!==n.directives.length?(i.push("{\n"),n.directives&&e.each(function(e){i.push(r(e).indent(t.tabWidth),";",n.directives.length>1||!o.isEmpty()?"\n":"")},"directives"),i.push(o.indent(t.tabWidth)),i.push("\n}"),w(i)):_("{}");case"ReturnStatement":if(i.push("return"),n.argument){var l=e.call(r,"argument");l.startsWithComment()||l.length>1&&P.JSXElement&&P.JSXElement.check(n.argument)?i.push(" (\n",l.indent(t.tabWidth),"\n)"):i.push(" ",l)}return i.push(";"),w(i);case"CallExpression":return w([e.call(r,"callee"),h(e,t,r)]);case"ObjectExpression":case"ObjectPattern":case"ObjectTypeAnnotation":var b=!1,x="ObjectTypeAnnotation"===n.type,A=t.flowObjectCommas?",":x?";":",",C=[];x&&C.push("indexers","callProperties"),C.push("properties");var S=0;C.forEach(function(e){S+=n[e].length});var k=x&&1===S||0===S,F=n.exact?"{|":"{",T=n.exact?"|}":"}";i.push(k?F:F+"\n");var B=i.length-1,O=0;return C.forEach(function(n){e.each(function(e){var n=r(e);k||(n=n.indent(t.tabWidth));var s=!x&&n.length>1;s&&b&&i.push("\n"),i.push(n),O0&&i.push(" "):n=n.indent(t.tabWidth),i.push(n),(r1?i.push(_(",\n").join(L).indentTail(n.kind.length+1)):i.push(L[0]);var U=e.getParentNode();return P.ForStatement.check(U)||P.ForInStatement.check(U)||P.ForOfStatement&&P.ForOfStatement.check(U)||P.ForAwaitStatement&&P.ForAwaitStatement.check(U)||i.push(";"),w(i);case"VariableDeclarator":return n.init?_(" = ").join([e.call(r,"id"),e.call(r,"init")]):e.call(r,"id");case"WithStatement":return w(["with (",e.call(r,"object"),") ",e.call(r,"body")]);case"IfStatement":var V=g(e.call(r,"consequent"),t),i=["if (",e.call(r,"test"),")",V];return n.alternate&&i.push(v(V)?" else":"\nelse",g(e.call(r,"alternate"),t)),w(i);case"ForStatement":var q=e.call(r,"init"),G=q.length>1?";\n":"; ",X=_(G).join([q,e.call(r,"test"),e.call(r,"update")]).indentTail("for (".length),J=w(["for (",X,")"]),W=g(e.call(r,"body"),t),i=[J];return J.length>1&&(i.push("\n"),W=W.trimLeft()),i.push(W),w(i);case"WhileStatement":return w(["while (",e.call(r,"test"),")",g(e.call(r,"body"),t)]);case"ForInStatement":return w([n.each?"for each (":"for (",e.call(r,"left")," in ",e.call(r,"right"),")",g(e.call(r,"body"),t)]);case"ForOfStatement":return w(["for (",e.call(r,"left")," of ",e.call(r,"right"),")",g(e.call(r,"body"),t)]);case"ForAwaitStatement":return w(["for await (",e.call(r,"left")," of ",e.call(r,"right"),")",g(e.call(r,"body"),t)]);case"DoWhileStatement":var K=w(["do",g(e.call(r,"body"),t)]),i=[K];return v(K)?i.push(" while"):i.push("\nwhile"),i.push(" (",e.call(r,"test"),");"),w(i);case"DoExpression":var z=e.call(function(e){return u(e,t,r)},"body");return w(["do {\n",z.indent(t.tabWidth),"\n}"]);case"BreakStatement":return i.push("break"),n.label&&i.push(" ",e.call(r,"label")),i.push(";"),w(i);case"ContinueStatement":return i.push("continue"),n.label&&i.push(" ",e.call(r,"label")),i.push(";"),w(i);case"LabeledStatement":return w([e.call(r,"label"),":\n",e.call(r,"body")]);case"TryStatement":return i.push("try ",e.call(r,"block")),n.handler?i.push(" ",e.call(r,"handler")):n.handlers&&e.each(function(e){i.push(" ",r(e))},"handlers"),n.finalizer&&i.push(" finally ",e.call(r,"finalizer")),w(i);case"CatchClause":return i.push("catch (",e.call(r,"param")),n.guard&&i.push(" if ",e.call(r,"guard")),i.push(") ",e.call(r,"body")),w(i);case"ThrowStatement":return w(["throw ",e.call(r,"argument"),";"]);case"SwitchStatement":return w(["switch (",e.call(r,"discriminant"),") {\n",_("\n").join(e.map(r,"cases")),"\n}"]);case"SwitchCase":return n.test?i.push("case ",e.call(r,"test"),":"):i.push("default:"),n.consequent.length>0&&i.push("\n",e.call(function(e){return u(e,t,r)},"consequent").indent(t.tabWidth)),w(i);case"DebuggerStatement":return _("debugger;");case"JSXAttribute":return i.push(e.call(r,"name")),n.value&&i.push("=",e.call(r,"value")),w(i);case"JSXIdentifier":return _(n.name,t);case"JSXNamespacedName":return _(":").join([e.call(r,"namespace"),e.call(r,"name")]);case"JSXMemberExpression":return _(".").join([e.call(r,"object"),e.call(r,"property")]);case"JSXSpreadAttribute":return w(["{...",e.call(r,"argument"),"}"]);case"JSXExpressionContainer":return w(["{",e.call(r,"expression"),"}"]);case"JSXElement":var Y=e.call(r,"openingElement");if(n.openingElement.selfClosing)return D.ok(!n.closingElement),Y;var H=w(e.map(function(e){var t=e.getValue();if(P.Literal.check(t)&&"string"==typeof t.value){if(/\S/.test(t.value))return t.value.replace(/^\s+|\s+$/g,"");if(/\n/.test(t.value))return"\n"}return r(e)},"children")).indentTail(t.tabWidth),$=e.call(r,"closingElement");return w([Y,H,$]);case"JSXOpeningElement":i.push("<",e.call(r,"name"));var Q=[];e.each(function(e){Q.push(" ",r(e))},"attributes");var Z=w(Q);return(Z.length>1||Z.getLineLength(1)>t.wrapColumn)&&(Q.forEach(function(e,t){" "===e&&(D.strictEqual(t%2,0),Q[t]="\n")}),Z=w(Q).indentTail(t.tabWidth)),i.push(Z,n.selfClosing?" />":">"),w(i);case"JSXClosingElement":return w([""]);case"JSXText":return _(n.value,t);case"JSXEmptyExpression":return _("");case"TypeAnnotatedIdentifier":return w([e.call(r,"annotation")," ",e.call(r,"identifier")]);case"ClassBody":return 0===n.body.length?_("{}"):w(["{\n",e.call(function(e){return u(e,t,r)},"body").indent(t.tabWidth),"\n}"]);case"ClassPropertyDefinition":return i.push("static ",e.call(r,"definition")),P.MethodDefinition.check(n.definition)||i.push(";"),w(i);case"ClassProperty":n.static&&i.push("static ");var j=e.call(r,"key");return n.computed?j=w(["[",j,"]"]):"plus"===n.variance?j=w(["+",j]):"minus"===n.variance&&(j=w(["-",j])),i.push(j),n.typeAnnotation&&i.push(e.call(r,"typeAnnotation")),n.value&&i.push(" = ",e.call(r,"value")),i.push(";"),w(i);case"ClassDeclaration":case"ClassExpression":return i.push("class"),n.id&&i.push(" ",e.call(r,"id"),e.call(r,"typeParameters")),n.superClass&&i.push(" extends ",e.call(r,"superClass"),e.call(r,"superTypeParameters")),n.implements&&n.implements.length>0&&i.push(" implements ",_(", ").join(e.map(r,"implements"))),i.push(" ",e.call(r,"body")),w(i);case"TemplateElement":return _(n.value.raw,t).lockIndentTail();case"TemplateLiteral":var ee=e.map(r,"expressions");return i.push("`"),e.each(function(e){var t=e.getName();i.push(r(e)),t ":": ",e.call(r,"returnType")),w(i);case"FunctionTypeParam":return w([e.call(r,"name"),n.optional?"?":"",": ",e.call(r,"typeAnnotation")]);case"GenericTypeAnnotation":return w([e.call(r,"id"),e.call(r,"typeParameters")]);case"DeclareInterface":i.push("declare ");case"InterfaceDeclaration":return i.push(_("interface ",t),e.call(r,"id"),e.call(r,"typeParameters")," "),n.extends&&i.push("extends ",_(", ").join(e.map(r,"extends"))),i.push(" ",e.call(r,"body")),w(i);case"ClassImplements":case"InterfaceExtends":return w([e.call(r,"id"),e.call(r,"typeParameters")]);case"IntersectionTypeAnnotation":return _(" & ").join(e.map(r,"types"));case"NullableTypeAnnotation":return w(["?",e.call(r,"typeAnnotation")]);case"NullLiteralTypeAnnotation":return _("null",t);case"ThisTypeAnnotation":return _("this",t);case"NumberTypeAnnotation":return _("number",t);case"ObjectTypeCallProperty":return e.call(r,"value");case"ObjectTypeIndexer":var ne="plus"===n.variance?"+":"minus"===n.variance?"-":"";return w([ne,"[",e.call(r,"id"),": ",e.call(r,"key"),"]: ",e.call(r,"value")]);case"ObjectTypeProperty":var ne="plus"===n.variance?"+":"minus"===n.variance?"-":"";return w([ne,e.call(r,"key"),n.optional?"?":"",": ",e.call(r,"value")]);case"QualifiedTypeIdentifier":return w([e.call(r,"qualification"),".",e.call(r,"id")]);case"StringLiteralTypeAnnotation":return _(E(n.value,t),t);case"NumberLiteralTypeAnnotation":case"NumericLiteralTypeAnnotation":return D.strictEqual(typeof n.value,"number"),_(JSON.stringify(n.value),t);case"StringTypeAnnotation":return _("string",t);case"DeclareTypeAlias":i.push("declare ");case"TypeAlias":return w(["type ",e.call(r,"id"),e.call(r,"typeParameters")," = ",e.call(r,"right"),";"]);case"TypeCastExpression":return w(["(",e.call(r,"expression"),e.call(r,"typeAnnotation"),")"]);case"TypeParameterDeclaration":case"TypeParameterInstantiation":return w(["<",_(", ").join(e.map(r,"params")),">"]);case"TypeParameter":switch(n.variance){case"plus":i.push("+");break;case"minus":i.push("-")}return i.push(e.call(r,"name")),n.bound&&i.push(e.call(r,"bound")),n.default&&i.push("=",e.call(r,"default")),w(i);case"TypeofTypeAnnotation":return w([_("typeof ",t),e.call(r,"argument")]);case"UnionTypeAnnotation":return _(" | ").join(e.map(r,"types"));case"VoidTypeAnnotation":return _("void",t);case"NullTypeAnnotation":return _("null",t);case"ClassHeritage":case"ComprehensionBlock":case"ComprehensionExpression":case"Glob":case"GeneratorExpression":case"LetStatement":case"LetExpression":case"GraphExpression":case"GraphIndexExpression":case"XMLDefaultDeclaration":case"XMLAnyName":case"XMLQualifiedIdentifier":case"XMLFunctionQualifiedIdentifier":case"XMLAttributeSelector":case"XMLFilterExpression":case"XML":case"XMLElement":case"XMLList":case"XMLEscape":case"XMLText":case"XMLStartTag":case"XMLEndTag":case"XMLPointTag":case"XMLName":case"XMLAttribute":case"XMLCdata":case"XMLComment":case"XMLProcessingInstruction":default:throw new Error("unknown type: "+JSON.stringify(n.type))}return p}function u(e,t,r){var n=(P.ClassBody&&P.ClassBody.check(e.getParentNode()),[]),i=!1,s=!1;e.each(function(e){var t=(e.getName(),e.getValue());t&&"EmptyStatement"!==t.type&&(P.Comment.check(t)?i=!0:P.Statement.check(t)?s=!0:B.assert(t),n.push({node:t,printed:r(e)}))}),i&&D.strictEqual(s,!1,"Comments may appear as statements in otherwise empty statement lists, but may not coexist with non-Comment nodes.");var a=null,o=n.length,u=[];return n.forEach(function(e,r){var n,i,s=e.printed,c=e.node,p=s.length>1,h=r>0,f=rr.length?n:r}function c(e,t,r){var n=e.getNode(),i=n.kind,s=[];"ObjectMethod"===n.type||"ClassMethod"===n.type?n.value=n:P.FunctionExpression.assert(n.value),n.value.async&&s.push("async "),i&&"init"!==i&&"method"!==i&&"constructor"!==i?(D.ok("get"===i||"set"===i),s.push(i," ")):n.value.generator&&s.push("*");var a=e.call(r,"key");return n.computed&&(a=w(["[",a,"]"])),s.push(a,e.call(r,"value","typeParameters"),"(",e.call(function(e){return f(e,t,r)},"value"),")",e.call(r,"value","returnType")," ",e.call(r,"value","body")),w(s)}function h(e,t,r){var n=e.map(r,"arguments"),i=N.isTrailingCommaEnabled(t,"parameters"),s=_(", ").join(n);return s.getLineLength(1)>t.wrapColumn?(s=_(",\n").join(n),w(["(\n",s.indent(t.tabWidth),i?",\n)":"\n)"])):w(["(",s,")"])}function f(e,t,r){var n=e.getValue();P.Function.assert(n);var i=e.map(r,"params");n.defaults&&e.each(function(e){var t=e.getName(),n=i[t];n&&e.getValue()&&(i[t]=w([n," = ",r(e)]))},"defaults"),n.rest&&i.push(w(["...",e.call(r,"rest")]));var s=_(", ").join(i);return s.length>1||s.getLineLength(1)>t.wrapColumn?(s=_(",\n").join(i),s=w(N.isTrailingCommaEnabled(t,"parameters")&&!n.rest&&"RestElement"!==n.params[n.params.length-1].type?[s,",\n"]:[s,"\n"]),w(["\n",s.indent(t.tabWidth)])):s}function d(e,t,r){var n=e.getValue(),i=[];if(n.async&&i.push("async "),n.generator&&i.push("*"),n.method||"get"===n.kind||"set"===n.kind)return c(e,t,r);var s=e.call(r,"key");return n.computed?i.push("[",s,"]"):i.push(s),i.push("(",f(e,t,r),")",e.call(r,"returnType")," ",e.call(r,"body")),w(i)}function m(e,t,r){var n=e.getValue(),i=["export "],s=t.objectCurlySpacing;P.Declaration.assert(n),(n.default||"ExportDefaultDeclaration"===n.type)&&i.push("default "),n.declaration?i.push(e.call(r,"declaration")):n.specifiers&&n.specifiers.length>0&&(1===n.specifiers.length&&"ExportBatchSpecifier"===n.specifiers[0].type?i.push("*"):i.push(s?"{ ":"{",_(", ").join(e.map(r,"specifiers")),s?" }":"}"),n.source&&i.push(" from ",e.call(r,"source")));var a=w(i);return";"===b(a)||n.declaration&&("FunctionDeclaration"===n.declaration.type||"ClassDeclaration"===n.declaration.type)||(a=w([a,";"])),a}function y(e,t){var r=N.getParentExportDeclaration(e);return r?D.strictEqual(r.type,"DeclareExportDeclaration"):t.unshift("declare "),w(t)}function g(e,t){return w(e.length>1?[" ",e]:["\n",A(e).indent(t.tabWidth)])}function b(e){var t=e.lastPos();do{var r=e.charAt(t);if(/\S/.test(r))return r}while(e.prevPos(t))}function v(e){return"}"===b(e)}function x(e){return e.replace(/['"]/g,function(e){return'"'===e?"'":'"'})}function E(e,t){switch(B.assert(e),t.quote){case"auto":var r=JSON.stringify(e),n=x(JSON.stringify(x(e)));return r.length>n.length?n:r;case"single":return x(JSON.stringify(x(e)));case"double":default:return JSON.stringify(e)}}function A(e){var t=b(e);return!t||"\n};".indexOf(t)<0?w([e,";"]):e}var D=e("assert"),C=(e("source-map"),e("./comments").printComments),S=e("./lines"),_=S.fromString,w=S.concat,k=e("./options").normalize,F=e("./patcher").getReprinter,T=e("./types"),P=T.namedTypes,B=T.builtInTypes.string,O=T.builtInTypes.object,j=e("./fast-path"),N=e("./util"),I=n.prototype,L=!1;I.toString=function(){return L||(console.warn("Deprecation warning: recast.print now returns an object with a .code property. You appear to be treating the object as a string, which might still work but is strongly discouraged."),L=!0),this.code};var M=new n("");r.Printer=i},{"./comments":551,"./fast-path":552,"./lines":553,"./options":555,"./patcher":557,"./types":559,"./util":560,assert:3,"source-map":573}],559:[function(e,t,r){t.exports=e("ast-types")},{"ast-types":22}],560:[function(e,t,r){function n(){for(var e={},t=arguments.length,r=0;r=0;--i){var s=this.leading[i];t.end.offset>=s.start&&(r.unshift(s.comment),this.leading.splice(i,1),this.trailing.splice(i,1))}r.length&&(e.innerComments=r)}},e.prototype.findTrailingComments=function(e,t){var r=[];if(this.trailing.length>0){for(var n=this.trailing.length-1;n>=0;--n){var i=this.trailing[n];i.start>=t.end.offset&&r.unshift(i.comment)}return this.trailing.length=0,r}var s=this.stack[this.stack.length-1];if(s&&s.node.trailingComments){var a=s.node.trailingComments[0];a&&a.range[0]>=t.end.offset&&(r=s.node.trailingComments,delete s.node.trailingComments)}return r},e.prototype.findLeadingComments=function(e,t){for(var r,n=[];this.stack.length>0;){var i=this.stack[this.stack.length-1];if(!(i&&i.start>=t.start.offset))break;r=this.stack.pop().node}if(r){for(var s=r.leadingComments?r.leadingComments.length:0,a=s-1;a>=0;--a){var o=r.leadingComments[a];o.range[1]<=t.start.offset&&(n.unshift(o),r.leadingComments.splice(a,1))}return r.leadingComments&&0===r.leadingComments.length&&delete r.leadingComments,n}for(var a=this.leading.length-1;a>=0;--a){var i=this.leading[a];i.start<=t.start.offset&&(n.unshift(i.comment),this.leading.splice(a,1))}return n},e.prototype.visitNode=function(e,t){if(!(e.type===n.Syntax.Program&&e.body.length>0)){this.insertInnerComments(e,t);var r=this.findTrailingComments(e,t),i=this.findLeadingComments(e,t);i.length>0&&(e.leadingComments=i),r.length>0&&(e.trailingComments=r),this.stack.push({node:e,start:t.start.offset})}},e.prototype.visitComment=function(e,t){var r="L"===e.type[0]?"Line":"Block",n={type:r,value:e.value};if(e.range&&(n.range=e.range),e.loc&&(n.loc=e.loc),this.comments.push(n),this.attach){var i={comment:{type:r,value:e.value,range:[t.start.offset,t.end.offset]},start:t.start.offset};e.loc&&(i.comment.loc=e.loc),e.type=r,this.leading.push(i),this.trailing.push(i)}},e.prototype.visit=function(e,t){"LineComment"===e.type?this.visitComment(e,t):"BlockComment"===e.type?this.visitComment(e,t):this.attach&&this.visitNode(e,t)},e}();t.CommentHandler=i},function(e,t){"use strict";t.Syntax={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForOfStatement:"ForOfStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"}},function(e,t,r){"use strict";var n=r(4),i=r(5),s=r(6),a=r(7),o=r(8),u=r(2),l=r(10),c=function(){function e(e,t,r){void 0===t&&(t={}),this.config={range:"boolean"==typeof t.range&&t.range,loc:"boolean"==typeof t.loc&&t.loc,source:null,tokens:"boolean"==typeof t.tokens&&t.tokens,comment:"boolean"==typeof t.comment&&t.comment,tolerant:"boolean"==typeof t.tolerant&&t.tolerant},this.config.loc&&t.source&&null!==t.source&&(this.config.source=String(t.source)),this.delegate=r,this.errorHandler=new s.ErrorHandler,this.errorHandler.tolerant=this.config.tolerant,this.scanner=new o.Scanner(e,this.errorHandler),this.scanner.trackComment=this.config.comment,this.operatorPrecedence={")":0,";":0,",":0,"=":0,"]":0,"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"===":6,"!==":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":11,"/":11,"%":11},this.sourceType=t&&"module"===t.sourceType?"module":"script",this.lookahead=null,this.hasLineTerminator=!1,this.context={allowIn:!0,allowYield:!0,firstCoverInitializedNameError:null,isAssignmentTarget:!1,isBindingElement:!1,inFunctionBody:!1,inIteration:!1,inSwitch:!1,labelSet:{},strict:"module"===this.sourceType},this.tokens=[],this.startMarker={index:0,lineNumber:this.scanner.lineNumber,lineStart:0},this.lastMarker={index:0,lineNumber:this.scanner.lineNumber,lineStart:0},this.nextToken(),this.lastMarker={index:this.scanner.index,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart}}return e.prototype.throwError=function(e){for(var t=[],r=1;r0&&this.delegate)for(var t=0;t>="===e||">>>="===e||"&="===e||"^="===e||"|="===e},e.prototype.isolateCoverGrammar=function(e){var t=this.context.isBindingElement,r=this.context.isAssignmentTarget,n=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var i=e.call(this);return null!==this.context.firstCoverInitializedNameError&&this.throwUnexpectedToken(this.context.firstCoverInitializedNameError),this.context.isBindingElement=t,this.context.isAssignmentTarget=r,this.context.firstCoverInitializedNameError=n,i},e.prototype.inheritCoverGrammar=function(e){var t=this.context.isBindingElement,r=this.context.isAssignmentTarget,n=this.context.firstCoverInitializedNameError;this.context.isBindingElement=!0,this.context.isAssignmentTarget=!0,this.context.firstCoverInitializedNameError=null;var i=e.call(this);return this.context.isBindingElement=this.context.isBindingElement&&t,this.context.isAssignmentTarget=this.context.isAssignmentTarget&&r,this.context.firstCoverInitializedNameError=n||this.context.firstCoverInitializedNameError,i},e.prototype.consumeSemicolon=function(){this.match(";")?this.nextToken():this.hasLineTerminator||(this.lookahead.type===a.Token.EOF||this.match("}")||this.throwUnexpectedToken(this.lookahead),this.lastMarker.index=this.startMarker.index,this.lastMarker.lineNumber=this.startMarker.lineNumber,this.lastMarker.lineStart=this.startMarker.lineStart)},e.prototype.parsePrimaryExpression=function(){var e,t,r,n=this.createNode();switch(this.lookahead.type){case a.Token.Identifier:"module"===this.sourceType&&"await"===this.lookahead.value&&this.tolerateUnexpectedToken(this.lookahead),e=this.finalize(n,new l.Identifier(this.nextToken().value));break;case a.Token.NumericLiteral:case a.Token.StringLiteral:this.context.strict&&this.lookahead.octal&&this.tolerateUnexpectedToken(this.lookahead,i.Messages.StrictOctalLiteral),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,t=this.nextToken(),r=this.getTokenRaw(t),e=this.finalize(n,new l.Literal(t.value,r));break;case a.Token.BooleanLiteral:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,t=this.nextToken(),t.value="true"===t.value,r=this.getTokenRaw(t),e=this.finalize(n,new l.Literal(t.value,r));break;case a.Token.NullLiteral:this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,t=this.nextToken(),t.value=null,r=this.getTokenRaw(t),e=this.finalize(n,new l.Literal(t.value,r));break;case a.Token.Template:e=this.parseTemplateLiteral();break;case a.Token.Punctuator:switch(this.lookahead.value){case"(":this.context.isBindingElement=!1,e=this.inheritCoverGrammar(this.parseGroupExpression);break;case"[":e=this.inheritCoverGrammar(this.parseArrayInitializer);break;case"{":e=this.inheritCoverGrammar(this.parseObjectInitializer);break;case"/":case"/=":this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.scanner.index=this.startMarker.index,t=this.nextRegexToken(),r=this.getTokenRaw(t),e=this.finalize(n,new l.RegexLiteral(t.value,r,t.regex));break;default:this.throwUnexpectedToken(this.nextToken())}break;case a.Token.Keyword:!this.context.strict&&this.context.allowYield&&this.matchKeyword("yield")?e=this.parseIdentifierName():!this.context.strict&&this.matchKeyword("let")?e=this.finalize(n,new l.Identifier(this.nextToken().value)):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.matchKeyword("function")?e=this.parseFunctionExpression():this.matchKeyword("this")?(this.nextToken(),e=this.finalize(n,new l.ThisExpression)):this.matchKeyword("class")?e=this.parseClassExpression():this.throwUnexpectedToken(this.nextToken()));break;default:this.throwUnexpectedToken(this.nextToken())}return e},e.prototype.parseSpreadElement=function(){var e=this.createNode();this.expect("...");var t=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.finalize(e,new l.SpreadElement(t))},e.prototype.parseArrayInitializer=function(){var e=this.createNode(),t=[];for(this.expect("[");!this.match("]");)if(this.match(","))this.nextToken(),t.push(null);else if(this.match("...")){var r=this.parseSpreadElement();this.match("]")||(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1,this.expect(",")),t.push(r)}else t.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.match("]")||this.expect(",");return this.expect("]"),this.finalize(e,new l.ArrayExpression(t))},e.prototype.parsePropertyMethod=function(e){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var t=this.context.strict,r=this.isolateCoverGrammar(this.parseFunctionSourceElements);return this.context.strict&&e.firstRestricted&&this.tolerateUnexpectedToken(e.firstRestricted,e.message),this.context.strict&&e.stricted&&this.tolerateUnexpectedToken(e.stricted,e.message),this.context.strict=t,r},e.prototype.parsePropertyMethodFunction=function(){var e=this.createNode(),t=this.context.allowYield;this.context.allowYield=!1;var r=this.parseFormalParameters(),n=this.parsePropertyMethod(r);return this.context.allowYield=t,this.finalize(e,new l.FunctionExpression(null,r.params,n,!1))},e.prototype.parseObjectPropertyKey=function(){var e=this.createNode(),t=this.nextToken(),r=null;switch(t.type){case a.Token.StringLiteral:case a.Token.NumericLiteral:this.context.strict&&t.octal&&this.tolerateUnexpectedToken(t,i.Messages.StrictOctalLiteral);var n=this.getTokenRaw(t);r=this.finalize(e,new l.Literal(t.value,n));break;case a.Token.Identifier:case a.Token.BooleanLiteral:case a.Token.NullLiteral:case a.Token.Keyword:r=this.finalize(e,new l.Identifier(t.value));break;case a.Token.Punctuator:"["===t.value?(r=this.isolateCoverGrammar(this.parseAssignmentExpression),this.expect("]")):this.throwUnexpectedToken(t);break;default:this.throwUnexpectedToken(t)}return r},e.prototype.isPropertyKey=function(e,t){return e.type===u.Syntax.Identifier&&e.name===t||e.type===u.Syntax.Literal&&e.value===t},e.prototype.parseObjectProperty=function(e){var t,r,n,s=this.createNode(),o=this.lookahead,u=!1,c=!1,p=!1;o.type===a.Token.Identifier?(this.nextToken(),r=this.finalize(s,new l.Identifier(o.value))):this.match("*")?this.nextToken():(u=this.match("["),r=this.parseObjectPropertyKey());var h=this.qualifiedPropertyName(this.lookahead);if(o.type===a.Token.Identifier&&"get"===o.value&&h)t="get",u=this.match("["),r=this.parseObjectPropertyKey(),this.context.allowYield=!1,n=this.parseGetterMethod();else if(o.type===a.Token.Identifier&&"set"===o.value&&h)t="set",u=this.match("["),r=this.parseObjectPropertyKey(),n=this.parseSetterMethod();else if(o.type===a.Token.Punctuator&&"*"===o.value&&h)t="init",u=this.match("["),r=this.parseObjectPropertyKey(),n=this.parseGeneratorMethod(),c=!0;else if(r||this.throwUnexpectedToken(this.lookahead),t="init",this.match(":"))!u&&this.isPropertyKey(r,"__proto__")&&(e.value&&this.tolerateError(i.Messages.DuplicateProtoProperty),e.value=!0),this.nextToken(),n=this.inheritCoverGrammar(this.parseAssignmentExpression);else if(this.match("("))n=this.parsePropertyMethodFunction(),c=!0;else if(o.type===a.Token.Identifier){var f=this.finalize(s,new l.Identifier(o.value));if(this.match("=")){this.context.firstCoverInitializedNameError=this.lookahead,this.nextToken(),p=!0;var d=this.isolateCoverGrammar(this.parseAssignmentExpression);n=this.finalize(s,new l.AssignmentPattern(f,d))}else p=!0,n=f}else this.throwUnexpectedToken(this.nextToken());return this.finalize(s,new l.Property(t,r,u,n,c,p))},e.prototype.parseObjectInitializer=function(){var e=this.createNode();this.expect("{");for(var t=[],r={value:!1};!this.match("}");)t.push(this.parseObjectProperty(r)),this.match("}")||this.expectCommaSeparator();return this.expect("}"),this.finalize(e,new l.ObjectExpression(t))},e.prototype.parseTemplateHead=function(){n.assert(this.lookahead.head,"Template literal must start with a template head");var e=this.createNode(),t=this.nextToken(),r={raw:t.value.raw,cooked:t.value.cooked};return this.finalize(e,new l.TemplateElement(r,t.tail))},e.prototype.parseTemplateElement=function(){this.lookahead.type!==a.Token.Template&&this.throwUnexpectedToken();var e=this.createNode(),t=this.nextToken(),r={raw:t.value.raw,cooked:t.value.cooked};return this.finalize(e,new l.TemplateElement(r,t.tail))},e.prototype.parseTemplateLiteral=function(){var e=this.createNode(),t=[],r=[],n=this.parseTemplateHead();for(r.push(n);!n.tail;)t.push(this.parseExpression()),n=this.parseTemplateElement(),r.push(n);return this.finalize(e,new l.TemplateLiteral(r,t))},e.prototype.reinterpretExpressionAsPattern=function(e){switch(e.type){case u.Syntax.Identifier:case u.Syntax.MemberExpression:case u.Syntax.RestElement:case u.Syntax.AssignmentPattern:break;case u.Syntax.SpreadElement:e.type=u.Syntax.RestElement,this.reinterpretExpressionAsPattern(e.argument);break;case u.Syntax.ArrayExpression:e.type=u.Syntax.ArrayPattern;for(var t=0;t")||this.expect("=>"),e={type:"ArrowParameterPlaceHolder",params:[]};else{var t=this.lookahead,r=[];if(this.match("..."))e=this.parseRestElement(r),this.expect(")"),this.match("=>")||this.expect("=>"),e={type:"ArrowParameterPlaceHolder",params:[e]};else{var n=!1;if(this.context.isBindingElement=!0,e=this.inheritCoverGrammar(this.parseAssignmentExpression),this.match(",")){var i=[];for(this.context.isAssignmentTarget=!1,i.push(e);this.startMarker.index")||this.expect("=>"),this.context.isBindingElement=!1;for(var s=0;s")&&(e.type===u.Syntax.Identifier&&"yield"===e.name&&(n=!0,e={type:"ArrowParameterPlaceHolder",params:[e]}),!n)){if(this.context.isBindingElement||this.throwUnexpectedToken(this.lookahead),e.type===u.Syntax.SequenceExpression)for(var s=0;s0){this.nextToken(),r.prec=n,this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;for(var i=[e,this.lookahead],s=t,a=this.isolateCoverGrammar(this.parseExponentiationExpression),o=[s,r,a];;){if((n=this.binaryPrecedence(this.lookahead))<=0)break;for(;o.length>2&&n<=o[o.length-2].prec;){a=o.pop();var u=o.pop().value;s=o.pop(),i.pop();var c=this.startNode(i[i.length-1]);o.push(this.finalize(c,new l.BinaryExpression(u,s,a)))}r=this.nextToken(),r.prec=n,o.push(r),i.push(this.lookahead),o.push(this.isolateCoverGrammar(this.parseExponentiationExpression))}var p=o.length-1;for(t=o[p],i.pop();p>1;){var c=this.startNode(i.pop());t=this.finalize(c,new l.BinaryExpression(o[p-1].value,o[p-2],t)),p-=2}}return t},e.prototype.parseConditionalExpression=function(){var e=this.lookahead,t=this.inheritCoverGrammar(this.parseBinaryExpression);if(this.match("?")){this.nextToken();var r=this.context.allowIn;this.context.allowIn=!0;var n=this.isolateCoverGrammar(this.parseAssignmentExpression);this.context.allowIn=r,this.expect(":");var i=this.isolateCoverGrammar(this.parseAssignmentExpression);t=this.finalize(this.startNode(e),new l.ConditionalExpression(t,n,i)),this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1}return t},e.prototype.checkPatternParam=function(e,t){switch(t.type){case u.Syntax.Identifier:this.validateParam(e,t,t.name);break;case u.Syntax.RestElement:this.checkPatternParam(e,t.argument);break;case u.Syntax.AssignmentPattern:this.checkPatternParam(e,t.left);break;case u.Syntax.ArrayPattern:for(var r=0;r")){this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1;var n=this.reinterpretAsCoverFormalsList(e);if(n){this.hasLineTerminator&&this.tolerateUnexpectedToken(this.lookahead),this.context.firstCoverInitializedNameError=null;var s=this.context.strict,a=this.context.allowYield;this.context.allowYield=!0;var o=this.startNode(t);this.expect("=>");var c=this.match("{")?this.parseFunctionSourceElements():this.isolateCoverGrammar(this.parseAssignmentExpression),p=c.type!==u.Syntax.BlockStatement;this.context.strict&&n.firstRestricted&&this.throwUnexpectedToken(n.firstRestricted,n.message),this.context.strict&&n.stricted&&this.tolerateUnexpectedToken(n.stricted,n.message),e=this.finalize(o,new l.ArrowFunctionExpression(n.params,c,p)),this.context.strict=s,this.context.allowYield=a}}else if(this.matchAssign()){if(this.context.isAssignmentTarget||this.tolerateError(i.Messages.InvalidLHSInAssignment),this.context.strict&&e.type===u.Syntax.Identifier){var h=e;this.scanner.isRestrictedWord(h.name)&&this.tolerateUnexpectedToken(r,i.Messages.StrictLHSAssignment),this.scanner.isStrictModeReservedWord(h.name)&&this.tolerateUnexpectedToken(r,i.Messages.StrictReservedWord)}this.match("=")?this.reinterpretExpressionAsPattern(e):(this.context.isAssignmentTarget=!1,this.context.isBindingElement=!1),r=this.nextToken();var f=this.isolateCoverGrammar(this.parseAssignmentExpression);e=this.finalize(this.startNode(t),new l.AssignmentExpression(r.value,e,f)),this.context.firstCoverInitializedNameError=null}}return e},e.prototype.parseExpression=function(){var e=this.lookahead,t=this.isolateCoverGrammar(this.parseAssignmentExpression);if(this.match(",")){var r=[];for(r.push(t);this.startMarker.index",t.TokenName[r.Identifier]="Identifier",t.TokenName[r.Keyword]="Keyword",t.TokenName[r.NullLiteral]="Null",t.TokenName[r.NumericLiteral]="Numeric",t.TokenName[r.Punctuator]="Punctuator",t.TokenName[r.StringLiteral]="String",t.TokenName[r.RegularExpression]="RegularExpression",t.TokenName[r.Template]="Template" +},function(e,t,r){"use strict";function n(e){return"0123456789abcdef".indexOf(e.toLowerCase())}function i(e){return"01234567".indexOf(e)}var s=r(4),a=r(5),o=r(9),u=r(7),l=function(){function e(e,t){this.source=e,this.errorHandler=t,this.trackComment=!1,this.length=e.length,this.index=0,this.lineNumber=e.length>0?1:0,this.lineStart=0,this.curlyStack=[]}return e.prototype.eof=function(){return this.index>=this.length},e.prototype.throwUnexpectedToken=function(e){void 0===e&&(e=a.Messages.UnexpectedTokenIllegal),this.errorHandler.throwError(this.index,this.lineNumber,this.index-this.lineStart+1,e)},e.prototype.tolerateUnexpectedToken=function(){this.errorHandler.tolerateError(this.index,this.lineNumber,this.index-this.lineStart+1,a.Messages.UnexpectedTokenIllegal)},e.prototype.skipSingleLineComment=function(e){var t,r,n;for(this.trackComment&&(t=[],r=this.index-e,n={start:{line:this.lineNumber,column:this.index-this.lineStart-e},end:{}});!this.eof();){var i=this.source.charCodeAt(this.index);if(++this.index,o.Character.isLineTerminator(i)){if(this.trackComment){n.end={line:this.lineNumber,column:this.index-this.lineStart-1};var s={multiLine:!1,slice:[r+e,this.index-1],range:[r,this.index-1],loc:n};t.push(s)}return 13===i&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t}}if(this.trackComment){n.end={line:this.lineNumber,column:this.index-this.lineStart};var s={multiLine:!1,slice:[r+e,this.index],range:[r,this.index],loc:n};t.push(s)}return t},e.prototype.skipMultiLineComment=function(){var e,t,r;for(this.trackComment&&(e=[],t=this.index-2,r={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{}});!this.eof();){var n=this.source.charCodeAt(this.index);if(o.Character.isLineTerminator(n))13===n&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===n){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart};var i={multiLine:!0,slice:[t+2,this.index-2],range:[t,this.index],loc:r};e.push(i)}return e}++this.index}else++this.index}if(this.trackComment){r.end={line:this.lineNumber,column:this.index-this.lineStart};var i={multiLine:!0,slice:[t+2,this.index],range:[t,this.index],loc:r};e.push(i)}return this.tolerateUnexpectedToken(),e},e.prototype.scanComments=function(){var e;this.trackComment&&(e=[]);for(var t=0===this.index;!this.eof();){var r=this.source.charCodeAt(this.index);if(o.Character.isWhiteSpace(r))++this.index;else if(o.Character.isLineTerminator(r))++this.index,13===r&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,t=!0;else if(47===r)if(47===(r=this.source.charCodeAt(this.index+1))){this.index+=2;var n=this.skipSingleLineComment(2);this.trackComment&&(e=e.concat(n)),t=!0}else{if(42!==r)break;this.index+=2;var n=this.skipMultiLineComment();this.trackComment&&(e=e.concat(n))}else if(t&&45===r){if(45!==this.source.charCodeAt(this.index+1)||62!==this.source.charCodeAt(this.index+2))break;this.index+=3;var n=this.skipSingleLineComment(3);this.trackComment&&(e=e.concat(n))}else{if(60!==r)break;if("!--"!==this.source.slice(this.index+1,this.index+4))break;this.index+=4;var n=this.skipSingleLineComment(4);this.trackComment&&(e=e.concat(n))}}return e},e.prototype.isFutureReservedWord=function(e){switch(e){case"enum":case"export":case"import":case"super":return!0;default:return!1}},e.prototype.isStrictModeReservedWord=function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}},e.prototype.isRestrictedWord=function(e){return"eval"===e||"arguments"===e},e.prototype.isKeyword=function(e){switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}},e.prototype.codePointAt=function(e){var t=this.source.charCodeAt(e);if(t>=55296&&t<=56319){var r=this.source.charCodeAt(e+1);if(r>=56320&&r<=57343){t=1024*(t-55296)+r-56320+65536}}return t},e.prototype.scanHexEscape=function(e){for(var t="u"===e?4:2,r=0,i=0;i1114111||"}"!==e)&&this.throwUnexpectedToken(),o.Character.fromCodePoint(t)},e.prototype.getIdentifier=function(){for(var e=this.index++;!this.eof();){var t=this.source.charCodeAt(this.index);if(92===t)return this.index=e,this.getComplexIdentifier();if(t>=55296&&t<57343)return this.index=e,this.getComplexIdentifier();if(!o.Character.isIdentifierPart(t))break;++this.index}return this.source.slice(e,this.index)},e.prototype.getComplexIdentifier=function(){var e=this.codePointAt(this.index),t=o.Character.fromCodePoint(e);this.index+=t.length;var r;for(92===e&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,r=this.scanUnicodeCodePointEscape()):(r=this.scanHexEscape("u"),e=r.charCodeAt(0),r&&"\\"!==r&&o.Character.isIdentifierStart(e)||this.throwUnexpectedToken()),t=r);!this.eof()&&(e=this.codePointAt(this.index),o.Character.isIdentifierPart(e));)r=o.Character.fromCodePoint(e),t+=r,this.index+=r.length,92===e&&(t=t.substr(0,t.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,r=this.scanUnicodeCodePointEscape()):(r=this.scanHexEscape("u"),e=r.charCodeAt(0),r&&"\\"!==r&&o.Character.isIdentifierPart(e)||this.throwUnexpectedToken()),t+=r);return t},e.prototype.octalToDecimal=function(e){var t="0"!==e,r=i(e);return!this.eof()&&o.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(t=!0,r=8*r+i(this.source[this.index++]),"0123".indexOf(e)>=0&&!this.eof()&&o.Character.isOctalDigit(this.source.charCodeAt(this.index))&&(r=8*r+i(this.source[this.index++]))),{code:r,octal:t}},e.prototype.scanIdentifier=function(){var e,t=this.index,r=92===this.source.charCodeAt(t)?this.getComplexIdentifier():this.getIdentifier();return e=1===r.length?u.Token.Identifier:this.isKeyword(r)?u.Token.Keyword:"null"===r?u.Token.NullLiteral:"true"===r||"false"===r?u.Token.BooleanLiteral:u.Token.Identifier,{type:e,value:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.scanPunctuator=function(){var e={type:u.Token.Punctuator,value:"",lineNumber:this.lineNumber,lineStart:this.lineStart,start:this.index,end:this.index},t=this.source[this.index];switch(t){case"(":case"{":"{"===t&&this.curlyStack.push("{"),++this.index;break;case".":++this.index,"."===this.source[this.index]&&"."===this.source[this.index+1]&&(this.index+=2,t="...");break;case"}":++this.index,this.curlyStack.pop();break;case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;default:t=this.source.substr(this.index,4),">>>="===t?this.index+=4:(t=t.substr(0,3),"==="===t||"!=="===t||">>>"===t||"<<="===t||">>="===t||"**="===t?this.index+=3:(t=t.substr(0,2),"&&"===t||"||"===t||"=="===t||"!="===t||"+="===t||"-="===t||"*="===t||"/="===t||"++"===t||"--"===t||"<<"===t||">>"===t||"&="===t||"|="===t||"^="===t||"%="===t||"<="===t||">="===t||"=>"===t||"**"===t?this.index+=2:(t=this.source[this.index],"<>=!+-*%&|^/".indexOf(t)>=0&&++this.index)))}return this.index===e.start&&this.throwUnexpectedToken(),e.end=this.index,e.value=t,e},e.prototype.scanHexLiteral=function(e){for(var t="";!this.eof()&&o.Character.isHexDigit(this.source.charCodeAt(this.index));)t+=this.source[this.index++];return 0===t.length&&this.throwUnexpectedToken(),o.Character.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:u.Token.NumericLiteral,value:parseInt("0x"+t,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanBinaryLiteral=function(e){for(var t,r="";!this.eof()&&("0"===(t=this.source[this.index])||"1"===t);)r+=this.source[this.index++];return 0===r.length&&this.throwUnexpectedToken(),this.eof()||(t=this.source.charCodeAt(this.index),(o.Character.isIdentifierStart(t)||o.Character.isDecimalDigit(t))&&this.throwUnexpectedToken()),{type:u.Token.NumericLiteral,value:parseInt(r,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}},e.prototype.scanOctalLiteral=function(e,t){var r="",n=!1;for(o.Character.isOctalDigit(e.charCodeAt(0))?(n=!0,r="0"+this.source[this.index++]):++this.index;!this.eof()&&o.Character.isOctalDigit(this.source.charCodeAt(this.index));)r+=this.source[this.index++];return n||0!==r.length||this.throwUnexpectedToken(),(o.Character.isIdentifierStart(this.source.charCodeAt(this.index))||o.Character.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:u.Token.NumericLiteral,value:parseInt(r,8),octal:n,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}},e.prototype.isImplicitOctalLiteral=function(){for(var e=this.index+1;e=0&&(r=r.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g,function(e,t,r){var i=parseInt(t||r,16);return i>1114111&&n.throwUnexpectedToken(a.Messages.InvalidRegExp),i<=65535?String.fromCharCode(i):"￿"}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"￿"));try{RegExp(r)}catch(e){this.throwUnexpectedToken(a.Messages.InvalidRegExp)}try{return new RegExp(e,t)}catch(e){return null}},e.prototype.scanRegExpBody=function(){var e=this.source[this.index];s.assert("/"===e,"Regular expression literal must start with a slash");for(var t=this.source[this.index++],r=!1,n=!1;!this.eof();)if(e=this.source[this.index++],t+=e,"\\"===e)e=this.source[this.index++],o.Character.isLineTerminator(e.charCodeAt(0))&&this.throwUnexpectedToken(a.Messages.UnterminatedRegExp),t+=e;else if(o.Character.isLineTerminator(e.charCodeAt(0)))this.throwUnexpectedToken(a.Messages.UnterminatedRegExp);else if(r)"]"===e&&(r=!1);else{if("/"===e){n=!0;break}"["===e&&(r=!0)}return n||this.throwUnexpectedToken(a.Messages.UnterminatedRegExp),{value:t.substr(1,t.length-2),literal:t}},e.prototype.scanRegExpFlags=function(){for(var e="",t="";!this.eof();){var r=this.source[this.index];if(!o.Character.isIdentifierPart(r.charCodeAt(0)))break;if(++this.index,"\\"!==r||this.eof())t+=r,e+=r;else if("u"===(r=this.source[this.index])){++this.index;var n=this.index;if(r=this.scanHexEscape("u"))for(t+=r,e+="\\u";n=55296&&e<57343&&o.Character.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()},e}();t.Scanner=l},function(e,t){"use strict";var r={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/};t.Character={fromCodePoint:function(e){return e<65536?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10))+String.fromCharCode(56320+(e-65536&1023))},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStart:function(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&r.NonAsciiIdentifierStart.test(t.Character.fromCodePoint(e))},isIdentifierPart:function(e){ +return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&r.NonAsciiIdentifierPart.test(t.Character.fromCodePoint(e))},isDecimalDigit:function(e){return e>=48&&e<=57},isHexDigit:function(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102},isOctalDigit:function(e){return e>=48&&e<=55}}},function(e,t,r){"use strict";var n=r(2),i=function(){function e(e){this.type=n.Syntax.ArrayExpression,this.elements=e}return e}();t.ArrayExpression=i;var s=function(){function e(e){this.type=n.Syntax.ArrayPattern,this.elements=e}return e}();t.ArrayPattern=s;var a=function(){function e(e,t,r){this.type=n.Syntax.ArrowFunctionExpression,this.id=null,this.params=e,this.body=t,this.generator=!1,this.expression=r}return e}();t.ArrowFunctionExpression=a;var o=function(){function e(e,t,r){this.type=n.Syntax.AssignmentExpression,this.operator=e,this.left=t,this.right=r}return e}();t.AssignmentExpression=o;var u=function(){function e(e,t){this.type=n.Syntax.AssignmentPattern,this.left=e,this.right=t}return e}();t.AssignmentPattern=u;var l=function(){function e(e,t,r){var i="||"===e||"&&"===e;this.type=i?n.Syntax.LogicalExpression:n.Syntax.BinaryExpression,this.operator=e,this.left=t,this.right=r}return e}();t.BinaryExpression=l;var c=function(){function e(e){this.type=n.Syntax.BlockStatement,this.body=e}return e}();t.BlockStatement=c;var p=function(){function e(e){this.type=n.Syntax.BreakStatement,this.label=e}return e}();t.BreakStatement=p;var h=function(){function e(e,t){this.type=n.Syntax.CallExpression,this.callee=e,this.arguments=t}return e}();t.CallExpression=h;var f=function(){function e(e,t){this.type=n.Syntax.CatchClause,this.param=e,this.body=t}return e}();t.CatchClause=f;var d=function(){function e(e){this.type=n.Syntax.ClassBody,this.body=e}return e}();t.ClassBody=d;var m=function(){function e(e,t,r){this.type=n.Syntax.ClassDeclaration,this.id=e,this.superClass=t,this.body=r}return e}();t.ClassDeclaration=m;var y=function(){function e(e,t,r){this.type=n.Syntax.ClassExpression,this.id=e,this.superClass=t,this.body=r}return e}();t.ClassExpression=y;var g=function(){function e(e,t){this.type=n.Syntax.MemberExpression,this.computed=!0,this.object=e,this.property=t}return e}();t.ComputedMemberExpression=g;var b=function(){function e(e,t,r){this.type=n.Syntax.ConditionalExpression,this.test=e,this.consequent=t,this.alternate=r}return e}();t.ConditionalExpression=b;var v=function(){function e(e){this.type=n.Syntax.ContinueStatement,this.label=e}return e}();t.ContinueStatement=v;var x=function(){function e(){this.type=n.Syntax.DebuggerStatement}return e}();t.DebuggerStatement=x;var E=function(){function e(e,t){this.type=n.Syntax.ExpressionStatement,this.expression=e,this.directive=t}return e}();t.Directive=E;var A=function(){function e(e,t){this.type=n.Syntax.DoWhileStatement,this.body=e,this.test=t}return e}();t.DoWhileStatement=A;var D=function(){function e(){this.type=n.Syntax.EmptyStatement}return e}();t.EmptyStatement=D;var C=function(){function e(e){this.type=n.Syntax.ExportAllDeclaration,this.source=e}return e}();t.ExportAllDeclaration=C;var S=function(){function e(e){this.type=n.Syntax.ExportDefaultDeclaration,this.declaration=e}return e}();t.ExportDefaultDeclaration=S;var _=function(){function e(e,t,r){this.type=n.Syntax.ExportNamedDeclaration,this.declaration=e,this.specifiers=t,this.source=r}return e}();t.ExportNamedDeclaration=_;var w=function(){function e(e,t){this.type=n.Syntax.ExportSpecifier,this.exported=t,this.local=e}return e}();t.ExportSpecifier=w;var k=function(){function e(e){this.type=n.Syntax.ExpressionStatement,this.expression=e}return e}();t.ExpressionStatement=k;var F=function(){function e(e,t,r){this.type=n.Syntax.ForInStatement,this.left=e,this.right=t,this.body=r,this.each=!1}return e}();t.ForInStatement=F;var T=function(){function e(e,t,r){this.type=n.Syntax.ForOfStatement,this.left=e,this.right=t,this.body=r}return e}();t.ForOfStatement=T;var P=function(){function e(e,t,r,i){this.type=n.Syntax.ForStatement,this.init=e,this.test=t,this.update=r,this.body=i}return e}();t.ForStatement=P;var B=function(){function e(e,t,r,i){this.type=n.Syntax.FunctionDeclaration,this.id=e,this.params=t,this.body=r,this.generator=i,this.expression=!1}return e}();t.FunctionDeclaration=B;var O=function(){function e(e,t,r,i){this.type=n.Syntax.FunctionExpression,this.id=e,this.params=t,this.body=r,this.generator=i,this.expression=!1}return e}();t.FunctionExpression=O;var j=function(){function e(e){this.type=n.Syntax.Identifier,this.name=e}return e}();t.Identifier=j;var N=function(){function e(e,t,r){this.type=n.Syntax.IfStatement,this.test=e,this.consequent=t,this.alternate=r}return e}();t.IfStatement=N;var I=function(){function e(e,t){this.type=n.Syntax.ImportDeclaration,this.specifiers=e,this.source=t}return e}();t.ImportDeclaration=I;var L=function(){function e(e){this.type=n.Syntax.ImportDefaultSpecifier,this.local=e}return e}();t.ImportDefaultSpecifier=L;var M=function(){function e(e){this.type=n.Syntax.ImportNamespaceSpecifier,this.local=e}return e}();t.ImportNamespaceSpecifier=M;var R=function(){function e(e,t){this.type=n.Syntax.ImportSpecifier,this.local=e,this.imported=t}return e}();t.ImportSpecifier=R;var U=function(){function e(e,t){this.type=n.Syntax.LabeledStatement,this.label=e,this.body=t}return e}();t.LabeledStatement=U;var V=function(){function e(e,t){this.type=n.Syntax.Literal,this.value=e,this.raw=t}return e}();t.Literal=V;var q=function(){function e(e,t){this.type=n.Syntax.MetaProperty,this.meta=e,this.property=t}return e}();t.MetaProperty=q;var G=function(){function e(e,t,r,i,s){this.type=n.Syntax.MethodDefinition,this.key=e,this.computed=t,this.value=r,this.kind=i,this.static=s}return e}();t.MethodDefinition=G;var X=function(){function e(e,t){this.type=n.Syntax.NewExpression,this.callee=e,this.arguments=t}return e}();t.NewExpression=X;var J=function(){function e(e){this.type=n.Syntax.ObjectExpression,this.properties=e}return e}();t.ObjectExpression=J;var W=function(){function e(e){this.type=n.Syntax.ObjectPattern,this.properties=e}return e}();t.ObjectPattern=W;var K=function(){function e(e,t){this.type=n.Syntax.Program,this.body=e,this.sourceType=t}return e}();t.Program=K;var z=function(){function e(e,t,r,i,s,a){this.type=n.Syntax.Property,this.key=t,this.computed=r,this.value=i,this.kind=e,this.method=s,this.shorthand=a}return e}();t.Property=z;var Y=function(){function e(e,t,r){this.type=n.Syntax.Literal,this.value=e,this.raw=t,this.regex=r}return e}();t.RegexLiteral=Y;var H=function(){function e(e){this.type=n.Syntax.RestElement,this.argument=e}return e}();t.RestElement=H;var $=function(){function e(e){this.type=n.Syntax.ReturnStatement,this.argument=e}return e}();t.ReturnStatement=$;var Q=function(){function e(e){this.type=n.Syntax.SequenceExpression,this.expressions=e}return e}();t.SequenceExpression=Q;var Z=function(){function e(e){this.type=n.Syntax.SpreadElement,this.argument=e}return e}();t.SpreadElement=Z;var ee=function(){function e(e,t){this.type=n.Syntax.MemberExpression,this.computed=!1,this.object=e,this.property=t}return e}();t.StaticMemberExpression=ee;var te=function(){function e(){this.type=n.Syntax.Super}return e}();t.Super=te;var re=function(){function e(e,t){this.type=n.Syntax.SwitchCase,this.test=e,this.consequent=t}return e}();t.SwitchCase=re;var ne=function(){function e(e,t){this.type=n.Syntax.SwitchStatement,this.discriminant=e,this.cases=t}return e}();t.SwitchStatement=ne;var ie=function(){function e(e,t){this.type=n.Syntax.TaggedTemplateExpression,this.tag=e,this.quasi=t}return e}();t.TaggedTemplateExpression=ie;var se=function(){function e(e,t){this.type=n.Syntax.TemplateElement,this.value=e,this.tail=t}return e}();t.TemplateElement=se;var ae=function(){function e(e,t){this.type=n.Syntax.TemplateLiteral,this.quasis=e,this.expressions=t}return e}();t.TemplateLiteral=ae;var oe=function(){function e(){this.type=n.Syntax.ThisExpression}return e}();t.ThisExpression=oe;var ue=function(){function e(e){this.type=n.Syntax.ThrowStatement,this.argument=e}return e}();t.ThrowStatement=ue;var le=function(){function e(e,t,r){this.type=n.Syntax.TryStatement,this.block=e,this.handler=t,this.finalizer=r}return e}();t.TryStatement=le;var ce=function(){function e(e,t){this.type=n.Syntax.UnaryExpression,this.operator=e,this.argument=t,this.prefix=!0}return e}();t.UnaryExpression=ce;var pe=function(){function e(e,t,r){this.type=n.Syntax.UpdateExpression,this.operator=e,this.argument=t,this.prefix=r}return e}();t.UpdateExpression=pe;var he=function(){function e(e,t){this.type=n.Syntax.VariableDeclaration,this.declarations=e,this.kind=t}return e}();t.VariableDeclaration=he;var fe=function(){function e(e,t){this.type=n.Syntax.VariableDeclarator,this.id=e,this.init=t}return e}();t.VariableDeclarator=fe;var de=function(){function e(e,t){this.type=n.Syntax.WhileStatement,this.test=e,this.body=t}return e}();t.WhileStatement=de;var me=function(){function e(e,t){this.type=n.Syntax.WithStatement,this.object=e,this.body=t}return e}();t.WithStatement=me;var ye=function(){function e(e,t){this.type=n.Syntax.YieldExpression,this.argument=e,this.delegate=t}return e}();t.YieldExpression=ye},function(e,t,r){"use strict";function n(e){var t;switch(e.type){case c.JSXSyntax.JSXIdentifier:t=e.name;break;case c.JSXSyntax.JSXNamespacedName:var r=e;t=n(r.namespace)+":"+n(r.name);break;case c.JSXSyntax.JSXMemberExpression:var i=e;t=n(i.object)+"."+n(i.property)}return t}var i,s=this&&this.__extends||function(e,t){function r(){this.constructor=e}for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)},a=r(9),o=r(7),u=r(3),l=r(12),c=r(13),p=r(10),h=r(14);!function(e){e[e.Identifier=100]="Identifier",e[e.Text=101]="Text"}(i||(i={})),o.TokenName[i.Identifier]="JSXIdentifier",o.TokenName[i.Text]="JSXText";var f=function(e){function t(t,r,n){e.call(this,t,r,n)}return s(t,e),t.prototype.parsePrimaryExpression=function(){return this.match("<")?this.parseJSXRoot():e.prototype.parsePrimaryExpression.call(this)},t.prototype.startJSX=function(){this.scanner.index=this.startMarker.index,this.scanner.lineNumber=this.startMarker.lineNumber,this.scanner.lineStart=this.startMarker.lineStart},t.prototype.finishJSX=function(){this.nextToken()},t.prototype.reenterJSX=function(){this.startJSX(),this.expectJSX("}"),this.config.tokens&&this.tokens.pop()},t.prototype.createJSXNode=function(){return this.collectComments(),{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.createJSXChildNode=function(){return{index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}},t.prototype.scanXHTMLEntity=function(e){for(var t="&",r=!0,n=!1,i=!1,s=!1;!this.scanner.eof()&&r&&!n;){var o=this.scanner.source[this.scanner.index];if(o===e)break;if(n=";"===o,t+=o,++this.scanner.index,!n)switch(t.length){case 2:i="#"===o;break;case 3:i&&(s="x"===o,r=s||a.Character.isDecimalDigit(o.charCodeAt(0)),i=i&&!s);break;default:r=r&&!(i&&!a.Character.isDecimalDigit(o.charCodeAt(0))),r=r&&!(s&&!a.Character.isHexDigit(o.charCodeAt(0)))}}if(r&&n&&t.length>2){var u=t.substr(1,t.length-2);i&&u.length>1?t=String.fromCharCode(parseInt(u.substr(1),10)):s&&u.length>2?t=String.fromCharCode(parseInt("0"+u.substr(1),16)):i||s||!l.XHTMLEntities[u]||(t=l.XHTMLEntities[u])}return t},t.prototype.lexJSX=function(){var e=this.scanner.source.charCodeAt(this.scanner.index);if(60===e||62===e||47===e||58===e||61===e||123===e||125===e){var t=this.scanner.source[this.scanner.index++];return{type:o.Token.Punctuator,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index-1,end:this.scanner.index}}if(34===e||39===e){for(var r=this.scanner.index,n=this.scanner.source[this.scanner.index++],s="";!this.scanner.eof();){var u=this.scanner.source[this.scanner.index++];if(u===n)break;s+="&"===u?this.scanXHTMLEntity(n):u}return{type:o.Token.StringLiteral,value:s,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:r,end:this.scanner.index}}if(46===e){var l=this.scanner.source.charCodeAt(this.scanner.index+1),c=this.scanner.source.charCodeAt(this.scanner.index+2),t=46===l&&46===c?"...":".",r=this.scanner.index;return this.scanner.index+=t.length,{type:o.Token.Punctuator,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:r,end:this.scanner.index}}if(96===e)return{type:o.Token.Template,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:this.scanner.index,end:this.scanner.index};if(a.Character.isIdentifierStart(e)&&92!==e){var r=this.scanner.index;for(++this.scanner.index;!this.scanner.eof();){var u=this.scanner.source.charCodeAt(this.scanner.index);if(a.Character.isIdentifierPart(u)&&92!==u)++this.scanner.index;else{if(45!==u)break;++this.scanner.index}}var p=this.scanner.source.slice(r,this.scanner.index);return{type:i.Identifier,value:p,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:r,end:this.scanner.index}}this.scanner.throwUnexpectedToken()},t.prototype.nextJSXToken=function(){this.collectComments(),this.startMarker.index=this.scanner.index,this.startMarker.lineNumber=this.scanner.lineNumber,this.startMarker.lineStart=this.scanner.lineStart;var e=this.lexJSX();return this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart,this.config.tokens&&this.tokens.push(this.convertToken(e)),e},t.prototype.nextJSXText=function(){this.startMarker.index=this.scanner.index,this.startMarker.lineNumber=this.scanner.lineNumber,this.startMarker.lineStart=this.scanner.lineStart;for(var e=this.scanner.index,t="";!this.scanner.eof();){var r=this.scanner.source[this.scanner.index];if("{"===r||"<"===r)break;++this.scanner.index,t+=r,a.Character.isLineTerminator(r.charCodeAt(0))&&(++this.scanner.lineNumber,"\r"===r&&"\n"===this.scanner.source[this.scanner.index]&&++this.scanner.index,this.scanner.lineStart=this.scanner.index)}this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart;var n={type:i.Text,value:t,lineNumber:this.scanner.lineNumber,lineStart:this.scanner.lineStart,start:e,end:this.scanner.index};return t.length>0&&this.config.tokens&&this.tokens.push(this.convertToken(n)),n},t.prototype.peekJSXToken=function(){var e=this.scanner.index,t=this.scanner.lineNumber,r=this.scanner.lineStart;this.scanner.scanComments();var n=this.lexJSX();return this.scanner.index=e,this.scanner.lineNumber=t,this.scanner.lineStart=r,n},t.prototype.expectJSX=function(e){var t=this.nextJSXToken();t.type===o.Token.Punctuator&&t.value===e||this.throwUnexpectedToken(t)},t.prototype.matchJSX=function(e){var t=this.peekJSXToken();return t.type===o.Token.Punctuator&&t.value===e},t.prototype.parseJSXIdentifier=function(){var e=this.createJSXNode(),t=this.nextJSXToken();return t.type!==i.Identifier&&this.throwUnexpectedToken(t),this.finalize(e,new h.JSXIdentifier(t.value))},t.prototype.parseJSXElementName=function(){var e=this.createJSXNode(),t=this.parseJSXIdentifier();if(this.matchJSX(":")){var r=t;this.expectJSX(":");var n=this.parseJSXIdentifier();t=this.finalize(e,new h.JSXNamespacedName(r,n))}else if(this.matchJSX("."))for(;this.matchJSX(".");){var i=t;this.expectJSX(".");var s=this.parseJSXIdentifier();t=this.finalize(e,new h.JSXMemberExpression(i,s))}return t},t.prototype.parseJSXAttributeName=function(){var e,t=this.createJSXNode(),r=this.parseJSXIdentifier();if(this.matchJSX(":")){var n=r;this.expectJSX(":");var i=this.parseJSXIdentifier();e=this.finalize(t,new h.JSXNamespacedName(n,i))}else e=r;return e},t.prototype.parseJSXStringLiteralAttribute=function(){var e=this.createJSXNode(),t=this.nextJSXToken();t.type!==o.Token.StringLiteral&&this.throwUnexpectedToken(t);var r=this.getTokenRaw(t);return this.finalize(e,new p.Literal(t.value,r))},t.prototype.parseJSXExpressionAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.finishJSX(),this.match("}")&&this.tolerateError("JSX attributes must only be assigned a non-empty expression");var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new h.JSXExpressionContainer(t))},t.prototype.parseJSXAttributeValue=function(){return this.matchJSX("{")?this.parseJSXExpressionAttribute():this.matchJSX("<")?this.parseJSXElement():this.parseJSXStringLiteralAttribute()},t.prototype.parseJSXNameValueAttribute=function(){var e=this.createJSXNode(),t=this.parseJSXAttributeName(),r=null;return this.matchJSX("=")&&(this.expectJSX("="),r=this.parseJSXAttributeValue()),this.finalize(e,new h.JSXAttribute(t,r))},t.prototype.parseJSXSpreadAttribute=function(){var e=this.createJSXNode();this.expectJSX("{"),this.expectJSX("..."),this.finishJSX();var t=this.parseAssignmentExpression();return this.reenterJSX(),this.finalize(e,new h.JSXSpreadAttribute(t))},t.prototype.parseJSXAttributes=function(){for(var e=[];!this.matchJSX("/")&&!this.matchJSX(">");){var t=this.matchJSX("{")?this.parseJSXSpreadAttribute():this.parseJSXNameValueAttribute();e.push(t)}return e},t.prototype.parseJSXOpeningElement=function(){var e=this.createJSXNode();this.expectJSX("<");var t=this.parseJSXElementName(),r=this.parseJSXAttributes(),n=this.matchJSX("/");return n&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new h.JSXOpeningElement(t,n,r))},t.prototype.parseJSXBoundaryElement=function(){var e=this.createJSXNode();if(this.expectJSX("<"),this.matchJSX("/")){this.expectJSX("/");var t=this.parseJSXElementName();return this.expectJSX(">"),this.finalize(e,new h.JSXClosingElement(t))}var r=this.parseJSXElementName(),n=this.parseJSXAttributes(),i=this.matchJSX("/");return i&&this.expectJSX("/"),this.expectJSX(">"),this.finalize(e,new h.JSXOpeningElement(r,i,n))},t.prototype.parseJSXEmptyExpression=function(){var e=this.createJSXChildNode();return this.collectComments(),this.lastMarker.index=this.scanner.index,this.lastMarker.lineNumber=this.scanner.lineNumber,this.lastMarker.lineStart=this.scanner.lineStart,this.finalize(e,new h.JSXEmptyExpression)},t.prototype.parseJSXExpressionContainer=function(){var e=this.createJSXNode();this.expectJSX("{");var t;return this.matchJSX("}")?(t=this.parseJSXEmptyExpression(),this.expectJSX("}")):(this.finishJSX(),t=this.parseAssignmentExpression(),this.reenterJSX()),this.finalize(e,new h.JSXExpressionContainer(t))},t.prototype.parseJSXChildren=function(){for(var e=[];!this.scanner.eof();){var t=this.createJSXChildNode(),r=this.nextJSXText();if(r.start0))break;var a=this.finalize(e.node,new h.JSXElement(e.opening,e.children,e.closing));e=t.pop(),e.children.push(a)}}return e},t.prototype.parseJSXElement=function(){var e=this.createJSXNode(),t=this.parseJSXOpeningElement(),r=[],n=null;if(!t.selfClosing){var i=this.parseComplexJSXElement({node:e,opening:t,closing:n,children:r});r=i.children,n=i.closing}return this.finalize(e,new h.JSXElement(t,r,n))},t.prototype.parseJSXRoot=function(){this.config.tokens&&this.tokens.pop(),this.startJSX();var e=this.parseJSXElement();return this.finishJSX(),e},t}(u.Parser);t.JSXParser=f},function(e,t){"use strict";t.XHTMLEntities={quot:'"',amp:"&",apos:"'",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦",lang:"⟨",rang:"⟩"}},function(e,t){"use strict";t.JSXSyntax={JSXAttribute:"JSXAttribute",JSXClosingElement:"JSXClosingElement",JSXElement:"JSXElement",JSXEmptyExpression:"JSXEmptyExpression",JSXExpressionContainer:"JSXExpressionContainer",JSXIdentifier:"JSXIdentifier",JSXMemberExpression:"JSXMemberExpression",JSXNamespacedName:"JSXNamespacedName",JSXOpeningElement:"JSXOpeningElement",JSXSpreadAttribute:"JSXSpreadAttribute",JSXText:"JSXText"}},function(e,t,r){"use strict";var n=r(13),i=function(){function e(e){this.type=n.JSXSyntax.JSXClosingElement,this.name=e}return e}();t.JSXClosingElement=i;var s=function(){function e(e,t,r){this.type=n.JSXSyntax.JSXElement,this.openingElement=e,this.children=t,this.closingElement=r}return e}();t.JSXElement=s;var a=function(){function e(){this.type=n.JSXSyntax.JSXEmptyExpression}return e}();t.JSXEmptyExpression=a;var o=function(){function e(e){this.type=n.JSXSyntax.JSXExpressionContainer,this.expression=e}return e}();t.JSXExpressionContainer=o;var u=function(){function e(e){this.type=n.JSXSyntax.JSXIdentifier,this.name=e}return e}();t.JSXIdentifier=u;var l=function(){function e(e,t){this.type=n.JSXSyntax.JSXMemberExpression,this.object=e,this.property=t}return e}();t.JSXMemberExpression=l;var c=function(){function e(e,t){this.type=n.JSXSyntax.JSXAttribute,this.name=e,this.value=t}return e}();t.JSXAttribute=c;var p=function(){function e(e,t){this.type=n.JSXSyntax.JSXNamespacedName,this.namespace=e,this.name=t}return e}();t.JSXNamespacedName=p;var h=function(){function e(e,t,r){this.type=n.JSXSyntax.JSXOpeningElement,this.name=e,this.selfClosing=t,this.attributes=r}return e}();t.JSXOpeningElement=h;var f=function(){function e(e){this.type=n.JSXSyntax.JSXSpreadAttribute,this.argument=e}return e}();t.JSXSpreadAttribute=f;var d=function(){function e(e,t){this.type=n.JSXSyntax.JSXText,this.value=e,this.raw=t}return e}();t.JSXText=d},function(e,t,r){"use strict";var n=r(8),i=r(6),s=r(7),a=function(){function e(){this.values=[],this.curly=this.paren=-1}return e.prototype.beforeFunctionExpression=function(e){return["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","**=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","**","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="].indexOf(e)>=0},e.prototype.isRegexStart=function(){var e=this.values[this.values.length-1],t=null!==e;switch(e){case"this":case"]":t=!1;break;case")":var r=this.values[this.paren-1];t="if"===r||"while"===r||"for"===r||"with"===r;break;case"}":if(t=!1,"function"===this.values[this.curly-3]){var n=this.values[this.curly-4];t=!!n&&!this.beforeFunctionExpression(n)}else if("function"===this.values[this.curly-4]){var i=this.values[this.curly-5];t=!i||!this.beforeFunctionExpression(i)}}return t},e.prototype.push=function(e){e.type===s.Token.Punctuator||e.type===s.Token.Keyword?("{"===e.value?this.curly=this.values.length:"("===e.value&&(this.paren=this.values.length),this.values.push(e.value)):this.values.push(null)},e}(),o=function(){function e(e,t){this.errorHandler=new i.ErrorHandler,this.errorHandler.tolerant=!!t&&("boolean"==typeof t.tolerant&&t.tolerant),this.scanner=new n.Scanner(e,this.errorHandler),this.scanner.trackComment=!!t&&("boolean"==typeof t.comment&&t.comment),this.trackRange=!!t&&("boolean"==typeof t.range&&t.range),this.trackLoc=!!t&&("boolean"==typeof t.loc&&t.loc),this.buffer=[],this.reader=new a}return e.prototype.errors=function(){return this.errorHandler.errors},e.prototype.getNextToken=function(){if(0===this.buffer.length){var e=this.scanner.scanComments();if(this.scanner.trackComment)for(var t=0;t=0,s=i&&n.regeneratorRuntime;if(n.regeneratorRuntime=void 0,t.exports=e("./runtime"),i)n.regeneratorRuntime=s;else try{delete n.regeneratorRuntime}catch(e){n.regeneratorRuntime=void 0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./runtime":577}],577:[function(e,t,r){(function(e,r){!function(r){"use strict";function n(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),o=new d(n||[]);return a._invoke=c(e,r,o),a}function i(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}function s(){}function a(){}function o(){}function u(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function l(t){function r(e,n,s,a){var o=i(t[e],t,n);if("throw"!==o.type){var u=o.arg,l=u.value;return l&&"object"==typeof l&&v.call(l,"__await")?Promise.resolve(l.__await).then(function(e){r("next",e,s,a)},function(e){r("throw",e,s,a)}):Promise.resolve(l).then(function(e){u.value=e,s(u)},a)}a(o.arg)}function n(e,t){function n(){return new Promise(function(n,i){r(e,t,n,i)})}return s=s?s.then(n,n):n()}"object"==typeof e&&e.domain&&(r=e.domain.bind(r));var s;this._invoke=n}function c(e,t,r){var n=S;return function(s,a){if(n===w)throw new Error("Generator is already running");if(n===k){if("throw"===s)throw a;return y()}for(r.method=s,r.arg=a;;){var o=r.delegate;if(o){var u=p(o,r);if(u){if(u===F)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===S)throw n=k,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=w;var l=i(e,t,r);if("normal"===l.type){if(n=r.done?k:_,l.arg===F)continue;return{value:l.arg,done:r.done}}"throw"===l.type&&(n=k,r.method="throw",r.arg=l.arg)}}}function p(e,t){var r=e.iterator[t.method];if(r===g){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=g,p(e,t),"throw"===t.method))return F;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return F}var n=i(r,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,F;var s=n.arg;return s?s.done?(t[e.resultName]=s.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=g),t.delegate=null,F):s:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,F)}function h(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function f(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function d(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(h,this),this.reset(!0)}function m(e){if(e){var t=e[E];if(t)return t.call(e);if("function"==typeof e.next)return e +;if(!isNaN(e.length)){var r=-1,n=function t(){for(;++r=0;--n){var i=this.tryEntries[n],s=i.completion;if("root"===i.tryLoc)return t("end");if(i.tryLoc<=this.prev){var a=v.call(i,"catchLoc"),o=v.call(i,"finallyLoc");if(a&&o){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&v.call(n,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),f(r),F}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;f(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:m(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=g),F}}}("object"==typeof r?r:"object"==typeof window?window:"object"==typeof self?self:this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:539}],578:[function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function i(e){return e&&e.__esModule?e:{default:e}}function s(e){h.default.ok(this instanceof s),d.assertIdentifier(e),this.nextTempId=0,this.contextId=e,this.listing=[],this.marked=[!0],this.finalLoc=a(),this.tryEntries=[],this.leapManager=new y.LeapManager(this)}function a(){return d.numericLiteral(-1)}function o(e){return new Error("all declarations should have been transformed into assignments before the Exploder began its work: "+(0,c.default)(e))}function u(e){var t=e.type;return"normal"===t?!E.call(e,"target"):"break"===t||"continue"===t?!E.call(e,"value")&&d.isLiteral(e.target):("return"===t||"throw"===t)&&(E.call(e,"value")&&!E.call(e,"target"))}var l=e("babel-runtime/core-js/json/stringify"),c=i(l),p=e("assert"),h=i(p),f=e("babel-types"),d=n(f),m=e("./leap"),y=n(m),g=e("./meta"),b=n(g),v=e("./util"),x=n(v),E=Object.prototype.hasOwnProperty,A=s.prototype;r.Emitter=s,A.mark=function(e){d.assertLiteral(e);var t=this.listing.length;return-1===e.value?e.value=t:h.default.strictEqual(e.value,t),this.marked[t]=!0,e},A.emit=function(e){d.isExpression(e)&&(e=d.expressionStatement(e)),d.assertStatement(e),this.listing.push(e)},A.emitAssign=function(e,t){return this.emit(this.assign(e,t)),e},A.assign=function(e,t){return d.expressionStatement(d.assignmentExpression("=",e,t))},A.contextProperty=function(e,t){return d.memberExpression(this.contextId,t?d.stringLiteral(e):d.identifier(e),!!t)},A.stop=function(e){e&&this.setReturnValue(e),this.jump(this.finalLoc)},A.setReturnValue=function(e){d.assertExpression(e.value),this.emitAssign(this.contextProperty("rval"),this.explodeExpression(e))},A.clearPendingException=function(e,t){d.assertLiteral(e);var r=d.callExpression(this.contextProperty("catch",!0),[e]);t?this.emitAssign(t,r):this.emit(r)},A.jump=function(e){this.emitAssign(this.contextProperty("next"),e),this.emit(d.breakStatement())},A.jumpIf=function(e,t){d.assertExpression(e),d.assertLiteral(t),this.emit(d.ifStatement(e,d.blockStatement([this.assign(this.contextProperty("next"),t),d.breakStatement()])))},A.jumpIfNot=function(e,t){d.assertExpression(e),d.assertLiteral(t);var r=void 0;r=d.isUnaryExpression(e)&&"!"===e.operator?e.argument:d.unaryExpression("!",e),this.emit(d.ifStatement(r,d.blockStatement([this.assign(this.contextProperty("next"),t),d.breakStatement()])))},A.makeTempVar=function(){return this.contextProperty("t"+this.nextTempId++)},A.getContextFunction=function(e){return d.functionExpression(e||null,[this.contextId],d.blockStatement([this.getDispatchLoop()]),!1,!1)},A.getDispatchLoop=function(){var e=this,t=[],r=void 0,n=!1;return e.listing.forEach(function(i,s){e.marked.hasOwnProperty(s)&&(t.push(d.switchCase(d.numericLiteral(s),r=[])),n=!1),n||(r.push(i),d.isCompletionStatement(i)&&(n=!0))}),this.finalLoc.value=this.listing.length,t.push(d.switchCase(this.finalLoc,[]),d.switchCase(d.stringLiteral("end"),[d.returnStatement(d.callExpression(this.contextProperty("stop"),[]))])),d.whileStatement(d.numericLiteral(1),d.switchStatement(d.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),t))},A.getTryLocsList=function(){if(0===this.tryEntries.length)return null;var e=0;return d.arrayExpression(this.tryEntries.map(function(t){var r=t.firstLoc.value;h.default.ok(r>=e,"try entries out of order"),e=r;var n=t.catchEntry,i=t.finallyEntry,s=[t.firstLoc,n?n.firstLoc:null];return i&&(s[2]=i.firstLoc,s[3]=i.afterLoc),d.arrayExpression(s)}))},A.explode=function(e,t){var r=e.node,n=this;if(d.assertNode(r),d.isDeclaration(r))throw o(r);if(d.isStatement(r))return n.explodeStatement(e);if(d.isExpression(r))return n.explodeExpression(e,t);switch(r.type){case"Program":return e.get("body").map(n.explodeStatement,n);case"VariableDeclarator":throw o(r);case"Property":case"SwitchCase":case"CatchClause":throw new Error(r.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+(0,c.default)(r.type))}},A.explodeStatement=function(e,t){var r=e.node,n=this,i=void 0,s=void 0,o=void 0;if(d.assertStatement(r),t?d.assertIdentifier(t):t=null,d.isBlockStatement(r))return void e.get("body").forEach(function(e){n.explodeStatement(e)});if(!b.containsLeap(r))return void n.emit(r);switch(r.type){case"ExpressionStatement":n.explodeExpression(e.get("expression"),!0);break;case"LabeledStatement":s=a(),n.leapManager.withEntry(new y.LabeledEntry(s,r.label),function(){n.explodeStatement(e.get("body"),r.label)}),n.mark(s);break;case"WhileStatement":i=a(),s=a(),n.mark(i),n.jumpIfNot(n.explodeExpression(e.get("test")),s),n.leapManager.withEntry(new y.LoopEntry(s,i,t),function(){n.explodeStatement(e.get("body"))}),n.jump(i),n.mark(s);break;case"DoWhileStatement":var u=a(),l=a();s=a(),n.mark(u),n.leapManager.withEntry(new y.LoopEntry(s,l,t),function(){n.explode(e.get("body"))}),n.mark(l),n.jumpIf(n.explodeExpression(e.get("test")),u),n.mark(s);break;case"ForStatement":o=a();var p=a();s=a(),r.init&&n.explode(e.get("init"),!0),n.mark(o),r.test&&n.jumpIfNot(n.explodeExpression(e.get("test")),s),n.leapManager.withEntry(new y.LoopEntry(s,p,t),function(){n.explodeStatement(e.get("body"))}),n.mark(p),r.update&&n.explode(e.get("update"),!0),n.jump(o),n.mark(s);break;case"TypeCastExpression":return n.explodeExpression(e.get("expression"));case"ForInStatement":o=a(),s=a();var f=n.makeTempVar();n.emitAssign(f,d.callExpression(x.runtimeProperty("keys"),[n.explodeExpression(e.get("right"))])),n.mark(o);var m=n.makeTempVar();n.jumpIf(d.memberExpression(d.assignmentExpression("=",m,d.callExpression(f,[])),d.identifier("done"),!1),s),n.emitAssign(r.left,d.memberExpression(m,d.identifier("value"),!1)),n.leapManager.withEntry(new y.LoopEntry(s,o,t),function(){n.explodeStatement(e.get("body"))}),n.jump(o),n.mark(s);break;case"BreakStatement":n.emitAbruptCompletion({type:"break",target:n.leapManager.getBreakLoc(r.label)});break;case"ContinueStatement":n.emitAbruptCompletion({type:"continue",target:n.leapManager.getContinueLoc(r.label)});break;case"SwitchStatement":var g=n.emitAssign(n.makeTempVar(),n.explodeExpression(e.get("discriminant")));s=a();for(var v=a(),E=v,A=[],C=r.cases||[],S=C.length-1;S>=0;--S){var _=C[S];d.assertSwitchCase(_),_.test?E=d.conditionalExpression(d.binaryExpression("===",g,_.test),A[S]=a(),E):A[S]=v}var w=e.get("discriminant");w.replaceWith(E),n.jump(n.explodeExpression(w)),n.leapManager.withEntry(new y.SwitchEntry(s),function(){e.get("cases").forEach(function(e){var t=e.key;n.mark(A[t]),e.get("consequent").forEach(function(e){n.explodeStatement(e)})})}),n.mark(s),-1===v.value&&(n.mark(v),h.default.strictEqual(s.value,v.value));break;case"IfStatement":var k=r.alternate&&a();s=a(),n.jumpIfNot(n.explodeExpression(e.get("test")),k||s),n.explodeStatement(e.get("consequent")),k&&(n.jump(s),n.mark(k),n.explodeStatement(e.get("alternate"))),n.mark(s);break;case"ReturnStatement":n.emitAbruptCompletion({type:"return",value:n.explodeExpression(e.get("argument"))});break;case"WithStatement":throw new Error("WithStatement not supported in generator functions.");case"TryStatement":s=a();var F=r.handler,T=F&&a(),P=T&&new y.CatchEntry(T,F.param),B=r.finalizer&&a(),O=B&&new y.FinallyEntry(B,s),j=new y.TryEntry(n.getUnmarkedCurrentLoc(),P,O);n.tryEntries.push(j),n.updateContextPrevLoc(j.firstLoc),n.leapManager.withEntry(j,function(){if(n.explodeStatement(e.get("block")),T){B?n.jump(B):n.jump(s),n.updateContextPrevLoc(n.mark(T));var t=e.get("handler.body"),r=n.makeTempVar();n.clearPendingException(j.firstLoc,r),t.traverse(D,{safeParam:r,catchParamName:F.param.name}),n.leapManager.withEntry(P,function(){n.explodeStatement(t)})}B&&(n.updateContextPrevLoc(n.mark(B)),n.leapManager.withEntry(O,function(){n.explodeStatement(e.get("finalizer"))}),n.emit(d.returnStatement(d.callExpression(n.contextProperty("finish"),[O.firstLoc]))))}),n.mark(s);break;case"ThrowStatement":n.emit(d.throwStatement(n.explodeExpression(e.get("argument"))));break;default:throw new Error("unknown Statement of type "+(0,c.default)(r.type))}};var D={Identifier:function(e,t){e.node.name===t.catchParamName&&x.isReference(e)&&e.replaceWith(t.safeParam)},Scope:function(e,t){e.scope.hasOwnBinding(t.catchParamName)&&e.skip()}};A.emitAbruptCompletion=function(e){u(e)||h.default.ok(!1,"invalid completion record: "+(0,c.default)(e)),h.default.notStrictEqual(e.type,"normal","normal completions are not abrupt");var t=[d.stringLiteral(e.type)];"break"===e.type||"continue"===e.type?(d.assertLiteral(e.target),t[1]=e.target):"return"!==e.type&&"throw"!==e.type||e.value&&(d.assertExpression(e.value),t[1]=e.value),this.emit(d.returnStatement(d.callExpression(this.contextProperty("abrupt"),t)))},A.getUnmarkedCurrentLoc=function(){return d.numericLiteral(this.listing.length)},A.updateContextPrevLoc=function(e){e?(d.assertLiteral(e),-1===e.value?e.value=this.listing.length:h.default.strictEqual(e.value,this.listing.length)):e=this.getUnmarkedCurrentLoc(),this.emitAssign(this.contextProperty("prev"),e)},A.explodeExpression=function(e,t){function r(e){if(d.assertExpression(e),!t)return e;s.emit(e)}function n(e,t,r){h.default.ok(!r||!e,"Ignoring the result of a child expression but forcing it to be assigned to a temporary variable?");var n=s.explodeExpression(t,r);return r||(e||l&&!d.isLiteral(n))&&(n=s.emitAssign(e||s.makeTempVar(),n)),n}var i=e.node;if(!i)return i;d.assertExpression(i);var s=this,o=void 0,u=void 0;if(!b.containsLeap(i))return r(i);var l=b.containsLeap.onlyChildren(i);switch(i.type){case"MemberExpression":return r(d.memberExpression(s.explodeExpression(e.get("object")),i.computed?n(null,e.get("property")):i.property,i.computed));case"CallExpression":var p=e.get("callee"),f=e.get("arguments"),m=void 0,y=[],g=!1;if(f.forEach(function(e){g=g||b.containsLeap(e.node)}),d.isMemberExpression(p.node))if(g){var v=n(s.makeTempVar(),p.get("object")),x=p.node.computed?n(null,p.get("property")):p.node.property;y.unshift(v),m=d.memberExpression(d.memberExpression(v,x,p.node.computed),d.identifier("call"),!1)}else m=s.explodeExpression(p);else m=n(null,p),d.isMemberExpression(m)&&(m=d.sequenceExpression([d.numericLiteral(0),m]));return f.forEach(function(e){y.push(n(null,e))}),r(d.callExpression(m,y));case"NewExpression":return r(d.newExpression(n(null,e.get("callee")),e.get("arguments").map(function(e){return n(null,e)})));case"ObjectExpression":return r(d.objectExpression(e.get("properties").map(function(e){return e.isObjectProperty()?d.objectProperty(e.node.key,n(null,e.get("value")),e.node.computed):e.node})));case"ArrayExpression":return r(d.arrayExpression(e.get("elements").map(function(e){return n(null,e)})));case"SequenceExpression":var E=i.expressions.length-1;return e.get("expressions").forEach(function(e){e.key===E?o=s.explodeExpression(e,t):s.explodeExpression(e,!0)}),o;case"LogicalExpression":u=a(),t||(o=s.makeTempVar());var A=n(o,e.get("left"));return"&&"===i.operator?s.jumpIfNot(A,u):(h.default.strictEqual(i.operator,"||"),s.jumpIf(A,u)),n(o,e.get("right"),t),s.mark(u),o;case"ConditionalExpression":var D=a();u=a();var C=s.explodeExpression(e.get("test"));return s.jumpIfNot(C,D),t||(o=s.makeTempVar()),n(o,e.get("consequent"),t),s.jump(u),s.mark(D),n(o,e.get("alternate"),t),s.mark(u),o;case"UnaryExpression":return r(d.unaryExpression(i.operator,s.explodeExpression(e.get("argument")),!!i.prefix));case"BinaryExpression":return r(d.binaryExpression(i.operator,n(null,e.get("left")),n(null,e.get("right"))));case"AssignmentExpression":return r(d.assignmentExpression(i.operator,s.explodeExpression(e.get("left")),s.explodeExpression(e.get("right"))));case"UpdateExpression":return r(d.updateExpression(i.operator,s.explodeExpression(e.get("argument")),i.prefix));case"YieldExpression":u=a();var S=i.argument&&s.explodeExpression(e.get("argument"));if(S&&i.delegate){var _=s.makeTempVar();return s.emit(d.returnStatement(d.callExpression(s.contextProperty("delegateYield"),[S,d.stringLiteral(_.property.name),u]))),s.mark(u),_}return s.emitAssign(s.contextProperty("next"),u),s.emit(d.returnStatement(S||null)),s.mark(u),s.contextProperty("sent");default:throw new Error("unknown Expression of type "+(0,c.default)(i.type))}}},{"./leap":581,"./meta":582,"./util":584,assert:3,"babel-runtime/core-js/json/stringify":114,"babel-types":169}],579:[function(e,t,r){"use strict";var n=e("babel-runtime/core-js/object/keys"),i=function(e){return e&&e.__esModule?e:{default:e}}(n),s=e("babel-types"),a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(s),o=Object.prototype.hasOwnProperty;r.hoist=function(e){function t(e,t){a.assertVariableDeclaration(e);var n=[];return e.declarations.forEach(function(e){r[e.id.name]=a.identifier(e.id.name),e.init?n.push(a.assignmentExpression("=",e.id,e.init)):t&&n.push(e.id)}),0===n.length?null:1===n.length?n[0]:a.sequenceExpression(n)}a.assertFunction(e.node);var r={};e.get("body").traverse({VariableDeclaration:{exit:function(e){var r=t(e.node,!1);null===r?e.remove():e.replaceWith(a.expressionStatement(r)),e.skip()}},ForStatement:function(e){var r=e.node.init;a.isVariableDeclaration(r)&&e.get("init").replaceWith(t(r,!1))},ForXStatement:function(e){var r=e.get("left");r.isVariableDeclaration()&&r.replaceWith(t(r.node,!0))},FunctionDeclaration:function(e){var t=e.node;r[t.id.name]=t.id;var n=a.expressionStatement(a.assignmentExpression("=",t.id,a.functionExpression(t.id,t.params,t.body,t.generator,t.expression)));e.parentPath.isBlockStatement()?(e.parentPath.unshiftContainer("body",n),e.remove()):e.replaceWith(n),e.skip()},FunctionExpression:function(e){e.skip()}});var n={};e.get("params").forEach(function(e){var t=e.node;a.isIdentifier(t)&&(n[t.name]=t)});var s=[];return(0,i.default)(r).forEach(function(e){o.call(n,e)||s.push(a.variableDeclarator(r[e],null))}),0===s.length?null:a.variableDeclaration("var",s)}},{"babel-runtime/core-js/object/keys":120,"babel-types":169}],580:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(){return e("./visit")}},{"./visit":585}],581:[function(e,t,r){"use strict";function n(){f.default.ok(this instanceof n)}function i(e){n.call(this),m.assertLiteral(e),this.returnLoc=e}function s(e,t,r){n.call(this),m.assertLiteral(e),m.assertLiteral(t),r?m.assertIdentifier(r):r=null,this.breakLoc=e,this.continueLoc=t,this.label=r}function a(e){n.call(this),m.assertLiteral(e),this.breakLoc=e}function o(e,t,r){n.call(this),m.assertLiteral(e),t?f.default.ok(t instanceof u):t=null,r?f.default.ok(r instanceof l):r=null,f.default.ok(t||r),this.firstLoc=e,this.catchEntry=t,this.finallyEntry=r}function u(e,t){n.call(this),m.assertLiteral(e),m.assertIdentifier(t),this.firstLoc=e,this.paramId=t}function l(e,t){n.call(this),m.assertLiteral(e),m.assertLiteral(t),this.firstLoc=e,this.afterLoc=t}function c(e,t){n.call(this),m.assertLiteral(e),m.assertIdentifier(t),this.breakLoc=e,this.label=t}function p(t){f.default.ok(this instanceof p);var r=e("./emit").Emitter;f.default.ok(t instanceof r),this.emitter=t,this.entryStack=[new i(t.finalLoc)]}var h=e("assert"),f=function(e){return e&&e.__esModule?e:{default:e}}(h),d=e("babel-types"),m=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}(d),y=e("util");(0,y.inherits)(i,n),r.FunctionEntry=i,(0,y.inherits)(s,n),r.LoopEntry=s,(0,y.inherits)(a,n),r.SwitchEntry=a,(0,y.inherits)(o,n),r.TryEntry=o,(0,y.inherits)(u,n),r.CatchEntry=u,(0,y.inherits)(l,n),r.FinallyEntry=l,(0,y.inherits)(c,n),r.LabeledEntry=c;var g=p.prototype;r.LeapManager=p,g.withEntry=function(e,t){f.default.ok(e instanceof n),this.entryStack.push(e);try{t.call(this.emitter)}finally{var r=this.entryStack.pop();f.default.strictEqual(r,e)}},g._findLeapLocation=function(e,t){for(var r=this.entryStack.length-1;r>=0;--r){var n=this.entryStack[r],i=n[e];if(i)if(t){if(n.label&&n.label.name===t.name)return i}else if(!(n instanceof c))return i}return null},g.getBreakLoc=function(e){return this._findLeapLocation("breakLoc",e)},g.getContinueLoc=function(e){return this._findLeapLocation("continueLoc",e)}},{"./emit":578,assert:3,"babel-types":169,util:601}],582:[function(e,t,r){"use strict";function n(e,t){function r(e){function t(e){return r||(Array.isArray(e)?e.some(t):o.isNode(e)&&(s.default.strictEqual(r,!1),r=n(e))),r}o.assertNode(e);var r=!1,i=o.VISITOR_KEYS[e.type];if(i)for(var a=0;a0&&(a.node.body=l);var c=s(e);p.assertIdentifier(r.id);var d=p.identifier(r.id.name+"$"),y=(0,h.hoist)(e);if(o(e,i)){y=y||p.variableDeclaration("var",[]);var b=p.identifier("arguments");b._shadowedFunctionLiteral=e,y.declarations.push(p.variableDeclarator(i,b))}var v=new f.Emitter(n);v.explode(e.get("body")),y&&y.declarations.length>0&&u.push(y);var A=[v.getContextFunction(d),r.generator?c:p.nullLiteral(),p.thisExpression()],D=v.getTryLocsList();D&&A.push(D);var C=p.callExpression(g.runtimeProperty(r.async?"async":"wrap"),A);u.push(p.returnStatement(C)),r.body=p.blockStatement(u);var S=a.node.directives;S&&(r.body.directives=S);var _=r.generator;_&&(r.generator=!1),r.async&&(r.async=!1),_&&p.isExpression(r)&&e.replaceWith(p.callExpression(g.runtimeProperty("mark"),[r])),e.requeue()}}};var v={"FunctionExpression|FunctionDeclaration":function(e){e.skip()},Identifier:function(e,t){"arguments"===e.node.name&&g.isReference(e)&&(e.replaceWith(t.argsId),t.didRenameArguments=!0)}},x={MetaProperty:function(e){var t=e.node;"function"===t.meta.name&&"sent"===t.property.name&&e.replaceWith(p.memberExpression(this.context,p.identifier("_sent")))}},E={Function:function(e){e.skip()},AwaitExpression:function(e){var t=e.node.argument;e.replaceWith(p.yieldExpression(p.callExpression(g.runtimeProperty("awrap"),[t]),!1))}}},{"./emit":578,"./hoist":579,"./replaceShorthandObjectMethod":583,"./util":584,assert:3,"babel-types":169,private:537}],586:[function(e,t,r){var n=(e("assert"),e("recast").types),i=n.namedTypes,s=n.builders,a=Object.prototype.hasOwnProperty;r.defaults=function(e){for(var t,r=arguments.length,n=1;n>=1);return r}},{"is-finite":309}],589:[function(e,t,r){"use strict";t.exports=function(e){var t=/^\\\\\?\\/.test(e),r=/[^\x00-\x80]+/.test(e);return t||r?e:e.replace(/\\/g,"/")}},{}],590:[function(e,t,r){function n(){i.call(this)}t.exports=n;var i=e("events").EventEmitter;e("inherits")(n,i),n.Readable=e("readable-stream/readable.js"),n.Writable=e("readable-stream/writable.js"),n.Duplex=e("readable-stream/duplex.js"),n.Transform=e("readable-stream/transform.js"),n.PassThrough=e("readable-stream/passthrough.js"),n.Stream=n,n.prototype.pipe=function(e,t){function r(t){e.writable&&!1===e.write(t)&&l.pause&&l.pause()}function n(){l.readable&&l.resume&&l.resume()}function s(){c||(c=!0,e.end())}function a(){c||(c=!0,"function"==typeof e.destroy&&e.destroy())}function o(e){if(u(),0===i.listenerCount(this,"error"))throw e}function u(){l.removeListener("data",r),e.removeListener("drain",n),l.removeListener("end",s),l.removeListener("close",a),l.removeListener("error",o),e.removeListener("error",o),l.removeListener("end",u),l.removeListener("close",u),e.removeListener("close",u)}var l=this;l.on("data",r),e.on("drain",n),e._isStdio||t&&!1===t.end||(l.on("end",s),l.on("close",a));var c=!1;return l.on("error",o),e.on("error",o),l.on("end",u),l.on("close",u),e.on("close",u),e.emit("pipe",l),e}},{events:301,inherits:306,"readable-stream/duplex.js":540,"readable-stream/passthrough.js":547,"readable-stream/readable.js":548,"readable-stream/transform.js":549,"readable-stream/writable.js":550}],591:[function(e,t,r){function n(e){if(e&&!u(e))throw new Error("Unknown encoding: "+e)}function i(e){return e.toString(this.encoding)}function s(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function a(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}var o=e("buffer").Buffer,u=o.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},l=r.StringDecoder=function(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),n(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=s;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=a;break;default:return void(this.write=i)}this.charBuffer=new o(6),this.charReceived=0,this.charLength=0};l.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&n<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived),t+=e.toString(this.encoding,0,i);var i=t.length-1,n=t.charCodeAt(i);if(n>=55296&&n<=56319){var s=this.surrogateSize;return this.charLength+=s,this.charReceived+=s,this.charBuffer.copy(this.charBuffer,s,0,s),e.copy(this.charBuffer,0,0,s),t.substring(0,i)}return t},l.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},l.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t}},{buffer:184}],592:[function(e,t,r){"use strict";var n=e("ansi-regex")();t.exports=function(e){return"string"==typeof e?e.replace(n,""):e}},{"ansi-regex":1}], +593:[function(e,t,r){(function(e){"use strict";var r=e.argv,n=r.indexOf("--"),i=function(e){e="--"+e;var t=r.indexOf(e);return-1!==t&&(-1===n||t=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),m(t)?n.showHidden=t:t&&r._extend(n,t),E(n.showHidden)&&(n.showHidden=!1),E(n.depth)&&(n.depth=2),E(n.colors)&&(n.colors=!1),E(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=s),u(n,e,n.depth)}function s(e,t){var r=i.styles[t];return r?"["+i.colors[r][0]+"m"+e+"["+i.colors[r][1]+"m":e}function a(e,t){return e}function o(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}function u(e,t,n){if(e.customInspect&&t&&_(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return v(i)||(i=u(e,i,n)),i}var s=l(e,t);if(s)return s;var a=Object.keys(t),m=o(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),S(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(t);if(0===a.length){if(_(t)){var y=t.name?": "+t.name:"";return e.stylize("[Function"+y+"]","special")}if(A(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(C(t))return e.stylize(Date.prototype.toString.call(t),"date");if(S(t))return c(t)}var g="",b=!1,x=["{","}"];if(d(t)&&(b=!0,x=["[","]"]),_(t)){g=" [Function"+(t.name?": "+t.name:"")+"]"}if(A(t)&&(g=" "+RegExp.prototype.toString.call(t)),C(t)&&(g=" "+Date.prototype.toUTCString.call(t)),S(t)&&(g=" "+c(t)),0===a.length&&(!b||0==t.length))return x[0]+g+x[1];if(n<0)return A(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var E;return E=b?p(e,t,n,m,a):a.map(function(r){return h(e,t,n,m,r,b)}),e.seen.pop(),f(E,g,x)}function l(e,t){if(E(t))return e.stylize("undefined","undefined");if(v(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return b(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function p(e,t,r,n,i){for(var s=[],a=0,o=t.length;a-1&&(o=s?o.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+o.split("\n").map(function(e){return" "+e}).join("\n"))):o=e.stylize("[Circular]","special")),E(a)){if(s&&i.match(/^\d+$/))return o;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+o}function f(e,t,r){var n=0;return e.reduce(function(e,t){return n++,t.indexOf("\n")>=0&&n++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}function d(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function y(e){return null===e}function g(e){return null==e}function b(e){return"number"==typeof e}function v(e){return"string"==typeof e}function x(e){return"symbol"==typeof e}function E(e){return void 0===e}function A(e){return D(e)&&"[object RegExp]"===k(e)}function D(e){return"object"==typeof e&&null!==e}function C(e){return D(e)&&"[object Date]"===k(e)}function S(e){return D(e)&&("[object Error]"===k(e)||e instanceof Error)}function _(e){return"function"==typeof e}function w(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e}function k(e){return Object.prototype.toString.call(e)}function F(e){return e<10?"0"+e.toString(10):e.toString(10)}function T(){var e=new Date,t=[F(e.getHours()),F(e.getMinutes()),F(e.getSeconds())].join(":");return[e.getDate(),j[e.getMonth()],t].join(" ")}function P(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.format=function(e){if(!v(e)){for(var t=[],r=0;r=s)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),o=n[r];r any): void; + /** + * Adds schema to the instance. + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + */ + addSchema(schema: Array | Object, key?: string): void; + /** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @param {Object} schema schema object + * @param {String} key optional schema key + */ + addMetaSchema(schema: Object, key?: string): void; + /** + * Validate schema + * @param {Object} schema schema to validate + * @return {Boolean} true if schema is valid + */ + validateSchema(schema: Object): boolean; + /** + * Get compiled schema from the instance by `key` or `ref`. + * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). + */ + getSchema(keyRef: string): ValidateFunction; + /** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + */ + removeSchema(schemaKeyRef?: Object | string | RegExp): void; + /** + * Add custom format + * @param {String} name format name + * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + */ + addFormat(name: string, format: FormatValidator | FormatDefinition): void; + /** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords. + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + */ + addKeyword(keyword: string, definition: KeywordDefinition): void; + /** + * Get keyword definition + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ + getKeyword(keyword: string): Object | boolean; + /** + * Remove keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + */ + removeKeyword(keyword: string): void; + /** + * Convert array of error message objects to string + * @param {Array} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ + errorsText(errors?: Array, options?: ErrorsTextOptions): string; + errors?: Array; + } + + interface Thenable { + then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + } + + interface ValidateFunction { + ( + data: any, + dataPath?: string, + parentData?: Object | Array, + parentDataProperty?: string | number, + rootData?: Object | Array + ): boolean | Thenable; + errors?: Array; + schema?: Object; + } + + interface Options { + v5?: boolean; + allErrors?: boolean; + verbose?: boolean; + jsonPointers?: boolean; + uniqueItems?: boolean; + unicode?: boolean; + format?: string; + formats?: Object; + unknownFormats?: boolean | string | Array; + schemas?: Array | Object; + ownProperties?: boolean; + missingRefs?: boolean | string; + extendRefs?: boolean | string; + loadSchema?: (uri: string, cb: (err: Error, schema: Object) => any) => any; + removeAdditional?: boolean | string; + useDefaults?: boolean | string; + coerceTypes?: boolean | string; + async?: boolean | string; + transpile?: string | ((code: string) => string); + meta?: boolean | Object; + validateSchema?: boolean | string; + addUsedSchema?: boolean; + inlineRefs?: boolean | number; + passContext?: boolean; + loopRequired?: number; + multipleOfPrecision?: number; + errorDataPath?: string; + messages?: boolean; + sourceCode?: boolean; + beautify?: boolean | Object; + cache?: Object; + } + + type FormatValidator = string | RegExp | ((data: string) => boolean); + + interface FormatDefinition { + validate: FormatValidator; + compare: (data1: string, data2: string) => number; + async?: boolean; + } + + interface KeywordDefinition { + type?: string | Array; + async?: boolean; + errors?: boolean | string; + // schema: false makes validate not to expect schema (ValidateFunction) + schema?: boolean; + modifying?: boolean; + valid?: boolean; + // one and only one of the following properties should be present + validate?: ValidateFunction | SchemaValidateFunction; + compile?: (schema: Object, parentSchema: Object) => ValidateFunction; + macro?: (schema: Object, parentSchema: Object) => Object; + inline?: (it: Object, keyword: string, schema: Object, parentSchema: Object) => string; + } + + interface SchemaValidateFunction { + ( + schema: Object, + data: any, + parentSchema?: Object, + dataPath?: string, + parentData?: Object | Array, + parentDataProperty?: string | number + ): boolean | Thenable; + errors?: Array; + } + + interface ErrorsTextOptions { + separator?: string; + dataVar?: string; + } + + interface ErrorObject { + keyword: string; + dataPath: string; + schemaPath: string; + params: ErrorParameters; + // Excluded if messages set to false. + message?: string; + // These are added with the `verbose` option. + schema?: Object; + parentSchema?: Object; + data?: any; + } + + type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | + DependenciesParams | FormatParams | ComparisonParams | + MultipleOfParams | PatternParams | RequiredParams | + TypeParams | UniqueItemsParams | CustomParams | + PatternGroupsParams | PatternRequiredParams | + SwitchParams | NoParams | EnumParams; + + interface RefParams { + ref: string; + } + + interface LimitParams { + limit: number; + } + + interface AdditionalPropertiesParams { + additionalProperty: string; + } + + interface DependenciesParams { + property: string; + missingProperty: string; + depsCount: number; + deps: string; + } + + interface FormatParams { + format: string + } + + interface ComparisonParams { + comparison: string; + limit: number | string; + exclusive: boolean; + } + + interface MultipleOfParams { + multipleOf: number; + } + + interface PatternParams { + pattern: string; + } + + interface RequiredParams { + missingProperty: string; + } + + interface TypeParams { + type: string; + } + + interface UniqueItemsParams { + i: number; + j: number; + } + + interface CustomParams { + keyword: string; + } + + interface PatternGroupsParams { + reason: string; + limit: number; + pattern: string; + } + + interface PatternRequiredParams { + missingPattern: string; + } + + interface SwitchParams { + caseIndex: number; + } + + interface NoParams {} + + interface EnumParams { + allowedValues: Array; + } +} + +export = ajv; diff --git a/node_modules/ajv/lib/ajv.js b/node_modules/ajv/lib/ajv.js new file mode 100644 index 000000000..0502c1fd3 --- /dev/null +++ b/node_modules/ajv/lib/ajv.js @@ -0,0 +1,420 @@ +'use strict'; + +var compileSchema = require('./compile') + , resolve = require('./compile/resolve') + , Cache = require('./cache') + , SchemaObject = require('./compile/schema_obj') + , stableStringify = require('json-stable-stringify') + , formats = require('./compile/formats') + , rules = require('./compile/rules') + , v5 = require('./v5') + , util = require('./compile/util') + , async = require('./async') + , co = require('co'); + +module.exports = Ajv; + +Ajv.prototype.compileAsync = async.compile; + +var customKeyword = require('./keyword'); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.ValidationError = require('./compile/validation_error'); + +var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema'; +var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i; +function SCHEMA_URI_FORMAT_FUNC(str) { + return SCHEMA_URI_FORMAT.test(str); +} + +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ]; + +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + var self = this; + + opts = this._opts = util.copy(opts) || {}; + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); + + // this is done on purpose, so that methods are bound to the instance + // (without using bind) so that they can be used without the instance + this.validate = validate; + this.compile = compile; + this.addSchema = addSchema; + this.addMetaSchema = addMetaSchema; + this.validateSchema = validateSchema; + this.getSchema = getSchema; + this.removeSchema = removeSchema; + this.addFormat = addFormat; + this.errorsText = errorsText; + + this._addSchema = _addSchema; + this._compile = _compile; + + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.async || opts.transpile) async.setup(opts); + if (opts.beautify === true) opts.beautify = { indent_size: 2 }; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + this._metaOpts = getMetaSchemaOptions(); + + if (opts.formats) addInitialFormats(); + addDraft4MetaSchema(); + if (opts.v5) v5.enable(this); + if (typeof opts.meta == 'object') addMetaSchema(opts.meta); + addInitialSchemas(); + + + /** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize. + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ + function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = _addSchema(schemaKeyRef); + v = schemaObj.validate || _compile(schemaObj); + } + + var valid = v(data); + if (v.$async === true) + return self._opts.async == '*' ? co(valid) : valid; + self.errors = v.errors; + return valid; + } + + + /** + * Create validating function for passed schema. + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ + function compile(schema, _meta) { + var schemaObj = _addSchema(schema, undefined, _meta); + return schemaObj.validate || _compile(schemaObj); + } + + + /** + * Adds schema to the instance. + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + */ + function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ + function errorsText(errors, options) { + errors = errors || self.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i= 1 && month <= 12 && day >= 1 && day <= DAYS[month]; +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +function hostname(str) { + // https://tools.ietf.org/html/rfc1034#section-3.5 + // https://tools.ietf.org/html/rfc1123#section-2 + return str.length <= 255 && HOSTNAME.test(str); +} + + +var NOT_URI_FRAGMENT = /\/|\:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +function regex(str) { + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} + + +function compareDate(d1, d2) { + if (!(d1 && d2)) return; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + if (d1 === d2) return 0; +} + + +function compareTime(t1, t2) { + if (!(t1 && t2)) return; + t1 = t1.match(TIME); + t2 = t2.match(TIME); + if (!(t1 && t2)) return; + t1 = t1[1] + t1[2] + t1[3] + (t1[4]||''); + t2 = t2[1] + t2[2] + t2[3] + (t2[4]||''); + if (t1 > t2) return 1; + if (t1 < t2) return -1; + if (t1 === t2) return 0; +} + + +function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return; + dt1 = dt1.split(DATE_TIME_SEPARATOR); + dt2 = dt2.split(DATE_TIME_SEPARATOR); + var res = compareDate(dt1[0], dt2[0]); + if (res === undefined) return; + return res || compareTime(dt1[1], dt2[1]); +} diff --git a/node_modules/ajv/lib/compile/index.js b/node_modules/ajv/lib/compile/index.js new file mode 100644 index 000000000..c9c6730f8 --- /dev/null +++ b/node_modules/ajv/lib/compile/index.js @@ -0,0 +1,390 @@ +'use strict'; + +var resolve = require('./resolve') + , util = require('./util') + , stableStringify = require('json-stable-stringify') + , async = require('../async'); + +var beautify; + +function loadBeautify(){ + if (beautify === undefined) { + var name = 'js-beautify'; + try { beautify = require(name).js_beautify; } + catch(e) { beautify = false; } + } +} + +var validateGenerator = require('../dotjs/validate'); + +/** + * Functions below are used inside compiled validations function + */ + +var co = require('co'); +var ucs2length = util.ucs2length; +var equal = require('./equal'); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = require('./validation_error'); + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = [] + , keepSourceCode = opts.sourceCode !== false; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (keepSourceCode) cv.sourceCode = v.sourceCode; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + function callValidate() { + var validate = compilation.validate; + var result = validate.apply(null, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + if ($async && !opts.transpile) async.setup(opts); + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.beautify) { + loadBeautify(); + /* istanbul ignore else */ + if (beautify) sourceCode = beautify(sourceCode, opts.beautify); + else console.error('"npm install js-beautify" to use beautify option'); + } + // console.log('\n\n\n *** \n', sourceCode); + var validate, validateCode + , transpile = opts._transpileFunc; + try { + validateCode = $async && transpile + ? transpile(sourceCode) + : sourceCode; + + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'co', + 'equal', + 'ucs2length', + 'ValidationError', + validateCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + co, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + console.error('Error compiling schema, function code:', validateCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (keepSourceCode) validate.sourceCode = sourceCode; + if (opts.sourceCode === true) { + validate.source = { + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (!v) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v) { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + var validateSchema = rule.definition.validateSchema; + if (validateSchema && self._opts.validateSchema !== false) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') console.error(message); + else throw new Error(message); + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + } + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; diff --git a/node_modules/ajv/lib/compile/util.js b/node_modules/ajv/lib/compile/util.js new file mode 100644 index 000000000..8451f83ae --- /dev/null +++ b/node_modules/ajv/lib/compile/util.js @@ -0,0 +1,257 @@ +'use strict'; + + +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + ucs2length: require('./ucs2length'), + varOccurences: varOccurences, + varReplace: varReplace, + cleanUpCode: cleanUpCode, + cleanUpVarErrors: cleanUpVarErrors, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + stableStringify: require('json-stable-stringify'), + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; + + +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} + + +function checkDataType(dataType, data, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} + + +function checkDataTypes(dataTypes, data) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; + } + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, true); + + return code; + } +} + + +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } + + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } + + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i' + , $notOp = $isMax ? '>' : '<'; +}} + +{{? $isDataExcl }} + {{ + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) + , $exclusive = 'exclusive' + $lvl + , $opExpr = 'op' + $lvl + , $opStr = '\' + ' + $opExpr + ' + \''; + }} + var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; + {{ $schemaValueExcl = 'schemaExcl' + $lvl; }} + + var exclusive{{=$lvl}}; + if (typeof {{=$schemaValueExcl}} != 'boolean' && typeof {{=$schemaValueExcl}} != 'undefined') { + {{ var $errorKeyword = $exclusiveKeyword; }} + {{# def.error:'_exclusiveLimit' }} + } else if({{# def.$dataNotType:'number' }} + ((exclusive{{=$lvl}} = {{=$schemaValueExcl}} === true) + ? {{=$data}} {{=$notOp}}= {{=$schemaValue}} + : {{=$data}} {{=$notOp}} {{=$schemaValue}}) + || {{=$data}} !== {{=$data}}) { + var op{{=$lvl}} = exclusive{{=$lvl}} ? '{{=$op}}' : '{{=$op}}='; +{{??}} + {{ + var $exclusive = $schemaExcl === true + , $opStr = $op; /*used in error*/ + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; /*used in error*/ + }} + + if ({{# def.$dataNotType:'number' }} + {{=$data}} {{=$notOp}}{{?$exclusive}}={{?}} {{=$schemaValue}} + || {{=$data}} !== {{=$data}}) { +{{?}} + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limit' }} + } {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/_limitItems.jst b/node_modules/ajv/lib/dot/_limitItems.jst new file mode 100644 index 000000000..a3e078e51 --- /dev/null +++ b/node_modules/ajv/lib/dot/_limitItems.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitItems' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/_limitLength.jst b/node_modules/ajv/lib/dot/_limitLength.jst new file mode 100644 index 000000000..cfc8dbb01 --- /dev/null +++ b/node_modules/ajv/lib/dot/_limitLength.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitLength' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/_limitProperties.jst b/node_modules/ajv/lib/dot/_limitProperties.jst new file mode 100644 index 000000000..da7ea776f --- /dev/null +++ b/node_modules/ajv/lib/dot/_limitProperties.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }} +if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_limitProperties' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/allOf.jst b/node_modules/ajv/lib/dot/allOf.jst new file mode 100644 index 000000000..4c2836311 --- /dev/null +++ b/node_modules/ajv/lib/dot/allOf.jst @@ -0,0 +1,34 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $currentBaseId = $it.baseId + , $allSchemasEmpty = true; +}} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{# def.ifResultValid }} + {{?}} +{{~}} + +{{? $breakOnError }} + {{? $allSchemasEmpty }} + if (true) { + {{??}} + {{= $closingBraces.slice(0,-1) }} + {{?}} +{{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/anyOf.jst b/node_modules/ajv/lib/dot/anyOf.jst new file mode 100644 index 000000000..93c3cd828 --- /dev/null +++ b/node_modules/ajv/lib/dot/anyOf.jst @@ -0,0 +1,48 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{ + var $noEmptySchema = $schema.every(function($sch) { + return {{# def.nonEmptySchema:$sch }}; + }); +}} +{{? $noEmptySchema }} + {{ var $currentBaseId = $it.baseId; }} + var {{=$errs}} = errors; + var {{=$valid}} = false; + + {{# def.setCompositeRule }} + + {{~ $schema:$sch:$i }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + + {{=$valid}} = {{=$valid}} || {{=$nextValid}}; + + if (!{{=$valid}}) { + {{ $closingBraces += '}'; }} + {{~}} + + {{# def.resetCompositeRule }} + + {{= $closingBraces }} + + if (!{{=$valid}}) { + {{# def.addError:'anyOf' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} + + {{# def.cleanUp }} +{{??}} + {{? $breakOnError }} + if (true) { + {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/coerce.def b/node_modules/ajv/lib/dot/coerce.def new file mode 100644 index 000000000..86e0e18af --- /dev/null +++ b/node_modules/ajv/lib/dot/coerce.def @@ -0,0 +1,61 @@ +{{## def.coerceType: + {{ + var $dataType = 'dataType' + $lvl + , $coerced = 'coerced' + $lvl; + }} + var {{=$dataType}} = typeof {{=$data}}; + {{? it.opts.coerceTypes == 'array'}} + if ({{=$dataType}} == 'object' && Array.isArray({{=$data}})) {{=$dataType}} = 'array'; + {{?}} + + var {{=$coerced}} = undefined; + + {{ var $bracesCoercion = ''; }} + {{~ $coerceToTypes:$type:$i }} + {{? $i }} + if ({{=$coerced}} === undefined) { + {{ $bracesCoercion += '}'; }} + {{?}} + + {{? it.opts.coerceTypes == 'array' && $type != 'array' }} + if ({{=$dataType}} == 'array' && {{=$data}}.length == 1) { + {{=$coerced}} = {{=$data}} = {{=$data}}[0]; + {{=$dataType}} = typeof {{=$data}}; + /*if ({{=$dataType}} == 'object' && Array.isArray({{=$data}})) {{=$dataType}} = 'array';*/ + } + {{?}} + + {{? $type == 'string' }} + if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean') + {{=$coerced}} = '' + {{=$data}}; + else if ({{=$data}} === null) {{=$coerced}} = ''; + {{?? $type == 'number' || $type == 'integer' }} + if ({{=$dataType}} == 'boolean' || {{=$data}} === null + || ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}} + {{? $type == 'integer' }} && !({{=$data}} % 1){{?}})) + {{=$coerced}} = +{{=$data}}; + {{?? $type == 'boolean' }} + if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null) + {{=$coerced}} = false; + else if ({{=$data}} === 'true' || {{=$data}} === 1) + {{=$coerced}} = true; + {{?? $type == 'null' }} + if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false) + {{=$coerced}} = null; + {{?? it.opts.coerceTypes == 'array' && $type == 'array' }} + if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null) + {{=$coerced}} = [{{=$data}}]; + {{?}} + {{~}} + + {{= $bracesCoercion }} + + if ({{=$coerced}} === undefined) { + {{# def.error:'type' }} + } else { + {{# def.setParentData }} + {{=$data}} = {{=$coerced}}; + {{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}} + {{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}}; + } +#}} diff --git a/node_modules/ajv/lib/dot/custom.jst b/node_modules/ajv/lib/dot/custom.jst new file mode 100644 index 000000000..e91c50e6f --- /dev/null +++ b/node_modules/ajv/lib/dot/custom.jst @@ -0,0 +1,184 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $rule = this + , $definition = 'definition' + $lvl + , $rDef = $rule.definition; + var $validate = $rDef.validate; + var $compile, $inline, $macro, $ruleValidate, $validateCode; +}} + +{{? $isData && $rDef.$data }} + {{ + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + }} + var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition; + var {{=$validateCode}} = {{=$definition}}.validate; +{{??}} + {{ + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + }} +{{?}} + +{{ + var $ruleErrs = $validateCode + '.errors' + , $i = 'i' + $lvl + , $ruleErr = 'ruleErr' + $lvl + , $asyncKeyword = $rDef.async; + + if ($asyncKeyword && !it.async) + throw new Error('async keyword in sync schema'); +}} + + +{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}} +var {{=$errs}} = errors; +var {{=$valid}}; + +{{## def.callRuleValidate: + {{=$validateCode}}.call( + {{? it.opts.passContext }}this{{??}}self{{?}} + {{? $compile || $rDef.schema === false }} + , {{=$data}} + {{??}} + , {{=$schemaValue}} + , {{=$data}} + , validate.schema{{=it.schemaPath}} + {{?}} + , {{# def.dataPath }} + {{# def.passParentData }} + , rootData + ) +#}} + +{{## def.extendErrors:_inline: + for (var {{=$i}}={{=$errs}}; {{=$i}} {{=$i}}) { + {{ + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + } + + {{# def.ifResultValid }} + {{?}} + {{~}} + + {{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }} + {{ + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + }} + {{=$nextValid}} = true; + + if ({{=$data}}.length > {{= $schema.length }}) { + {{# def.validateItems: $schema.length }} + } + + {{# def.ifResultValid }} + {{?}} + +{{?? {{# def.nonEmptySchema:$schema }} }} + {{ /* 'items' is a single schema */}} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + {{# def.validateItems: 0 }} + {{# def.ifResultValid }} +{{?}} + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/missing.def b/node_modules/ajv/lib/dot/missing.def new file mode 100644 index 000000000..23ad04cf4 --- /dev/null +++ b/node_modules/ajv/lib/dot/missing.def @@ -0,0 +1,34 @@ +{{## def.checkMissingProperty:_properties: + {{~ _properties:_$property:$i }} + {{?$i}} || {{?}} + {{ var $prop = it.util.getProperty(_$property); }} + ( {{=$data}}{{=$prop}} === undefined && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop) }}) ) + {{~}} +#}} + + +{{## def.errorMissingProperty:_error: + {{ + var $propertyPath = 'missing' + $lvl + , $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers + ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) + : $currentErrorPath + ' + ' + $propertyPath; + } + }} + {{# def.error:_error }} +#}} + +{{## def.allErrorsMissingProperty:_error: + {{ + var $prop = it.util.getProperty($reqProperty) + , $missingProperty = it.util.escapeQuotes($reqProperty); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); + } + }} + if ({{=$data}}{{=$prop}} === undefined) { + {{# def.addError:_error }} + } +#}} diff --git a/node_modules/ajv/lib/dot/multipleOf.jst b/node_modules/ajv/lib/dot/multipleOf.jst new file mode 100644 index 000000000..5f8dd33b5 --- /dev/null +++ b/node_modules/ajv/lib/dot/multipleOf.jst @@ -0,0 +1,20 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +var division{{=$lvl}}; +if ({{?$isData}} + {{=$schemaValue}} !== undefined && ( + typeof {{=$schemaValue}} != 'number' || + {{?}} + (division{{=$lvl}} = {{=$data}} / {{=$schemaValue}}, + {{? it.opts.multipleOfPrecision }} + Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}} + {{??}} + division{{=$lvl}} !== parseInt(division{{=$lvl}}) + {{?}} + ) + {{?$isData}} ) {{?}} ) { + {{# def.error:'multipleOf' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/not.jst b/node_modules/ajv/lib/dot/not.jst new file mode 100644 index 000000000..e03185ae8 --- /dev/null +++ b/node_modules/ajv/lib/dot/not.jst @@ -0,0 +1,43 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +{{? {{# def.nonEmptySchema:$schema }} }} + {{ + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + }} + + var {{=$errs}} = errors; + + {{# def.setCompositeRule }} + + {{ + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + }} + {{= it.validate($it) }} + {{ + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + }} + + {{# def.resetCompositeRule }} + + if ({{=$nextValid}}) { + {{# def.error:'not' }} + } else { + {{# def.resetErrors }} + {{? it.opts.allErrors }} } {{?}} +{{??}} + {{# def.addError:'not' }} + {{? $breakOnError}} + if (false) { + {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/oneOf.jst b/node_modules/ajv/lib/dot/oneOf.jst new file mode 100644 index 000000000..b7f7bff07 --- /dev/null +++ b/node_modules/ajv/lib/dot/oneOf.jst @@ -0,0 +1,44 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + +var {{=$errs}} = errors; +var prevValid{{=$lvl}} = false; +var {{=$valid}} = false; + +{{ var $currentBaseId = $it.baseId; }} +{{# def.setCompositeRule }} + +{{~ $schema:$sch:$i }} + {{? {{# def.nonEmptySchema:$sch }} }} + {{ + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + }} + + {{# def.insertSubschemaCode }} + {{??}} + var {{=$nextValid}} = true; + {{?}} + + {{? $i }} + if ({{=$nextValid}} && prevValid{{=$lvl}}) + {{=$valid}} = false; + else { + {{ $closingBraces += '}'; }} + {{?}} + + if ({{=$nextValid}}) {{=$valid}} = prevValid{{=$lvl}} = true; +{{~}} + +{{# def.resetCompositeRule }} + +{{= $closingBraces }} + +if (!{{=$valid}}) { + {{# def.error:'oneOf' }} +} else { + {{# def.resetErrors }} +{{? it.opts.allErrors }} } {{?}} diff --git a/node_modules/ajv/lib/dot/pattern.jst b/node_modules/ajv/lib/dot/pattern.jst new file mode 100644 index 000000000..3a37ef6cb --- /dev/null +++ b/node_modules/ajv/lib/dot/pattern.jst @@ -0,0 +1,14 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ + var $regexp = $isData + ? '(new RegExp(' + $schemaValue + '))' + : it.usePattern($schema); +}} + +if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) { + {{# def.error:'pattern' }} +} {{? $breakOnError }} else { {{?}} diff --git a/node_modules/ajv/lib/dot/properties.jst b/node_modules/ajv/lib/dot/properties.jst new file mode 100644 index 000000000..3a4b966ff --- /dev/null +++ b/node_modules/ajv/lib/dot/properties.jst @@ -0,0 +1,319 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateAdditional: + {{ /* additionalProperties is schema */ + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty + ? it.errorPath + : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} +#}} + + +{{ + var $key = 'key' + $lvl + , $dataNxt = $it.dataLevel = it.dataLevel + 1 + , $nextData = 'data' + $dataNxt; + + var $schemaKeys = Object.keys($schema || {}) + , $pProperties = it.schema.patternProperties || {} + , $pPropertyKeys = Object.keys($pProperties) + , $aProperties = it.schema.additionalProperties + , $someProperties = $schemaKeys.length || $pPropertyKeys.length + , $noAdditional = $aProperties === false + , $additionalIsSchema = typeof $aProperties == 'object' + && Object.keys($aProperties).length + , $removeAdditional = it.opts.removeAdditional + , $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional + , $ownProperties = it.opts.ownProperties + , $currentBaseId = it.baseId; + + var $required = it.schema.required; + if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) + var $requiredHash = it.util.toHash($required); + + if (it.opts.v5) { + var $pgProperties = it.schema.patternGroups || {} + , $pgPropertyKeys = Object.keys($pgProperties); + } +}} + + +var {{=$errs}} = errors; +var {{=$nextValid}} = true; + +{{? $checkAdditional }} + for (var {{=$key}} in {{=$data}}) { + {{# def.checkOwnProperty }} + {{? $someProperties }} + var isAdditional{{=$lvl}} = !(false + {{? $schemaKeys.length }} + {{? $schemaKeys.length > 5 }} + || validate.schema{{=$schemaPath}}[{{=$key}}] + {{??}} + {{~ $schemaKeys:$propertyKey }} + || {{=$key}} == {{= it.util.toQuotedString($propertyKey) }} + {{~}} + {{?}} + {{?}} + {{? $pPropertyKeys.length }} + {{~ $pPropertyKeys:$pProperty:$i }} + || {{= it.usePattern($pProperty) }}.test({{=$key}}) + {{~}} + {{?}} + {{? it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length }} + {{~ $pgPropertyKeys:$pgProperty:$i }} + || {{= it.usePattern($pgProperty) }}.test({{=$key}}) + {{~}} + {{?}} + ); + + if (isAdditional{{=$lvl}}) { + {{?}} + {{? $removeAdditional == 'all' }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{ + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + }} + {{? $noAdditional }} + {{? $removeAdditional }} + delete {{=$data}}[{{=$key}}]; + {{??}} + {{=$nextValid}} = false; + {{ + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + }} + {{# def.error:'additionalProperties' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{? $breakOnError }} break; {{?}} + {{?}} + {{?? $additionalIsSchema }} + {{? $removeAdditional == 'failing' }} + var {{=$errs}} = errors; + {{# def.setCompositeRule }} + + {{# def.validateAdditional }} + + if (!{{=$nextValid}}) { + errors = {{=$errs}}; + if (validate.errors !== null) { + if (errors) validate.errors.length = errors; + else validate.errors = null; + } + delete {{=$data}}[{{=$key}}]; + } + + {{# def.resetCompositeRule }} + {{??}} + {{# def.validateAdditional }} + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + {{?}} + {{?}} + {{ it.errorPath = $currentErrorPath; }} + {{?}} + {{? $someProperties }} + } + {{?}} + } + + {{# def.ifResultValid }} +{{?}} + +{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }} + +{{? $schemaKeys.length }} + {{~ $schemaKeys:$propertyKey }} + {{ var $sch = $schema[$propertyKey]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + var $prop = it.util.getProperty($propertyKey) + , $passData = $data + $prop + , $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + }} + + {{# def.generateSubschemaCode }} + + {{? {{# def.willOptimize }} }} + {{ + $code = {{# def._optimizeValidate }}; + var $useData = $passData; + }} + {{??}} + {{ var $useData = $nextData; }} + var {{=$nextData}} = {{=$passData}}; + {{?}} + + {{? $hasDefault }} + {{= $code }} + {{??}} + {{? $requiredHash && $requiredHash[$propertyKey] }} + if ({{=$useData}} === undefined) { + {{=$nextValid}} = false; + {{ + var $currentErrorPath = it.errorPath + , $currErrSchemaPath = $errSchemaPath + , $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + }} + {{# def.error:'required' }} + {{ $errSchemaPath = $currErrSchemaPath; }} + {{ it.errorPath = $currentErrorPath; }} + } else { + {{??}} + {{? $breakOnError }} + if ({{=$useData}} === undefined) { + {{=$nextValid}} = true; + } else { + {{??}} + if ({{=$useData}} !== undefined) { + {{?}} + {{?}} + + {{= $code }} + } + {{?}} {{ /* $hasDefault */ }} + {{?}} {{ /* def.nonEmptySchema */ }} + + {{# def.ifResultValid }} + {{~}} +{{?}} + +{{~ $pPropertyKeys:$pProperty }} + {{ var $sch = $pProperties[$pProperty]; }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + + it.util.escapeFragment($pProperty); + }} + + for (var {{=$key}} in {{=$data}}) { + {{# def.checkOwnProperty }} + if ({{= it.usePattern($pProperty) }}.test({{=$key}})) { + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + } + {{? $breakOnError }} else {{=$nextValid}} = true; {{?}} + } + + {{# def.ifResultValid }} + {{?}} {{ /* def.nonEmptySchema */ }} +{{~}} + + +{{? it.opts.v5 }} + {{~ $pgPropertyKeys:$pgProperty }} + {{ + var $pgSchema = $pgProperties[$pgProperty] + , $sch = $pgSchema.schema; + }} + + {{? {{# def.nonEmptySchema:$sch}} }} + {{ + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema'; + $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + + it.util.escapeFragment($pgProperty) + + '/schema'; + }} + + var pgPropCount{{=$lvl}} = 0; + + for (var {{=$key}} in {{=$data}}) { + {{# def.checkOwnProperty }} + if ({{= it.usePattern($pgProperty) }}.test({{=$key}})) { + pgPropCount{{=$lvl}}++; + + {{ + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + }} + + {{# def.generateSubschemaCode }} + {{# def.optimizeValidate }} + + {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} + } + {{? $breakOnError }} else {{=$nextValid}} = true; {{?}} + } + + {{# def.ifResultValid }} + + {{ + var $pgMin = $pgSchema.minimum + , $pgMax = $pgSchema.maximum; + }} + {{? $pgMin !== undefined || $pgMax !== undefined }} + var {{=$valid}} = true; + + {{ var $currErrSchemaPath = $errSchemaPath; }} + + {{? $pgMin !== undefined }} + {{ var $limit = $pgMin, $reason = 'minimum', $moreOrLess = 'less'; }} + {{=$valid}} = pgPropCount{{=$lvl}} >= {{=$pgMin}}; + {{ $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; }} + {{# def.checkError:'patternGroups' }} + {{? $pgMax !== undefined }} + else + {{?}} + {{?}} + + {{? $pgMax !== undefined }} + {{ var $limit = $pgMax, $reason = 'maximum', $moreOrLess = 'more'; }} + {{=$valid}} = pgPropCount{{=$lvl}} <= {{=$pgMax}}; + {{ $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; }} + {{# def.checkError:'patternGroups' }} + {{?}} + + {{ $errSchemaPath = $currErrSchemaPath; }} + + {{# def.ifValid }} + {{?}} + {{?}} {{ /* def.nonEmptySchema */ }} + {{~}} +{{?}} + + +{{? $breakOnError }} + {{= $closingBraces }} + if ({{=$errs}} == errors) { +{{?}} + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/ref.jst b/node_modules/ajv/lib/dot/ref.jst new file mode 100644 index 000000000..e8cdc4435 --- /dev/null +++ b/node_modules/ajv/lib/dot/ref.jst @@ -0,0 +1,86 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} + +{{## def._validateRef:_v: + {{? it.opts.passContext }} + {{=_v}}.call(this, + {{??}} + {{=_v}}( + {{?}} + {{=$data}}, {{# def.dataPath }}{{# def.passParentData }}, rootData) +#}} + +{{ var $async, $refCode; }} +{{? $schema == '#' || $schema == '#/' }} + {{ + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + }} +{{??}} + {{ var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); }} + {{? $refVal === undefined }} + {{ var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId; }} + {{? it.opts.missingRefs == 'fail' }} + {{ console.log($message); }} + {{# def.error:'$ref' }} + {{? $breakOnError }} if (false) { {{?}} + {{?? it.opts.missingRefs == 'ignore' }} + {{ console.log($message); }} + {{? $breakOnError }} if (true) { {{?}} + {{??}} + {{ + var $error = new Error($message); + $error.missingRef = it.resolve.url(it.baseId, $schema); + $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef)); + throw $error; + }} + {{?}} + {{?? $refVal.inline }} + {{# def.setupNextLevel }} + {{ + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + }} + {{ var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); }} + {{= $code }} + {{? $breakOnError}} + if ({{=$nextValid}}) { + {{?}} + {{??}} + {{ + $async = $refVal.$async === true; + $refCode = $refVal.code; + }} + {{?}} +{{?}} + +{{? $refCode }} + {{# def.beginDefOut}} + {{# def._validateRef:$refCode }} + {{# def.storeDefOut:__callValidate }} + + {{? $async }} + {{ if (!it.async) throw new Error('async schema referenced by sync schema'); }} + try { {{? $breakOnError }}var {{=$valid}} ={{?}} {{=it.yieldAwait}} {{=__callValidate}}; } + catch (e) { + if (!(e instanceof ValidationError)) throw e; + if (vErrors === null) vErrors = e.errors; + else vErrors = vErrors.concat(e.errors); + errors = vErrors.length; + } + {{? $breakOnError }} if ({{=$valid}}) { {{?}} + {{??}} + if (!{{=__callValidate}}) { + if (vErrors === null) vErrors = {{=$refCode}}.errors; + else vErrors = vErrors.concat({{=$refCode}}.errors); + errors = vErrors.length; + } {{? $breakOnError }} else { {{?}} + {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/required.jst b/node_modules/ajv/lib/dot/required.jst new file mode 100644 index 000000000..e109568f3 --- /dev/null +++ b/node_modules/ajv/lib/dot/required.jst @@ -0,0 +1,96 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.missing }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{ var $vSchema = 'schema' + $lvl; }} + +{{## def.setupLoop: + {{? !$isData }} + var {{=$vSchema}} = validate.schema{{=$schemaPath}}; + {{?}} + + {{ + var $i = 'i' + $lvl + , $propertyPath = 'schema' + $lvl + '[' + $i + ']' + , $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + }} +#}} + + +{{? !$isData }} + {{? $schema.length < it.opts.loopRequired && + it.schema.properties && Object.keys(it.schema.properties).length }} + {{ var $required = []; }} + {{~ $schema:$property }} + {{ var $propertySch = it.schema.properties[$property]; }} + {{? !($propertySch && {{# def.nonEmptySchema:$propertySch}}) }} + {{ $required[$required.length] = $property; }} + {{?}} + {{~}} + {{??}} + {{ var $required = $schema; }} + {{?}} +{{?}} + + +{{? $isData || $required.length }} + {{ + var $currentErrorPath = it.errorPath + , $loopRequired = $isData || $required.length >= it.opts.loopRequired; + }} + + {{? $breakOnError }} + var missing{{=$lvl}}; + {{? $loopRequired }} + {{# def.setupLoop }} + var {{=$valid}} = true; + + {{?$isData}}{{# def.check$dataIsArray }}{{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + {{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined; + if (!{{=$valid}}) break; + } + + {{? $isData }} } {{?}} + + {{# def.checkError:'required' }} + else { + {{??}} + if ({{# def.checkMissingProperty:$required }}) { + {{# def.errorMissingProperty:'required' }} + } else { + {{?}} + {{??}} + {{? $loopRequired }} + {{# def.setupLoop }} + {{? $isData }} + if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) { + {{# def.addError:'required' }} + } else if ({{=$vSchema}} !== undefined) { + {{?}} + + for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { + if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined) { + {{# def.addError:'required' }} + } + } + + {{? $isData }} } {{?}} + {{??}} + {{~ $required:$reqProperty }} + {{# def.allErrorsMissingProperty:'required' }} + {{~}} + {{?}} + {{?}} + + {{ it.errorPath = $currentErrorPath; }} + +{{?? $breakOnError }} + if (true) { +{{?}} diff --git a/node_modules/ajv/lib/dot/uniqueItems.jst b/node_modules/ajv/lib/dot/uniqueItems.jst new file mode 100644 index 000000000..dfc42b03b --- /dev/null +++ b/node_modules/ajv/lib/dot/uniqueItems.jst @@ -0,0 +1,38 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + + +{{? ($schema || $isData) && it.opts.uniqueItems !== false }} + {{? $isData }} + var {{=$valid}}; + if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined) + {{=$valid}} = true; + else if (typeof {{=$schemaValue}} != 'boolean') + {{=$valid}} = false; + else { + {{?}} + + var {{=$valid}} = true; + if ({{=$data}}.length > 1) { + var i = {{=$data}}.length, j; + outer: + for (;i--;) { + for (j = i; j--;) { + if (equal({{=$data}}[i], {{=$data}}[j])) { + {{=$valid}} = false; + break outer; + } + } + } + } + + {{? $isData }} } {{?}} + + if (!{{=$valid}}) { + {{# def.error:'uniqueItems' }} + } {{? $breakOnError }} else { {{?}} +{{??}} + {{? $breakOnError }} if (true) { {{?}} +{{?}} diff --git a/node_modules/ajv/lib/dot/v5/_formatLimit.jst b/node_modules/ajv/lib/dot/v5/_formatLimit.jst new file mode 100644 index 000000000..af16b88d8 --- /dev/null +++ b/node_modules/ajv/lib/dot/v5/_formatLimit.jst @@ -0,0 +1,116 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} + +var {{=$valid}} = undefined; + +{{## def.skipFormatLimit: + {{=$valid}} = true; + {{ return out; }} +#}} + +{{## def.compareFormat: + {{? $isData }} + if ({{=$schemaValue}} === undefined) {{=$valid}} = true; + else if (typeof {{=$schemaValue}} != 'string') {{=$valid}} = false; + else { + {{ $closingBraces += '}'; }} + {{?}} + + {{? $isDataFormat }} + if (!{{=$compare}}) {{=$valid}} = true; + else { + {{ $closingBraces += '}'; }} + {{?}} + + var {{=$result}} = {{=$compare}}({{=$data}}, {{# def.schemaValueQS }}); + + if ({{=$result}} === undefined) {{=$valid}} = false; +#}} + + +{{? it.opts.format === false }}{{# def.skipFormatLimit }}{{?}} + +{{ + var $schemaFormat = it.schema.format + , $isDataFormat = it.opts.v5 && $schemaFormat.$data + , $closingBraces = ''; +}} + +{{? $isDataFormat }} + {{ + var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr) + , $format = 'format' + $lvl + , $compare = 'compare' + $lvl; + }} + + var {{=$format}} = formats[{{=$schemaValueFormat}}] + , {{=$compare}} = {{=$format}} && {{=$format}}.compare; +{{??}} + {{ var $format = it.formats[$schemaFormat]; }} + {{? !($format && $format.compare) }} + {{# def.skipFormatLimit }} + {{?}} + {{ var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare'; }} +{{?}} + +{{ + var $isMax = $keyword == 'formatMaximum' + , $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum') + , $schemaExcl = it.schema[$exclusiveKeyword] + , $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data + , $op = $isMax ? '<' : '>' + , $result = 'result' + $lvl; +}} + +{{# def.$data }} + + +{{? $isDataExcl }} + {{ + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) + , $exclusive = 'exclusive' + $lvl + , $opExpr = 'op' + $lvl + , $opStr = '\' + ' + $opExpr + ' + \''; + }} + var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; + {{ $schemaValueExcl = 'schemaExcl' + $lvl; }} + + if (typeof {{=$schemaValueExcl}} != 'boolean' && {{=$schemaValueExcl}} !== undefined) { + {{=$valid}} = false; + {{ var $errorKeyword = $exclusiveKeyword; }} + {{# def.error:'_formatExclusiveLimit' }} + } + + {{# def.elseIfValid }} + + {{# def.compareFormat }} + var {{=$exclusive}} = {{=$schemaValueExcl}} === true; + + if ({{=$valid}} === undefined) { + {{=$valid}} = {{=$exclusive}} + ? {{=$result}} {{=$op}} 0 + : {{=$result}} {{=$op}}= 0; + } + + if (!{{=$valid}}) var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; +{{??}} + {{ + var $exclusive = $schemaExcl === true + , $opStr = $op; /*used in error*/ + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; /*used in error*/ + }} + + {{# def.compareFormat }} + + if ({{=$valid}} === undefined) + {{=$valid}} = {{=$result}} {{=$op}}{{?!$exclusive}}={{?}} 0; +{{?}} + +{{= $closingBraces }} + +if (!{{=$valid}}) { + {{ var $errorKeyword = $keyword; }} + {{# def.error:'_formatLimit' }} +} diff --git a/node_modules/ajv/lib/dot/v5/constant.jst b/node_modules/ajv/lib/dot/v5/constant.jst new file mode 100644 index 000000000..67969c1b9 --- /dev/null +++ b/node_modules/ajv/lib/dot/v5/constant.jst @@ -0,0 +1,10 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.$data }} + +{{? !$isData }} + var schema{{=$lvl}} = validate.schema{{=$schemaPath}}; +{{?}} +var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}}); +{{# def.checkError:'constant' }} diff --git a/node_modules/ajv/lib/dot/v5/patternRequired.jst b/node_modules/ajv/lib/dot/v5/patternRequired.jst new file mode 100644 index 000000000..9af2cdc9d --- /dev/null +++ b/node_modules/ajv/lib/dot/v5/patternRequired.jst @@ -0,0 +1,28 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} + +{{ + var $key = 'key' + $lvl + , $matched = 'patternMatched' + $lvl + , $closingBraces = '' + , $ownProperties = it.opts.ownProperties; +}} + +var {{=$valid}} = true; +{{~ $schema:$pProperty }} + var {{=$matched}} = false; + for (var {{=$key}} in {{=$data}}) { + {{# def.checkOwnProperty }} + {{=$matched}} = {{= it.usePattern($pProperty) }}.test({{=$key}}); + if ({{=$matched}}) break; + } + + {{ var $missingPattern = it.util.escapeQuotes($pProperty); }} + if (!{{=$matched}}) { + {{=$valid}} = false; + {{# def.addError:'patternRequired' }} + } {{# def.elseIfValid }} +{{~}} + +{{= $closingBraces }} diff --git a/node_modules/ajv/lib/dot/v5/switch.jst b/node_modules/ajv/lib/dot/v5/switch.jst new file mode 100644 index 000000000..389678e34 --- /dev/null +++ b/node_modules/ajv/lib/dot/v5/switch.jst @@ -0,0 +1,73 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.setupKeyword }} +{{# def.setupNextLevel }} + + +{{## def.validateIf: + {{# def.setCompositeRule }} + {{ $it.createErrors = false; }} + {{# def._validateSwitchRule:if }} + {{ $it.createErrors = true; }} + {{# def.resetCompositeRule }} + {{=$ifPassed}} = {{=$nextValid}}; +#}} + +{{## def.validateThen: + {{? typeof $sch.then == 'boolean' }} + {{? $sch.then === false }} + {{# def.error:'switch' }} + {{?}} + var {{=$nextValid}} = {{= $sch.then }}; + {{??}} + {{# def._validateSwitchRule:then }} + {{?}} +#}} + +{{## def._validateSwitchRule:_clause: + {{ + $it.schema = $sch._clause; + $it.schemaPath = $schemaPath + '[' + $caseIndex + ']._clause'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/_clause'; + }} + {{# def.insertSubschemaCode }} +#}} + +{{## def.switchCase: + {{? $sch.if && {{# def.nonEmptySchema:$sch.if }} }} + var {{=$errs}} = errors; + {{# def.validateIf }} + if ({{=$ifPassed}}) { + {{# def.validateThen }} + } else { + {{# def.resetErrors }} + } + {{??}} + {{=$ifPassed}} = true; + {{# def.validateThen }} + {{?}} +#}} + + +{{ + var $ifPassed = 'ifPassed' + it.level + , $currentBaseId = $it.baseId + , $shouldContinue; +}} +var {{=$ifPassed}}; + +{{~ $schema:$sch:$caseIndex }} + {{? $caseIndex && !$shouldContinue }} + if (!{{=$ifPassed}}) { + {{ $closingBraces+= '}'; }} + {{?}} + + {{# def.switchCase }} + {{ $shouldContinue = $sch.continue }} +{{~}} + +{{= $closingBraces }} + +var {{=$valid}} = {{=$nextValid}}; + +{{# def.cleanUp }} diff --git a/node_modules/ajv/lib/dot/validate.jst b/node_modules/ajv/lib/dot/validate.jst new file mode 100644 index 000000000..896e0860a --- /dev/null +++ b/node_modules/ajv/lib/dot/validate.jst @@ -0,0 +1,210 @@ +{{# def.definitions }} +{{# def.errors }} +{{# def.defaults }} +{{# def.coerce }} + +{{ /** + * schema compilation (render) time: + * it = { schema, RULES, _validate, opts } + * it.validate - this template function, + * it is used recursively to generate code for subschemas + * + * runtime: + * "validate" is a variable name to which this function will be assigned + * validateRef etc. are defined in the parent scope in index.js + */ }} + +{{ var $async = it.schema.$async === true; }} + +{{? it.isTop}} + {{ + var $top = it.isTop + , $lvl = it.level = 0 + , $dataLvl = it.dataLevel = 0 + , $data = 'data'; + it.rootId = it.resolve.fullPath(it.root.schema.id); + it.baseId = it.baseId || it.rootId; + if ($async) { + it.async = true; + var $es7 = it.opts.async == 'es7'; + it.yieldAwait = $es7 ? 'await' : 'yield'; + } + delete it.isTop; + + it.dataPathArr = [undefined]; + }} + + var validate = + {{? $async }} + {{? $es7 }} + (async function + {{??}} + {{? it.opts.async == 'co*'}}co.wrap{{?}}(function* + {{?}} + {{??}} + (function + {{?}} + (data, dataPath, parentData, parentDataProperty, rootData) { + 'use strict'; + var vErrors = null; {{ /* don't edit, used in replace */ }} + var errors = 0; {{ /* don't edit, used in replace */ }} + if (rootData === undefined) rootData = data; +{{??}} + {{ + var $lvl = it.level + , $dataLvl = it.dataLevel + , $data = 'data' + ($dataLvl || ''); + + if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id); + + if ($async && !it.async) throw new Error('async schema in sync schema'); + }} + + var errs_{{=$lvl}} = errors; +{{?}} + +{{ + var $valid = 'valid' + $lvl + , $breakOnError = !it.opts.allErrors + , $closingBraces1 = '' + , $closingBraces2 = ''; + + var $errorKeyword; + var $typeSchema = it.schema.type + , $typeIsArray = Array.isArray($typeSchema); +}} + +{{## def.checkType: + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type' + , $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + }} + + if ({{= it.util[$method]($typeSchema, $data, true) }}) { +#}} + +{{? $typeSchema && it.opts.coerceTypes }} + {{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }} + {{? $coerceToTypes }} + {{# def.checkType }} + {{# def.coerceType }} + } + {{?}} +{{?}} + +{{ var $refKeywords; }} +{{? it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref')) }} + {{? it.opts.extendRefs == 'fail' }} + {{ throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"'); }} + {{?? it.opts.extendRefs == 'ignore' }} + {{ + $refKeywords = false; + console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + }} + {{?? it.opts.extendRefs !== true }} + {{ console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour'); }} + {{?}} +{{?}} + +{{? it.schema.$ref && !$refKeywords }} + {{= it.RULES.all.$ref.code(it, '$ref') }} + {{? $breakOnError }} + } + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} +{{??}} + {{~ it.RULES:$rulesGroup }} + {{? $shouldUseGroup($rulesGroup) }} + {{? $rulesGroup.type }} + if ({{= it.util.checkDataType($rulesGroup.type, $data) }}) { + {{?}} + {{? it.opts.useDefaults && !it.compositeRule }} + {{? $rulesGroup.type == 'object' && it.schema.properties }} + {{# def.defaultProperties }} + {{?? $rulesGroup.type == 'array' && Array.isArray(it.schema.items) }} + {{# def.defaultItems }} + {{?}} + {{?}} + {{~ $rulesGroup.rules:$rule }} + {{? $shouldUseRule($rule) }} + {{= $rule.code(it, $rule.keyword) }} + {{? $breakOnError }} + {{ $closingBraces1 += '}'; }} + {{?}} + {{?}} + {{~}} + {{? $breakOnError }} + {{= $closingBraces1 }} + {{ $closingBraces1 = ''; }} + {{?}} + {{? $rulesGroup.type }} + } + {{? $typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes }} + {{ var $typeChecked = true; }} + else { + {{ + var $schemaPath = it.schemaPath + '.type' + , $errSchemaPath = it.errSchemaPath + '/type'; + }} + {{# def.error:'type' }} + } + {{?}} + {{?}} + + {{? $breakOnError }} + if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) { + {{ $closingBraces2 += '}'; }} + {{?}} + {{?}} + {{~}} +{{?}} + +{{? $typeSchema && !$typeChecked && !$coerceToTypes }} + {{# def.checkType }} + {{# def.error:'type' }} + } +{{?}} + +{{? $breakOnError }} {{= $closingBraces2 }} {{?}} + +{{? $top }} + {{? $async }} + if (errors === 0) return true; {{ /* don't edit, used in replace */ }} + else throw new ValidationError(vErrors); {{ /* don't edit, used in replace */ }} + {{??}} + validate.errors = vErrors; {{ /* don't edit, used in replace */ }} + return errors === 0; {{ /* don't edit, used in replace */ }} + {{?}} + }); + + return validate; +{{??}} + var {{=$valid}} = errors === errs_{{=$lvl}}; +{{?}} + +{{# def.cleanUp }} + +{{? $top && $breakOnError }} + {{# def.cleanUpVarErrors }} +{{?}} + +{{ + function $shouldUseGroup($rulesGroup) { + for (var i=0; i < $rulesGroup.rules.length; i++) + if ($shouldUseRule($rulesGroup.rules[i])) + return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || + ( $rule.keyword == 'properties' && + ( it.schema.additionalProperties === false || + typeof it.schema.additionalProperties == 'object' + || ( it.schema.patternProperties && + Object.keys(it.schema.patternProperties).length ) + || ( it.opts.v5 && it.schema.patternGroups && + Object.keys(it.schema.patternGroups).length ))); + } +}} diff --git a/node_modules/ajv/lib/dotjs/README.md b/node_modules/ajv/lib/dotjs/README.md new file mode 100644 index 000000000..4d994846c --- /dev/null +++ b/node_modules/ajv/lib/dotjs/README.md @@ -0,0 +1,3 @@ +These files are compiled dot templates from dot folder. + +Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. diff --git a/node_modules/ajv/lib/dotjs/_formatLimit.js b/node_modules/ajv/lib/dotjs/_formatLimit.js new file mode 100644 index 000000000..996e1f2c2 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_formatLimit.js @@ -0,0 +1,176 @@ +'use strict'; +module.exports = function generate__formatLimit(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + out += 'var ' + ($valid) + ' = undefined;'; + if (it.opts.format === false) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $schemaFormat = it.schema.format, + $isDataFormat = it.opts.v5 && $schemaFormat.$data, + $closingBraces = ''; + if ($isDataFormat) { + var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr), + $format = 'format' + $lvl, + $compare = 'compare' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;'; + } else { + var $format = it.formats[$schemaFormat]; + if (!($format && $format.compare)) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare'; + } + var $isMax = $keyword == 'formatMaximum', + $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'), + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $result = 'result' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op); + if (!$exclusive) { + out += '='; + } + out += ' 0;'; + } + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '}'; + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limit.js b/node_modules/ajv/lib/dotjs/_limit.js new file mode 100644 index 000000000..4d92024af --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limit.js @@ -0,0 +1,124 @@ +'use strict'; +module.exports = function generate__limit(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<'; + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp); + if ($exclusive) { + out += '='; + } + out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {'; + } + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schema) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limitItems.js b/node_modules/ajv/lib/dotjs/_limitItems.js new file mode 100644 index 000000000..6a843627b --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limitItems.js @@ -0,0 +1,76 @@ +'use strict'; +module.exports = function generate__limitItems(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'less'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limitLength.js b/node_modules/ajv/lib/dotjs/_limitLength.js new file mode 100644 index 000000000..e378104df --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limitLength.js @@ -0,0 +1,81 @@ +'use strict'; +module.exports = function generate__limitLength(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' characters\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/_limitProperties.js b/node_modules/ajv/lib/dotjs/_limitProperties.js new file mode 100644 index 000000000..74c085184 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/_limitProperties.js @@ -0,0 +1,76 @@ +'use strict'; +module.exports = function generate__limitProperties(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'less'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/allOf.js b/node_modules/ajv/lib/dotjs/allOf.js new file mode 100644 index 000000000..0063ecf1a --- /dev/null +++ b/node_modules/ajv/lib/dotjs/allOf.js @@ -0,0 +1,43 @@ +'use strict'; +module.exports = function generate_allOf(it, $keyword) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/anyOf.js b/node_modules/ajv/lib/dotjs/anyOf.js new file mode 100644 index 000000000..c95f8ff9a --- /dev/null +++ b/node_modules/ajv/lib/dotjs/anyOf.js @@ -0,0 +1,65 @@ +'use strict'; +module.exports = function generate_anyOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return it.util.schemaHasRules($sch, it.RULES.all); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/constant.js b/node_modules/ajv/lib/dotjs/constant.js new file mode 100644 index 000000000..2a3e147ff --- /dev/null +++ b/node_modules/ajv/lib/dotjs/constant.js @@ -0,0 +1,52 @@ +'use strict'; +module.exports = function generate_constant(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('constant') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + return out; +} diff --git a/node_modules/ajv/lib/dotjs/custom.js b/node_modules/ajv/lib/dotjs/custom.js new file mode 100644 index 000000000..cbd481ccf --- /dev/null +++ b/node_modules/ajv/lib/dotjs/custom.js @@ -0,0 +1,220 @@ +'use strict'; +module.exports = function generate_custom(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($validateSchema) { + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {'; + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += '' + (it.yieldAwait); + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + if ($validateSchema) { + out += ' }'; + } + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/multipleOf.js b/node_modules/ajv/lib/dotjs/multipleOf.js new file mode 100644 index 000000000..d0e43daa3 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/multipleOf.js @@ -0,0 +1,76 @@ +'use strict'; +module.exports = function generate_multipleOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schema) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/not.js b/node_modules/ajv/lib/dotjs/not.js new file mode 100644 index 000000000..2cb2a4765 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/not.js @@ -0,0 +1,83 @@ +'use strict'; +module.exports = function generate_not(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/oneOf.js b/node_modules/ajv/lib/dotjs/oneOf.js new file mode 100644 index 000000000..39f60e620 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/oneOf.js @@ -0,0 +1,76 @@ +'use strict'; +module.exports = function generate_oneOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;'; + var $currentBaseId = $it.baseId; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/pattern.js b/node_modules/ajv/lib/dotjs/pattern.js new file mode 100644 index 000000000..5518152a8 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/pattern.js @@ -0,0 +1,74 @@ +'use strict'; +module.exports = function generate_pattern(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/patternRequired.js b/node_modules/ajv/lib/dotjs/patternRequired.js new file mode 100644 index 000000000..07bf31d29 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/patternRequired.js @@ -0,0 +1,51 @@ +'use strict'; +module.exports = function generate_patternRequired(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $key = 'key' + $lvl, + $matched = 'patternMatched' + $lvl, + $closingBraces = '', + $ownProperties = it.opts.ownProperties; + out += 'var ' + ($valid) + ' = true;'; + var arr1 = $schema; + if (arr1) { + var $pProperty, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $pProperty = arr1[i1 += 1]; + out += ' var ' + ($matched) + ' = false; for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } '; + var $missingPattern = it.util.escapeQuotes($pProperty); + out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + out += '' + ($closingBraces); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/properties.js b/node_modules/ajv/lib/dotjs/properties.js new file mode 100644 index 000000000..32eafce6a --- /dev/null +++ b/node_modules/ajv/lib/dotjs/properties.js @@ -0,0 +1,445 @@ +'use strict'; +module.exports = function generate_properties(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt; + var $schemaKeys = Object.keys($schema || {}), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); + if (it.opts.v5) { + var $pgProperties = it.schema.patternGroups || {}, + $pgPropertyKeys = Object.keys($pgProperties); + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($checkAdditional) { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 5) { + out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) { + var arr3 = $pgPropertyKeys; + if (arr3) { + var $pgProperty, $i = -1, + l3 = arr3.length - 1; + while ($i < l3) { + $pgProperty = arr3[$i += 1]; + out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have additional properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr4 = $schemaKeys; + if (arr4) { + var $propertyKey, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $propertyKey = arr4[i4 += 1]; + var $sch = $schema[$propertyKey]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + var arr5 = $pPropertyKeys; + if (arr5) { + var $pProperty, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $pProperty = arr5[i5 += 1]; + var $sch = $pProperties[$pProperty]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (it.opts.v5) { + var arr6 = $pgPropertyKeys; + if (arr6) { + var $pgProperty, i6 = -1, + l6 = arr6.length - 1; + while (i6 < l6) { + $pgProperty = arr6[i6 += 1]; + var $pgSchema = $pgProperties[$pgProperty], + $sch = $pgSchema.schema; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema'; + $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema'; + out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + var $pgMin = $pgSchema.minimum, + $pgMax = $pgSchema.maximum; + if ($pgMin !== undefined || $pgMax !== undefined) { + out += ' var ' + ($valid) + ' = true; '; + var $currErrSchemaPath = $errSchemaPath; + if ($pgMin !== undefined) { + var $limit = $pgMin, + $reason = 'minimum', + $moreOrLess = 'less'; + out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($pgMax !== undefined) { + out += ' else '; + } + } + if ($pgMax !== undefined) { + var $limit = $pgMax, + $reason = 'maximum', + $moreOrLess = 'more'; + out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/ref.js b/node_modules/ajv/lib/dotjs/ref.js new file mode 100644 index 000000000..e07c70c3b --- /dev/null +++ b/node_modules/ajv/lib/dotjs/ref.js @@ -0,0 +1,119 @@ +'use strict'; +module.exports = function generate_ref(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); + if ($refVal === undefined) { + var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId; + if (it.opts.missingRefs == 'fail') { + console.log($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; + } + if (it.opts.verbose) { + out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + console.log($message); + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + var $error = new Error($message); + $error.missingRef = it.resolve.url(it.baseId, $schema); + $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef)); + throw $error; + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + ($code) + ' '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + } + } else { + $async = $refVal.$async === true; + $refCode = $refVal.code; + } + } + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; + } else { + out += ' ' + ($refCode) + '( '; + } + out += ' ' + ($data) + ', (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); + out += ' try { '; + if ($breakOnError) { + out += 'var ' + ($valid) + ' ='; + } + out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + } + } else { + out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' else { '; + } + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/required.js b/node_modules/ajv/lib/dotjs/required.js new file mode 100644 index 000000000..eb32aeae5 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/required.js @@ -0,0 +1,249 @@ +'use strict'; +module.exports = function generate_required(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var _$property, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + _$property = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty(_$property); + out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $reqProperty, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $reqProperty = arr3[i3 += 1]; + var $prop = it.util.getProperty($reqProperty), + $missingProperty = it.util.escapeQuotes($reqProperty); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); + } + out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/switch.js b/node_modules/ajv/lib/dotjs/switch.js new file mode 100644 index 000000000..18f17e487 --- /dev/null +++ b/node_modules/ajv/lib/dotjs/switch.js @@ -0,0 +1,128 @@ +'use strict'; +module.exports = function generate_switch(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $ifPassed = 'ifPassed' + it.level, + $currentBaseId = $it.baseId, + $shouldContinue; + out += 'var ' + ($ifPassed) + ';'; + var arr1 = $schema; + if (arr1) { + var $sch, $caseIndex = -1, + l1 = arr1.length - 1; + while ($caseIndex < l1) { + $sch = arr1[$caseIndex += 1]; + if ($caseIndex && !$shouldContinue) { + out += ' if (!' + ($ifPassed) + ') { '; + $closingBraces += '}'; + } + if ($sch.if && it.util.schemaHasRules($sch.if, it.RULES.all)) { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + $it.schema = $sch.if; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } '; + } else { + out += ' ' + ($ifPassed) + ' = true; '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + } + $shouldContinue = $sch.continue + } + } + out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + '; '; + out = it.util.cleanUpCode(out); + return out; +} diff --git a/node_modules/ajv/lib/dotjs/uniqueItems.js b/node_modules/ajv/lib/dotjs/uniqueItems.js new file mode 100644 index 000000000..2f27b0eea --- /dev/null +++ b/node_modules/ajv/lib/dotjs/uniqueItems.js @@ -0,0 +1,71 @@ +'use strict'; +module.exports = function generate_uniqueItems(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} diff --git a/node_modules/ajv/lib/dotjs/validate.js b/node_modules/ajv/lib/dotjs/validate.js new file mode 100644 index 000000000..0c4112e1d --- /dev/null +++ b/node_modules/ajv/lib/dotjs/validate.js @@ -0,0 +1,375 @@ +'use strict'; +module.exports = function generate_validate(it, $keyword) { + var out = ''; + var $async = it.schema.$async === true; + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.root.schema.id); + it.baseId = it.baseId || it.rootId; + if ($async) { + it.async = true; + var $es7 = it.opts.async == 'es7'; + it.yieldAwait = $es7 ? 'await' : 'yield'; + } + delete it.isTop; + it.dataPathArr = [undefined]; + out += ' var validate = '; + if ($async) { + if ($es7) { + out += ' (async function '; + } else { + if (it.opts.async == 'co*') { + out += 'co.wrap'; + } + out += '(function* '; + } + } else { + out += ' (function '; + } + out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data;'; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + if ($coerceToTypes) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; + } + out += ' var ' + ($coerced) + ' = undefined; '; + var $bracesCoercion = ''; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($i) { + out += ' if (' + ($coerced) + ' === undefined) { '; + $bracesCoercion += '}'; + } + if (it.opts.coerceTypes == 'array' && $type != 'array') { + out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; + } + if ($type == 'string') { + out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } '; + } + } + var $refKeywords; + if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"'); + } else if (it.opts.extendRefs == 'ignore') { + $refKeywords = false; + console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } else if (it.opts.extendRefs !== true) { + console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour'); + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { '; + } + if (it.opts.useDefaults && !it.compositeRule) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + out += ' ' + ($rule.code(it, $rule.keyword)) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + var $typeChecked = true; + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($typeSchema && !$typeChecked && !$coerceToTypes) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return true; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }); return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + out = it.util.cleanUpCode(out); + if ($top && $breakOnError) { + out = it.util.cleanUpVarErrors(out, $async); + } + + function $shouldUseGroup($rulesGroup) { + for (var i = 0; i < $rulesGroup.rules.length; i++) + if ($shouldUseRule($rulesGroup.rules[i])) return true; + } + + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length))); + } + return out; +} diff --git a/node_modules/ajv/lib/keyword.js b/node_modules/ajv/lib/keyword.js new file mode 100644 index 000000000..1c9cccfe6 --- /dev/null +++ b/node_modules/ajv/lib/keyword.js @@ -0,0 +1,129 @@ +'use strict'; + +var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i; +var customRuleCode = require('./dotjs/custom'); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword +}; + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + if (definition.macro && definition.valid !== undefined) + throw new Error('"valid" option cannot be used with macro keywords'); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + var i, len = dataType.length; + for (i=0; i=4.9.1-0 <5.0.0-0", + "_id": "ajv@4.11.8", + "_inCache": true, + "_location": "/ajv", + "_nodeVersion": "4.6.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/ajv-4.11.8.tgz_1493407396661_0.6132844805251807" + }, + "_npmUser": { + "email": "e.poberezkin@me.com", + "name": "esp" + }, + "_npmVersion": "2.15.9", + "_phantomChildren": {}, + "_requested": { + "name": "ajv", + "raw": "ajv@^4.9.1", + "rawSpec": "^4.9.1", + "scope": null, + "spec": ">=4.9.1-0 <5.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/har-validator" + ], + "_resolved": "https://registry.npmjs.org/ajv/-/ajv-4.11.8.tgz", + "_shasum": "82ffb02b29e662ae53bdc20af15947706739c536", + "_shrinkwrap": null, + "_spec": "ajv@^4.9.1", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\har-validator", + "author": { + "name": "Evgeny Poberezkin" + }, + "bugs": { + "url": "https://github.com/epoberezkin/ajv/issues" + }, + "dependencies": { + "co": "^4.6.0", + "json-stable-stringify": "^1.0.1" + }, + "description": "Another JSON Schema Validator", + "devDependencies": { + "bluebird": "^3.1.5", + "brfs": "^1.4.3", + "browserify": "^14.1.0", + "chai": "^3.5.0", + "coveralls": "^2.11.4", + "del-cli": "^0.2.1", + "dot": "^1.0.3", + "eslint": "^3.2.2", + "gh-pages-generator": "^0.2.0", + "glob": "^7.0.0", + "if-node-version": "^1.0.0", + "js-beautify": "^1.5.6", + "jshint": "^2.8.0", + "json-schema-test": "^1.1.1", + "karma": "^1.0.0", + "karma-chrome-launcher": "^2.0.0", + "karma-mocha": "^1.1.1", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sauce-launcher": "^1.1.0", + "mocha": "^3.0.0", + "nodent": "^3.0.17", + "nyc": "^10.0.0", + "phantomjs-prebuilt": "^2.1.4", + "pre-commit": "^1.1.1", + "regenerator": "0.9.7", + "require-globify": "^1.3.0", + "typescript": "^2.0.3", + "uglify-js": "^2.6.1", + "watch": "^1.0.0" + }, + "directories": {}, + "dist": { + "shasum": "82ffb02b29e662ae53bdc20af15947706739c536", + "tarball": "https://registry.npmjs.org/ajv/-/ajv-4.11.8.tgz" + }, + "files": [ + ".tonic_example.js", + "LICENSE", + "dist/", + "lib/", + "scripts/" + ], + "gitHead": "de9fad502273ade9bdcf976e418bdd5b61b14a07", + "homepage": "https://github.com/epoberezkin/ajv", + "installable": true, + "keywords": [ + "JSON", + "json-schema", + "json-schema-validation", + "json-schema-validator", + "jsonschema", + "schema", + "validation", + "validator" + ], + "license": "MIT", + "main": "lib/ajv.js", + "maintainers": [ + { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" + }, + { + "name": "esp", + "email": "e.poberezkin@me.com" + } + ], + "name": "ajv", + "nyc": { + "exclude": [ + "**/spec/**", + "node_modules" + ], + "reporter": [ + "lcov", + "text-summary" + ] + }, + "optionalDependencies": {}, + "publishConfig": { + "tag": "4.x" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/epoberezkin/ajv.git" + }, + "scripts": { + "build": "del-cli lib/dotjs/*.js && node scripts/compile-dots.js", + "bundle": "node ./scripts/bundle.js . Ajv pure_getters", + "bundle-all": "del-cli dist && npm run bundle && npm run bundle-regenerator && npm run bundle-nodent", + "bundle-beautify": "node ./scripts/bundle.js js-beautify", + "bundle-nodent": "node ./scripts/bundle.js nodent", + "bundle-regenerator": "node ./scripts/bundle.js regenerator", + "eslint": "if-node-version \">=4\" eslint lib/*.js lib/compile/*.js spec scripts", + "jshint": "jshint lib/*.js lib/**/*.js --exclude lib/dotjs/**/*", + "prepublish": "npm run build && npm run bundle-all", + "test": "npm run jshint && npm run eslint && npm run test-ts && npm run build && npm run test-cov && if-node-version 4 npm run test-browser", + "test-browser": "del-cli .browser && npm run bundle-all && scripts/prepare-tests && npm run test-karma", + "test-cov": "nyc npm run test-spec", + "test-debug": "mocha spec/*.spec.js --debug-brk -R spec", + "test-fast": "AJV_FAST_TEST=true npm run test-spec", + "test-karma": "karma start --single-run --browsers PhantomJS", + "test-spec": "mocha spec/*.spec.js -R spec", + "test-ts": "tsc --target ES5 --noImplicitAny lib/ajv.d.ts", + "watch": "watch 'npm run build' ./lib/dot" + }, + "tonicExampleFilename": ".tonic_example.js", + "typings": "lib/ajv.d.ts", + "version": "4.11.8", + "webpack": "dist/ajv.bundle.js" +} diff --git a/node_modules/ajv/scripts/.eslintrc.yml b/node_modules/ajv/scripts/.eslintrc.yml new file mode 100644 index 000000000..493d7d312 --- /dev/null +++ b/node_modules/ajv/scripts/.eslintrc.yml @@ -0,0 +1,3 @@ +rules: + no-console: 0 + no-empty: [2, allowEmptyCatch: true] diff --git a/node_modules/ajv/scripts/bundle.js b/node_modules/ajv/scripts/bundle.js new file mode 100644 index 000000000..b3a9890c5 --- /dev/null +++ b/node_modules/ajv/scripts/bundle.js @@ -0,0 +1,54 @@ +'use strict'; + +var fs = require('fs') + , path = require('path') + , browserify = require('browserify') + , uglify = require('uglify-js'); + +var pkg = process.argv[2] + , standalone = process.argv[3] + , compress = process.argv[4]; + +var packageDir = path.join(__dirname, '..'); +if (pkg != '.') packageDir = path.join(packageDir, 'node_modules', pkg); + +var json = require(path.join(packageDir, 'package.json')); + +var distDir = path.join(__dirname, '..', 'dist'); +if (!fs.existsSync(distDir)) fs.mkdirSync(distDir); + +var bOpts = {}; +if (standalone) bOpts.standalone = standalone; + +browserify(bOpts) +.require(path.join(packageDir, json.main), {expose: json.name}) +.bundle(function (err, buf) { + if (err) { + console.error('browserify error:', err); + process.exit(1); + } + + var outputFile = path.join(distDir, json.name); + var outputBundle = outputFile + '.bundle.js'; + fs.writeFileSync(outputBundle, buf); + var uglifyOpts = { + warnings: true, + compress: {}, + output: { + preamble: '/* ' + json.name + ' ' + json.version + ': ' + json.description + ' */' + } + }; + if (compress) { + var compressOpts = compress.split(','); + for (var i=0; i]+ajv_logo[^>]+>//" index.md + git config user.email "$GIT_USER_EMAIL" + git config user.name "$GIT_USER_NAME" + git add . + git commit -am "updated by travis build #$TRAVIS_BUILD_NUMBER" + git push --quiet origin gh-pages > /dev/null 2>&1 + } +fi diff --git a/node_modules/asn1/.npmignore b/node_modules/asn1/.npmignore new file mode 100644 index 000000000..eb03e3e1e --- /dev/null +++ b/node_modules/asn1/.npmignore @@ -0,0 +1,2 @@ +node_modules +*.log diff --git a/node_modules/asn1/.travis.yml b/node_modules/asn1/.travis.yml new file mode 100644 index 000000000..09d3ef378 --- /dev/null +++ b/node_modules/asn1/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.8 + - 0.10 diff --git a/node_modules/asn1/LICENSE b/node_modules/asn1/LICENSE new file mode 100644 index 000000000..9b5dcdb7f --- /dev/null +++ b/node_modules/asn1/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Mark Cavage, 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/asn1/README.md b/node_modules/asn1/README.md new file mode 100644 index 000000000..7cebf7a2e --- /dev/null +++ b/node_modules/asn1/README.md @@ -0,0 +1,50 @@ +node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. +Currently BER encoding is supported; at some point I'll likely have to do DER. + +## Usage + +Mostly, if you're *actually* needing to read and write ASN.1, you probably don't +need this readme to explain what and why. If you have no idea what ASN.1 is, +see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc + +The source is pretty much self-explanatory, and has read/write methods for the +common types out there. + +### Decoding + +The following reads an ASN.1 sequence with a boolean. + + var Ber = require('asn1').Ber; + + var reader = new Ber.Reader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff])); + + reader.readSequence(); + console.log('Sequence len: ' + reader.length); + if (reader.peek() === Ber.Boolean) + console.log(reader.readBoolean()); + +### Encoding + +The following generates the same payload as above. + + var Ber = require('asn1').Ber; + + var writer = new Ber.Writer(); + + writer.startSequence(); + writer.writeBoolean(true); + writer.endSequence(); + + console.log(writer.buffer); + +## Installation + + npm install asn1 + +## License + +MIT. + +## Bugs + +See . diff --git a/node_modules/asn1/lib/ber/errors.js b/node_modules/asn1/lib/ber/errors.js new file mode 100644 index 000000000..ff21d4fab --- /dev/null +++ b/node_modules/asn1/lib/ber/errors.js @@ -0,0 +1,13 @@ +// Copyright 2011 Mark Cavage All rights reserved. + + +module.exports = { + + newInvalidAsn1Error: function(msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } + +}; diff --git a/node_modules/asn1/lib/ber/index.js b/node_modules/asn1/lib/ber/index.js new file mode 100644 index 000000000..4fb90aea9 --- /dev/null +++ b/node_modules/asn1/lib/ber/index.js @@ -0,0 +1,27 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var errors = require('./errors'); +var types = require('./types'); + +var Reader = require('./reader'); +var Writer = require('./writer'); + + +///--- Exports + +module.exports = { + + Reader: Reader, + + Writer: Writer + +}; + +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; +} diff --git a/node_modules/asn1/lib/ber/reader.js b/node_modules/asn1/lib/ber/reader.js new file mode 100644 index 000000000..0a00e98e3 --- /dev/null +++ b/node_modules/asn1/lib/ber/reader.js @@ -0,0 +1,261 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var assert = require('assert'); + +var ASN1 = require('./types'); +var errors = require('./errors'); + + +///--- Globals + +var newInvalidAsn1Error = errors.newInvalidAsn1Error; + + + +///--- API + +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); + + this._buf = data; + this._size = data.length; + + // These hold the "current" state + this._len = 0; + this._offset = 0; +} + +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); + +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); + +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); + +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); + + +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ +Reader.prototype.readByte = function(peek) { + if (this._size - this._offset < 1) + return null; + + var b = this._buf[this._offset] & 0xff; + + if (!peek) + this._offset += 1; + + return b; +}; + + +Reader.prototype.peek = function() { + return this.readByte(true); +}; + + +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ +Reader.prototype.readLength = function(offset) { + if (offset === undefined) + offset = this._offset; + + if (offset >= this._size) + return null; + + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; + + if ((lenB & 0x80) == 0x80) { + lenB &= 0x7f; + + if (lenB == 0) + throw newInvalidAsn1Error('Indefinite length not supported'); + + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); + + if (this._size - offset < lenB) + return null; + + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + + } else { + // Wasn't a variable length + this._len = lenB; + } + + return offset; +}; + + +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function(tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); + + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; + + this._offset = o; + return seq; +}; + + +Reader.prototype.readInt = function() { + return this._readTag(ASN1.Integer); +}; + + +Reader.prototype.readBoolean = function() { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; + + +Reader.prototype.readEnumeration = function() { + return this._readTag(ASN1.Enumeration); +}; + + +Reader.prototype.readString = function(tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; + + var b = this.peek(); + if (b === null) + return null; + + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); + + var o = this.readLength(this._offset + 1); // stored in `length` + + if (o === null) + return null; + + if (this.length > this._size - o) + return null; + + this._offset = o; + + if (this.length === 0) + return retbuf ? new Buffer(0) : ''; + + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; + + return retbuf ? str : str.toString('utf8'); +}; + +Reader.prototype.readOID = function(tag) { + if (!tag) + tag = ASN1.OID; + + var b = this.readString(tag, true); + if (b === null) + return null; + + var values = []; + var value = 0; + + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; + + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) == 0) { + values.push(value); + value = 0; + } + } + + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); + + return values.join('.'); +}; + + +Reader.prototype._readTag = function(tag) { + assert.ok(tag !== undefined); + + var b = this.peek(); + + if (b === null) + return null; + + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); + + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; + + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); + + if (this.length > this._size - o) + return null; + this._offset = o; + + var fb = this._buf[this._offset]; + var value = 0; + + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); + } + + if ((fb & 0x80) == 0x80 && i !== 4) + value -= (1 << (i * 8)); + + return value >> 0; +}; + + + +///--- Exported API + +module.exports = Reader; diff --git a/node_modules/asn1/lib/ber/types.js b/node_modules/asn1/lib/ber/types.js new file mode 100644 index 000000000..8aea00013 --- /dev/null +++ b/node_modules/asn1/lib/ber/types.js @@ -0,0 +1,36 @@ +// Copyright 2011 Mark Cavage All rights reserved. + + +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; diff --git a/node_modules/asn1/lib/ber/writer.js b/node_modules/asn1/lib/ber/writer.js new file mode 100644 index 000000000..d9d99af68 --- /dev/null +++ b/node_modules/asn1/lib/ber/writer.js @@ -0,0 +1,316 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var assert = require('assert'); +var ASN1 = require('./types'); +var errors = require('./errors'); + + +///--- Globals + +var newInvalidAsn1Error = errors.newInvalidAsn1Error; + +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; + + +///--- Helpers + +function merge(from, to) { + assert.ok(from); + assert.equal(typeof(from), 'object'); + assert.ok(to); + assert.equal(typeof(to), 'object'); + + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function(key) { + if (to[key]) + return; + + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); + + return to; +} + + + +///--- API + +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); + + this._buf = new Buffer(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; + + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; +} + +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)'); + + return (this._buf.slice(0, this._offset)); + } +}); + +Writer.prototype.writeByte = function(b) { + if (typeof(b) !== 'number') + throw new TypeError('argument must be a Number'); + + this._ensure(1); + this._buf[this._offset++] = b; +}; + + +Writer.prototype.writeInt = function(i, tag) { + if (typeof(i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof(tag) !== 'number') + tag = ASN1.Integer; + + var sz = 4; + + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; + } + + if (sz > 4) + throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff'); + + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; + + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } + +}; + + +Writer.prototype.writeNull = function() { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; + + +Writer.prototype.writeEnumeration = function(i, tag) { + if (typeof(i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof(tag) !== 'number') + tag = ASN1.Enumeration; + + return this.writeInt(i, tag); +}; + + +Writer.prototype.writeBoolean = function(b, tag) { + if (typeof(b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof(tag) !== 'number') + tag = ASN1.Boolean; + + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; + + +Writer.prototype.writeString = function(s, tag) { + if (typeof(s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof(s) + ')'); + if (typeof(tag) !== 'number') + tag = ASN1.OctetString; + + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; + + +Writer.prototype.writeBuffer = function(buf, tag) { + if (typeof(tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); + + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; + + +Writer.prototype.writeStringArray = function(strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); + + var self = this; + strings.forEach(function(s) { + self.writeString(s); + }); +}; + +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function(s, tag) { + if (typeof(s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof(tag) !== 'number') + tag = ASN1.OID; + + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } + } + + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function(b) { + encodeOctet(bytes, parseInt(b, 10)); + }); + + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function(b) { + self.writeByte(b); + }); +}; + + +Writer.prototype.writeLength = function(len) { + if (typeof(len) !== 'number') + throw new TypeError('argument must be a Number'); + + this._ensure(4); + + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw new InvalidAsn1ERror('Length too long (> 4 bytes)'); + } +}; + +Writer.prototype.startSequence = function(tag) { + if (typeof(tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; + + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; + + +Writer.prototype.endSequence = function() { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; + + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw new InvalidAsn1Error('Sequence too long'); + } +}; + + +Writer.prototype._shift = function(start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); + + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; + +Writer.prototype._ensure = function(len) { + assert.ok(len); + + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; + + var buf = new Buffer(sz); + + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; + } +}; + + + +///--- Exported API + +module.exports = Writer; diff --git a/node_modules/asn1/lib/index.js b/node_modules/asn1/lib/index.js new file mode 100644 index 000000000..d1766e7a6 --- /dev/null +++ b/node_modules/asn1/lib/index.js @@ -0,0 +1,20 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +// If you have no idea what ASN.1 or BER is, see this: +// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc + +var Ber = require('./ber/index'); + + + +///--- Exported API + +module.exports = { + + Ber: Ber, + + BerReader: Ber.Reader, + + BerWriter: Ber.Writer + +}; diff --git a/node_modules/asn1/package.json b/node_modules/asn1/package.json new file mode 100644 index 000000000..b5a2b83bb --- /dev/null +++ b/node_modules/asn1/package.json @@ -0,0 +1,89 @@ +{ + "_args": [ + [ + "asn1@~0.2.3", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\sshpk" + ] + ], + "_from": "asn1@>=0.2.3-0 <0.3.0-0", + "_id": "asn1@0.2.3", + "_inCache": true, + "_location": "/asn1", + "_npmUser": { + "email": "patrick.f.mooney@gmail.com", + "name": "pfmooney" + }, + "_npmVersion": "1.4.28", + "_phantomChildren": {}, + "_requested": { + "name": "asn1", + "raw": "asn1@~0.2.3", + "rawSpec": "~0.2.3", + "scope": null, + "spec": ">=0.2.3-0 <0.3.0-0", + "type": "range" + }, + "_requiredBy": [ + "/sshpk" + ], + "_resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz", + "_shasum": "dac8787713c9966849fc8180777ebe9c1ddf3b86", + "_shrinkwrap": null, + "_spec": "asn1@~0.2.3", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\sshpk", + "author": { + "email": "mcavage@gmail.com", + "name": "Mark Cavage" + }, + "bugs": { + "url": "https://github.com/mcavage/node-asn1/issues" + }, + "contributors": [ + { + "name": "David Gwynne", + "email": "loki@animata.net" + }, + { + "name": "Yunong Xiao", + "email": "yunong@joyent.com" + }, + { + "name": "Alex Wilson", + "email": "alex.wilson@joyent.com" + } + ], + "dependencies": {}, + "description": "Contains parsers and serializers for ASN.1 (currently BER only)", + "devDependencies": { + "tap": "0.4.8" + }, + "directories": {}, + "dist": { + "shasum": "dac8787713c9966849fc8180777ebe9c1ddf3b86", + "tarball": "https://registry.npmjs.org/asn1/-/asn1-0.2.3.tgz" + }, + "homepage": "https://github.com/mcavage/node-asn1", + "installable": true, + "license": "MIT", + "main": "lib/index.js", + "maintainers": [ + { + "name": "mcavage", + "email": "mcavage@gmail.com" + }, + { + "name": "pfmooney", + "email": "patrick.f.mooney@gmail.com" + } + ], + "name": "asn1", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/mcavage/node-asn1.git" + }, + "scripts": { + "test": "tap ./tst" + }, + "version": "0.2.3" +} diff --git a/node_modules/asn1/tst/ber/reader.test.js b/node_modules/asn1/tst/ber/reader.test.js new file mode 100644 index 000000000..062fd7ee3 --- /dev/null +++ b/node_modules/asn1/tst/ber/reader.test.js @@ -0,0 +1,208 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var test = require('tap').test; + + + +///--- Globals + +var BerReader; + + + +///--- Tests + +test('load library', function(t) { + BerReader = require('../../lib/index').BerReader; + t.ok(BerReader); + try { + new BerReader(); + t.fail('Should have thrown'); + } catch (e) { + t.ok(e instanceof TypeError, 'Should have been a type error'); + } + t.end(); +}); + + +test('read byte', function(t) { + var reader = new BerReader(new Buffer([0xde])); + t.ok(reader); + t.equal(reader.readByte(), 0xde, 'wrong value'); + t.end(); +}); + + +test('read 1 byte int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x01, 0x03])); + t.ok(reader); + t.equal(reader.readInt(), 0x03, 'wrong value'); + t.equal(reader.length, 0x01, 'wrong length'); + t.end(); +}); + + +test('read 2 byte int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x02, 0x7e, 0xde])); + t.ok(reader); + t.equal(reader.readInt(), 0x7ede, 'wrong value'); + t.equal(reader.length, 0x02, 'wrong length'); + t.end(); +}); + + +test('read 3 byte int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x03, 0x7e, 0xde, 0x03])); + t.ok(reader); + t.equal(reader.readInt(), 0x7ede03, 'wrong value'); + t.equal(reader.length, 0x03, 'wrong length'); + t.end(); +}); + + +test('read 4 byte int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x04, 0x7e, 0xde, 0x03, 0x01])); + t.ok(reader); + t.equal(reader.readInt(), 0x7ede0301, 'wrong value'); + t.equal(reader.length, 0x04, 'wrong length'); + t.end(); +}); + + +test('read 1 byte negative int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x01, 0xdc])); + t.ok(reader); + t.equal(reader.readInt(), -36, 'wrong value'); + t.equal(reader.length, 0x01, 'wrong length'); + t.end(); +}); + + +test('read 2 byte negative int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x02, 0xc0, 0x4e])); + t.ok(reader); + t.equal(reader.readInt(), -16306, 'wrong value'); + t.equal(reader.length, 0x02, 'wrong length'); + t.end(); +}); + + +test('read 3 byte negative int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x03, 0xff, 0x00, 0x19])); + t.ok(reader); + t.equal(reader.readInt(), -65511, 'wrong value'); + t.equal(reader.length, 0x03, 'wrong length'); + t.end(); +}); + + +test('read 4 byte negative int', function(t) { + var reader = new BerReader(new Buffer([0x02, 0x04, 0x91, 0x7c, 0x22, 0x1f])); + t.ok(reader); + t.equal(reader.readInt(), -1854135777, 'wrong value'); + t.equal(reader.length, 0x04, 'wrong length'); + t.end(); +}); + + +test('read boolean true', function(t) { + var reader = new BerReader(new Buffer([0x01, 0x01, 0xff])); + t.ok(reader); + t.equal(reader.readBoolean(), true, 'wrong value'); + t.equal(reader.length, 0x01, 'wrong length'); + t.end(); +}); + + +test('read boolean false', function(t) { + var reader = new BerReader(new Buffer([0x01, 0x01, 0x00])); + t.ok(reader); + t.equal(reader.readBoolean(), false, 'wrong value'); + t.equal(reader.length, 0x01, 'wrong length'); + t.end(); +}); + + +test('read enumeration', function(t) { + var reader = new BerReader(new Buffer([0x0a, 0x01, 0x20])); + t.ok(reader); + t.equal(reader.readEnumeration(), 0x20, 'wrong value'); + t.equal(reader.length, 0x01, 'wrong length'); + t.end(); +}); + + +test('read string', function(t) { + var dn = 'cn=foo,ou=unit,o=test'; + var buf = new Buffer(dn.length + 2); + buf[0] = 0x04; + buf[1] = Buffer.byteLength(dn); + buf.write(dn, 2); + var reader = new BerReader(buf); + t.ok(reader); + t.equal(reader.readString(), dn, 'wrong value'); + t.equal(reader.length, dn.length, 'wrong length'); + t.end(); +}); + + +test('read sequence', function(t) { + var reader = new BerReader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff])); + t.ok(reader); + t.equal(reader.readSequence(), 0x30, 'wrong value'); + t.equal(reader.length, 0x03, 'wrong length'); + t.equal(reader.readBoolean(), true, 'wrong value'); + t.equal(reader.length, 0x01, 'wrong length'); + t.end(); +}); + + +test('anonymous LDAPv3 bind', function(t) { + var BIND = new Buffer(14); + BIND[0] = 0x30; // Sequence + BIND[1] = 12; // len + BIND[2] = 0x02; // ASN.1 Integer + BIND[3] = 1; // len + BIND[4] = 0x04; // msgid (make up 4) + BIND[5] = 0x60; // Bind Request + BIND[6] = 7; // len + BIND[7] = 0x02; // ASN.1 Integer + BIND[8] = 1; // len + BIND[9] = 0x03; // v3 + BIND[10] = 0x04; // String (bind dn) + BIND[11] = 0; // len + BIND[12] = 0x80; // ContextSpecific (choice) + BIND[13] = 0; // simple bind + + // Start testing ^^ + var ber = new BerReader(BIND); + t.equal(ber.readSequence(), 48, 'Not an ASN.1 Sequence'); + t.equal(ber.length, 12, 'Message length should be 12'); + t.equal(ber.readInt(), 4, 'Message id should have been 4'); + t.equal(ber.readSequence(), 96, 'Bind Request should have been 96'); + t.equal(ber.length, 7, 'Bind length should have been 7'); + t.equal(ber.readInt(), 3, 'LDAP version should have been 3'); + t.equal(ber.readString(), '', 'Bind DN should have been empty'); + t.equal(ber.length, 0, 'string length should have been 0'); + t.equal(ber.readByte(), 0x80, 'Should have been ContextSpecific (choice)'); + t.equal(ber.readByte(), 0, 'Should have been simple bind'); + t.equal(null, ber.readByte(), 'Should be out of data'); + t.end(); +}); + + +test('long string', function(t) { + var buf = new Buffer(256); + var o; + var s = + '2;649;CN=Red Hat CS 71GA Demo,O=Red Hat CS 71GA Demo,C=US;' + + 'CN=RHCS Agent - admin01,UID=admin01,O=redhat,C=US [1] This is ' + + 'Teena Vradmin\'s description.'; + buf[0] = 0x04; + buf[1] = 0x81; + buf[2] = 0x94; + buf.write(s, 3); + var ber = new BerReader(buf.slice(0, 3 + s.length)); + t.equal(ber.readString(), s); + t.end(); +}); diff --git a/node_modules/asn1/tst/ber/writer.test.js b/node_modules/asn1/tst/ber/writer.test.js new file mode 100644 index 000000000..d87cb7bc9 --- /dev/null +++ b/node_modules/asn1/tst/ber/writer.test.js @@ -0,0 +1,370 @@ +// Copyright 2011 Mark Cavage All rights reserved. + +var test = require('tap').test; +var sys = require('sys'); + +///--- Globals + +var BerWriter; + +var BerReader; + + +///--- Tests + +test('load library', function(t) { + BerWriter = require('../../lib/index').BerWriter; + t.ok(BerWriter); + t.ok(new BerWriter()); + t.end(); +}); + + +test('write byte', function(t) { + var writer = new BerWriter(); + + writer.writeByte(0xC2); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 1, 'Wrong length'); + t.equal(ber[0], 0xC2, 'value wrong'); + + t.end(); +}); + + +test('write 1 byte int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(0x7f); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 3, 'Wrong length for an int: ' + ber.length); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong (2) -> ' + ber[0]); + t.equal(ber[1], 0x01, 'length wrong(1) -> ' + ber[1]); + t.equal(ber[2], 0x7f, 'value wrong(3) -> ' + ber[2]); + + t.end(); +}); + + +test('write 2 byte int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(0x7ffe); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 4, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x02, 'length wrong'); + t.equal(ber[2], 0x7f, 'value wrong (byte 1)'); + t.equal(ber[3], 0xfe, 'value wrong (byte 2)'); + + t.end(); +}); + + +test('write 3 byte int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(0x7ffffe); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 5, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x03, 'length wrong'); + t.equal(ber[2], 0x7f, 'value wrong (byte 1)'); + t.equal(ber[3], 0xff, 'value wrong (byte 2)'); + t.equal(ber[4], 0xfe, 'value wrong (byte 3)'); + + t.end(); +}); + + +test('write 4 byte int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(0x7ffffffe); + var ber = writer.buffer; + + t.ok(ber); + + t.equal(ber.length, 6, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x04, 'length wrong'); + t.equal(ber[2], 0x7f, 'value wrong (byte 1)'); + t.equal(ber[3], 0xff, 'value wrong (byte 2)'); + t.equal(ber[4], 0xff, 'value wrong (byte 3)'); + t.equal(ber[5], 0xfe, 'value wrong (byte 4)'); + + t.end(); +}); + + +test('write 1 byte negative int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(-128); + var ber = writer.buffer; + + t.ok(ber); + + t.equal(ber.length, 3, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x01, 'length wrong'); + t.equal(ber[2], 0x80, 'value wrong (byte 1)'); + + t.end(); +}); + + +test('write 2 byte negative int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(-22400); + var ber = writer.buffer; + + t.ok(ber); + + t.equal(ber.length, 4, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x02, 'length wrong'); + t.equal(ber[2], 0xa8, 'value wrong (byte 1)'); + t.equal(ber[3], 0x80, 'value wrong (byte 2)'); + + t.end(); +}); + + +test('write 3 byte negative int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(-481653); + var ber = writer.buffer; + + t.ok(ber); + + t.equal(ber.length, 5, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x03, 'length wrong'); + t.equal(ber[2], 0xf8, 'value wrong (byte 1)'); + t.equal(ber[3], 0xa6, 'value wrong (byte 2)'); + t.equal(ber[4], 0x8b, 'value wrong (byte 3)'); + + t.end(); +}); + + +test('write 4 byte negative int', function(t) { + var writer = new BerWriter(); + + writer.writeInt(-1522904131); + var ber = writer.buffer; + + t.ok(ber); + + t.equal(ber.length, 6, 'Wrong length for an int'); + t.equal(ber[0], 0x02, 'ASN.1 tag wrong'); + t.equal(ber[1], 0x04, 'length wrong'); + t.equal(ber[2], 0xa5, 'value wrong (byte 1)'); + t.equal(ber[3], 0x3a, 'value wrong (byte 2)'); + t.equal(ber[4], 0x53, 'value wrong (byte 3)'); + t.equal(ber[5], 0xbd, 'value wrong (byte 4)'); + + t.end(); +}); + + +test('write boolean', function(t) { + var writer = new BerWriter(); + + writer.writeBoolean(true); + writer.writeBoolean(false); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 6, 'Wrong length'); + t.equal(ber[0], 0x01, 'tag wrong'); + t.equal(ber[1], 0x01, 'length wrong'); + t.equal(ber[2], 0xff, 'value wrong'); + t.equal(ber[3], 0x01, 'tag wrong'); + t.equal(ber[4], 0x01, 'length wrong'); + t.equal(ber[5], 0x00, 'value wrong'); + + t.end(); +}); + + +test('write string', function(t) { + var writer = new BerWriter(); + writer.writeString('hello world'); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 13, 'wrong length'); + t.equal(ber[0], 0x04, 'wrong tag'); + t.equal(ber[1], 11, 'wrong length'); + t.equal(ber.slice(2).toString('utf8'), 'hello world', 'wrong value'); + + t.end(); +}); + +test('write buffer', function(t) { + var writer = new BerWriter(); + // write some stuff to start with + writer.writeString('hello world'); + var ber = writer.buffer; + var buf = new Buffer([0x04, 0x0b, 0x30, 0x09, 0x02, 0x01, 0x0f, 0x01, 0x01, + 0xff, 0x01, 0x01, 0xff]); + writer.writeBuffer(buf.slice(2, buf.length), 0x04); + ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 26, 'wrong length'); + t.equal(ber[0], 0x04, 'wrong tag'); + t.equal(ber[1], 11, 'wrong length'); + t.equal(ber.slice(2, 13).toString('utf8'), 'hello world', 'wrong value'); + t.equal(ber[13], buf[0], 'wrong tag'); + t.equal(ber[14], buf[1], 'wrong length'); + for (var i = 13, j = 0; i < ber.length && j < buf.length; i++, j++) { + t.equal(ber[i], buf[j], 'buffer contents not identical'); + } + t.end(); +}); + +test('write string array', function(t) { + var writer = new BerWriter(); + writer.writeStringArray(['hello world', 'fubar!']); + var ber = writer.buffer; + + t.ok(ber); + + t.equal(ber.length, 21, 'wrong length'); + t.equal(ber[0], 0x04, 'wrong tag'); + t.equal(ber[1], 11, 'wrong length'); + t.equal(ber.slice(2, 13).toString('utf8'), 'hello world', 'wrong value'); + + t.equal(ber[13], 0x04, 'wrong tag'); + t.equal(ber[14], 6, 'wrong length'); + t.equal(ber.slice(15).toString('utf8'), 'fubar!', 'wrong value'); + + t.end(); +}); + + +test('resize internal buffer', function(t) { + var writer = new BerWriter({size: 2}); + writer.writeString('hello world'); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 13, 'wrong length'); + t.equal(ber[0], 0x04, 'wrong tag'); + t.equal(ber[1], 11, 'wrong length'); + t.equal(ber.slice(2).toString('utf8'), 'hello world', 'wrong value'); + + t.end(); +}); + + +test('sequence', function(t) { + var writer = new BerWriter({size: 25}); + writer.startSequence(); + writer.writeString('hello world'); + writer.endSequence(); + var ber = writer.buffer; + + t.ok(ber); + console.log(ber); + t.equal(ber.length, 15, 'wrong length'); + t.equal(ber[0], 0x30, 'wrong tag'); + t.equal(ber[1], 13, 'wrong length'); + t.equal(ber[2], 0x04, 'wrong tag'); + t.equal(ber[3], 11, 'wrong length'); + t.equal(ber.slice(4).toString('utf8'), 'hello world', 'wrong value'); + + t.end(); +}); + + +test('nested sequence', function(t) { + var writer = new BerWriter({size: 25}); + writer.startSequence(); + writer.writeString('hello world'); + writer.startSequence(); + writer.writeString('hello world'); + writer.endSequence(); + writer.endSequence(); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 30, 'wrong length'); + t.equal(ber[0], 0x30, 'wrong tag'); + t.equal(ber[1], 28, 'wrong length'); + t.equal(ber[2], 0x04, 'wrong tag'); + t.equal(ber[3], 11, 'wrong length'); + t.equal(ber.slice(4, 15).toString('utf8'), 'hello world', 'wrong value'); + t.equal(ber[15], 0x30, 'wrong tag'); + t.equal(ber[16], 13, 'wrong length'); + t.equal(ber[17], 0x04, 'wrong tag'); + t.equal(ber[18], 11, 'wrong length'); + t.equal(ber.slice(19, 30).toString('utf8'), 'hello world', 'wrong value'); + + t.end(); +}); + + +test('LDAP bind message', function(t) { + var dn = 'cn=foo,ou=unit,o=test'; + var writer = new BerWriter(); + writer.startSequence(); + writer.writeInt(3); // msgid = 3 + writer.startSequence(0x60); // ldap bind + writer.writeInt(3); // ldap v3 + writer.writeString(dn); + writer.writeByte(0x80); + writer.writeByte(0x00); + writer.endSequence(); + writer.endSequence(); + var ber = writer.buffer; + + t.ok(ber); + t.equal(ber.length, 35, 'wrong length (buffer)'); + t.equal(ber[0], 0x30, 'wrong tag'); + t.equal(ber[1], 33, 'wrong length'); + t.equal(ber[2], 0x02, 'wrong tag'); + t.equal(ber[3], 1, 'wrong length'); + t.equal(ber[4], 0x03, 'wrong value'); + t.equal(ber[5], 0x60, 'wrong tag'); + t.equal(ber[6], 28, 'wrong length'); + t.equal(ber[7], 0x02, 'wrong tag'); + t.equal(ber[8], 1, 'wrong length'); + t.equal(ber[9], 0x03, 'wrong value'); + t.equal(ber[10], 0x04, 'wrong tag'); + t.equal(ber[11], dn.length, 'wrong length'); + t.equal(ber.slice(12, 33).toString('utf8'), dn, 'wrong value'); + t.equal(ber[33], 0x80, 'wrong tag'); + t.equal(ber[34], 0x00, 'wrong len'); + + t.end(); +}); + + +test('Write OID', function(t) { + var oid = '1.2.840.113549.1.1.1'; + var writer = new BerWriter(); + writer.writeOID(oid); + + var ber = writer.buffer; + t.ok(ber); + console.log(require('util').inspect(ber)); + console.log(require('util').inspect(new Buffer([0x06, 0x09, 0x2a, 0x86, + 0x48, 0x86, 0xf7, 0x0d, + 0x01, 0x01, 0x01]))); + + t.end(); +}); diff --git a/node_modules/assert-plus/AUTHORS b/node_modules/assert-plus/AUTHORS new file mode 100644 index 000000000..1923524fe --- /dev/null +++ b/node_modules/assert-plus/AUTHORS @@ -0,0 +1,6 @@ +Dave Eddy +Fred Kuo +Lars-Magnus Skog +Mark Cavage +Patrick Mooney +Rob Gulewich diff --git a/node_modules/assert-plus/CHANGES.md b/node_modules/assert-plus/CHANGES.md new file mode 100644 index 000000000..d249d9b2a --- /dev/null +++ b/node_modules/assert-plus/CHANGES.md @@ -0,0 +1,8 @@ +# assert-plus Changelog + +## 0.2.0 + +- Fix `assert.object(null)` so it throws +- Fix optional/arrayOf exports for non-type-of asserts +- Add optiona/arrayOf exports for Stream/Date/Regex/uuid +- Add basic unit test coverage diff --git a/node_modules/assert-plus/README.md b/node_modules/assert-plus/README.md new file mode 100644 index 000000000..0b39593ce --- /dev/null +++ b/node_modules/assert-plus/README.md @@ -0,0 +1,155 @@ +# assert-plus + +This library is a super small wrapper over node's assert module that has two +things: (1) the ability to disable assertions with the environment variable +NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like +`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks +like this: + +```javascript + var assert = require('assert-plus'); + + function fooAccount(options, callback) { + assert.object(options, 'options'); + assert.number(options.id, 'options.id'); + assert.bool(options.isManager, 'options.isManager'); + assert.string(options.name, 'options.name'); + assert.arrayOfString(options.email, 'options.email'); + assert.func(callback, 'callback'); + + // Do stuff + callback(null, {}); + } +``` + +# API + +All methods that *aren't* part of node's core assert API are simply assumed to +take an argument, and then a string 'name' that's not a message; `AssertionError` +will be thrown if the assertion fails with a message like: + + AssertionError: foo (string) is required + at test (/home/mark/work/foo/foo.js:3:9) + at Object. (/home/mark/work/foo/foo.js:15:1) + at Module._compile (module.js:446:26) + at Object..js (module.js:464:10) + at Module.load (module.js:353:31) + at Function._load (module.js:311:12) + at Array.0 (module.js:484:10) + at EventEmitter._tickCallback (node.js:190:38) + +from: + +```javascript + function test(foo) { + assert.string(foo, 'foo'); + } +``` + +There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`: + +```javascript + function test(foo) { + assert.arrayOfString(foo, 'foo'); + } +``` + +You can assert IFF an argument is not `undefined` (i.e., an optional arg): + +```javascript + assert.optionalString(foo, 'foo'); +``` + +Lastly, you can opt-out of assertion checking altogether by setting the +environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have +lots of assertions, and don't want to pay `typeof ()` taxes to v8 in +production. Be advised: The standard functions re-exported from `assert` are +also disabled in assert-plus if NDEBUG is specified. Using them directly from +the `assert` module avoids this behavior. + +The complete list of APIs is: + +* assert.array +* assert.bool +* assert.buffer +* assert.func +* assert.number +* assert.object +* assert.string +* assert.stream +* assert.date +* assert.regex +* assert.uuid +* assert.arrayOfArray +* assert.arrayOfBool +* assert.arrayOfBuffer +* assert.arrayOfFunc +* assert.arrayOfNumber +* assert.arrayOfObject +* assert.arrayOfString +* assert.arrayOfStream +* assert.arrayOfDate +* assert.arrayOfUuid +* assert.optionalArray +* assert.optionalBool +* assert.optionalBuffer +* assert.optionalFunc +* assert.optionalNumber +* assert.optionalObject +* assert.optionalString +* assert.optionalStream +* assert.optionalDate +* assert.optionalUuid +* assert.optionalArrayOfArray +* assert.optionalArrayOfBool +* assert.optionalArrayOfBuffer +* assert.optionalArrayOfFunc +* assert.optionalArrayOfNumber +* assert.optionalArrayOfObject +* assert.optionalArrayOfString +* assert.optionalArrayOfStream +* assert.optionalArrayOfDate +* assert.optionalArrayOfUuid +* assert.AssertionError +* assert.fail +* assert.ok +* assert.equal +* assert.notEqual +* assert.deepEqual +* assert.notDeepEqual +* assert.strictEqual +* assert.notStrictEqual +* assert.throws +* assert.doesNotThrow +* assert.ifError + +# Installation + + npm install assert-plus + +## License + +The MIT License (MIT) +Copyright (c) 2012 Mark Cavage + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## Bugs + +See . diff --git a/node_modules/assert-plus/assert.js b/node_modules/assert-plus/assert.js new file mode 100644 index 000000000..6bce4d8c6 --- /dev/null +++ b/node_modules/assert-plus/assert.js @@ -0,0 +1,206 @@ +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. + +var assert = require('assert'); +var Stream = require('stream').Stream; +var util = require('util'); + + +///--- Globals + +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; + + +///--- Internal + +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); +} + +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); +} + +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); +} + +function noop() { + // Why even bother with asserts? +} + + +///--- Exports + +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; + } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; + +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; + + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } + + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); + + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); + + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); + + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; + + return out; +} + +module.exports = _setExports(process.env.NODE_NDEBUG); diff --git a/node_modules/assert-plus/package.json b/node_modules/assert-plus/package.json new file mode 100644 index 000000000..3fbf7b2b0 --- /dev/null +++ b/node_modules/assert-plus/package.json @@ -0,0 +1,106 @@ +{ + "_args": [ + [ + "assert-plus@^0.2.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\http-signature" + ] + ], + "_from": "assert-plus@>=0.2.0-0 <0.3.0-0", + "_id": "assert-plus@0.2.0", + "_inCache": true, + "_location": "/assert-plus", + "_nodeVersion": "0.10.36", + "_npmUser": { + "email": "patrick.f.mooney@gmail.com", + "name": "pfmooney" + }, + "_npmVersion": "3.3.8", + "_phantomChildren": {}, + "_requested": { + "name": "assert-plus", + "raw": "assert-plus@^0.2.0", + "rawSpec": "^0.2.0", + "scope": null, + "spec": ">=0.2.0-0 <0.3.0-0", + "type": "range" + }, + "_requiredBy": [ + "/http-signature" + ], + "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz", + "_shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234", + "_shrinkwrap": null, + "_spec": "assert-plus@^0.2.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\http-signature", + "author": { + "email": "mcavage@gmail.com", + "name": "Mark Cavage" + }, + "bugs": { + "url": "https://github.com/mcavage/node-assert-plus/issues" + }, + "contributors": [ + { + "name": "Dave Eddy", + "email": "dave@daveeddy.com" + }, + { + "name": "Fred Kuo", + "email": "fred.kuo@joyent.com" + }, + { + "name": "Lars-Magnus Skog", + "email": "ralphtheninja@riseup.net" + }, + { + "name": "Mark Cavage", + "email": "mcavage@gmail.com" + }, + { + "name": "Patrick Mooney", + "email": "pmooney@pfmooney.com" + }, + { + "name": "Rob Gulewich", + "email": "robert.gulewich@joyent.com" + } + ], + "dependencies": {}, + "description": "Extra assertions on top of node's assert module", + "devDependencies": { + "faucet": "0.0.1", + "tape": "4.2.2" + }, + "directories": {}, + "dist": { + "shasum": "d74e1b87e7affc0db8aadb7021f3fe48101ab234", + "tarball": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.2.0.tgz" + }, + "engines": { + "node": ">=0.8" + }, + "homepage": "https://github.com/mcavage/node-assert-plus#readme", + "installable": true, + "license": "MIT", + "main": "./assert.js", + "maintainers": [ + { + "name": "mcavage", + "email": "mcavage@gmail.com" + }, + { + "name": "pfmooney", + "email": "patrick.f.mooney@gmail.com" + } + ], + "name": "assert-plus", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/mcavage/node-assert-plus.git" + }, + "scripts": { + "test": "tape tests/*.js | ./node_modules/.bin/faucet" + }, + "version": "0.2.0" +} diff --git a/node_modules/asynckit/LICENSE b/node_modules/asynckit/LICENSE new file mode 100644 index 000000000..c9eca5dd9 --- /dev/null +++ b/node_modules/asynckit/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Alex Indigo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/asynckit/README.md b/node_modules/asynckit/README.md new file mode 100644 index 000000000..ddcc7e6b9 --- /dev/null +++ b/node_modules/asynckit/README.md @@ -0,0 +1,233 @@ +# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) + +Minimal async jobs utility library, with streams support. + +[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) +[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) + +[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) +[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) +[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) + + + +AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. +Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. + +It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. + +| compression | size | +| :----------------- | -------: | +| asynckit.js | 12.34 kB | +| asynckit.min.js | 4.11 kB | +| asynckit.min.js.gz | 1.47 kB | + + +## Install + +```sh +$ npm install --save asynckit +``` + +## Examples + +### Parallel Jobs + +Runs iterator over provided array in parallel. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will terminate rest of the active jobs (if abort function is provided) +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var parallel = require('asynckit').parallel + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , target = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// async job accepts one element from the array +// and a callback function +function asyncJob(item, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var parallel = require('asynckit/parallel') + , assert = require('assert') + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] + , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] + , target = [] + , keys = [] + ; + +parallel(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); + assert.deepEqual(keys, expectedKeys); +}); + +// supports full value, key, callback (shortcut) interface +function asyncJob(item, key, cb) +{ + // different delays (in ms) per item + var delay = item * 25; + + // pretend different jobs take different time to finish + // and not in consequential order + var timeoutId = setTimeout(function() { + keys.push(key); + target.push(item); + cb(null, item * 2); + }, delay); + + // allow to cancel "leftover" jobs upon error + // return function, invoking of which will abort this job + return clearTimeout.bind(null, timeoutId); +} +``` + +More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). + +### Serial Jobs + +Runs iterator over provided array sequentially. Stores output in the `result` array, +on the matching positions. In unlikely event of an error from one of the jobs, +will not proceed to the rest of the items in the list +and return error along with salvaged data to the main callback function. + +#### Input Array + +```javascript +var serial = require('asynckit/serial') + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// extended interface (item, key, callback) +// also supported for arrays +function asyncJob(item, key, cb) +{ + target.push(key); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). + +#### Input Object + +Also it supports named jobs, listed via object. + +```javascript +var serial = require('asynckit').serial + , assert = require('assert') + ; + +var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] + , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] + , target = [] + ; + +var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } + , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } + , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] + , target = [] + ; + + +serial(source, asyncJob, function(err, result) +{ + assert.deepEqual(result, expectedResult); + assert.deepEqual(target, expectedTarget); +}); + +// shortcut interface (item, callback) +// works for object as well as for the arrays +function asyncJob(item, cb) +{ + target.push(item); + + // it will be automatically made async + // even it iterator "returns" in the same event loop + cb(null, item * 2); +} +``` + +More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). + +_Note: Since _object_ is an _unordered_ collection of properties, +it may produce unexpected results with sequential iterations. +Whenever order of the jobs' execution is important please use `serialOrdered` method._ + +### Ordered Serial Iterations + +TBD + +For example [compare-property](compare-property) package. + +### Streaming interface + +TBD + +## Want to Know More? + +More examples can be found in [test folder](test/). + +Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. + +## License + +AsyncKit is licensed under the MIT license. diff --git a/node_modules/asynckit/bench.js b/node_modules/asynckit/bench.js new file mode 100644 index 000000000..c612f1a55 --- /dev/null +++ b/node_modules/asynckit/bench.js @@ -0,0 +1,76 @@ +/* eslint no-console: "off" */ + +var asynckit = require('./') + , async = require('async') + , assert = require('assert') + , expected = 0 + ; + +var Benchmark = require('benchmark'); +var suite = new Benchmark.Suite; + +var source = []; +for (var z = 1; z < 100; z++) +{ + source.push(z); + expected += z; +} + +suite +// add tests + +.add('async.map', function(deferred) +{ + var total = 0; + + async.map(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +.add('asynckit.parallel', function(deferred) +{ + var total = 0; + + asynckit.parallel(source, + function(i, cb) + { + setImmediate(function() + { + total += i; + cb(null, total); + }); + }, + function(err, result) + { + assert.ifError(err); + assert.equal(result[result.length - 1], expected); + deferred.resolve(); + }); +}, {'defer': true}) + + +// add listeners +.on('cycle', function(ev) +{ + console.log(String(ev.target)); +}) +.on('complete', function() +{ + console.log('Fastest is ' + this.filter('fastest').map('name')); +}) +// run async +.run({ 'async': true }); diff --git a/node_modules/asynckit/index.js b/node_modules/asynckit/index.js new file mode 100644 index 000000000..455f9454e --- /dev/null +++ b/node_modules/asynckit/index.js @@ -0,0 +1,6 @@ +module.exports = +{ + parallel : require('./parallel.js'), + serial : require('./serial.js'), + serialOrdered : require('./serialOrdered.js') +}; diff --git a/node_modules/asynckit/lib/abort.js b/node_modules/asynckit/lib/abort.js new file mode 100644 index 000000000..114367e5f --- /dev/null +++ b/node_modules/asynckit/lib/abort.js @@ -0,0 +1,29 @@ +// API +module.exports = abort; + +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); + + // reset leftover jobs + state.jobs = {}; +} + +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} diff --git a/node_modules/asynckit/lib/async.js b/node_modules/asynckit/lib/async.js new file mode 100644 index 000000000..7f1288a4c --- /dev/null +++ b/node_modules/asynckit/lib/async.js @@ -0,0 +1,34 @@ +var defer = require('./defer.js'); + +// API +module.exports = async; + +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; + + // check if async happened + defer(function() { isAsync = true; }); + + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} diff --git a/node_modules/asynckit/lib/defer.js b/node_modules/asynckit/lib/defer.js new file mode 100644 index 000000000..b67110c7a --- /dev/null +++ b/node_modules/asynckit/lib/defer.js @@ -0,0 +1,26 @@ +module.exports = defer; + +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} diff --git a/node_modules/asynckit/lib/iterate.js b/node_modules/asynckit/lib/iterate.js new file mode 100644 index 000000000..5d2839a59 --- /dev/null +++ b/node_modules/asynckit/lib/iterate.js @@ -0,0 +1,75 @@ +var async = require('./async.js') + , abort = require('./abort.js') + ; + +// API +module.exports = iterate; + +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } + + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } + + // return salvaged results + callback(error, state.results); + }); +} + +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } + + return aborter; +} diff --git a/node_modules/asynckit/lib/readable_asynckit.js b/node_modules/asynckit/lib/readable_asynckit.js new file mode 100644 index 000000000..78ad240f0 --- /dev/null +++ b/node_modules/asynckit/lib/readable_asynckit.js @@ -0,0 +1,91 @@ +var streamify = require('./streamify.js') + , defer = require('./defer.js') + ; + +// API +module.exports = ReadableAsyncKit; + +/** + * Base constructor for all streams + * used to hold properties/methods + */ +function ReadableAsyncKit() +{ + ReadableAsyncKit.super_.apply(this, arguments); + + // list of active jobs + this.jobs = {}; + + // add stream methods + this.destroy = destroy; + this._start = _start; + this._read = _read; +} + +/** + * Destroys readable stream, + * by aborting outstanding jobs + * + * @returns {void} + */ +function destroy() +{ + if (this.destroyed) + { + return; + } + + this.destroyed = true; + + if (typeof this.terminator == 'function') + { + this.terminator(); + } +} + +/** + * Starts provided jobs in async manner + * + * @private + */ +function _start() +{ + // first argument – runner function + var runner = arguments[0] + // take away first argument + , args = Array.prototype.slice.call(arguments, 1) + // second argument - input data + , input = args[0] + // last argument - result callback + , endCb = streamify.callback.call(this, args[args.length - 1]) + ; + + args[args.length - 1] = endCb; + // third argument - iterator + args[1] = streamify.iterator.call(this, args[1]); + + // allow time for proper setup + defer(function() + { + if (!this.destroyed) + { + this.terminator = runner.apply(null, args); + } + else + { + endCb(null, Array.isArray(input) ? [] : {}); + } + }.bind(this)); +} + + +/** + * Implement _read to comply with Readable streams + * Doesn't really make sense for flowing object mode + * + * @private + */ +function _read() +{ + +} diff --git a/node_modules/asynckit/lib/readable_parallel.js b/node_modules/asynckit/lib/readable_parallel.js new file mode 100644 index 000000000..5d2929f7a --- /dev/null +++ b/node_modules/asynckit/lib/readable_parallel.js @@ -0,0 +1,25 @@ +var parallel = require('../parallel.js'); + +// API +module.exports = ReadableParallel; + +/** + * Streaming wrapper to `asynckit.parallel` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableParallel(list, iterator, callback) +{ + if (!(this instanceof ReadableParallel)) + { + return new ReadableParallel(list, iterator, callback); + } + + // turn on object mode + ReadableParallel.super_.call(this, {objectMode: true}); + + this._start(parallel, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial.js b/node_modules/asynckit/lib/readable_serial.js new file mode 100644 index 000000000..782269820 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial.js @@ -0,0 +1,25 @@ +var serial = require('../serial.js'); + +// API +module.exports = ReadableSerial; + +/** + * Streaming wrapper to `asynckit.serial` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerial(list, iterator, callback) +{ + if (!(this instanceof ReadableSerial)) + { + return new ReadableSerial(list, iterator, callback); + } + + // turn on object mode + ReadableSerial.super_.call(this, {objectMode: true}); + + this._start(serial, list, iterator, callback); +} diff --git a/node_modules/asynckit/lib/readable_serial_ordered.js b/node_modules/asynckit/lib/readable_serial_ordered.js new file mode 100644 index 000000000..3de89c472 --- /dev/null +++ b/node_modules/asynckit/lib/readable_serial_ordered.js @@ -0,0 +1,29 @@ +var serialOrdered = require('../serialOrdered.js'); + +// API +module.exports = ReadableSerialOrdered; +// expose sort helpers +module.exports.ascending = serialOrdered.ascending; +module.exports.descending = serialOrdered.descending; + +/** + * Streaming wrapper to `asynckit.serialOrdered` + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {stream.Readable#} + */ +function ReadableSerialOrdered(list, iterator, sortMethod, callback) +{ + if (!(this instanceof ReadableSerialOrdered)) + { + return new ReadableSerialOrdered(list, iterator, sortMethod, callback); + } + + // turn on object mode + ReadableSerialOrdered.super_.call(this, {objectMode: true}); + + this._start(serialOrdered, list, iterator, sortMethod, callback); +} diff --git a/node_modules/asynckit/lib/state.js b/node_modules/asynckit/lib/state.js new file mode 100644 index 000000000..cbea7ad8f --- /dev/null +++ b/node_modules/asynckit/lib/state.js @@ -0,0 +1,37 @@ +// API +module.exports = state; + +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; + + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } + + return initState; +} diff --git a/node_modules/asynckit/lib/streamify.js b/node_modules/asynckit/lib/streamify.js new file mode 100644 index 000000000..f56a1c92b --- /dev/null +++ b/node_modules/asynckit/lib/streamify.js @@ -0,0 +1,141 @@ +var async = require('./async.js'); + +// API +module.exports = { + iterator: wrapIterator, + callback: wrapCallback +}; + +/** + * Wraps iterators with long signature + * + * @this ReadableAsyncKit# + * @param {function} iterator - function to wrap + * @returns {function} - wrapped function + */ +function wrapIterator(iterator) +{ + var stream = this; + + return function(item, key, cb) + { + var aborter + , wrappedCb = async(wrapIteratorCallback.call(stream, cb, key)) + ; + + stream.jobs[key] = wrappedCb; + + // it's either shortcut (item, cb) + if (iterator.length == 2) + { + aborter = iterator(item, wrappedCb); + } + // or long format (item, key, cb) + else + { + aborter = iterator(item, key, wrappedCb); + } + + return aborter; + }; +} + +/** + * Wraps provided callback function + * allowing to execute snitch function before + * real callback + * + * @this ReadableAsyncKit# + * @param {function} callback - function to wrap + * @returns {function} - wrapped function + */ +function wrapCallback(callback) +{ + var stream = this; + + var wrapped = function(error, result) + { + return finisher.call(stream, error, result, callback); + }; + + return wrapped; +} + +/** + * Wraps provided iterator callback function + * makes sure snitch only called once, + * but passes secondary calls to the original callback + * + * @this ReadableAsyncKit# + * @param {function} callback - callback to wrap + * @param {number|string} key - iteration key + * @returns {function} wrapped callback + */ +function wrapIteratorCallback(callback, key) +{ + var stream = this; + + return function(error, output) + { + // don't repeat yourself + if (!(key in stream.jobs)) + { + callback(error, output); + return; + } + + // clean up jobs + delete stream.jobs[key]; + + return streamer.call(stream, error, {key: key, value: output}, callback); + }; +} + +/** + * Stream wrapper for iterator callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects iterator results + */ +function streamer(error, output, callback) +{ + if (error && !this.error) + { + this.error = error; + this.pause(); + this.emit('error', error); + // send back value only, as expected + callback(error, output && output.value); + return; + } + + // stream stuff + this.push(output); + + // back to original track + // send back value only, as expected + callback(error, output && output.value); +} + +/** + * Stream wrapper for finishing callback + * + * @this ReadableAsyncKit# + * @param {mixed} error - error response + * @param {mixed} output - iterator output + * @param {function} callback - callback that expects final results + */ +function finisher(error, output, callback) +{ + // signal end of the stream + // only for successfully finished streams + if (!error) + { + this.push(null); + } + + // back to original track + callback(error, output); +} diff --git a/node_modules/asynckit/lib/terminator.js b/node_modules/asynckit/lib/terminator.js new file mode 100644 index 000000000..d6eb99219 --- /dev/null +++ b/node_modules/asynckit/lib/terminator.js @@ -0,0 +1,29 @@ +var abort = require('./abort.js') + , async = require('./async.js') + ; + +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } + + // fast forward iteration index + this.index = this.size; + + // abort jobs + abort(this); + + // send back results we have so far + async(callback)(null, this.results); +} diff --git a/node_modules/asynckit/package.json b/node_modules/asynckit/package.json new file mode 100644 index 000000000..a27fa26d1 --- /dev/null +++ b/node_modules/asynckit/package.json @@ -0,0 +1,118 @@ +{ + "_args": [ + [ + "asynckit@^0.4.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\form-data" + ] + ], + "_from": "asynckit@>=0.4.0-0 <0.5.0-0", + "_id": "asynckit@0.4.0", + "_inCache": true, + "_location": "/asynckit", + "_nodeVersion": "0.12.11", + "_npmOperationalInternal": { + "host": "packages-16-east.internal.npmjs.com", + "tmp": "tmp/asynckit-0.4.0.tgz_1465928940169_0.8008207362145185" + }, + "_npmUser": { + "email": "iam@alexindigo.com", + "name": "alexindigo" + }, + "_npmVersion": "2.15.6", + "_phantomChildren": {}, + "_requested": { + "name": "asynckit", + "raw": "asynckit@^0.4.0", + "rawSpec": "^0.4.0", + "scope": null, + "spec": ">=0.4.0-0 <0.5.0-0", + "type": "range" + }, + "_requiredBy": [ + "/form-data", + "/request/form-data" + ], + "_resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "_shasum": "c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79", + "_shrinkwrap": null, + "_spec": "asynckit@^0.4.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\form-data", + "author": { + "email": "iam@alexindigo.com", + "name": "Alex Indigo" + }, + "bugs": { + "url": "https://github.com/alexindigo/asynckit/issues" + }, + "dependencies": {}, + "description": "Minimal async jobs utility library, with streams support", + "devDependencies": { + "browserify": "^13.0.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^2.11.9", + "eslint": "^2.9.0", + "istanbul": "^0.4.3", + "obake": "^0.1.2", + "phantomjs-prebuilt": "^2.1.7", + "pre-commit": "^1.1.3", + "reamde": "^1.1.0", + "rimraf": "^2.5.2", + "size-table": "^0.2.0", + "tap-spec": "^4.1.1", + "tape": "^4.5.1" + }, + "directories": {}, + "dist": { + "shasum": "c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79", + "tarball": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz" + }, + "gitHead": "583a75ed4fe41761b66416bb6e703ebb1f8963bf", + "homepage": "https://github.com/alexindigo/asynckit#readme", + "installable": true, + "keywords": [ + "abort", + "array", + "async", + "destroy", + "iterator", + "jobs", + "object", + "parallel", + "serial", + "stream", + "terminate" + ], + "license": "MIT", + "main": "index.js", + "maintainers": [ + { + "name": "alexindigo", + "email": "iam@alexindigo.com" + } + ], + "name": "asynckit", + "optionalDependencies": {}, + "pre-commit": [ + "browser", + "clean", + "lint", + "report", + "size", + "test" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/alexindigo/asynckit.git" + }, + "scripts": { + "browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec", + "clean": "rimraf coverage", + "debug": "tape test/test-*.js", + "lint": "eslint *.js lib/*.js test/*.js", + "report": "istanbul report", + "size": "browserify index.js | size-table asynckit", + "test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec", + "win-test": "tape test/test-*.js" + }, + "version": "0.4.0" +} diff --git a/node_modules/asynckit/parallel.js b/node_modules/asynckit/parallel.js new file mode 100644 index 000000000..3c50344d8 --- /dev/null +++ b/node_modules/asynckit/parallel.js @@ -0,0 +1,43 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = parallel; + +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); + + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); +} diff --git a/node_modules/asynckit/serial.js b/node_modules/asynckit/serial.js new file mode 100644 index 000000000..6cd949a67 --- /dev/null +++ b/node_modules/asynckit/serial.js @@ -0,0 +1,17 @@ +var serialOrdered = require('./serialOrdered.js'); + +// Public API +module.exports = serial; + +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} diff --git a/node_modules/asynckit/serialOrdered.js b/node_modules/asynckit/serialOrdered.js new file mode 100644 index 000000000..607eafea5 --- /dev/null +++ b/node_modules/asynckit/serialOrdered.js @@ -0,0 +1,75 @@ +var iterate = require('./lib/iterate.js') + , initState = require('./lib/state.js') + , terminator = require('./lib/terminator.js') + ; + +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; + +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); + + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } + + state.index++; + + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } + + // done here + callback(null, state.results); + }); + + return terminator.bind(state, callback); +} + +/* + * -- Sort methods + */ + +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} diff --git a/node_modules/asynckit/stream.js b/node_modules/asynckit/stream.js new file mode 100644 index 000000000..d43465f90 --- /dev/null +++ b/node_modules/asynckit/stream.js @@ -0,0 +1,21 @@ +var inherits = require('util').inherits + , Readable = require('stream').Readable + , ReadableAsyncKit = require('./lib/readable_asynckit.js') + , ReadableParallel = require('./lib/readable_parallel.js') + , ReadableSerial = require('./lib/readable_serial.js') + , ReadableSerialOrdered = require('./lib/readable_serial_ordered.js') + ; + +// API +module.exports = +{ + parallel : ReadableParallel, + serial : ReadableSerial, + serialOrdered : ReadableSerialOrdered, +}; + +inherits(ReadableAsyncKit, Readable); + +inherits(ReadableParallel, ReadableAsyncKit); +inherits(ReadableSerial, ReadableAsyncKit); +inherits(ReadableSerialOrdered, ReadableAsyncKit); diff --git a/node_modules/aws-sign2/LICENSE b/node_modules/aws-sign2/LICENSE new file mode 100644 index 000000000..a4a9aee0c --- /dev/null +++ b/node_modules/aws-sign2/LICENSE @@ -0,0 +1,55 @@ +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 \ No newline at end of file diff --git a/node_modules/aws-sign2/README.md b/node_modules/aws-sign2/README.md new file mode 100644 index 000000000..763564e0a --- /dev/null +++ b/node_modules/aws-sign2/README.md @@ -0,0 +1,4 @@ +aws-sign +======== + +AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module. diff --git a/node_modules/aws-sign2/index.js b/node_modules/aws-sign2/index.js new file mode 100644 index 000000000..ac7209308 --- /dev/null +++ b/node_modules/aws-sign2/index.js @@ -0,0 +1,212 @@ + +/*! + * Copyright 2010 LearnBoost + * + * 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. + */ + +/** + * Module dependencies. + */ + +var crypto = require('crypto') + , parse = require('url').parse + ; + +/** + * Valid keys. + */ + +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] + +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS :" + * + * @param {Object} options + * @return {String} + * @api private + */ + +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) +} + +module.exports = authorization +module.exports.authorization = authorization + +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ + +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} + +module.exports.hmacSha1 = hmacSha1 + +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ + +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) +} +module.exports.sign = sign + +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ + +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery + +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * \n + * \n + * \n + * \n + * [headers\n] + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.queryStringToSign = stringToSign + +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * \n + * + * + * @param {Object} options + * @return {String} + * @api private + */ + +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign + +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ + +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) + } + return buf.sort().join('\n') +} +module.exports.canonicalizeHeaders = canonicalizeHeaders + +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ + +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; + + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) + + return path + (buf.length ? '?' + buf.sort().join('&') : '') +} +module.exports.canonicalizeResource = canonicalizeResource diff --git a/node_modules/aws-sign2/package.json b/node_modules/aws-sign2/package.json new file mode 100644 index 000000000..edcd064fb --- /dev/null +++ b/node_modules/aws-sign2/package.json @@ -0,0 +1,72 @@ +{ + "_args": [ + [ + "aws-sign2@~0.6.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request" + ] + ], + "_from": "aws-sign2@>=0.6.0-0 <0.7.0-0", + "_id": "aws-sign2@0.6.0", + "_inCache": true, + "_location": "/aws-sign2", + "_nodeVersion": "4.1.2", + "_npmUser": { + "email": "mikeal.rogers@gmail.com", + "name": "mikeal" + }, + "_npmVersion": "2.14.4", + "_phantomChildren": {}, + "_requested": { + "name": "aws-sign2", + "raw": "aws-sign2@~0.6.0", + "rawSpec": "~0.6.0", + "scope": null, + "spec": ">=0.6.0-0 <0.7.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage/request" + ], + "_resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz", + "_shasum": "14342dd38dbcc94d0e5b87d763cd63612c0e794f", + "_shrinkwrap": null, + "_spec": "aws-sign2@~0.6.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request", + "author": { + "email": "mikeal.rogers@gmail.com", + "name": "Mikeal Rogers", + "url": "http://www.futurealoof.com" + }, + "bugs": { + "url": "https://github.com/mikeal/aws-sign/issues" + }, + "dependencies": {}, + "description": "AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module.", + "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "14342dd38dbcc94d0e5b87d763cd63612c0e794f", + "tarball": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.6.0.tgz" + }, + "engines": { + "node": "*" + }, + "gitHead": "8554bdb41268fa295eb1ee300f4adaa9f7f07fec", + "homepage": "https://github.com/mikeal/aws-sign#readme", + "installable": true, + "license": "Apache-2.0", + "main": "index.js", + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + } + ], + "name": "aws-sign2", + "optionalDependencies": {}, + "repository": { + "url": "git+https://github.com/mikeal/aws-sign.git" + }, + "scripts": {}, + "version": "0.6.0" +} diff --git a/node_modules/aws4/.npmignore b/node_modules/aws4/.npmignore new file mode 100644 index 000000000..6c6ade6ff --- /dev/null +++ b/node_modules/aws4/.npmignore @@ -0,0 +1,4 @@ +test +examples +example.js +browser diff --git a/node_modules/aws4/.tern-port b/node_modules/aws4/.tern-port new file mode 100644 index 000000000..7fd1b5223 --- /dev/null +++ b/node_modules/aws4/.tern-port @@ -0,0 +1 @@ +62638 \ No newline at end of file diff --git a/node_modules/aws4/.travis.yml b/node_modules/aws4/.travis.yml new file mode 100644 index 000000000..61d063404 --- /dev/null +++ b/node_modules/aws4/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4.2" diff --git a/node_modules/aws4/LICENSE b/node_modules/aws4/LICENSE new file mode 100644 index 000000000..4f321e599 --- /dev/null +++ b/node_modules/aws4/LICENSE @@ -0,0 +1,19 @@ +Copyright 2013 Michael Hart (michael.hart.au@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/aws4/README.md b/node_modules/aws4/README.md new file mode 100644 index 000000000..6b002d02f --- /dev/null +++ b/node_modules/aws4/README.md @@ -0,0 +1,523 @@ +aws4 +---- + +[![Build Status](https://secure.travis-ci.org/mhart/aws4.png?branch=master)](http://travis-ci.org/mhart/aws4) + +A small utility to sign vanilla node.js http(s) request options using Amazon's +[AWS Signature Version 4](http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html). + +Can also be used [in the browser](./browser). + +This signature is supported by nearly all Amazon services, including +[S3](http://docs.aws.amazon.com/AmazonS3/latest/API/), +[EC2](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/), +[DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html), +[Kinesis](http://docs.aws.amazon.com/kinesis/latest/APIReference/), +[Lambda](http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html), +[SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/), +[SNS](http://docs.aws.amazon.com/sns/latest/api/), +[IAM](http://docs.aws.amazon.com/IAM/latest/APIReference/), +[STS](http://docs.aws.amazon.com/STS/latest/APIReference/), +[RDS](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/), +[CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/), +[CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/), +[CodeDeploy](http://docs.aws.amazon.com/codedeploy/latest/APIReference/), +[CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/), +[CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/), +[ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/), +[EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/API/), +[Glacier](http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html), +[CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/APIReq.html), +[Elastic Load Balancing](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/), +[Elastic Transcoder](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/api-reference.html), +[CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/), +[Elastic Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/api/), +[Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html), +[Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/APIReference/), +[Direct Connect](http://docs.aws.amazon.com/directconnect/latest/APIReference/), +[Redshift](http://docs.aws.amazon.com/redshift/latest/APIReference/), +[OpsWorks](http://docs.aws.amazon.com/opsworks/latest/APIReference/), +[SES](http://docs.aws.amazon.com/ses/latest/APIReference/), +[SWF](http://docs.aws.amazon.com/amazonswf/latest/apireference/), +[AutoScaling](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/), +[Mobile Analytics](http://docs.aws.amazon.com/mobileanalytics/latest/ug/server-reference.html), +[Cognito Identity](http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/), +[Cognito Sync](http://docs.aws.amazon.com/cognitosync/latest/APIReference/), +[Container Service](http://docs.aws.amazon.com/AmazonECS/latest/APIReference/), +[AppStream](http://docs.aws.amazon.com/appstream/latest/developerguide/appstream-api-rest.html), +[Key Management Service](http://docs.aws.amazon.com/kms/latest/APIReference/), +[Config](http://docs.aws.amazon.com/config/latest/APIReference/), +[CloudHSM](http://docs.aws.amazon.com/cloudhsm/latest/dg/api-ref.html), +[Route53](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rest.html) and +[Route53 Domains](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rpc.html). + +Indeed, the only AWS services that *don't* support v4 as of 2014-12-30 are +[Import/Export](http://docs.aws.amazon.com/AWSImportExport/latest/DG/api-reference.html) and +[SimpleDB](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html) +(they only support [AWS Signature Version 2](https://github.com/mhart/aws2)). + +It also provides defaults for a number of core AWS headers and +request parameters, making it very easy to query AWS services, or +build out a fully-featured AWS library. + +Example +------- + +```javascript +var http = require('http'), + https = require('https'), + aws4 = require('aws4') + +// given an options object you could pass to http.request +var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'} + +// alternatively (as aws4 can infer the host): +opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'} + +// alternatively (as us-east-1 is default): +opts = {service: 'sqs', path: '/?Action=ListQueues'} + +aws4.sign(opts) // assumes AWS credentials are available in process.env + +console.log(opts) +/* +{ + host: 'sqs.us-east-1.amazonaws.com', + path: '/?Action=ListQueues', + headers: { + Host: 'sqs.us-east-1.amazonaws.com', + 'X-Amz-Date': '20121226T061030Z', + Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...' + } +} +*/ + +// we can now use this to query AWS using the standard node.js http API +http.request(opts, function(res) { res.pipe(process.stdout) }).end() +/* + + +... +*/ +``` + +More options +------------ + +```javascript +// you can also pass AWS credentials in explicitly (otherwise taken from process.env) +aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''}) + +// can also add the signature to query strings +aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true}) + +// create a utility function to pipe to stdout (with https this time) +function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') } + +// aws4 can infer the HTTP method if a body is passed in +// method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8' +request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'})) +/* + +... +*/ + +// can specify any custom option or header as per usual +request(aws4.sign({ + service: 'dynamodb', + region: 'ap-southeast-2', + method: 'POST', + path: '/', + headers: { + 'Content-Type': 'application/x-amz-json-1.0', + 'X-Amz-Target': 'DynamoDB_20120810.ListTables' + }, + body: '{}' +})) +/* +{"TableNames":[]} +... +*/ + +// works with all other services that support Signature Version 4 + +request(aws4.sign({service: 's3', path: '/', signQuery: true})) +/* + +... +*/ + +request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'})) +/* + +... +*/ + +request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'})) +/* + +... +*/ + +request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'})) +/* + +... +*/ + +request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'})) +/* + +... +*/ + +request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'})) +/* + +... +*/ + +request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'})) +/* + +... +*/ + +request(aws4.sign({service: 'appstream', path: '/applications'})) +/* +{"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/... +... +*/ + +request(aws4.sign({service: 'cognito-sync', path: '/identitypools'})) +/* +{"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null} +... +*/ + +request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'})) +/* +{"NextPageToken":null,"Pipelines":[]} +... +*/ + +request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'})) +/* +{"Functions":[],"NextMarker":null} +... +*/ + +request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'})) +/* + +... +*/ + +request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}})) +/* +{"Marker":null,"VaultList":[]} +... +*/ + +request(aws4.sign({service: 'storagegateway', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'StorageGateway_20120630.ListGateways' +}})) +/* +{"Gateways":[]} +... +*/ + +request(aws4.sign({service: 'datapipeline', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'DataPipeline.ListPipelines' +}})) +/* +{"hasMoreResults":false,"pipelineIdList":[]} +... +*/ + +request(aws4.sign({service: 'opsworks', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks' +}})) +/* +{"Stacks":[]} +... +*/ + +request(aws4.sign({service: 'route53domains', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'Route53Domains_v20140515.ListDomains' +}})) +/* +{"Domains":[]} +... +*/ + +request(aws4.sign({service: 'kinesis', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'Kinesis_20131202.ListStreams' +}})) +/* +{"HasMoreStreams":false,"StreamNames":[]} +... +*/ + +request(aws4.sign({service: 'cloudtrail', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails' +}})) +/* +{"trailList":[]} +... +*/ + +request(aws4.sign({service: 'logs', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'Logs_20140328.DescribeLogGroups' +}})) +/* +{"logGroups":[]} +... +*/ + +request(aws4.sign({service: 'codedeploy', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'CodeDeploy_20141006.ListApplications' +}})) +/* +{"applications":[]} +... +*/ + +request(aws4.sign({service: 'directconnect', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'OvertureService.DescribeConnections' +}})) +/* +{"connections":[]} +... +*/ + +request(aws4.sign({service: 'kms', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'TrentService.ListKeys' +}})) +/* +{"Keys":[],"Truncated":false} +... +*/ + +request(aws4.sign({service: 'config', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels' +}})) +/* +{"DeliveryChannels":[]} +... +*/ + +request(aws4.sign({service: 'cloudhsm', body: '{}', headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones' +}})) +/* +{"AZList":["us-east-1a","us-east-1b","us-east-1c"]} +... +*/ + +request(aws4.sign({ + service: 'swf', + body: '{"registrationStatus":"REGISTERED"}', + headers: { + 'Content-Type': 'application/x-amz-json-1.0', + 'X-Amz-Target': 'SimpleWorkflowService.ListDomains' + } +})) +/* +{"domainInfos":[]} +... +*/ + +request(aws4.sign({ + service: 'cognito-identity', + body: '{"MaxResults": 1}', + headers: { + 'Content-Type': 'application/x-amz-json-1.1', + 'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools' + } +})) +/* +{"IdentityPools":[]} +... +*/ + +request(aws4.sign({ + service: 'mobileanalytics', + path: '/2014-06-05/events', + body: JSON.stringify({events:[{ + eventType: 'a', + timestamp: new Date().toISOString(), + session: {}, + }]}), + headers: { + 'Content-Type': 'application/json', + 'X-Amz-Client-Context': JSON.stringify({ + client: {client_id: 'a', app_title: 'a'}, + custom: {}, + env: {platform: 'a'}, + services: {}, + }), + } +})) +/* +(HTTP 202, empty response) +*/ + +// Generate CodeCommit Git access password +var signer = new aws4.RequestSigner({ + service: 'codecommit', + host: 'git-codecommit.us-east-1.amazonaws.com', + method: 'GIT', + path: '/v1/repos/MyAwesomeRepo', +}) +var password = signer.getDateTime() + 'Z' + signer.signature() +``` + +API +--- + +### aws4.sign(requestOptions, [credentials]) + +This calculates and populates the `Authorization` header of +`requestOptions`, and any other necessary AWS headers and/or request +options. Returns `requestOptions` as a convenience for chaining. + +`requestOptions` is an object holding the same options that the node.js +[http.request](http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback) +function takes. + +The following properties of `requestOptions` are used in the signing or +populated if they don't already exist: + +- `hostname` or `host` (will be determined from `service` and `region` if not given) +- `method` (will use `'GET'` if not given or `'POST'` if there is a `body`) +- `path` (will use `'/'` if not given) +- `body` (will use `''` if not given) +- `service` (will be calculated from `hostname` or `host` if not given) +- `region` (will be calculated from `hostname` or `host` or use `'us-east-1'` if not given) +- `headers['Host']` (will use `hostname` or `host` or be calculated if not given) +- `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'` + if not given and there is a `body`) +- `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used) + +Your AWS credentials (which can be found in your +[AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials)) +can be specified in one of two ways: + +- As the second argument, like this: + +```javascript +aws4.sign(requestOptions, { + secretAccessKey: "", + accessKeyId: "", + sessionToken: "" +}) +``` + +- From `process.env`, such as this: + +``` +export AWS_SECRET_ACCESS_KEY="" +export AWS_ACCESS_KEY_ID="" +export AWS_SESSION_TOKEN="" +``` + +(will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available) + +The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing +with [IAM STS temporary credentials](http://docs.aws.amazon.com/STS/latest/UsingSTS/using-temp-creds.html). + +Installation +------------ + +With [npm](http://npmjs.org/) do: + +``` +npm install aws4 +``` + +Can also be used [in the browser](./browser). + +Thanks +------ + +Thanks to [@jed](https://github.com/jed) for his +[dynamo-client](https://github.com/jed/dynamo-client) lib where I first +committed and subsequently extracted this code. + +Also thanks to the +[official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving +me a start on implementing the v4 signature. + diff --git a/node_modules/aws4/aws4.js b/node_modules/aws4/aws4.js new file mode 100644 index 000000000..0cff0f0ea --- /dev/null +++ b/node_modules/aws4/aws4.js @@ -0,0 +1,332 @@ +var aws4 = exports, + url = require('url'), + querystring = require('querystring'), + crypto = require('crypto'), + lru = require('./lru'), + credentialsCache = lru(1000) + +// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html + +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) +} + +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} + +// This function assumes the string has already been percent encoded +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} + +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { + + if (typeof request === 'string') request = url.parse(request) + + var headers = request.headers = (request.headers || {}), + hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host) + + this.request = request + this.credentials = credentials || this.defaultCredentials() + + this.service = request.service || hostParts[0] || '' + this.region = request.region || hostParts[1] || 'us-east-1' + + // SES uses a different domain from the service name + if (this.service === 'email') this.service = 'ses' + + if (!request.method && request.body) + request.method = 'POST' + + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() + + // If a port is specified explicitly, use it as is + if (request.port) + headers.Host += ':' + request.port + } + if (!request.hostname && !request.host) + request.hostname = headers.Host || headers.host + + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +} + +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/) + var hostParts = (match || []).slice(1, 3) + + // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com + if (hostParts[1] === 'es') + hostParts = hostParts.reverse() + + return hostParts +} + +// http://docs.aws.amazon.com/general/latest/gr/rande.html +RequestSigner.prototype.isSingleRegion = function() { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true + + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} + +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : + (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region, + service = this.service === 'ses' ? 'email' : this.service + return service + region + '.amazonaws.com' +} + +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() + + var request = this.request, headers = request.headers, query + + if (request.signQuery) { + + this.parsedPath.query = query = this.parsedPath.query || {} + + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 + + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() + + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() + + } else { + + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) + headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' + + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) + + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken + + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') + + if (headers['X-Amz-Date'] || headers['x-amz-date']) + this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] + else + headers['X-Amz-Date'] = this.getDateTime() + } + + delete headers.Authorization + delete headers.authorization + } +} + +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() + + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } + + this.request.path = this.formatPath() + + return this.request +} + +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) + + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') + + // Remove the trailing 'Z' on the timestamp string for CodeCommit git access + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) + } + return this.datetime +} + +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} + +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} + +RequestSigner.prototype.signature = function() { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) + kRegion = hmac(kDate, this.region) + kService = hmac(kRegion, this.service) + kCredentials = hmac(kService, 'aws4_request') + credentialsCache.set(cacheKey, kCredentials) + } + return hmac(kCredentials, this.stringToSign(), 'hex') +} + +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} + +RequestSigner.prototype.canonicalString = function() { + if (!this.parsedPath) this.prepareRequest() + + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash + + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD' + } else if (this.isCodeCommitGit) { + bodyHash = '' + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || + hash(this.request.body || '', 'hex') + } + + if (query) { + queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) { + if (!key) return obj + obj[key] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key].slice().sort()) + return obj + }, {}))) + } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') + pathStr = pathStr.split('/').reduce(function(path, piece) { + if (normalizePath && piece === '..') { + path.pop() + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = querystring.unescape(piece) + path.push(encodeRfc3986(querystring.escape(piece))) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') + } + + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} + +RequestSigner.prototype.canonicalHeaders = function() { + var headers = this.request.headers + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' ') + } + return Object.keys(headers) + .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) + .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) + .join('\n') +} + +RequestSigner.prototype.signedHeaders = function() { + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .sort() + .join(';') +} + +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} + +RequestSigner.prototype.defaultCredentials = function() { + var env = process.env + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN, + } +} + +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/', + queryIx = path.indexOf('?'), + query = null + + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } + + // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all + if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) { + path = path.split('/').map(function(piece) { + return querystring.escape(querystring.unescape(piece)) + }).join('/') + } + + this.parsedPath = { + path: path, + query: query, + } +} + +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query + + if (!query) return path + + // Services don't support empty query string keys + if (query[''] != null) delete query[''] + + return path + '?' + encodeRfc3986(querystring.stringify(query)) +} + +aws4.RequestSigner = RequestSigner + +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} diff --git a/node_modules/aws4/lru.js b/node_modules/aws4/lru.js new file mode 100644 index 000000000..333f66a44 --- /dev/null +++ b/node_modules/aws4/lru.js @@ -0,0 +1,96 @@ +module.exports = function(size) { + return new LruCache(size) +} + +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} + +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} + +LruCache.prototype.set = function(key, val) { + var node = this.map[key] + if (node != null) { + node.val = val + } else { + if (!this.capacity) this.prune() + if (!this.capacity) return false + node = new DoublyLinkedNode(key, val) + this.map[key] = node + this.capacity-- + } + this.used(node) + return true +} + +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} + +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} + + +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} + +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return + + this.remove(node) + + if (this.firstNode == null) { + this.firstNode = node + this.lastNode = node + node.prev = null + node.next = null + } else { + node.prev = null + node.next = this.firstNode + node.next.prev = node + this.firstNode = node + } +} + +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) + } + return lastNode +} + +DoublyLinkedList.prototype.remove = function(node) { + if (this.firstNode == node) { + this.firstNode = node.next + } else if (node.prev != null) { + node.prev.next = node.next + } + if (this.lastNode == node) { + this.lastNode = node.prev + } else if (node.next != null) { + node.next.prev = node.prev + } +} + + +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null +} diff --git a/node_modules/aws4/package.json b/node_modules/aws4/package.json new file mode 100644 index 000000000..0ed04ad11 --- /dev/null +++ b/node_modules/aws4/package.json @@ -0,0 +1,132 @@ +{ + "_args": [ + [ + "aws4@^1.2.1", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request" + ] + ], + "_from": "aws4@>=1.2.1-0 <2.0.0-0", + "_id": "aws4@1.6.0", + "_inCache": true, + "_location": "/aws4", + "_nodeVersion": "4.5.0", + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/aws4-1.6.0.tgz_1486481933920_0.6127187723759562" + }, + "_npmUser": { + "email": "michael.hart.au@gmail.com", + "name": "hichaelmart" + }, + "_npmVersion": "4.0.5", + "_phantomChildren": {}, + "_requested": { + "name": "aws4", + "raw": "aws4@^1.2.1", + "rawSpec": "^1.2.1", + "scope": null, + "spec": ">=1.2.1-0 <2.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage/request", + "/request" + ], + "_resolved": "https://registry.npmjs.org/aws4/-/aws4-1.6.0.tgz", + "_shasum": "83ef5ca860b2b32e4a0deedee8c771b9db57471e", + "_shrinkwrap": null, + "_spec": "aws4@^1.2.1", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request", + "author": { + "email": "michael.hart.au@gmail.com", + "name": "Michael Hart", + "url": "http://github.com/mhart" + }, + "bugs": { + "url": "https://github.com/mhart/aws4/issues" + }, + "dependencies": {}, + "description": "Signs and prepares requests using AWS Signature Version 4", + "devDependencies": { + "mocha": "^2.4.5", + "should": "^8.2.2" + }, + "directories": {}, + "dist": { + "shasum": "83ef5ca860b2b32e4a0deedee8c771b9db57471e", + "tarball": "https://registry.npmjs.org/aws4/-/aws4-1.6.0.tgz" + }, + "gitHead": "74bf0b64d1e8cbcd184964999c7ef53f52d7ad32", + "homepage": "https://github.com/mhart/aws4#readme", + "installable": true, + "keywords": [ + "amazon", + "appstream", + "autoscaling", + "aws", + "cloudformation", + "cloudfront", + "cloudhsm", + "cloudsearch", + "cloudtrail", + "cloudwatch", + "codedeploy", + "cognito", + "cognitoidentity", + "cognitosync", + "config", + "containerservice", + "datapipeline", + "directconnect", + "dynamodb", + "ec2", + "ecs", + "elasticache", + "elasticbeanstalk", + "elasticloadbalancing", + "elasticmapreduce", + "elastictranscoder", + "elb", + "emr", + "glacier", + "iam", + "keymanagementservice", + "kinesis", + "kms", + "lambda", + "logs", + "mobileanalytics", + "monitoring", + "opsworks", + "rds", + "redshift", + "route53", + "route53domains", + "s3", + "ses", + "signature", + "sns", + "sqs", + "storagegateway", + "sts", + "swf" + ], + "license": "MIT", + "main": "aws4.js", + "maintainers": [ + { + "name": "hichaelmart", + "email": "michael.hart.au@gmail.com" + } + ], + "name": "aws4", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/mhart/aws4.git" + }, + "scripts": { + "test": "mocha ./test/fast.js ./test/slow.js -b -t 100s -R list" + }, + "version": "1.6.0" +} diff --git a/node_modules/azure-storage/.jshintignore b/node_modules/azure-storage/.jshintignore new file mode 100644 index 000000000..65880a4cc --- /dev/null +++ b/node_modules/azure-storage/.jshintignore @@ -0,0 +1,3 @@ +node_modules/* +packages +.git \ No newline at end of file diff --git a/node_modules/azure-storage/.jshintrc b/node_modules/azure-storage/.jshintrc new file mode 100644 index 000000000..8543421aa --- /dev/null +++ b/node_modules/azure-storage/.jshintrc @@ -0,0 +1,32 @@ +{ + "bitwise": true, + "camelcase": true, + "curly": false, + "eqeqeq": false, + "forin": true, + "immed": true, + "indent": 2, + "latedef": true, + "maxparams": false, + "maxdepth": false, + "maxstatements": false, + "maxcomplexity": false, + "newcap": true, + "noarg": true, + "node": true, + "noempty": true, + "nonew": true, + "plusplus": false, + "quotmark": "single", + "regexp": true, + "sub": true, + "strict": false, + "trailing": true, + "undef": true, + "unused": true, + "shadow": true, + "globals": { + "FileReader": true, + "window": true + } +} \ No newline at end of file diff --git a/node_modules/azure-storage/.npmignore b/node_modules/azure-storage/.npmignore new file mode 100644 index 000000000..62701d98d --- /dev/null +++ b/node_modules/azure-storage/.npmignore @@ -0,0 +1,11 @@ +# git # +.git* + +# Node # +node_modules/ + +# Test # +test/ + +# Examples # +examples/blobuploader/ \ No newline at end of file diff --git a/node_modules/azure-storage/.travis.yml b/node_modules/azure-storage/.travis.yml new file mode 100644 index 000000000..350b859c1 --- /dev/null +++ b/node_modules/azure-storage/.travis.yml @@ -0,0 +1,19 @@ +language: node_js +node_js: + - "4" + - "5" + - "6" + - "7" + +after_script: + - npm run coveralls + +install: + - npm --version + - npm install + +allow_failures: + - node_js: "5" + - node_js: "7" + +sudo: false \ No newline at end of file diff --git a/node_modules/azure-storage/BreakingChanges.md b/node_modules/azure-storage/BreakingChanges.md new file mode 100644 index 000000000..3f90681e5 --- /dev/null +++ b/node_modules/azure-storage/BreakingChanges.md @@ -0,0 +1,104 @@ +Tracking Breaking Changes in 2.0.0 + +ALL +* Fixed the issue that retry filter will continuously retry for client error like `ETIMEDOUT`. + +BLOB +* When specifiying access condition `If-None-Match: *` for read, it will always fail. + +QUEUE +* `createMessage` callback has been changed from `errorOrResponse` to `errorOrResult` which contains `messageId`, `popReceipt`, `timeNextVisible`, `insertionTime` and `expirationTime`. It can be passed to `updateMessage` and `deleteMessage` APIs. + +Tracking Breaking Changes in 1.4.0 + +BLOB +* Changed `/S` of SpeedSummary to `/s`. + +FILE +* Changed `/S` of SpeedSummary to `/s`. + +Tracking Breaking Changes in 1.3.0 + +QUEUE +* Updated the `QueueMessageResult.dequeueCount` from `string` to `number`. + +Tracking Breaking Changes in 1.2.0 + +TABLE +* Beginning with version 2015-12-11, the Atom feed is no longer supported as a payload format for Table service operations. Version 2015-12-11 and later versions support only JSON for the payload format. + +Tracking Breaking Changes in 1.0.0 + +BLOB +* The `blob` property of BlobResult has been renamed to `name` to keep consistent with other services API and the `listBlob` API. +* Decoded the block name of LockListResult from base64 string to utf-8 string. + +QUEUE +* The `encodeMessage` flag of QueueService has been replaced by `messageEncoder` which support `TextBase64QueueMessageEncoder`, `BinaryBase64QueueMessageEncoder`, `TextXmlQueueMessageEncoder` and custom implementation of QueueMessageEncoder. + +Tracking Breaking Changes in 0.10.0 + +ALL +* The `signedIdentifiers` parameter and result properties have been changed from array to hash map to avoid non unique signed identifier id. + +BLOB +* The `contentType`, `contentEncoding`, `contentLanguage`, `contentDisposition`, 'contentMD5' and `cacheControl` parameters and return values about the blob's content settings are grouped into a `contentSettings` sub property. +* The `contentMD5` parameter to verify the integrity of the data during the transport is changed to `transactionalContentMD5` +* The `copy*` return values are grouped into a `copy` sub property. +* The `lease*` return values are grouped into a `lease` sub property. +* The options.accessConditions parameter is changed to AccessConditions type. + +QUEUE +* Renamed QueueResult.approximatemessagecount to camelCase and change its type to 'number'. +* Renamed the property names of QueueMessageResult to camelCase +* Renamed the parameter options.messagettl of the createMessage API to options.messageTimeToLive. +* Updated the callback of the createMessage API from errorOrResult to errorOrResponse. +* Removed peekOnly option from the options parameter of the getMessages API. To peek messages, use peekMessages instead. + +FILE +* The `contentType`, `contentEncoding`, `contentLanguage`, `contentDisposition`, 'contentMD5' and `cacheControl` parameters and return values about the blob's content settings are grouped into a `contentSettings` sub property. +* The `contentMD5` parameter to verify the integrity of the data during the transport is changed to `transactionalContentMD5` +* The `copy*` return values are grouped into a `copy` sub property. +* The options.accessConditions parameter is changed to AccessConditions type. + +TABLE +* Renamed the function updateEntity to replaceEntity. +* Renamed TableUtilities.entityGenerator.Entity to EntityProperty. + +Tracking Breaking Changes in 0.7.0 + +ALL +* The generateDevelopmentStorageCredendentials function in the azure-storage.js is renamed to generateDevelopmentStorageCredentials. + +BLOB +* The AppendFromLocalFile function in the blobservice.js is renamed to appendFromLocalFile. +* The AppendFromStream function in the blobservice.js is renamed to appendFromStream. +* The AppendFromText function in the blobservice.js is renamed to appendFromText. +* The properties in the properties object of BlobResult and ContainerResult when listing blobs or containers are moved to the result object. +* The property names returned from listing blobs or containers are changed to camelCase. +* The blob result is added to the result of BlobService.commitBlocks and the blob list information is embedded in it. + +FILE +* The properties in the properties object of FileResult and ShareResult when listing files or shares are moved to the result object. +* The property names returned from listing files or shares are changed to camelCase. +* The property names returned from getting share stats are changed to camelCase. + +Tracking Breaking Changes in 0.5.0 + +ALL +* The suffix "_HEADER" is removed from all the http header constants. +* The generateSharedAccessSignatureWithVersion function in each service is deprecated. +* The shouldRetry function in the retry policy filters takes a "requestOption" object instead of a "retryData" object. + +BLOB +* The "publicAccessLevel" parameter in the BlobService.setContainerACL function is moved into the "options" parameter. +* The properties in the BlobService.setBlobProperties function are moved from the "options" to the "properties" parameter. +* The "AccessPolicy.Permission" is renamed to "AccessPolicy.Permissions" on the result object of the BlobService.getContainerAcl function. + +TABLE +* The "signedIdentifiers" parameter in the TableService.SetTableACL function is moved out from the "options" parameter. +* The "AccessPolicy.Permission" is renamed to "AccessPolicy.Permissions" on the result object of the TableService.getTableAcl function. + +QUEUE +* The option "options.messagetext" is renamed to "options.messageText" in the QueueService.UpdateMessage function. +* The "AccessPolicy.Permission" is renamed to "AccessPolicy.Permissions" on the result object of the QueueService.getQueueAcl function. diff --git a/node_modules/azure-storage/CONTRIBUTING.md b/node_modules/azure-storage/CONTRIBUTING.md new file mode 100644 index 000000000..288c5f378 --- /dev/null +++ b/node_modules/azure-storage/CONTRIBUTING.md @@ -0,0 +1,81 @@ +# Contribute Code or Provide Feedback + +If you would like to become an active contributor to this project please follow the instructions provided in [Microsoft Azure Projects Contribution Guidelines](https://azure.github.io/guidelines/). + +## Project Steup +The Azure Storage development team uses Visual Studio Code so instructions will be tailored to that preference. However, any preferred IDE or other toolset should be usable. + +### Install +* Node v0.10, v0.12 or v4 +* [Visual Studio Code](https://code.visualstudio.com/) + +### Development Environment Setup +To get the source code of the SDK via **git** just type: + +```bash +git clone https://github.com/Azure/azure-storage-node.git +cd ./azure-storage-node +``` + +Then, run NPM to install all the NPM dependencies: + +```bash +npm install +``` + +## Tests + +### Running +Unit tests don't require real credentials and don't require any environment variables to be set. By default the unit tests are run with Nock recording data. + +If you would like to run the unit test against a live storage account, you will need to setup environment variables which will be used. These test will use these credentials to run live tests against Azure with the provided credentials. Note that you will be charged for storage usage. You need verify the clean up script did its job at the end of a test run. + +Unit tests can then be run from root directory using: + +```bash +npm test +``` + +To run unit tests against live storage accounts, please set environment variable to turn off Nock by: + +```bash +export NOCK_OFF=true +``` + +and set up the following environment variables for storage account credentials by: + +```bash +export AZURE_STORAGE_CONNECTION_STRING="valid storage connection string" +export AZURE_STORAGE_CONNECTION_STRING_PREMIUM_ACCOUNT="optional valid storage connection string for premium storage account" +export AZURE_STORAGE_CONNECTION_STRING_SSE_ENABLED_ACCOUNT="optional valid storage connection string for storage account with storage service encryption enabled" +``` + +Note: `AZURE_STORAGE_CONNECTION_STRING_PREMIUM_ACCOUNT` and `AZURE_STORAGE_CONNECTION_STRING_SSE_ENABLED_ACCOUNT` are optional settings to enable testing suites related to premium storage account and storage service encryption, and only needed to be set when you are developing related features. + +### Testing Features +As you develop a feature, you'll need to write tests to ensure quality. Your changes should be covered by both unit tests. You should also run existing tests related to your change to address any unexpected breaks. + +## Pull Requests + +### Guidelines +The following are the minimum requirements for any pull request that must be met before contributions can be accepted. +* Make sure you've signed the [CLA](https://cla.azure.com/) before you start working on any change. +* Discuss any proposed contribution with the team via a GitHub issue **before** starting development. +* Code must be professional quality + * No style issues + * You should strive to mimic the style with which we have written the library + * Clean, well-commented, well-designed code + * Try to limit the number of commits for a feature to 1-2. If you end up having too many we may ask you to squash your changes into fewer commits. +* [ChangeLog.md](ChangeLog.md) needs to be updated describing the new change +* Thoroughly test your feature + +### Branching Policy +Changes should be based on the **dev** branch, not master as master is considered publicly released code. Each breaking change should be recorded in [BreakingChanges.md](BreakingChanges.md). + +### Adding Features for All Platforms +We strive to release each new feature for each of our environments at the same time. Therefore, we ask that all contributions be written for Node v0.10 and later. + +### Review Process +We expect all guidelines to be met before accepting a pull request. As such, we will work with you to address issues we find by leaving comments in your code. Please understand that it may take a few iterations before the code is accepted as we maintain high standards on code quality. Once we feel comfortable with a contribution, we will validate the change and accept the pull request. + +Thank you for any contributions! Please let the team know if you have any questions or concerns about our contribution policy. \ No newline at end of file diff --git a/node_modules/azure-storage/CONTRIBUTORS.txt b/node_modules/azure-storage/CONTRIBUTORS.txt new file mode 100644 index 000000000..8c3beba6c --- /dev/null +++ b/node_modules/azure-storage/CONTRIBUTORS.txt @@ -0,0 +1,7 @@ +Contributors should submit an update to this file with a commit in order to receive recognition. Thank you for your contributions. + +List of Contributors +==================== + +Microsoft Corporation +Microsoft Open Technologies, Inc \ No newline at end of file diff --git a/node_modules/azure-storage/ChangeLog.md b/node_modules/azure-storage/ChangeLog.md new file mode 100644 index 000000000..2f5d45f7a --- /dev/null +++ b/node_modules/azure-storage/ChangeLog.md @@ -0,0 +1,761 @@ +Note: This is an Azure Storage only package. The all up Azure node sdk still has the old storage bits in there. In a future release, those storage bits will be removed and an npm dependency to this storage node sdk will +be taken. This is a GA release and the changes described below indicate the changes from the Azure node SDK 0.9.8 available here - https://github.com/Azure/azure-sdk-for-node. + +2018.02 Version 2.8.0 + +ALL +* Updated storage service version to 2017-07-29. + +BLOB +* Added support for Soft Delete feature. +* Fixed several blobuploader example issues. +* Fixed a compatibility issue for `getBlobToLocalFile` and `createReadStream` with Node.js v9. +* Fixed a bug that blob name will be wrongly trimmed to empty string when listing blobs. +* Fixed a bug when blob size > 32M, GetBlobStream returns root blob data instead of snapshot data. + +FILE +* Fixed a compatibility issue for `getFileToLocalFile` and `createReadStream` with Node.js v9. + +2017.12 Version 2.7.0 + +ALL +* Default HTTP connection will enable keep-alive to improve performance. + +BLOB +* Added support for `getBlobProperties`, `listBlobsSegmented` and `listBlobsSegmentedWithPrefix` to return `AccessTierChangeTime` and `AccessTierInferred` properties. +* Fixed a blob lease support issue for `appendFromText` and `resizePageBlob`. + +TABLE +* Fixed an apostrophe missing issue in `TableQuery.where()` example. + +2017.10 Version 2.6.0 + +FILE + +* Added support for file share snapshot. + +2017.09 Version 2.5.0 + +ALL +* Optimized samples and documentation for retry policies. +* Added additional samples for blob and file. + +BLOB +* Optimized `commitBlocks` API implementation and documentation. + +FILE +* Added support for File metrics. + +2017.08 Version 2.4.0 + +ALL +* Fixed a TypeScript issue that `browserFile` should be `Object` type in the TypeScript definition file. + +BLOB +* Added support for getting and setting a tier for a block blob under a LRS Blob Storage Account from tiers hot, cool and archive. + +2017.08 Version 2.3.0 + +ALL +* Updated storage service version to 2017-04-17. For more information, please see - https://docs.microsoft.com/en-us/rest/api/storageservices/versioning-for-the-azure-storage-services +* Updated the dependency of the 'request' module to avoid security vulnerability: (https://snyk.io/test/npm/azure-storage). +* Added `requestServerEncrypted` property to `ServiceResponse` which indicates if the contents of the request have been successfully encrypted. +* Improved API documentation. + +BLOB +* PageBlobs: For Premium Accounts only, added support for getting and setting the tier on a page blob. The tier can also be set when creating or copying from an existing page blob. + +FILE +* Added `serverEncryped` property to `FileResult` and `DirectoryResult` which indicates if the file data and application metadata are completely encrypted using the specified algorithm on the server. +* Fixed a TypeScript issue that SharedAccessPermissions for FileUtilities is missing in type definition file. + +TABLE +* Fixed a typo in table query example for combineFilters function. + +2017.08 Version 2.2.2 + +ALL + +* Fixed a retry timeout issue during uploading. + +2017.07 Version 2.2.1 + +BLOB + +* Optimized memory usage especially for uploading blobs with large block size. + +2017.06 Version 2.2.0 + +ALL +* Fixed a TypeScript issue that callback of `createWriteStreamToBlockBlob` should be optional in the TypeScript definition file. +* Fixed a bug in TypeScript definition file about `AccessConditions` mismatches with `AccessCondition` which is exported in JavaScript. +* Fixed an undefined property issue in `BlobResult` object of the sample code. +* Updated node-uuid to uuid. +* Updated underscore version to 1.8.3. +* Updated validator version to 3.35.0. + +BLOB +* Added a `defaultEnableReuseSocket` option for `BlobService` to control reuseSocket settings. +* Fixed a hanging or silent failing issue for blob uploading under some situations. +* Fixed a bug that `doesBlobExist` does not support `snapshotId` parameter. +* Fixed a bug in `getBlobToLocalFile` that `fs` will throw exceptions instead of returning errors in callback. + +FILE +* Added a `defaultEnableReuseSocket` option for `FileService` to control reuseSocket settings. +* Fixed a hanging or silent failing issue for file uploading under some situations. +* Fixed a bug in `getFileToLocalFile` that `fs` will throw exceptions instead of returning errors in callback. + +2017.03 Version 2.1.0 + +ALL +* Fixed the type script issue that AccessConditions is missing in the type definition file. + +BLOB +* Added support for page blob incremental copy. Refer to https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/incremental-copy-blob + +QUEUE +* Fixed the issue that `responseObject` may not have response body in `createMessage` function. + +BROWSER +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.1.0 + +2017.01 Version 2.0.0 + +ALL +* Updated storage service version to 2016-05-31. Fore more information, please see - https://msdn.microsoft.com/en-us/library/azure/dd894041.aspx +* Fixed the issue that `BatchOperation` doesn't support socket reuse for some node versions. +* Fixed the issue that `BatchOperation` request pool size is too big when the socket reuse is supported. +* Added empty headers to string-to-sign. +* For response has body and no `content-type` header, try to parse the body using xml format. +* Fixed the issue that retry filter will continuously retry for client error like `ETIMEDOUT`. +* Added support for client side timeout. In order to set the timeout per API, please use `options.clientRequestTimeoutInMs`. To set the default value for all requests made via a particular service, please use `{blob|queue|table|file}Service.defaultClientRequestTimeoutInMs`. + +BLOB +* Added support for large block blob. +* Added `publicAccessLevel` to `ContainerResult` for the APIs `listContainersSegmented` and `listContainersSegmentedWithPrefix`. +* When specifying access condition `If-None-Match: *` for reading, it will always fail. +* Returned content MD5 for range gets Blobs. +* Fixed the issue that `useTransactionalMD5` didn't take effect for downloading a big blob. + +QUEUE +* `createMessage` callback has been changed from `errorOrResponse` to `errorOrResult` which contains `messageId`, `popReceipt`, `timeNextVisible`, `insertionTime` and `expirationTime`. It can be passed to updateMessage and deleteMessage APIs. + +FILE +* Returned content MD5 for range gets Files. +* Fixed the issue that `useTransactionalMD5` didn't take effect for downloading a big file. +* Added support for listing files and directories with prefix, refer to `FileService.listFilesAndDirectoriesSegmentedWithPrefix`. + +TABLE +* Fixed the issue that response in incorrect for table batch operation when the error response item is not the first item in the responses. + +2016.11 Version 1.4.0 + +ALL +* Added `ENOTFOUND` for secondary endpoint and `ECONNREFUSED` to `RetryPolicyFilter`. +* Added support for `text/html` error response body. + +BLOB +* Fixed the issue that the ChunkAllocator maxCount is aligned with parallelOperationThreadCount. +* Changed `/S` of SpeedSummary to `/s`. +* Fixed the issue that `BlobService.createBlockBlobFromText` will hang when passed `null` or `undefined` `text` argument. +* Fixed the issue that `BlobService.createBlockBlobFromText` will always set `content-type` to `text/plain`. + +QUEUE +* Allowed `QueueService.peekMessages` against secondary endpoint. + +FILE +* Fixed the issue that the ChunkAllocator maxCount is aligned with parallelOperationThreadCount. +* Changed `/S` of SpeedSummary to `/s`. + +2016.10 Version 1.3.2 + +BLOB +* Prevent a blockId from being generated with a decimal point. + +2016.09 Version 1.3.1 + +ALL +* Improved the type script support. + +2016.08 Version 1.3.0 + +ALL + +* Fixed the issue that retry filter will fail against storage emulator. +* Fixed a hang issue of `StorageServiceClient` with retry policy filter set when retrying sending the request, the stream is not readable anymore. +* Updated the default value of `CorsRule.ExposedHeaders`, `CorsRule.AllowedHeaders` to empty and `CorsRule.MaxAgeInSeconds` to `0` for `setServiceProperties` APIs of all services. +* Fixed the issue that service SAS doesn't work if specifying the `AccessPolicy.Protocols`. + +BLOB +* Added the API `BlobService.getPageRangesDiff` for getting the page ranges difference. Refer to https://msdn.microsoft.com/en-us/library/azure/mt736912.aspx for more detailed information. + +QUEUE +* Updated the `QueueMessageResult.dequeueCount` from `string` to `number`. +* Added the API `QueueService.getUrl` for getting the queue url. + +TABLE +* Added the API `TableService.getUrl` for getting the table url. + +2016.07 Version 1.2.0 + +ALL +* Fixed the issue that metadata name will be converted to lower-case after retrieving back from the server. **Note** that this fix is only applicable for Node 0.12 or higher version. +* Added support for EndpointSuffix for all service constructors. +* Updated storage service version to 2015-12-11. Fore more information, please see - https://msdn.microsoft.com/en-us/library/azure/dd894041.aspx +* Updated the `request` package to version 2.74.0 to address the security vulnerability - https://nodesecurity.io/advisories/130 + +BLOB +* Fixed the issue that the service error message will be written to the destination stream if getting error when downloading the blob to a stream/file. +* Added `serverEncryped` property to `BlobResult` class which indicates if the blob data and application metadata are completely encrypted using the specified algorithm on the server. + +FILE +* Fixed the issue that the service error message will be written to the destination stream if getting error when downloading the file to a stream/file. + +TABLE +* The atom feed payload format is not supported anymore for table service APIs. + +2016.06 Version 1.1.0 + +ALL +* Fixed the issue that using SAS doesn't work against storage emulator. +* Fixed the issue that the service SAS signature is incorrect when protocol parameter is specified. +* Fixed the issue that the timeout query string should be in seconds instead of milliseconds. + +BLOB +* Added parameter snapshotId to BlobService.getUrl function to support getting url of a specified snapshot. +* Fixed the issue that the getUrl doesn't work against storage emulator. +* Fixed the race issue that the _rangeList may be deleted before using it in the BlockRangeStream._getTypeList function. +* Fixed the issue that downloading block blob with size bigger than 32MB will fail when using anonymous credential. +* Added `CREATE` to `BlobUtilities.SharedAccessPermissions`. + +TABLE +* Supported string type value for entity PartionKey and RowKey. +* Supported implicit Edm type value for entity properties. The supported implicit Edm types including Int32, Double, Bool, DateTime and String. + +FILE +* Fixed the issue that the getUrl doesn't work against storage emulator. +* Added `CREATE` to `FileUtilities.SharedAccessPermissions`. + +2016.05 Version 1.0.1 + +ALL +* Fixed the issue that StorageServiceClient._normalizeError will throw exception on Node below v4 because string.startsWith is not available on Node below v4. + +2016.05 Version 1.0.0 + +BLOB +* The `blob` property of BlobResult has been renamed to `name` to keep consistent with other services API and the `listBlob` API. +* Decoded the block name of LockListResult from base64 string to utf-8 string. + +QUEUE +* The `encodeMessage` flag of QueueService has been replaced by `messageEncoder` which support `TextBase64QueueMessageEncoder`, `BinaryBase64QueueMessageEncoder`, `TextXmlQueueMessageEncoder` and custom implementation of QueueMessageEncoder. + +TABLE +* Fixed the issue that loses the data type for Edm.Double value like: 1.0. +* Fixed the issue that loses the data precision for Edm.Int64 value when it is outisde of the range (2^53 - 1) to -(2^53 - 1). + +2016.03 Version 0.10.0 + +ALL +* The `signedIdentifiers` parameter and result properties have been changed from array to hash map to avoid non unique signed identifier id. + +BLOB +* Added 'COPY' to the BlobUtilities.BlobListingDetails to include copy information in the results. +* Added 'bytesCopied' and 'totalBytes' to the blob result. +* Added the blob result to the callback of BlobService.commitBlocks. +* Moved the properties in the properties object of BlobResult and ContainerResult when listing blobs or containers to the result object. +* Renamed the property names returned from listing blobs or containers to camelCase. +* The `contentType`, `contentEncoding`, `contentLanguage`, `contentDisposition`, 'contentMD5' and `cacheControl` parameters and return values about the blob's content settings are grouped into a `contentSettings` sub property. +* The `contentMD5` parameter to verify the integrity of the data during the transport is changed to `transactionalContentMD5` +* The `copy*` return values are grouped into a `copy` sub property. +* The `lease*` return values are grouped into a `lease` sub property. +* The options.accessConditions parameter is changed to AccessConditions type. + +QUEUE +* Renamed QueueResult.approximatemessagecount to camelCase and change its type to 'number. +* Renamed the property names of QueueMessageResult to camelCase. +* Renamed the parameter options.messagettl of the createMessage API to options.messageTimeToLive. +* Updated the callback of the createMessage API from errorOrResult to errorOrResponse. +* Removed peekOnly option from the options parameter of the getMessages API. To peek messages, use peekMessages instead. +* Added getMessage and peekMessage API. + +FILE +* Moved the properties in the properties object of FileResult and ShareResult when listing files or shares to the result object. +* Renamed the property names returned from listing files or shares to camelCase. +* Renamed the property names returned from getting share stats to camelCase. +* The `contentType`, `contentEncoding`, `contentLanguage`, `contentDisposition`, 'contentMD5' and `cacheControl` parameters and return values about the blob's content settings are grouped into a `contentSettings` sub property. +* The `contentMD5` parameter to verify the integrity of the data during the transport is changed to `transactionalContentMD5` +* The `copy*` return values are grouped into a `copy` sub property. +* Fixed the issue that SAS tokens created from table names with upper-case letters do not work. +* The options.accessConditions parameter is changed to AccessConditions type. + +TABLE +* Fixed the issue that getTableAcl returns empty array with signedIdentifier property. +* Renamed the function updateEntity to replaceEntity. +* Renamed TableUtilities.entityGenerator.Entity to EntityProperty. + +2016.03 Version 0.9.0 + +ALL +* Updated storage service version to 2015-04-05. Fore more information, please see - https://msdn.microsoft.com/en-us/library/azure/dd894041.aspx +* Added support for Account SAS. +* Added support for IPACL and Protocols options for service SAS. +* Fixed the issue where the authentication may fail when a metadata key is in upper case. +* Added 'nsp check' task for security vulnerability check. +* Updated the dependency of the 'request' module to avoid the security vulnerability reported by the 'nsp' tool. + +BLOB +* Added new permission 'ADD' for service SAS. + +FILE +* Added support for metrics setting for service properties. + +2016.01 Version 0.8.0 + +ALL +* Preview release of the TypeScript definition file at "lib/azure-storage.d.ts". + +BLOB +* Added the blob result to the callback of BlobService.commitBlocks. +* Added the speed summary to the downloading APIs. + +2015.12 Version 0.7.0 + +ALL +* Fixed the typo in the function generateDevelopmentStorageCredentials. +* Fixed the issue that the HTTP global agent setting is changed during parallel uploading and downloading and impacts on other Node.js applications. +* Fixed the issue that the chunked stream writing methods do not accept string. +* Fixed the issue that the request fails when the content-length is set to string '0' in the 'sendingRequestEvent' event handler. +* Supported retry on XML parsing errors when the XML in the response body is corrupted. +* Replaced the dependency "mime" to "browserify-mime" to work with Browserify. + +BLOB +* Added an option to skip the blob or file size checking prior to the actual downloading. +* Fixed the issue that it doesn't callback when loses the internet connection during uploading/uploading. +* Fixed the issue that the local file cannot be removed in the callback when uploading a blob from a local file. +* Fixed the issue that the stream length doesn't work when it is larger than 32MB in the createBlockBlobFromStream, createPageBlobFromStream, createAppendBlobFromStream and appendFromStream functions. +* Fixed the issue that it doesn't return error in the page range validation when the size exceeds the limit. +* Renamed the function AppendFromLocalFile to appendFromLocalFile. +* Renamed the function AppendFromStream to appendFromStream. +* Renamed the function AppendFromText to appendFromText. + +TABLE +* Fixed the issue that listTablesSegmentedWithPrefix with maxResult option throws exception. + +2015.09 Version 0.6.0 + +ALL +* Fixed the MD5 mismatch issue in uploading a blob when running with Node.js v4.0 or io.js. + +BLOB +* Fixed the issue that it doesn't prompt appropriate error message when the source URI is missing in BlobService.startCopyBlob(). + +2015.08 Version 0.5.0 + +ALL +* Updated storage service version to 2015-02-21. For more information, please see - https://msdn.microsoft.com/en-us/library/azure/dd894041.aspx +* Unified the function parameters for setting ACL of container, table, queue and share. +* Renamed 'AccessPolicy.Permission' to 'AccessPolicy.Permissions' on the result object from get*Acl to match the property name on the signedIdentifier property passed to set*Acl calls. +* Unified the name pattern of the http header constants. +* Split the property parameters from the options parameter for setting properties of blob, share and file. +* Updated the error message when an argument is in a wrong type while it requires a string. +* Exported AccessCondition to generate an object that represents a condition. +* Fixed an issue that the SAS in the SharedAccessSignature part of the connection string cannot start with '?'. +* Deprecated the generateSharedAccessSignatureWithVersion() method in each service. + +BLOB +* Supported operating against append blobs. +* Fixed an issue that the file descriptor in the FileReadStream is not closed. + +QUEUE +* Fixed an issue that options.messageText doesn't work in QueueService.updateMessage. + +2015.06 Version 0.4.5 + +* Updated the dependency of the 'request' module to avoid the security vulnerability reported by the 'nsp' tool: (https://nodesecurity.io/advisories/qs_dos_extended_event_loop_blocking) and (https://nodesecurity.io/advisories/qs_dos_memory_exhaustion). +* Included package validation in grunt tasks. + +2015.05 Version 0.4.4 + +ALL +* Updated the dependency of the 'validator' module to avoid the security vulnerability reported by the 'nsp' tool. (https://nodesecurity.io/advisories/validator-isurl-denial-of-service) +* Updated the error message when an argument is in a wrong type while it requires a string. +* Updated the grunt file to run test with mocha and generate jsDoc. + +BLOB +* Fixed an issue that the metadata is duplicated when creating a page blob. +* Fixed an issue that the metadata is duplicated when setting blob's metadata with metadata in the options. +* Fixed an issue that cannot create an empty block blob with useTransactionalMD5 option. + +FILE +* Fixed an issue that the result of file downloading contains wrong values for share, directory or file names. + +TABLE +* Fixed an issue that it prompts "Cannot set property 'isSuccessful' of null" when TableService.createTableIfNotExists is called. + +2015.03 Version 0.4.3 + +ALL +* Fixed an issue that setting metadata keys are converted into lowercase. The metadata keys retrieved from the service will however still be converted into lowercase by the http component of Node.js.(https://github.com/joyent/node/issues/1954) +* Included all storage error code strings in the error constants definition. +* Documented the client request ID option in all APIs. + +BLOB +* Supported listing blob virtual directories. +* Fixed an issue that exception is thrown when downloading a blob larger than 32MB to a stream. +* Fixed an issue that the process exits when the free memory is low. + +2014.12 Version 0.4.2 + +ALL +* Fixed an issue that batch operation could probably wait without callback. +* Added the readable-stream module to adapt stream operations in both node 0.8 and node 0.10. +* Supported nock in tests. + +BLOB +* Supported trimming the default port of http or https when getting URL for the blob service. +* Fixed an issue that the metadata is not populated when getting the blob to text. + +FILE +* Supported trimming the default port of http or https when getting URL for the file service. + +2014.11.28 Version 0.4.1 + +ALL +* Fixed an issue where the request does not invoke the callback when the input stream ends with an 'end' event instead of a 'finish' event. +* Fixed an issue where the request does not invoke the callback when the input stream ends with a 'close' event on Node 0.8.X. +* Fixed an issue that the temporary files generated by unit tests are not cleaned up. +* Fixed an issue that the unit tests may fail when the file generated by previous tests is not accessible temporarily. + +FILE +* Added support to download a single file in parallel similar to upload. You can set ‘parallelOperationThreadCount’ option for api’s that download a file to indicate number of parallel operations to use for download. + +TABLE +* Fixed an issue which caused invalid input errors when the partition key or the row key contains an apostrophe. + +2014.10.28 Version 0.4.0 + +ALL +* Provide an option to enable/disable nagling. Nagling is disabled by default. It can be enabled by setting options.useNagleAlgorithm to true. +* Added batch operation callback in sequence mode. + +BLOB +* Added support to download a single blob in parallel similar to upload. You can set ‘parallelOperationThreadCount’ option for api’s that download a blob to indicate number of parallel operations to use for download. +* Added speed summary in blob downloading. + +FILE +* Fixed an issue which caused an invalid resource name error when the directory name starts or ends with a '/' + +2014.08.20 Version 0.3.3 + +BLOB +* Fixed an issue where SAS tokens were being incorrectly generated for the root container and when the blob name required encoding. +* Documented the 'parallelOperationThreadCount' option as input to various uploadBlob APIs. + +FILE +* Fixed an issue where signing was incorrect when the URI contained '.' or '..'. +* Fixed an issue where "getURI" was requiring a file parameter, although the parameter should be optional. + +2014.07.25 Version 0.3.2 + +ALL +* Fixed an issue which prevented transient server errors like ECONNRESET, ESOCKETTIMEDOUT and ETIMEDOUT from being retried. + +BLOB +* Fixed an issue which caused a reference error in blobs due to 'err' not being defined. + +2014.07.22 Version 0.3.1 + +ALL +* Fixed an issue which failed to validate special names for containers and tables. +* Exposed the Validation utility methods so users can use it to validate resource names. + +BLOB +* Fixed an issue which caused failures when an error was encountered while uploading big blobs. + +2014.07.07 Version 0.3.0 + +BLOB +* Fixed an issue which failed to return single item blocklists while doing listBlocks. + +FILE +* Added File Service support. The File Service and the associated APIs are in preview. + +2014.07.01 Version 0.2.1 + +ALL +* Fixed an issue with casing which caused the module to fail on linux machines. + +BLOB +* Fixed an issue which failed to upload an empty blob for empty block blob files uploaded using createBlockBlobFromFile when retry policies were used. + +2014.06.16 Version 0.2.0 + +ALL +* Updated storage service version to 2014-02-14. The SAS tokens generated will therefore contain a signed version of 2014-02-14 and all the requests using SAS credentials have the api-version query parameter appended to the URI. + +2014.06.12 Version 0.1.0 + +ALL +* The package has been renamed to azure-storage. +* There is no separate azure-common sub-package. Everything is condensed into a single package called azure-storage. +* azure.create*Service supports the following configurations: + * create*Service(connection string) + * create*Service(account name, account key) + * create*Service(storage host, sasToken) +* Added the ability to choose which SAS Version to use when generating Shared Access Signatures (either the 2012-02-12 or 2013-08-15 versions). +* Host can be given as either an object with primaryHost and secondaryHost or as a string representing the primary. +* The order credentials are assessed is consistent: If parameters are passed in, they and they alone are honored. There is no mixing (ex, if users pass in host, they won't get the access key from your env var). If no parameters are passed in, the env vars are used. Within both those strategies, the order of evaluation is emulator (in the case of EMULATED env var only), connection string, account/key or SAS, anonymous. If account/key and SAS are passed in, an error is thrown indicating the credentials are invalid. +* Removed the ability to create a storage service from a config file. +* azure.create*Service supports secondaryHost only, but either primaryHost or secondaryHost must be provided. +* Storage service client constructors take the sasToken rather than a credentials object, meaning that the SharedAccessSignature class no longer needs to be used by consumers. +* Ensure request is always built/signed for every retry attempt. +* Custom retry policies should implement the shouldRetry method and return an object with the retryInterval and retryable information in it. Optionally, they can also set the locationMode and targetLocation to which the request should be sent. +* Implemented RA-GRS support. For more information on this, please see - http://blogs.msdn.com/b/windowsazurestorage/archive/2013/12/04/introducing-read-access-geo-replicated-storage-ra-grs-for-windows-azure-storage.aspx +* Service properties updated: replaced metrics with hour metrics and minute metrics, added cors support, added defaults if properties are unspecified to reduce invalid xml exceptions. +* Added maximum execution time, settable for all requests via {blob|queue|table}service.defaultMaximumExecutionTime or for an individual request via options.maximumExecutionTime. This applies to all requests except blob downloads. +* The blob, queue and table services no longer set/modify any values within the options object optionally passed in by the user for every API. +* Fixed an issue where null, empty and white-space only metadata header values were allowed. +* "timeout" query parameter will not be sent to the server if not set by the user. In order to set the timeout per API, please use options.timeoutIntervalInMs. To set it for all requests made via a particular service, please use {blob|queue|table}Service.defaultTimeoutIntervalInMs. +* ECONNRESET is handled in the retry policy filter. +* DevStore with secondary access is supported. +* Set*Acl takes signed identifiers as a parameter - before it was in options. +* GenerateSharedAccessSignature() produces a query string rather than an object. +* The SharedKey class has the methods to create shared access signatures. These should not be in the SharedAccessSignature class because one can only create a SAS if they have the account/key. +* The service client no longer evaluates the port and protocol set on it. Before, if storageserviceclient.host was called and port and protocol had been changed after host was set, host would be incorrect. +* Removed SharedKeyLite and SharedKeyLiteTable in favor of SharedKey and SharedKeyTable which were already the defaults. +* Added separate utility files for Blob, Queue, Table, and Storage. These contain useful enums that were previously found in a single Constants file as well as new utility functions. The old Constants file will mostly include internal-use constants. + +BLOB +* createBlobServiceWithSas has been provided to create a blobService to use with a Shared Access Signature. Users can create a blobService using azure.createBlobServiceWithSas(host, sasToken). +* Anonymous access for the blob service is supported. +* Added support for 2013-08-15 Blob SAS changes. +* Renamed listBlobs to listBlobsSegmented and added listBlobsSegmentedWithPrefix. listBlobsSegmented takes in currentToken and listBlobsSegmentedWithPrefix takes in prefix and currentToken along with other parameters. Please look at the documentation of these APIs for a list of parameters that users can set on the options object. These APIs return only error, result and response. The result contains entries which is a list of blobs and a continuation token for successive listing operations. +* Renamed copyBlob to startCopyBlob. +* Renamed putBlockBlobFromStream to _putBlockBlobFromStream and putBlockBlobFromFile to _putBlockBlobFromFile. These are internal methods and should not be called by users directly. Please use createBlockBlobFromStream and createBlockBlobFromFile. +* Renamed page methods: listBlobRegions to listPageRanges, createBlobPagesFromText to createPagesFromText, clearBlobPages to clearPageRanges. +* Renamed block methods: createBlobBlockFromStream to createBlockFromStream, createBlobBlockFromText to createBlockFromText, commitBlobBlocks to commitBlocks, listBlobBlocks to listBlocks. +* BlobService lease methods also work with container leases, simply specify null for the blob parameter. +* Added changeLease method to modify the lease ID of an active lease. +* Fixed lease issues, break lease allows a leaseBreakPeriod of 0, lease time header is returned as an int rather than a string. +* Added snapshot delete options: when deleting a blob with snapshots, users can decide to delete blob and snapshots or just snapshots. The options are provided in BlobUtilities.SnapshotDeleteOptions.*. +* deleteBlob callback does not return isSuccessful. +* Added does{Container|Blob}Exist methods in blobservice that can be used to determine if a particular container or blob exists. +* Added delete{Container|Blob}IfExists methods in blobservice that can be used to delete a container or a blob only when they exist. +* Added ContentMD5 validation for blob downloads. This is turned on by default for all block blob downloads and all page blob range downloads as long as the range is less than 4MB. In order to turn this off, set options.disableContentMD5Validation to true explicitly. +* x-ms-range-get-content-md5 is set internally by the library and users do not have to specify it in the options. +* Removed the option of doing range downloads while downloading a blob to text. +* Added sequence number support for page blobs. Users can set the sequence number of a page blob using blobService.setPageBlobSequenceNumber and manage concurrency issues using x-ms-if-sequence-number-le, x-ms-if-sequence-number-lt and x-ms-if-sequence-number-eq. Please see http://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more details about using sequence numbers. +* Removed createBlob API. Please use createPageBlob and createBlockBlob* APIs to create the respective blobs. +* Renamed createPagesFromText to _createPagesFromText. This is an internal method and should not be called by users directly. +* Added resizePageBlob that can be used to resize a page blob. +* createPageBlob takes in the blob's sequence number using options.sequenceNumber. +* All the BlobService APIs that took cacheControl/cacheControlHeader, contentType/contentTypeHeader, contentEncoding/contentEncodingHeader, contentLanguage/contentLanguageHeader, contentMD5/contentMD5Header in options only take cacheControl, contentType, contentEncoding, contentLanguage and contentMD5. These are the values that will be set on the blob at the server. +* createPagesFromStream takes in the following 2 options - useTransactionalMD5 to calculate and send/validate content MD5 for each transaction and contentMD5 which is an optional hash value. When contentMD5 is provided, the client library uses that instead of trying to calculate it based on the data being uploaded. +* createBlockBlobFromText, createBlockFromStream and createBlockFromText allows users to set useTransactionalMD5 on options to calculate and send/validate content MD5 for each transaction. +* Added createWriteStreamToBlockBlob, createWriteStreamToNewPageBlob and createWriteStreamToExistingPageBlob that provide a stream for writing to the blob. +* Added createReadStream that provides a stream for reading from the blob. +* blobService can have a default parallelOperationThreadCount which specifies the number of parallel upload operations that may be performed when uploading a blob that is greater than the value specified by singleBlobPutUploadThresholdInBytes. This value can be set using blobService.parallelOperationThreadCount. The default value set on blobService is 1. +* createBlockBlobFromText supports text Buffers in addition to strings. +* createBlockBlobFromText will throw an error if the uploaded content exceeds 64MB. +* BlobService getBlobUrl has been renamed to getUrl as it can also produce container urls. It can no longer create a SAS token (it used to take sharedAccessPolicy) but can take a sasToken produced by the generateSharedAccessSignature method and produce a url with that. + +QUEUE +* Added Shared Access Signatures for queues. createQueueServiceWithSas has been provided to create a queueService to use with a Shared Access Signature. Users can create a queueService using azure.createQueueServiceWithSas(host, sasToken). +* Renamed listQueues to listQueuesSegmented and added listQueuesSegmentedWithPrefix. listQueuesSegmented takes in currentToken and listQueuesSegmentedWithPrefix takes in prefix and currentToken along with other parameters. Please look at the documentation of these APIs for a list of parameters that users can set on the options object. These APIs return only error, result and response. The result contains entries which is a list of queues and a continuation token for successive listing operations. +* deleteQueue and deleteMessage callbacks do not return isSuccessful. +* Added an option in the queue service to turn base 64 encoding off. + +TABLE +* Added Shared Access Signatures for tables. createTableServiceWithSas has been provided to create a tableService to use with a Shared Access Signature. Users can create a tableService using azure.createTableServiceWithSas(host, sasToken). +* Added JSON support for tables and removed AtomPub. For the different flavours of JSON supported, please see - http://blogs.msdn.com/b/windowsazurestorage/archive/2013/12/05/windows-azure-tables-introducing-json.aspx. +* Renamed queryTables to listTablesSegmented and added listTablesSegmentedWithPrefix. listTablesSegmented takes in currentToken and listTablesSegmentedWithPrefix takes in prefix and currentToken along with options and callback. Please look at the documentation of these APIs for a list of parameters that users can set on the options object. These APIs return only error, result and response. The result contains entries which is a list of tables and a continuation token for successive listing operations. +* deleteTable and deleteEntity callbacks do not return isSuccessful. +* queryEntities in TableService returns 3 parameters instead of 4: the entities and queryResultContinuation parameters are returned within a queryResult object. +* Added support for disabling echo content in inserts. By default, inserts do not echo content. +* Changed table error parsing so that the code string and message string are directly accessible from the error object. +* Removed the getTable method; doesTableExist works similarly. +* createTable does not request content back from the service, but still returns an object containing the TableName. +* Renamed queryEntity in TableService to retrieveEntity. +* Modified how batches work. Instead of turning the service batch mode on/off, a batch is a separate entity like query. Batches are constructed and then executed. +* queryEntities in TableService requires a continuation token. +* TableService updateEntity, mergeEntity and deleteEntity do not take a checkEtag option. The entity's etag is sent if it exists, otherwise * is sent. +* retrieveEntity and queryEntities accept empty partition and row keys. +* Added entity-property-creation helper methods. Users can use the entityGenerator provided in TableUtilities and create entity properties as follows: + var entGen = TableUtilities.entityGenerator; + var entity = { PartitionKey: entGen.String('part2'), + RowKey: entGen.String('row1'), + boolValueTrue: entGen.Boolean(true), + boolValueFalse: entGen.Boolean(false), + intValue: entGen.Int32(42), + dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))), + complexDateValue: entGen.DateTime(new Date(Date.UTC(2013, 02, 16, 01, 46, 20))) + }; +* Removed TableQuery whereKeys method. Instead of tableQuery.whereKeys, tableService.retrieveEntity should be used. +* Removed TableQuery whereNextKeys method. Instead of tableQuery.whereNextKeys, tableService.queryEntities takes currentToken which can be retrieved from a previous queryEntities call in results. +* Removed TableQuery from method. Instead of tableQuery.from, tableService.queryEntities takes table and tableQuery may be null to represent retrieving all entities in the table. +* TableQuery select is an instance method for consistency with top and where. Instead of TableQuery.select('foo'), use new TableQuery().select('foo'). +* TableQuery provides helper methods to create filter strings to use with the where clause for a query. Query strings may also include type specifiers where necessary. + For example, to query on a long value, users could do the following: + var tableQuery = new TableQuery().where(TableQuery.int64Filter('Int64Field', TableUtilities.QueryComparisons.EQUAL, '4294967296')); + OR + var tableQuery = new TableQuery().where('Int64Field == ?int64?', '4294967296'); + +2013.01.15 Version 0.8.0 +* Added the Preview Service Management libraries as separate modules +* Added ability to consume PEM files directly from the Service Management libraries +* Added support for createOrUpdate and createRegistrationId in the Notification Hubs libraries + +2013.01.10 Version 0.7.19 +* Lock validator version + +2013.11.27 Version 0.7.18 +* Lock xmlbuilder version + +2013.11.5 Version 0.7.17 +* Added getBlob and createBlob operations that support stream piping +* Added compute, management, network, serviceBus, sql, storage management, store and subscription preview wrappers +* Multiple bugfixes + +2013.10.16 Version 0.7.16 +* Improved API documentation +* Updated Virtual Machines API to 2013-06-01 +* Added website management preview wrappers +* Multiple bugfixes + +2013.08.19 Version 0.7.15 +* Multiple storage fixes +* Fix issue with Notification Hubs template message sending + +2013.08.12 Version 0.7.14 +* Multiple storage fixes +* Documentation improvements +* Added support for large blobs upload / download + +2013.08.08 Version 0.7.13 +* Lock request version + +2013.07.29 Version 0.7.12 +* Added MPNS support +* Added Service management vnet operations support + +2013.07.10 Version 0.7.11 +* Hooked up new configuration system to storage APIs +* Support for AZURE_STORAGE_CONNECTION_STRING environment variable +* Included API for websites management +* Fixed UTF-8 support in table batch submit + +2013.06.26 Version 0.7.10 +* Various fixes in storage APIs + +2013.06.19 Version 0.7.9 +* First part of new SDK configuration system +* Support for AZURE_SERVICEBUS_CONNECTION_STRING environment variable +* Updated SAS generation logic to include version number +* Infrastructure support for creating passwordless VMs + +2013.06.13 Version 0.7.8 +* Updates to HDInsight operations + +2013.06.06 Version 0.7.7 +* Added support for Android notification through Service Bus Notification Hubs +* Support prefixes when listing tables +* Support '$logs' as a valid blob container name to support reading diagnostic information +* Fix for network configuration serialization for subnets + +2013.05.30 Version 0.7.6 +* Added list, delete and create cluster operations for HD Insight. + +2013.05.15 Version 0.7.5 +* Fixed registration hubs issue with requiring access key when shared key was provided. +* Fixed registration hubs issue with listByTag, Channel and device token + +2013.05.09 Version 0.7.4 +* Fixed encoding issue with partition and row keys in table storage query + +2013.05.01 Version 0.7.3 +* Fixed issue #680: BlobService.getBlobUrl puts permissions in SAS url even if not given +* Changes to test suite & sdk to run in other environments +* Notification hubs registrations +* Support in ServiceManagementClient for role reboot and reimage + +2013.04.05 Version 0.7.2 +* Removing workaround for SSL issue and forcing node version to be outside the > 0.8 && < 0.10.3 range where the issue occurs + +2013.04.03 Version 0.7.1 +* Adding (limited) support for node 0.10 +* Fixing issue regarding registering providers when using websites or mobiles services + +2013.03.25 Version 0.7.0 +* Breaking change: Primitive types will be stored for table storage. +* Adding support for creating and deleting affinity groups +* Replacing http-mock by nock and making all tests use it by default +* Adding notification hubs messages for WNS and APNS +* Add Strict SSL validation for server certificates +* Add support for creating subscriptions that expire + +2013.03.12 Version 0.6.11 +* Added constraint to package.json to restrict to node versions < 0.9. + +2013.02.11 Version 0.6.10 +* Added helper date.* functions for generating SAS expirations (secondsFromNow, minutesFromNow, hoursFromNow, daysFromNow) +* Added SQL classes for managing SQL Servers, Databases and Firewall rules +* Updating to use latest xml2js + +2012.12.12 Version 0.6.9 +* Exporting WebResource, Client classes from package to support CLI. +* Install message updated to remind users the CLI is now a separate package. + +2012.11.20 Version 0.6.8 + * CLI functionality has been pulled out into a new "azure-cli" module. See https://github.com/WindowsAzure/azure-sdk-tools-xplat for details. + * Add support for sb: in ServiceBus connection strings. + * Add functions to ServiceManagement for managing storage accounts. + * Merged #314 from @smarx for allowing empty partition keys on the client. + * Merged #447 from @anodejs for array enumeration and exception on batch response. + * Various other fixes + +2012.10.15 Version 0.6.7 + * Adding connection strings support for storage and service bus + * Fixing issue with EMULATED and explicit variables making the later more relevant + * Adding Github support + * Adding website application settings support + +2012.10.12 Version 0.6.6 + * Using fixed version of commander.js to avoid bug in commander.js 1.0.5 + +2012.10.01 Version 0.6.5 + * Bugfixing + +2012.09.18 Version 0.6.4 + * Multiple Bugfixes around blob streaming + +2012.09.09 Version 0.6.3 + * Fixing issue with xml2js + +2012.08.15 Version 0.6.2 + * Multiple Bugfixes + +2012.07.02 Version 0.6.1 + * Multiple Bugfixes + * Adding subscription setting and listing functionality. + +2012.06.06 Version 0.6.0 + * Adding CLI tool + * Multiple Bugfixes + +2012.04.19 Version 0.5.3 + * Service Runtime Wrappers + * Multiple Bugfixes + * Unit tests converted to mocha and code coverage made easy through JSCoverage + +2012.02.10 Version 0.5.2 + * Service Bus Wrappers + * Storage Services UT run against a mock server. + * Node.exe version requirement lowered to raise compatibility. + * Multiple Bugfixes + +2011.12.14 Version 0.5.1 + * Multiple bug fixes + +2011.12.09 Version 0.5.0 + * Initial Release diff --git a/node_modules/azure-storage/LICENSE.txt b/node_modules/azure-storage/LICENSE.txt new file mode 100644 index 000000000..2bb9ad240 --- /dev/null +++ b/node_modules/azure-storage/LICENSE.txt @@ -0,0 +1,176 @@ + 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 \ No newline at end of file diff --git a/node_modules/azure-storage/README.md b/node_modules/azure-storage/README.md new file mode 100644 index 000000000..b8d141e47 --- /dev/null +++ b/node_modules/azure-storage/README.md @@ -0,0 +1,535 @@ +# Microsoft Azure Storage SDK for Node.js + +[![NPM version](https://badge.fury.io/js/azure-storage.svg)](http://badge.fury.io/js/azure-storage) [![Slack](https://azurestorageslack.azurewebsites.net/badge.svg)]( https://azurestorageslack.azurewebsites.net) + +* Master [![Build Status](https://travis-ci.org/Azure/azure-storage-node.svg?branch=master)](https://travis-ci.org/Azure/azure-storage-node/branches) [![Coverage Status](https://coveralls.io/repos/Azure/azure-storage-node/badge.svg?branch=master&service=github)](https://coveralls.io/github/Azure/azure-storage-node?branch=master) +* Dev [![Build Status](https://travis-ci.org/Azure/azure-storage-node.svg?branch=dev)](https://travis-ci.org/Azure/azure-storage-node/branches) [![Coverage Status](https://coveralls.io/repos/Azure/azure-storage-node/badge.svg?branch=dev&service=github)](https://coveralls.io/github/Azure/azure-storage-node?branch=dev) + +This project provides a Node.js package and a browser compatible [JavaScript Client Library](#azure-storage-javascript-client-library-for-browsers) that makes it easy to consume and manage Microsoft Azure Storage Services. + +> If you are looking for the Node.js SDK for other Azure services, visit [https://github.com/Azure/azure-sdk-for-node](https://github.com/Azure/azure-sdk-for-node). + +# Features + +- Tables + - Create/Delete Tables + - Query/Create/Read/Update/Delete Entities +- Blobs + - Create/Delete Containers + - Create/Read/Update/Delete Blobs +- Files + - Create/Delete Shares + - Create/Delete Directories + - Create/Read/Update/Delete Files +- Queues + - Create/Delete Queues + - Insert/Peek Queue Messages + - Advanced Queue Operations +- Service Properties + - Get Service Properties + - Set Service Properties + +Please check details on [API reference documents](http://azure.github.io/azure-storage-node). + +# Getting Started + +## Install + +```shell +npm install azure-storage +``` + +## Usage + +```Javascript +var azure = require('azure-storage'); +``` + +When using the Storage SDK, you must provide connection information for the storage account to use. This can be provided using: + +* Environment variables - **AZURE_STORAGE_ACCOUNT** and **AZURE_STORAGE_ACCESS_KEY**, or **AZURE_STORAGE_CONNECTION_STRING**. + +* Constructors - For example, `var tableSvc = azure.createTableService(accountName, accountKey);` + +### Table Storage + +To ensure a table exists, call **createTableIfNotExists**: + +```Javascript +var azure = require('azure-storage'); +var tableService = azure.createTableService(); +tableService.createTableIfNotExists('mytable', function(error, result, response) { + if (!error) { + // result contains true if created; false if already exists + } +}); +``` +A new entity can be added by calling **insertEntity**: + +```Javascript +var azure = require('azure-storage'); +var tableService = azure.createTableService(); +var entGen = azure.TableUtilities.entityGenerator; +var entity = { + PartitionKey: entGen.String('part2'), + RowKey: entGen.String('row1'), + boolValueTrue: entGen.Boolean(true), + boolValueFalse: entGen.Boolean(false), + intValue: entGen.Int32(42), + dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))), + complexDateValue: entGen.DateTime(new Date(Date.UTC(2013, 02, 16, 01, 46, 20))) +}; +tableService.insertEntity('mytable', entity, function(error, result, response) { + if (!error) { + // result contains the ETag for the new entity + } +}); +``` + + +Instead of creating entities manually, you can use **entityGenerator**: + +```Javascript +var azure = require('azure-storage'); +var entGen = azure.TableUtilities.entityGenerator; +var task = { + PartitionKey: entGen.String('hometasks'), + RowKey: entGen.String('1'), + description: entGen.String('take out the trash'), + dueDate: entGen.DateTime(new Date(Date.UTC(2015, 6, 20))) +}; +``` + +The method **retrieveEntity** can then be used to fetch the entity that was just inserted: + +```Javascript +var azure = require('azure-storage'); +var tableService = azure.createTableService(); +tableService.retrieveEntity('mytable', 'part2', 'row1', function(error, result, response) { + if (!error) { + // result contains the entity + } +}); +``` + +Use **TableQuery** to build complex queries: + +```Javascript +var azure = require('azure-storage'); +var tableService = azure.createTableService(); +var query = new azure.TableQuery() + .top(5) + .where('PartitionKey eq ?', 'part2'); + +tableService.queryEntities('mytable', query, null, function(error, result, response) { + if (!error) { + // result.entries contains entities matching the query + } +}); +``` + +### Blob Storage + +The **createContainerIfNotExists** method can be used to create a +container in which to store a blob: + +```Javascript +var azure = require('azure-storage'); +var blobService = azure.createBlobService(); +blobService.createContainerIfNotExists('taskcontainer', { + publicAccessLevel: 'blob' +}, function(error, result, response) { + if (!error) { + // if result = true, container was created. + // if result = false, container already existed. + } +}); +``` + +To upload a file (assuming it is called task1-upload.txt and it is placed in the same folder as the script below), the method **createBlockBlobFromLocalFile** can be used. + +```Javascript +var azure = require('azure-storage'); +var blobService = azure.createBlobService(); + +blobService.createBlockBlobFromLocalFile('mycontainer', 'taskblob', 'task1-upload.txt', function(error, result, response) { + if (!error) { + // file uploaded + } +}); +``` + + +For page blobs, use **createPageBlobFromLocalFile**. There are other methods for uploading blobs also, such as **createBlockBlobFromText** or **createPageBlobFromStream**. + +There are also several ways to download block and page blobs. For example, **getBlobToStream** downloads the blob to a stream: + +```Javascript +var blobService = azure.createBlobService(); +var fs = require('fs'); +blobService.getBlobToStream('mycontainer', 'taskblob', fs.createWriteStream('output.txt'), function(error, result, response) { + if (!error) { + // blob retrieved + } +}); +``` + +To create a Shared Access Signature (SAS), use the **generateSharedAccessSignature** method. Additionally you can use the **date** helper functions to easily create a SAS that expires at some point relative to the current time. + +```Javascript +var azure = require('azure-storage'); +var blobService = azure.createBlobService(); + +var startDate = new Date(); +var expiryDate = new Date(startDate); +expiryDate.setMinutes(startDate.getMinutes() + 100); +startDate.setMinutes(startDate.getMinutes() - 100); + +var sharedAccessPolicy = { + AccessPolicy: { + Permissions: azure.BlobUtilities.SharedAccessPermissions.READ, + Start: startDate, + Expiry: expiryDate + } +}; + +var token = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy); +var sasUrl = blobService.getUrl(containerName, blobName, token); +``` + +### Queue Storage + +The **createQueueIfNotExists** method can be used to ensure a queue exists: + +```Javascript +var azure = require('azure-storage'); +var queueService = azure.createQueueService(); +queueService.createQueueIfNotExists('taskqueue', function(error) { + if (!error) { + // Queue exists + } +}); +``` + +The **createMessage** method can then be called to insert the message into the queue: + +```Javascript +var queueService = azure.createQueueService(); +queueService.createMessage('taskqueue', 'Hello world!', function(error) { + if (!error) { + // Message inserted + } +}); +``` + +It is then possible to call the **getMessage** method, process the message and then call **deleteMessage** inside the callback. This two-step process ensures messages don't get lost when they are removed from the queue. + +```Javascript +var queueService = azure.createQueueService(), + queueName = 'taskqueue'; +queueService.getMessages(queueName, function(error, serverMessages) { + if (!error) { + // Process the message in less than 30 seconds, the message + // text is available in serverMessages[0].messageText + + queueService.deleteMessage(queueName, serverMessages[0].messageId, serverMessages[0].popReceipt, function(error) { + if (!error) { + // Message deleted + } + }); + } +}); +``` + +### File Storage + +The **createShareIfNotExists** method can be used to create a +share in which to store a file or a directory of files: + +```Javascript +var azure = require('azure-storage'); +var fileService = azure.createFileService(); +fileService.createShareIfNotExists('taskshare', function(error, result, response) { + if (!error) { + // if result = true, share was created. + // if result = false, share already existed. + } +}); +``` + +To create a directory, the method **createDirectoryIfNotExists** can be used. + +```Javascript +var azure = require('azure-storage'); +var fileService = azure.createFileService(); + +fileService.createDirectoryIfNotExists('taskshare', 'taskdirectory', function(error, result, response) { + if (!error) { + // if result = true, share was created. + // if result = false, share already existed. + } +}); +``` + +To upload a file (assuming it is called task1-upload.txt and it is placed in the same folder as the script below), the method **createFileFromLocalFile** can be used. + +```Javascript +var azure = require('azure-storage'); +var fileService = azure.createFileService(); + +fileService.createFileFromLocalFile('taskshare', 'taskdirectory', 'taskfile', 'task1-upload.txt', function(error, result, response) { + if (!error) { + // file uploaded + } +}); +``` + +To upload a file from a stream, the method **createFileFromStream** can be used. The var `myFileBuffer` in the script below is a native Node Buffer, or ArrayBuffer object if within a browser environment. + +```Javascript + var stream = require('stream'); + var azure = require('azure-storage'); + var fileService = azure.createFileService(); + + var fileStream = new stream.Readable(); + fileStream.push(myFileBuffer); + fileStream.push(null); + + fileService.createFileFromStream('taskshare', 'taskdirectory', 'taskfile', fileStream, myFileBuffer.length, function(error, result, response) { + if (!error) { + // file uploaded + } + }); +``` + +To create a file from a text string, the method **createFileFromText** can be used. A Node Buffer or ArrayBuffer object containing the text can also be supplied. + +```Javascript + var azure = require('azure-storage'); + var fileService = azure.createFileService(); + + var text = 'Hello World!'; + + fileService.createFileFromText('taskshare', 'taskdirectory', 'taskfile', text, function(error, result, response) { + if (!error) { + // file created + } + }); +``` + +There are also several ways to download files. For example, **getFileToStream** downloads the file to a stream: + +```Javascript +var fileService = azure.createFileService(); +var fs = require('fs'); +fileService.getFileToStream('taskshare', 'taskdirectory', 'taskfile', fs.createWriteStream('output.txt'), function(error, result, response) { + if (!error) { + // file retrieved + } +}); +``` + +### Service Properties + +The **getServiceProperties** method can be used to fetch the logging, metrics and CORS settings on your storage account: + +```Javascript +var azure = require('azure-storage'); +var blobService = azure.createBlobService(); + +blobService.getServiceProperties(function(error, result, response) { + if (!error) { + var serviceProperties = result; + // properties are fetched + } +}); +``` + +The **setServiceProperties** method can be used to modify the logging, metrics and CORS settings on your storage account: + +```Javascript +var azure = require('azure-storage'); +var blobService = azure.createBlobService(); + +var serviceProperties = generateServiceProperties(); + +blobService.setServiceProperties(serviceProperties, function(error, result, response) { + if (!error) { + // properties are set + } +}); + +function generateServiceProperties() { + return serviceProperties = { + Logging: { + Version: '1.0', + Delete: true, + Read: true, + Write: true, + RetentionPolicy: { + Enabled: true, + Days: 10, + }, + }, + HourMetrics: { + Version: '1.0', + Enabled: true, + IncludeAPIs: true, + RetentionPolicy: { + Enabled: true, + Days: 10, + }, + }, + MinuteMetrics: { + Version: '1.0', + Enabled: true, + IncludeAPIs: true, + RetentionPolicy: { + Enabled: true, + Days: 10, + }, + }, + Cors: { + CorsRule: [ + { + AllowedOrigins: ['www.azure.com', 'www.microsoft.com'], + AllowedMethods: ['GET', 'PUT'], + AllowedHeaders: ['x-ms-meta-data*', 'x-ms-meta-target*', 'x-ms-meta-xyz', 'x-ms-meta-foo'], + ExposedHeaders: ['x-ms-meta-data*', 'x-ms-meta-source*', 'x-ms-meta-abc', 'x-ms-meta-bcd'], + MaxAgeInSeconds: 500, + }, + { + AllowedOrigins: ['www.msdn.com', 'www.asp.com'], + AllowedMethods: ['GET', 'PUT'], + AllowedHeaders: ['x-ms-meta-data*', 'x-ms-meta-target*', 'x-ms-meta-xyz', 'x-ms-meta-foo'], + ExposedHeaders: ['x-ms-meta-data*', 'x-ms-meta-source*', 'x-ms-meta-abc', 'x-ms-meta-bcd'], + MaxAgeInSeconds: 500, + }, + ], + }, + }; +} +``` + +When modifying the service properties, you can fetch the properties and then modify the them to prevent overwriting the existing settings. + +```Javascript +var azure = require('azure-storage'); +var blobService = azure.createBlobService(); + +blobService.getServiceProperties(function(error, result, response) { + if (!error) { + var serviceProperties = result; + + // modify the properties + + blobService.setServiceProperties(serviceProperties, function(error, result, response) { + if (!error) { + // properties are set + } + }); + } +}); +``` + +### Retry Policies + +By default, no retry will be performed with service instances newly created by Azure storage client library for Node.js. +Two pre-written retry polices [ExponentialRetryPolicyFilter](http://azure.github.io/azure-storage-node/ExponentialRetryPolicyFilter.html) and [LinearRetryPolicyFilter](http://azure.github.io/azure-storage-node/LinearRetryPolicyFilter.html) are available with modifiable settings, and can be used through associating filter. +Any custom retry logic may be used by customizing RetryPolicyFilter instance. + +For how to use pre-writtern retry policies and how to define customized retry policy, please refer to **retrypolicysample** in samples directory. + +## Code Samples + +How-Tos focused around accomplishing specific tasks are available on the [Microsoft Azure Node.js Developer Center](http://azure.microsoft.com/en-us/develop/nodejs/). + +* [How to use the Blob Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/) + +* [How to use the Table Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-table-storage/) + +* [How to use the Queue Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-queues/) + +# Running Tests + +Unit tests can then be run from the module's root directory using: + +```shell +npm test +``` + +Running test is also supported by Grunt by: + +```shell +grunt # mochaTest as the default task +``` + +By default the unit tests are ran with Nock recording data. To run tests against real storage account, please set environment variable to turn off Nock by: + +``` +set NOCK_OFF=true +``` + +and set up the following environment variable for storage account credentials by + +```Batchfile +set AZURE_STORAGE_CONNECTION_STRING="valid storage connection string" +``` + +To record the data in a test pass against real storage account for future Nock usage: + +```Batchfile +set AZURE_NOCK_RECORD=true +``` + +In order to be able to use a proxy like fiddler, an additional environment variable should be set up: + +```Batchfile +set NODE_TLS_REJECT_UNAUTHORIZED=0 +set HTTP_PROXY=http://127.0.0.1:8888 +``` + +On Linux, please use `export` other than `set` to set the variables. + +# Azure Storage JavaScript Client Library for Browsers + +* JavaScript Client Library is currently in Preview. Questions and feedback are welcome in our [Slack channel](https://azurestorageslack.azurewebsites.net). + +Azure Storage Node.js Client Library is compatible with [Browserify](http://browserify.org/). This means you can bundle your Node.js application which depends on the Node.js Client Library using Browserify. + +You can also choose to download the JavaScript Client Library provided by us, or generate the library by yourself. Please refer to the [README.md](browser/README.md) under `browser` folder for detailed usage guidelines. + +## Downloading Azure Storage JavaScript Client Library + +It's recommended to use the Azure Storage JavaScript Client Library provided by us. Please [download the latest library](https://aka.ms/downloadazurestoragejs). + +## Generating Azure Storage JavaScript Client Library + +We also provide browserify bundle scripts which generate Azure Storage JavaScript Client Library. The bundle script reduces the size of the Storage Client Library by splitting into smaller files, one per storage service and a common shared file. For more detailed information, refer to [README.md](browser/README.md) under `browser` folder. + +# JsDoc + +JsDoc can be generated by `grunt jsdoc`. + +To load the docs by devserver after generation, run `grunt doc` and then browse the docs at [http://localhost:8888](http://localhost:8888). + +# Need Help? + +Be sure to check out the Microsoft Azure [Developer Forums on MSDN](http://go.microsoft.com/fwlink/?LinkId=234489) if you have trouble with the provided code or use StackOverflow. + +# Learn More + +- [Microsoft Azure Node.js Developer Center](http://azure.microsoft.com/en-us/develop/nodejs/) +- [Azure Storage Team Blog](http://blogs.msdn.com/b/windowsazurestorage/) + +# Contribute + +We gladly accept community contributions. + +- Issues: Please report bugs using the Issues section of GitHub +- Forums: Interact with the development teams on StackOverflow or the Microsoft Azure Forums +- Source Code Contributions: If you would like to become an active contributor to this project please follow the instructions provided in [Contributing.md](CONTRIBUTING.md). + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +For general suggestions about Microsoft Azure please use our [UserVoice forum](http://feedback.azure.com/forums/34192--general-feedback). diff --git a/node_modules/azure-storage/browser/ChangeLog.md b/node_modules/azure-storage/browser/ChangeLog.md new file mode 100644 index 000000000..4e6e8292c --- /dev/null +++ b/node_modules/azure-storage/browser/ChangeLog.md @@ -0,0 +1,69 @@ +Note: This is the change log file for Azure Storage JavaScript Client Library. + +2018.02 Version 0.2.8-preview.14 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.8.0. + +2017.12 Version 0.2.7-preview.13 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.7.0. + +2017.10 Version 0.2.6-preview.12 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.6.0. + +2017.09 Version 0.2.5-preview.11 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.5.0. + +2017.08 Version 0.2.4-preview.10 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.4.0. + +2017.08 Version 0.2.3-preview.9 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.3.0. + +2017.08 Version 0.2.2-preview.8 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.2.2. + +2017.07 Version 0.2.2-preview.7 + +* Added browser specific APIs for blobs and files uploading. + * `BlobService.createBlockBlobFromBrowserFile` + * `BlobService.createPageBlobFromBrowserFile` + * `BlobService.createAppendBlobFromBrowserFile` + * `BlobService.appendFromBrowserFile` + * `FileService.createFileFromBrowserFile` +* Updated samples with above new added APIs. +* Dropped dependency to browserify-fs. + +2017.07 Version 0.2.2-preview.6 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.2.1. + +2017.06 Version 0.2.2-preview.5 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.2.0. + +2017.05 Version 0.2.1-preview.4 + +* Reduced footprint of the generated JavaScript files. +* Removed 7 local-file related APIs which are limited by browser's sandbox. + +2017.03 Version 0.2.1-preview.3 + +* Fixed missing 100% upload progress issue in blob sample for uploading blobs smaller than 32MB. +* Added speedSummary code example in the blob & file samples. + +2017.03 Version 0.2.1-preview.2 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.1.0. + +2017.03 Version 0.2.0-preview.1 + +* Generated browser compatible JavaScript files based on Microsoft Azure Storage SDK for Node.js 2.0.0. +* Added bundle scripts to generate Azure Storage JavaScript Client Library. +* Added npm command `npm run genjs` to generate JavaScript Client Library. +* Added samples for Azure Storage JavaScript Client Library. \ No newline at end of file diff --git a/node_modules/azure-storage/browser/README.md b/node_modules/azure-storage/browser/README.md new file mode 100644 index 000000000..edd5b6c14 --- /dev/null +++ b/node_modules/azure-storage/browser/README.md @@ -0,0 +1,106 @@ +# Azure Storage JavaScript Client Library for Browsers + +* Join the community discussion on Slack! [![Slack](https://azurestorageslack.azurewebsites.net/badge.svg)]( https://azurestorageslack.azurewebsites.net) + +There are 5 generated JavaScript files for Azure Storage JavaScript Client Library: +- `azure-storage.common.js` contains the common part for other 4 JavaScript files. +- `azure-storage.table.js` contains the Azure Storage table service operation logic, which depends on azure-storage.common.js +- `azure-storage.blob.js` contains the Azure Storage blob service operation logic, which depends on azure-storage.common.js +- `azure-storage.queue.js` contains the Azure Storage queue service operation logic, which depends on azure-storage.common.js +- `azure-storage.file.js` contains the Azure Storage file service operation logic, which depends on azure-storage.common.js + +We also provide samples to guide you quickly start with the Azure Storage JavaScript Client Library. In the [JavaScript Client Library zip file](https://aka.ms/downloadazurestoragejs) or [azure-storage-node/browser/samples](samples), you will find 4 HTML samples: +- `sample-table.html` demonstrates how to operate with Azure Storage table service in the browser +- `sample-blob.html` demonstrates how to operate with Azure Storage blob service in the browser +- `sample-queue.html` demonstrates how to operate with Azure Storage queue service in the browser +- `sample-file.html` demonstrates how to operate with Azure Storage file service in the browser + +After generating the JavaScript Client Library, you can try the samples in browsers such as Chrome/Edge/Firefox directly. + +**Note**: An HTTP server should be set to host the samples for IE browser. + +## Limitations + +The Azure Storage JavaScript Client Library is currently in preview stage, there are some known issues or limitations as follows. + +### Compatibility + +Compatibility with mobile browsers have not been fully validated, please open issues when you get errors. Current validated browsers are as below: + +| Chrome | Firefox | Internet Explorer | Microsoft Edge | +|------------|----------|--------------------|-----------------| +| v64 | v58 | v11 | v41 | + +## Generating a Custom Azure Storage JavaScript Client Library + +If you wish to customize the library and generate the Azure Storage JavaScript Client Library, you can follow the following steps. + +We provide browserify bundle scripts which generate Azure Storage JavaScript Client Library. The bundle script reduces the size of the Storage Client Library by splitting into smaller files, one per storage service and a common shared file. + +The generated JavaScript Client Library includes 5 separated JavaScript files: +- `azure-storage.common.js` +- `azure-storage.table.js` +- `azure-storage.blob.js` +- `azure-storage.queue.js` +- `azure-storage.file.js` + +Let's get started to generate the Azure Storage JavaScript Client Library! + +### Step 1: Cloning Repo + +Azure Storage JavaScript Client Library is generated from Azure Storage SDK for Node.js. Clone `azure-storage-node` repo with following command: + +```Batchfile +git clone https://github.com/Azure/azure-storage-node.git +``` + +### Step 2: Installing Node.js Modules + +Change to the root directory of the cloned repo: + +```Batchfile +cd azure-storage-node +``` + +Install the dependent Node.js modules: + +```Batchfile +npm install +``` + +### Step 3: Generating JavaScript Client Library with Bundle Scripts + +We provide bundle scripts to help quickly generate the JavaScript Client Library. At the root directory of the cloned repo: + +```Batchfile +npm run genjs +``` + +### Step 4: Finding the Generated JavaScript Files + +If everything goes well, the generated JavaScript files should be saved to `azure-storage-node/browser/bundle`. There will be 5 generated JavaScript files totally: +- `azure-storage.common.js` +- `azure-storage.table.js` +- `azure-storage.blob.js` +- `azure-storage.queue.js` +- `azure-storage.file.js` + +### Step 5: JavaScript Files Minify + +You are able to minify the generated JavaScript files with your favorite minify tools. Here we show the minify process with Node.js minify tool [uglifyJS](https://github.com/mishoo/UglifyJS2). + +Install uglifyJS: + +```Batchfile +npm install -g uglify-js +``` + +Minify the JavaScript files: + +```Batchfile +uglifyjs --compress --mangle -- azure-storage.common.js > azure-storage.common.min.js +uglifyjs --compress --mangle -- azure-storage.table.js > azure-storage.table.min.js +uglifyjs --compress --mangle -- azure-storage.blob.js > azure-storage.blob.min.js +uglifyjs --compress --mangle -- azure-storage.queue.js > azure-storage.queue.min.js +uglifyjs --compress --mangle -- azure-storage.file.js > azure-storage.file.min.js +``` \ No newline at end of file diff --git a/node_modules/azure-storage/browser/azure-storage.blob.export.js b/node_modules/azure-storage/browser/azure-storage.blob.export.js new file mode 100644 index 000000000..a11d0b6b2 --- /dev/null +++ b/node_modules/azure-storage/browser/azure-storage.blob.export.js @@ -0,0 +1,73 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var AzureStorage = window.AzureStorage || {}; + +AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) { + var devStore = 'UseDevelopmentStorage=true;'; + if(proxyUri){ + devStore += 'DevelopmentStorageProxyUri=' + proxyUri; + } + + return devStore; +}; + +var BlobService = require('../lib/services/blob/blobservice.browser'); + +AzureStorage.BlobService = BlobService; +AzureStorage.BlobUtilities = require('../lib/services/blob/blobutilities'); + +AzureStorage.createBlobService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new BlobService(storageAccountOrConnectionString, storageAccessKey, host, null); +}; + +AzureStorage.createBlobServiceWithSas = function (host, sasToken) { + return new BlobService(null, null, host, sasToken); +}; + +AzureStorage.createBlobServiceAnonymous = function (host) { + return new BlobService(null, null, host, null); +}; + +var azureCommon = require('../lib/common/common.browser'); +var StorageServiceClient = azureCommon.StorageServiceClient; +var SharedKey = azureCommon.SharedKey; + +AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy) +{ + var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey); + var sharedKey = new SharedKey(storageSettings._name, storageSettings._key); + + return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy); +}; + +AzureStorage.Constants = azureCommon.Constants; +AzureStorage.StorageUtilities = azureCommon.StorageUtilities; +AzureStorage.AccessCondition = azureCommon.AccessCondition; + +AzureStorage.SR = azureCommon.SR; +AzureStorage.StorageServiceClient = StorageServiceClient; +AzureStorage.Logger = azureCommon.Logger; +AzureStorage.WebResource = azureCommon.WebResource; +AzureStorage.Validate = azureCommon.validate; +AzureStorage.date = azureCommon.date; + +// Other filters +AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter; +AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter; +AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter; + +window.AzureStorage = AzureStorage; \ No newline at end of file diff --git a/node_modules/azure-storage/browser/azure-storage.file.export.js b/node_modules/azure-storage/browser/azure-storage.file.export.js new file mode 100644 index 000000000..f94ca38da --- /dev/null +++ b/node_modules/azure-storage/browser/azure-storage.file.export.js @@ -0,0 +1,69 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var AzureStorage = window.AzureStorage || {}; + +AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) { + var devStore = 'UseDevelopmentStorage=true;'; + if(proxyUri){ + devStore += 'DevelopmentStorageProxyUri=' + proxyUri; + } + + return devStore; +}; + +var FileService = require('../lib/services/file/fileservice.browser'); + +AzureStorage.FileService = FileService; +AzureStorage.FileUtilities = require('../lib/services/file/fileutilities'); + +AzureStorage.createFileService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new FileService(storageAccountOrConnectionString, storageAccessKey, host); +}; + +AzureStorage.createFileServiceWithSas = function (hostUri, sasToken) { + return new FileService(null, null, hostUri, sasToken); +}; + +var azureCommon = require('../lib/common/common.browser'); +var StorageServiceClient = azureCommon.StorageServiceClient; +var SharedKey = azureCommon.SharedKey; + +AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy) +{ + var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey); + var sharedKey = new SharedKey(storageSettings._name, storageSettings._key); + + return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy); +}; + +AzureStorage.Constants = azureCommon.Constants; +AzureStorage.StorageUtilities = azureCommon.StorageUtilities; +AzureStorage.AccessCondition = azureCommon.AccessCondition; + +AzureStorage.SR = azureCommon.SR; +AzureStorage.StorageServiceClient = StorageServiceClient; +AzureStorage.Logger = azureCommon.Logger; +AzureStorage.WebResource = azureCommon.WebResource; +AzureStorage.Validate = azureCommon.validate; +AzureStorage.date = azureCommon.date; + +// Other filters +AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter; +AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter; +AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter; + +window.AzureStorage = AzureStorage; \ No newline at end of file diff --git a/node_modules/azure-storage/browser/azure-storage.queue.export.js b/node_modules/azure-storage/browser/azure-storage.queue.export.js new file mode 100644 index 000000000..bb0a686b6 --- /dev/null +++ b/node_modules/azure-storage/browser/azure-storage.queue.export.js @@ -0,0 +1,70 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var AzureStorage = window.AzureStorage || {}; + +AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) { + var devStore = 'UseDevelopmentStorage=true;'; + if(proxyUri){ + devStore += 'DevelopmentStorageProxyUri=' + proxyUri; + } + + return devStore; +}; + +var QueueService = require('../lib/services/queue/queueservice'); + +AzureStorage.QueueService = QueueService; +AzureStorage.QueueUtilities = require('../lib/services/queue/queueutilities'); +AzureStorage.QueueMessageEncoder = require('../lib/services/queue/queuemessageencoder'); + +AzureStorage.createQueueService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new QueueService(storageAccountOrConnectionString, storageAccessKey, host); +}; + +AzureStorage.createQueueServiceWithSas = function(hostUri, sasToken) { + return new QueueService(null, null, hostUri, sasToken); +}; + +var azureCommon = require('../lib/common/common.browser'); +var StorageServiceClient = azureCommon.StorageServiceClient; +var SharedKey = azureCommon.SharedKey; + +AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy) +{ + var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey); + var sharedKey = new SharedKey(storageSettings._name, storageSettings._key); + + return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy); +}; + +AzureStorage.Constants = azureCommon.Constants; +AzureStorage.StorageUtilities = azureCommon.StorageUtilities; +AzureStorage.AccessCondition = azureCommon.AccessCondition; + +AzureStorage.SR = azureCommon.SR; +AzureStorage.StorageServiceClient = StorageServiceClient; +AzureStorage.Logger = azureCommon.Logger; +AzureStorage.WebResource = azureCommon.WebResource; +AzureStorage.Validate = azureCommon.validate; +AzureStorage.date = azureCommon.date; + +// Other filters +AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter; +AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter; +AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter; + +window.AzureStorage = AzureStorage; \ No newline at end of file diff --git a/node_modules/azure-storage/browser/azure-storage.table.export.js b/node_modules/azure-storage/browser/azure-storage.table.export.js new file mode 100644 index 000000000..444dde79d --- /dev/null +++ b/node_modules/azure-storage/browser/azure-storage.table.export.js @@ -0,0 +1,70 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var AzureStorage = window.AzureStorage || {}; + +AzureStorage.generateDevelopmentStorageCredentials = function (proxyUri) { + var devStore = 'UseDevelopmentStorage=true;'; + if(proxyUri){ + devStore += 'DevelopmentStorageProxyUri=' + proxyUri; + } + + return devStore; +}; + +var TableService = require('../lib/services/table/tableservice'); +AzureStorage.TableService = TableService; +AzureStorage.TableQuery = require('../lib/services/table/tablequery'); +AzureStorage.TableBatch = require('../lib/services/table/tablebatch'); +AzureStorage.TableUtilities = require('../lib/services/table/tableutilities'); + +AzureStorage.createTableService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new TableService(storageAccountOrConnectionString, storageAccessKey, host); +}; + +AzureStorage.createTableServiceWithSas = function (hostUri, sasToken) { + return new TableService(null, null, hostUri, sasToken); +}; + +var azureCommon = require('../lib/common/common.browser'); +var StorageServiceClient = azureCommon.StorageServiceClient; +var SharedKey = azureCommon.SharedKey; + +AzureStorage.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy) +{ + var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey); + var sharedKey = new SharedKey(storageSettings._name, storageSettings._key); + + return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy); +}; + +AzureStorage.Constants = azureCommon.Constants; +AzureStorage.StorageUtilities = azureCommon.StorageUtilities; +AzureStorage.AccessCondition = azureCommon.AccessCondition; + +AzureStorage.SR = azureCommon.SR; +AzureStorage.StorageServiceClient = StorageServiceClient; +AzureStorage.Logger = azureCommon.Logger; +AzureStorage.WebResource = azureCommon.WebResource; +AzureStorage.Validate = azureCommon.validate; +AzureStorage.date = azureCommon.date; + +// Other filters +AzureStorage.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter; +AzureStorage.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter; +AzureStorage.RetryPolicyFilter = azureCommon.RetryPolicyFilter; + +window.AzureStorage = AzureStorage; \ No newline at end of file diff --git a/node_modules/azure-storage/browser/bundle.js b/node_modules/azure-storage/browser/bundle.js new file mode 100644 index 000000000..eacf66cf2 --- /dev/null +++ b/node_modules/azure-storage/browser/bundle.js @@ -0,0 +1,49 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var browserify = require('browserify'); +var factor = require('factor-bundle'); +var fs = require('fs'); +var path = require('path'); + +var outputFolder = 'bundle'; +var outputFolderPath = path.resolve(__dirname, outputFolder); + +console.log('Generating Azure Storage JavaScript Client Library to ' + outputFolderPath + ' ...\n'); + +if (!fs.existsSync(outputFolderPath)) { + fs.mkdirSync(outputFolderPath); +} + +var b = browserify([ + path.resolve(__dirname, 'azure-storage.blob.export.js'), + path.resolve(__dirname, 'azure-storage.file.export.js'), + path.resolve(__dirname, 'azure-storage.queue.export.js'), + path.resolve(__dirname, 'azure-storage.table.export.js') +], {require: ['stream', 'util', 'buffer']}); + +b.plugin(factor, { + outputs: [ + path.resolve(outputFolderPath, 'azure-storage.blob.js'), + path.resolve(outputFolderPath, 'azure-storage.file.js'), + path.resolve(outputFolderPath, 'azure-storage.queue.js'), + path.resolve(outputFolderPath, 'azure-storage.table.js') + ] +}); + +b.bundle().pipe( + fs.createWriteStream(path.resolve(outputFolderPath, 'azure-storage.common.js')) +); diff --git a/node_modules/azure-storage/browser/samples/cors.PNG b/node_modules/azure-storage/browser/samples/cors.PNG new file mode 100644 index 0000000000000000000000000000000000000000..4f6a97f5a12605924e7d4de002117b2f73d6ad30 GIT binary patch literal 13072 zcmeI2XIPWnzUHG~K}3|QfPf&qNtgbjAkuqp(tCi=gisVkrAZIHNGCL@AxIIG-lPi& zO$ZPWLP-b&0u$eT&b(*#wfCNV=9&-lVLs$ao;+=3J!{?TfB)`8>*=UbU1Pci005}e zpQ;!D02ic5uNPM@lfLQO<~k?6UGOtddjzN%VL_8N$X%4Rl>vad1jm1`2ye9j@-U<&+gdKj9F|vwZgbgs9gJLf4K*%ox=tS+|_AmSMj|# zb3fxXf&+Qu9_twEBTI_;%qjU3`7)i^vVqXe&PevYmfpE{>{rEh{$poV{MAVI71n>e3oq*} z`Hn%@V6ORwc{sPoctDP>V^jCs!?SDM-EC7hG~~O zEH}>D*~Vs%y#th9p5$fjY)Vi50eqSeik_3x!w`>Sv62Go1k^$5;)$Harem!rL^eSh?Ph0K1Se}@?L$aPPT{g8`NBa)8`h*|wnOd59(A8CWxZs0pegVJBeIhoqg0|f8 zkk01`0?mJPe!AI5g}!BIHb`o^-8b$Q1Woog(j&gkD-FLA(A7d6NZbr241<@wbSEyk zfA`q8(B6K8MJ9-3D8Du+oiK3AZ82UX`ad#$b_EBbhI=JBoI&_ga+|{#Kb1kry3;3Y z@|dhvTD6TnlsCFmng#FuJ^D0nB*f9!5ngWrJV&UT`M|iO zqMLkg-}wWW3)Uk%A-*A|I@j?9Uuu?IEfv>8H7l29S~*3r-Zm>Dj7&reK>|MfO1hR% zR=NN(1A=*zm9$;f+gB*Hyqzotw;LborWIY;Hng=&&0+Gl%S-SUp>+MKJlBG|vAU)^ zrKF&mQ2CY>yy2^ekwy`j@shXj4OZqtu=DL6x*W$@`xGXx!|mGzP@~>yYvY9) zM3CY!ds2E5)P z*|N(xUuluy_O6ec^20_tUZo+3pMtZ74b{vSVPX>#kA4o|uw%fkD}}4mVV*D^*sBF4 zeh4_iV_}8fREeprP^Cw4Fl`ESvZzBEBHhk9`srK`f8R#{j;l<4!v#~*88@$Zewh%S z)3F{n*kLF0x~xPn`tg3d{K1FEwVq}19I4$RZnjDlZ}>%&U_8>AC2r%Gpf?ZGQ3LL9 zVtV$+ACBfA%g6@O6oe%sY`~I*ViNFRL!n!rEw%{HCMU*Y%Lt~zn{Iq;L7#s9f*`^Y zSoEmxM%vy%(+7KZU7@x{--G3)nb^Yb*0G4xTl}r#LH4xSaNz8JTs6BURk*E5X|g6t zf)4K6Jm7x-Zrxn~NbeFmym1-a&7I;dIx=1$hdmY|=p!@MT{blKEvv$6>B!zst~pv) zSWf5nLo#)iJ8q%s*O?HvzrORbef3RhI=APX#@oy@T&t`4NMsMnjEI$%)xDAbP~}*B z-$j=oK)c;B4>B~YuaunYOIyt1ImEW>ajJ<_Fz@g4=!3DgcaivS7v^{)?)vO$%G#Yq zJ^F~bfTP2oRbN3%ds`QZnDt1*uU%hw2OAuYcm_I{s8?)W!H%FV8!u#)##^GI%T5En z@Ii+nYI}ZJnja=-pB3)n#GNn-{S#~Wb@bNmF{O8B+9(hHm=Jf~m^!))dEB^8T(b3G zFN)=hQMPAxxLvpHk@%yhb)qldD7ukg>{PEqK%OXd*4t~i%P9!i5|=0^S1buXhty;I zqw6ezXZc2aYoikrYqFZ25h5C~ZJoLvsW%iRUGY=%ud^vRN*5w5-Lu!KW%jtd(Wc%f zZlhP?mlm7%&qP9f3@BvVyx7}Ud(6cv&IPsh6s*@{JROd}k&x|~Uk_EwhC6*x4#$L_ zYFKRb`%B6_T+>g;l@omvnrb91yI#Zyr;boZ zOGE}~F(m7qd-yuT>a11$eEnDF;jnZy#^0M7k+G6SB@$^@7615Mv{$myaCZfh8B9bEYV?9R|xLW$8eES_Jdvo2u9jsP99lh!0K2@#Cb0arl@ zq$S}I>55*Wb=95T_+Ua-RG=eFYqoh}?(sVMo4#fzeTGe>W%G~w9I(MM+&*i}s!|~( zrHZsjUa{nIM-W#cbNxk!-`6<%`eu7t(Rnpest%{mh?`2-8M_p^UPm$F$X=&@5i~Jt zQ6%D;r{gI)w`0LB?Rcr@cPI8yfr7975V5t&ooQF_bXb5zi4=BY&|Bg>ZYyuTw-%*u zv@SrNYnWs@eqe1?kzOC2SP9RkswbwWrhCEiiYE>hx6T&FXKAlQuEg`UlS_a6abF7V z%LQKLAB%#mHr>l6t?j=e&lQ8AtutF}G6U;5l?n-$Q6;t8EFdsp2l~VN{6`oS(7sD!QN~2BE{e=%8;?JvOISipJWn zFHBef(<^?fR$NuWx|^JP)kD_zVWDGaey3%Q5;$>>8u%S2-U}ZMm+dl;&t2b!_0b6r z!K^C$F)kTsE~)&Nmt4}a!z13V2B-n^-T}YQ;s>!uv^I;99Ku||ekTj-dK3n^k82n6 zbm11@hzJ)16^CXYmAT!YBllIPi{{Q?<`05@Nmvrws)m+ui`!hw3SeF-IH~N*LKIrz zb&E>pY?l&|51NcfZyaUu_*NIKU0S%zxA{k8L%;TdxGo%Du{n_e0Zn_#=+x$BuJiGj z)(P&$3!Y}@LtY{9GH>nR+n=5)!z&Ib;P(Usr+e;w`_{a`K#L%pEVQaHE@YR!Gh!FJ zOGvG}Zu~N*xIt`qpg~2Nr8o?^V|v$Mj0H{*vTg}|)$x3^likTeBeVb0;isP}~z>ix!oW$wniB zy+usb=l?S01^&Gt=zSKoiYy46RVk65Z8{1YHC-jo=bYEsPmDr@ z8Sq)1T^jHrzGDtfNoM{N#(Ogp{OYmXk)o@GiETa(>Uh|xZ!K^3I z<7k?Sb2@IxuZdz$x(-hjA;*m zPkPdT*I5z{yDmxny@^c;%28WVE#jxD;ar~@zkW<3?ehp2lMQ&Np%9RlSYRTm0J_cP@vpAx0qZ6fttQk zWSm=&5sryB$TC<4r(Cwn#JQ7wR()av7rJswW2E6$!#BeTSC?6Sm`=$|Phw$QS?D*h zLCB_2e@NK6*^2?MaZ_mCA1V(ZzUKT=aP_F!imM81*C;g7Rf=q;jB#0a9$Ro!EVX6F zRM>zHY$+`I2Q_!mc?a~}k;)6$~u6|Kf z(8Mg1;9!k%Nh9P{-!O*xa}_~e#s1YmwZ4{qGl!(Dw`ddp?DxQZ8wj7YU4?SfIC+Wv z9sWu$xura2v*9Wh_!PGshX-eJfAaooW8lx)9XGc^>sxhKlkW^TVu_Lq!r6mkBZuLu z9z6OQ4abouIB1W*-E=l&APkPu(xeR?+I&HHr=EAM*UxC|k-HH$K}++bPn&byu1r>6 zIYdcFb?P$GIjT=c;*wURdZH<(A$G082=!;xsU2CHv3VX=kYEe#&cmDy43Sls@5_34fYcX;ks!;ALdk z^$L|K-^wd|YbQ5;hK&xVUp65V*vvz0zA2ly5Pbo#L*D15`n{NtdY;M%cyOH^ z2EMEdrVWwx3|FECJfQn`lz=qxv%Nc_+57lM+wE6LGErsoFHU=MAkhv}F~!mVK2w=A zA%QuenRzm1rH^Y_3eaCg#wjr)TathmzAjUyK81aq**)Tw>~vGok!%4T%6A4P7}YS!LW|4FV!#fZ&iuk-TI{JmCTVM z+5SMwUE)sW>Un!uc*H5W7dTwb>l8)1xn8HFMe3U>nK%?js*$rcYeWB?}OocR#pTv_dSwo^S-o5dKoeKJT~JFCB& z&wGvvwDpKz%Fs0uF1U5UtUAsLIE?Eo*vif;jam;Jvn|Z__YhetPwX2TqS5r_R`Zd)oSvPjdG~byJbC`?HO6PjD;5`)Ryc zMzfh8BJ1x>*rU7K!w4%-NlibafsfAw(=7GA_!((AS8y=zDH?cvP*)u|5$R9v6V%8| z7MUBVmo-v+)BilV&GLP{a4&x|EyTQ53Sh#?S&M|cy2`aa`z{H}J7?ZJP;H2A5-sLk z;bW_FtuK)^uD4l~VJO&7!lDKQY2FzbLVPQm2ehC0y5G}i%9sS@3EY3Q0-8LuK~3L+ zn8GtTrDOOQKDe5#G8av%M7vWRJd^)V?K2S&cnUOdi*o$D2YukI2k%c6FJ*hOam}kH z(Kt=7A;)P}vOINK>=yhuj4Z=A|E-a0`wslrpk_T~n-AJ2RH@POz%DajP^itzulbQ- zCOOx>B*x0sXO!y2!e8PyHX&b$l&>Qpg6Knur0%34J?5*0EYq7S|%tDb@`gt5KsW?G4<*}R+aQX42bU_2?e;!ve0Jc5yF zvu@CuJ)#@lRLx(|)zoi#IW>GO$XysDCimig)yPh~^e55pRT{+Sy zBxxx;%Xpy7VYBPy97zeMp%baVgwoP-8#KPrXs1baj+#c^tg(cJYwFbvR?fV87^!S+ z;Qotyl?$)rC;MRWyrA^A6gJ>>JGGk_Ffea*m4~17(0(Y8Q1ESr|6b)onuF4dp|r}0 z#(CiGKGbD^S^GaNn374t6`ZwjYDgH<^=F-bs=Fg>u$^Til!KTt7n!x3V3vPKg}A+eF?u?@Mx4HWZ~k8U?%Vz* z8ik1+JViU*?G^K^8!Sr~+uLzvjp!f7?Z0S|J6!=31YFmIzmtCLjU^lr_lYuOc9s9G z_J$u9_9UzkF*8;=&(%sdH`C<)QY;#WEx-o5DtLv|JY_V>|Gxg>U|gmt`sH!>^!TV$ zrw&`z`f}w2c6>S>`>`s$F8G{r2-fgCvouIaRSDc@nICLAVtRxm%(|S;B!@AS2mVr> zYXnwra(14ZR<2>Hd-rfemOiPjFzd`&wa)j|hGDE$c)IP76~E2Xh@RkezIwdFwLA;f zvYGWm){Ag2DdFkv;MUz9Z*%s}5+wqg*0GP-{prei{#dDbw$i+nY{C7&y)su@ocqb+ zfE9yG8`&z@mfVvKg*UggfX%Vm2gXTKUSUaMbu;Kl;Qm!F*z+{SP!wOtLz}BO+7?X2 z3B5ul?>PPZ_*%mZI`cUPFU;~xkzwO&J2Tmr_AeN}uYn9Bl3|yRpS!=cErU%3qa)tS z58)f0n(B0DB~?3NzMRL5&J>M~kBy#EQ`P1NXR^lLEy!A!k9x&?tY9_Wsl+hVpFk$I zaSk^xX6nrE4GcQ-HETPRxjWzXJ}-D?v2=8g&l4khB$w=m-F0RNKk>3EG5i$VSsPlI zVA=EINvCskCn3}Q`|iU;%NJ=p(!(VVx?^t~(%Yk63YXsanvUQIYXRTg&Kk>iXAbMV zU5%{Sh0jTT6&luLZy!*d^ zP~1m@l-S;FW^{==9;2qHw%|KDfyj1zxh-EKu)Y@Fe#tj1!iC6N4#zqt60Tea7&7nS!uHv3&g+ zP1aRWrQA6hZ!uHzUCXR$lxw5BUaNNH03L-rIt@6tkr!q;g`Zui5bue4Wu={MymAv2 zh^nmIM*ErB*Z-uvGGbMQcUf?1bcB5*`H`LvHLj)Fnf~gYkSz5$v)-mF?nOR-lfoQd&k0TqJ zaAcqc>!b9TM&2$L% z`_VoY-tM^w^j$-Zq;_hTVd8^eXs}cML?s1A(PruPm7}oo6OZi^mHJZw50oKdD?j~g zz3=gR{Xt!Y2fLT1R`8sC>#msIkgm7g2R+_yWP_jStU5=vYgf|!!eh#|7yMx}d&k)H z?DoRL7JtF631Bci%j59$go?M6zlRTZh8UvGFX#lvZcob&tFdhfI*{@+NT(*V(&GM_ zo-H4LDs#StJeD@|9Yyu*o7akPb5b{#r8RG_ntj1fkr&k(y&z5Y#~nU-lhou80cnil zm|;k3PapO>Xivx%*nIGP1^=~ALHdMtX@`g-BC!v{14gTf>}8}@{a7ffi$`8G8?F7c z@FqvIGwVjeJv4{@k!XLm$8e~LBIq{gu$n)Z=^I82VPsmy)l+0S|?i&&5Hv%ts zf}sJ}hT}lV`sX#DjbAR*U~UsdkO&Af=D_aYEaTB@7cJws?N#&w_AvfKMY8TkOw=n~ zeaA4Dkk(Lm|M9F^f&!k0*r*2`z=d|i)fNhlOt8UD)=SQ1_BVW4$uskm_&eEb9c=;* z%`D~HYQOfR%tcMemx$-}i4&EiLEc{0OGk{Igp5P3>439aJ3*l_mVNO_8mG(EJrm=X zh;kl_noV){bYqU$lC?RcgL!X>Jf~(FnjyT@dCsrM8$QLYluowljPwZhnKw+8VF^{K z6=rH*h&_9Nbxo&sD^S=K$wHC+aLA#?6QpAl7*LgLXZZ5)`uD7e)`W$_&c3Ow+w>6X z`?|`f70b^+;=K^CJO?GhP#3e-U|LNMGh7@5&z$pRNPuG@W@te#r6!o^lPjn;^@1i-teg6WZ06BuM$iI4jh@a6`?#Mt)NXgx?R|*B8{H58PdO(RFugD`Kk5(XX$*%K(+c* zXqNrhRaFjsjWrDk#LqSOMXq}KH5RgEkLKH_ZqnB<41uboP}ubL@;W#gDJdR$W{&D5+WhG@K3^i$d!1o^ zuR7G7CUv8)>VzK_=aoGNzWL#0FFl|dA5;Doxq1Aso2Qa+5%_mz!<+%&T}0RmPu9rM zhW;ATQ=Uz9tHb_WP$c?JWtGVAJIVX{bAn`&BeiIcDodsQ}kVJ*X@$J@uk23tF zw8d?RDm|$z?(;y023d6q8O`x!l|p&}sFiboT^1PQeBnFF>65 zUq;0IXN6m1gJ+s$*|>+pQ~e&p86{0_OQ<2&7B1J}0zXXM)>t9)R;F2xQzjOIAfJg; z%yrwex_65ydxf$>R&~}WlBV@bvU7!r+*HZ;0{elK?5Zs$&3x)4OX!az=dhUGVJ&?p zDXWIy*8`5#yOAQXn>aVOOfmNXCV7J{ZfR=8h`ro}W6H4;H$JG;(q#b^ z;0M0)m-1KpQfF@{toBfD_H>36+>E~?y?x0WsUvwmP49k7zH{0>IwQ!>wi%CUXxfx0 zK@?T+K}|1*S-1-~cxuXElwZZsjwZHB!i>ruX_OX)dddkH<$MP@FwxH|WfkP6@zcj& zxi;)>qvW|%XRn@x1=dHc_Iw!$30qx$G9q1a>3d>Y}tr%nIFD<>) zvX5h{aZSSIfmNe&J&JQHgtYzgz8|_?C1#=tG(lfv%7>JoJ7wx%D zm0=(1YiOsrLGzK<#Eph}p8w+Qt}i*fJ(-0H^v)kM%PQR@m^o91f*HOF{-Gel+?;2<~?|{)^EJCy?VP{v@Kk8U?xCXyB0c34V8YdL+X%-leNoX zDFfyCG`Dh28#zH+NblHkN~5`KqyEzJ2Wm#6Wv&K8-0kMvW8dx@H|4CwwB=;)-8UOG zlwUBPv5zh;lF3?5tG9;sy~^}CPrWB`N7LAD_?lCZ+x{o%%9PY4lnuzRx9EoV`v)nuUjVOx}3dLrhyVFn|JuS8f1vZxtrs`gG5^5#aDfI@mN0ilE>)Fnqs{r)} zQn6hcP3e^(wL-6*rYosl_&TkoA(pV25GjpR^%CB%j4dXwP5Ca#Hb@laNsw5!5JNs! zR=;Zd6*{YEE}A=8(4qQ3`QivQsH}kyXe#4oWwV=}=#(X}!rn#oj{P)g7D_+iZ>W?N)V0}Ka!u*$gM>hPh3gj`x_i?;}(QDRK!cIMeO zouSWp##raDRZ{XE%W=c!Cr*W!#z}r@#WOKofeCpS)u!tGHQnIjBTD&dW6%L~h=kHB z4N&3M&n%b>4X1ZM%%RrC1YP(PB`ecqvEddmP^vg30WDw`8q%kHKWVpw3;&rW^g`vM zwcY@Cfv(oG5UOc+3{ z)s;LG@i#|PTk>chfoSb2@n13d=eKtA?OyM7tgor-gcsVA)qIRxZI=Hcb^!pO{Y#5` zOh`KOo%*jY{!#hoSPTLm3`^f4H%GxuNmv%}Vv6!#FlyJlQaofM#^xfRr3(r{#HWZ% zh+i4>-$)~q2s=^@S)LDWzYKV=Q$-lq?tx!yPdpO3D+?>I1OS9T4xj?l78b0FHN_;2 zl`a5kK5hz-(!cC~3bX!8Ir?`E|JjJVNp3z*YOfLL7y8t`_}AIt-<|!>L&m>55M;V~ zIKRBYPr3!{b_Mb*WT%ZVJJ(>Vx{GLa)8o7Q!K|YuT^r)c%~;ass4XIr;4Jf4f2-w2 zol#N$B)PF=NO06|eYSSrD7hKWQPM!~zNyOmk1ApUi7*c<)#shHtzBq6Tv0P#ZEBpo z1ux-E8yOo)2JX8-_)?zg{ggsAGi3;H^BL}xMS~yP!uOOcn)>hK2th800}=j;D9&WE zC6l;Ni&p6=}^rZXFo^i29| z79|ILHlM_w6&2Ru9|V?O&p`rHa1Bj{V-T*wP%*PCBw#!PGGcJ=PLb>VM@g=6^@N{p z!>ha_VUtmXrEV!kD{fiAFQ>RUCCn@KGUSKjOI@K0j=|1+4Dosrq`2}dz)T$9dwbBm z%|1=TT=9)-WZ?dj;YL7f~Zd;J!>I8JcXb!AInh#KmkYJYv6|{eaLc7OQ887WRo(JJL*xKHIq6@{}iRR{;2`_3Z&B9zEUN^+;a+7CUTK%$m(l2H^OA+JK_zaX7E^5Y(Z)^3%DBtG-yzC> zjXrhdEPzz-P6lsXV~Ckq1xKZ@Aag#0EsJQUyPE;mAZU397aGIe?Wtu3+>Z4PjEVXN zO5K~{usuC{?|lzu*1Ss5V*J4>Rb;mx%GA)!=p$i?w)$nVR-U0#zJh%(GfwbvE+61Oa44m`oKZN3( zRZV#k5L3^m=xogu{56`TMa)=1o=Kj{bVX!XPlvzkk2w4$t?V>`4#O#~nr7ZPo$TiE zoW=XRzSi@HVEv*>S4#RQDZ^=%y`J~jVYc4-q@7p4mse81km;Oky6dQ&`9CXrtb@~l zHh=7W&1#e4)Ci@XmKT<3f`he>{HhshDXm$AIzA^;X!zQm(`<@J7tyqO!7riQ)3UG1 zSr>#9sR}86JoNQJrBhMZ)g*583Efu|SaxuNFiG-j7xVT^482LV3<|hEc_2Cv`AUmlnUH>DK?B#)m~F{X*Sqa|QY2O`LMX@c z360K_sqYDh{zl$mW20DTsGaUK7Ud@gqE+uctu=W*Q7@O2eN{$kS=+jz%W$?Of`w!M zxywM`*6#ve#zBV~T!6o`Pi9ya8d{c|mDBK0H}@0aoqsUYlB(*XwkECBa&RumsbavQ zt`I)v{6h1lXPxWZe_M`_S@Z(Z#tOx8S12#+8M*SC5=n@+H;@sEF(Vh8I#*e zga#}?kY!wEoLmp zVX+g&_?pWZ86?<{F*!LA>hnyIeTn#u2zHKZ9TTBuT7A-a4tT_R-4RQc=$a#Dh&v1i z55|iw#I}u&fRh}s?*(?By+$!L$P3~ATANQF!8p0>*#<(A^`Aagg+f&ESvS?sfaP-5$vTL#*d}I7p1)i&RSjADkdA(gl4cd?aR}q8 zZ6|ul1{yN}06~4joi=5s=qnq!qj^(8tR%LS|6S7=WgM2t8j7OD8K~g4g22)79*vud z18w?Z%`USF=>QGxD3kxr|8<<04~o%#hlY$!hT<1KXN*ZiQ>#v{@8)aSXvujmLw*|$ULbA0&xxLw*{Jlv>28>Ab5 z(6D}1Tv_pFG!^3G*Z)bnd6%L+>qw@ZkSX|774p6I6^N2@YmRv|1T>)}=a0Vxz&?SB zWrhsUO|EZ6HE4LkQ_k~hBJfeb?T@Xf=3SnFZ}7SChEWe5+fr?LA?ryHSiLlr$yU#F zfs|+fP3_3~w&z(v;0?g)<1q%148vpRmBa@fouxXd5~}|k?y>4T{-Q@sW}qfzN4$DiPf^& z8KhX47)KvYjKAJ9VgNkg1$k>1b07CMMATYtR{`OorjGorIvwlHknrZ?0K!M&)rN!I zCekpZYnO1)5eWNYI97@6o!1@vYBj8o^E~s+wa;g-;i3ZP358M)$%w~ksj2#$uMj0) zo_I@{w3EuBm8hrMtlY?d{+Fx&TeZ~HvGXhQ#i + + + + + Azure Storage JavaScript Client Library Sample for Blob Operations + + + +
+
+

Azure Storage JavaScript Client Library Sample for Blob Operations

+
+

In this sample, we will demonstrate common scenarios for Azure Blob Storage that includes creating, listing and deleting containers and blobs.

+
+

Azure Blob storage is a service for storing large amounts of unstructured object data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.

+ +
+
+ Note: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB. +
+
+ +

Contents:

+ + +

Step 1: Preparing an Azure Storage account with CORS rules set

+

Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. + You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. + The "Allowed origins" could be set to "*" to allow all the origins in this sample. + For more information about CORS, see Cross-Origin Resource Sharing (CORS).

+ + +

Step 2: Importing Azure Storage JavaScript Client Library

+

+ Importing azure-storage.common.js and azure-storage.blob.js in your HTML file for blob operations, and make sure azure-storage.common.js is in front of azure-storage.blob.js. +

+

+<script src="azure-storage.common.js"></script>
+<script src="azure-storage.blob.js"></script>
+
+ +

Step 3: Creating an Azure Storage Blob Service Object

+

+ The BlobService object lets you work with containers and blobs. + Following code creates a BlobService object with storage account and SAS Token. +

+
+var blobUri = 'https://' + 'STORAGE_ACCOUNT' + '.blob.core.windows.net';
+var blobService = AzureStorage.createBlobServiceWithSas(blobUri, 'SAS_TOKEN');
+
+

+ In Azure Storage JavaScript Client Library, a global variable AzureStorage is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities. +

+
+
+ How to get full detailed API definitions? Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK. + Please check API details on Azure Storage Node.js API reference documents. The JavaScript global variable AzureStorage is just like the object require('azure-storage') returns in Node.js. +
+
+
+
+ Warning: Azure Storage JavaScript Client Library also supports creating BlobService based on Storage Account Key for authentication besides SAS Token. + However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy. +
+
+ +

Step 4: Container Operations

+

+ A container provides a grouping of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs. Note that the container name must be lowercase. + BlobService object provides plenty of interfaces for container operations. +

+ +

List Containers

+

BlobService provides listContainersSegmented and listContainersSegmentedWithPrefix for retrieving the containers list under a storage account.

+
+blobService.listContainersSegmented(null, function (error, results) {
+    if (error) {
+        // List container error
+    } else {
+        for (var i = 0, container; container = results.entries[i]; i++) {
+            // Deal with container object
+        }
+    }
+});
+
+ +

Create Container

+

BlobService provides createContainer and createContainerIfNotExists for creating a container under a storage account.

+
+blobService.createContainerIfNotExists('mycontainer', function(error, result) {
+    if (error) {
+        // Create container error
+    } else {
+        // Create container successfully
+    }
+});
+
+ +

Delete Container

+

BlobService provides deleteContainer and deleteContainerIfExists for deleting a container under a storage account.

+
+blobService.deleteContainerIfExists('mycontainer', function(error, result) {
+    if (error) {
+        // Delete container error
+    } else {
+        // Delete container successfully
+    }
+});
+
+ +

Executable Example

+

+ The sample will try to create an Azure Storage blob service object based on SAS Token authorization. + Enter your Azure Storage account name and SAS Token here, and executable examples in following steps dependent on the settings here. + Make sure you have set the CORS rules for the Azure Storage blob service, and the SAS Token is in valid period. +

+

+ + +

+

In the following executable example, you can try to list all the containers under your storage account settings, and try to create or delete one container from your account.

+
    +
  • Click button to view the container list under your Azure Storage account

  • +
  • +

    Click button to create a container under your Azure Storage account:

    +

    +
  • +
  • Click "Delete" button in the container list to delete the container under your Azure Storage account

  • +
  • Click "Select" button to select and operate with the blobs in next step

  • +
+
+ +

Step 5: Blob Operations

+

Blob: A file of any type and size. Azure Storage offers three types of blobs: block blobs, page blobs, and append blobs.

+

Block blobs are ideal for storing text or binary files, such as documents and media files. Append blobs are similar to block blobs in that they are made up of blocks, but they are optimized for append operations, so they are useful for logging scenarios. A single block blob can contain up to 50,000 blocks of up to 100 MB each, for a total size of slightly more than 4.75 TB (100 MB X 50,000). A single append blob can contain up to 50,000 blocks of up to 4 MB each, for a total size of slightly more than 195 GB (4 MB X 50,000).

+

Page blobs can be up to 1 TB in size, and are more efficient for frequent read/write operations. Azure Virtual Machines use page blobs as OS and data disks.

+

For details about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

+ +

List Blobs

+

BlobService provides listBlobsSegmented and listBlobsSegmentedWithPrefix for retrieving the blobs list under a container.

+
+blobService.listBlobsSegmented('mycontainer', null, function (error, results) {
+    if (error) {
+        // List blobs error
+    } else {
+        for (var i = 0, blob; blob = results.entries[i]; i++) {
+            // Deal with blob object
+        }
+    }
+});
+
+

Upload Blob

+

BlobService provides createBlockBlobFromBrowserFile, createPageBlobFromBrowserFile, createAppendBlobFromBrowserFile and appendFromBrowserFile for uploading or appending a blob from an HTML file in browsers. +

+ +

Uploading blob from stream. You can set up the blob name as well as the size of this uploading session.

+
+// If one file has been selected in the HTML file input element
+var file = document.getElementById('fileinput').files[0];
+
+var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512;
+blobService.singleBlobPutThresholdInBytes = customBlockSize;
+
+var finishedOrError = false;
+var speedSummary = blobService.createBlockBlobFromBrowserFile('mycontainer', file.name, file, {blockSize : customBlockSize}, function(error, result, response) {
+    finishedOrError = true;
+    if (error) {
+        // Upload blob failed
+    } else {
+        // Upload successfully
+    }
+});
+refreshProgress();
+
+

Checking the upload progress with speedSummary object.

+
+function refreshProgress() {
+    setTimeout(function() {
+        if (!finishedOrError) {
+            var process = speedSummary.getCompletePercent();
+            displayProcess(process);
+            refreshProgress();
+        }
+    }, 200);
+}
+
+
+
+ Warning: + By default, the speedSummary.getCompletePercent() only updates progress when a block is uploaded to server. There are 2 default settings may influence the upload progress display. + +
    +
  • blobService.singleBlobPutThresholdInBytes is the maximum size (default 32MB), in bytes, of a blob before it must be separated into blocks.
  • +
  • Option {blockSize: SizeInBytes} of blobService.createBlockBlobFromStream() is the size (default 4MB) of every block in the storage layer.
  • +
+ + This means, by default, blobs smaller than 32MB will only get the progress update when the upload is over, and blobs larger than 32MB will update the process every 4MB. + For slow connections or progress reporting for small blobs, you can customize both the two settings into samller values such as 1MB or 512KB. Thus the progress will update with the smaller step you set. + However, very small block sizes will impact the storage performance especially for a large blob. +
+
+ +

Download Blob

+

+ BlobService provides interfaces for downloading a blob into browser memory. + Because of browser's sandbox limitation, we cannot save the downloaded data trunks into disk until we get all the data trunks of a blob into browser memory. + The browser's memory size is also limited especially for downloading huge blobs, so it's recommended to download a blob in browser with SAS Token authorized link directly. +

+

+ Shared access signatures (SAS) are a secure way to provide granular access to blobs and containers without providing your storage account name or keys. Shared access signatures are often used to provide limited access to your data, such as allowing a mobile app to access blobs. + The following code example generates a new shared access policy that allows the shared access signatures holder to perform read operations on the myblob blob, and expires 100 minutes after the time it is created. +

+
+
+ Note: You can choose to use the SAS Token in browser side, or generate a temporary SAS Token dynamically in your server side with Azure Storage C# or Node.js SDKs etc. according to your security requirements. +
+
+
+var downloadLink = blobService.getUrl('mycontainer', 'myblob', 'SAS_TOKEN');
+
+ +

Delete Blob

+

BlobService provides deleteContainer and deleteContainerIfExists for deleting a blob under a storage account.

+
+blobService.deleteBlobIfExists(container, blob, function(error, result) {
+    if (error) {
+        // Delete blob failed
+    } else {
+        // Delete blob successfully
+    }
+});
+
+

Executable Example

+

After clicked the "Select" button on the container list in last step, you are able to operate with the blobs under the selected container.

+ +
    +
  • Click button to view the blobs under your selected container

  • +
  • + Click button to upload a local file to current container after selecting a file: +

    +

  • +
  • Click "Delete" button to delete the blob

  • +
  • Click "Download" link to download a blob to local

  • +
+ +
+
Uploaded Bytes:
+
+
+ 0% +
+
+ +
+ +

Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

+
    +
  • 1. Setting CORS rules for your selected Azure-Storage account blob service.
  • +
  • 2. Including "azure-storage.common.js" in the html file.
  • +
  • 3. Including functional file(s) needed, such as "azure-storage.blob.js" for blob operation.
  • +
  • 4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.
  • +
  • 5. Referring to Azure Storage Node.js SDK documents for detailed API definitions which keep same with JavaScript APIs.
  • +
+

You can view the source code of this sample for detailed reference.

+
+ + + + + + + + \ No newline at end of file diff --git a/node_modules/azure-storage/browser/samples/sample-file.html b/node_modules/azure-storage/browser/samples/sample-file.html new file mode 100644 index 000000000..c635815fc --- /dev/null +++ b/node_modules/azure-storage/browser/samples/sample-file.html @@ -0,0 +1,588 @@ + + + + + + Azure Storage JavaScript Client Library Sample for File Operations + + + +
+
+

Azure Storage JavaScript Client Library Sample for File Operations

+
+

In this sample, we will demonstrate common scenarios for Azure File Storage that includes creating, listing and deleting file shares, directories and files.

+
+

Azure File storage is a service for storing large amounts of unstructured object data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use file storage to expose data publicly to the world, or to store application data privately.

+

With Azure File storage, you can migrate legacy applications that rely on file shares to Azure quickly and without costly rewrites. Applications running in Azure virtual machines or cloud services or from on-premises clients can mount a file share in the cloud, just as a desktop application mounts a typical SMB share. Any number of application components can then mount and access the File storage share simultaneously. In this sample, you are able to create a file service with storage account and SAS Token. Based on the file service, you could create a file share, list files, upload files and delete files.

+ +
+
+ Note: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB. +
+
+ +

Contents:

+ + +

Step 1: Preparing an Azure Storage account with CORS rules set

+

Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. + You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. + The "Allowed origins" could be set to "*" to allow all the origins in this sample. + For more information about CORS, see Cross-Origin Resource Sharing (CORS).

+ + +

Step 2: Importing Azure Storage JavaScript Files

+

+ Importing azure-storage.common.js and azure-storage.file.js in your HTML file for file operations, and make sure azure-storage.common.js is in front of azure-storage.file.js. +

+

+<script src="azure-storage.common.js"></script>
+<script src="azure-storage.file.js"></script>
+
+ +

Step 3: Creating an Azure Storage File Service Object

+

+ The FileService object lets you work with files and directories. + Following code creates a FileService object with storage account and SAS Token. +

+
+var fileUri = 'https://' + 'STORAGE_ACCOUNT' + '.file.core.windows.net';
+var fileService = AzureStorage.createFileServiceWithSas(fileUri, 'SAS_TOKEN');
+
+

+ In Azure Storage JavaScript Client Library, a global variable AzureStorage is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities. +

+
+
+ How to get full detailed API definitions? Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK. + Please check API details on Azure Storage Node.js API reference documents. The JavaScript global variable AzureStorage is just like the object require('azure-storage') returns in Node.js. +
+
+
+
+ Warning: Azure Storage JavaScript Client Library also supports creating FileService based on Storage Account Key for authentication besides SAS Token. + However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy. +
+
+ +

Step 4: File Share Operations

+

Share: A File storage share is an SMB file share in Azure. All directories and files must be created in a parent share. An account can contain an unlimited number of shares, and a share can store an unlimited number of files, up to the 5 TB total capacity of the file share.

+ +

List File Shares

+

FileService provides listSharesSegmented and listSharesSegmentedWithPrefix for listing file shares under a storage account.

+
+fileService.listSharesSegmented(null, function(error, result) {
+    if(error) {
+        // List shares error
+    } else {
+        for (var i = 0, share; share = results.entries[i]; i++) {
+            // Deal with share object
+        }
+    }
+});
+
+ +

Create File Share

+

FileService provides createShare and createShareIfNotExists for creating a file share under a storage account.

+
+fileService.createShareIfNotExists('myshare', function(error, result) {
+    if(error) {
+        // Create share error
+    } else {
+        // Create share successfully
+    }
+});
+
+ +

Delete File Share

+

FileService provides deleteShare and deleteShareIfExists for deleting a file share under a storage account.

+
+fileService.deleteShareIfExists('myshare', function(error, result) {
+    if(error) {
+        // Delete share error
+    } else {
+        // Delete share successfully
+    }
+});
+
+ +

Executable Example

+

The sample will try to create an Azure Storage file service object based on SAS Token authorization. Enter your Azure Storage account name and SAS Token here. Make sure you have set the CORS rules for the Azure Storage file service, and the SAS Token is in valid period.

+ + +

Azure Storage file service provides plenty of interfaces for file operations. In following example, you can try to list all the file shares under your storage account, and try to create or delete one file share from your account.

+
    +
  • Click button to view the file share list under your Azure Storage account

  • +
  • +

    Click button to create a file share under your Azure Storage account

    +

    +
  • +
  • Click "Delete" button to delete the file share under your Azure Storage account

  • +
  • Click "Select" button to operate with the directories and files in next step

  • +
+
+ +

Step 5: Directory and File Operations

+

Directory in storage is an optional hierarchy of directories.

+

File: A file in the share. A file may be up to 1 TB in size.

+ +

List Files and Directories

+

FileService provides listFilesAndDirectoriesSegmented for listing directories and files under a file share.

+
+fileService.listFilesAndDirectoriesSegmented('myfileshare', '', null, function(error, result, response) {
+    if(error) {
+        // List table entity error
+    } else {
+        for (var i = 0, dir; dir = results.entries.directories[i]; i++) {
+            // Deal with directory object
+        }
+        for (var i = 0, file; file = results.entries.files[i]; i++) {
+            // Deal with file object
+        }
+    }
+});
+
+ +

Create Directory

+

FileService provides createDirectory and createDirectoryIfNotExists for creating directories under a file share.

+
+fileService.createDirectoryIfNotExists('myfileshare', 'mydirectory', function(error, result, response) {
+    if(error) {
+        // Create directory error
+    } else {
+        // Create directory successfully
+    }
+});
+
+ +

Delete Directory

+

FileService provides deleteDirectory and deleteDirectoryIfExists for deleting directories under a file share.

+
+fileService.deleteDirectoryIfExists('myfileshare', 'mydirectory', function(error, result, response) {
+    if(error) {
+        // Delete directory error
+    } else {
+        // Delete directory successfully
+    }
+});
+
+ +

Upload File

+

FileService provides createFileFromBrowserFile for uploading a file from an HTML file in browsers. +

+ +

Uploading file from stream. You can set up the file name as well as the size of this uploading session.

+
+// If one file has been selected in the HTML file input element
+var files = document.getElementById('fileinput').files;
+var file = files[0];
+
+var finishedOrError = false;
+var speedSummary = fileService.createFileFromBrowserFile('myfileshare', 'mydirectory', file.name, file, {}, function(error, result, response) {
+    finishedOrError = true;
+    if (error) {
+        // Upload file failed
+    } else {
+        // Upload successfully
+    }
+});
+refreshProgress();
+
+

Checking the upload progress with speedSummary object.

+
+function refreshProgress() {
+    setTimeout(function() {
+        if (!finishedOrError) {
+            var process = speedSummary.getCompletePercent();
+            displayProcess(process);
+            refreshProgress();
+        }
+    }, 200);
+}
+
+

Download File

+

+ FileService provides interfaces for downloading a file into browser memory directly. + Because of browser's sandbox limitation, we cannot save the downloaded data trunks into disk until we get all the data trunks of a file into browser memory. + The browser's memory size is also limited especially for downloading huge files, so it's recommended to download a file in browser with SAS Token authorized link directly. +

+

+ Shared access signatures (SAS) are a secure way to provide granular access to files and directories without providing your storage account name or keys. Shared access signatures are often used to provide limited access to your data, such as allowing a mobile app to access files. + The following code example generates a new shared access policy that allows the shared access signatures holder to perform read operations on the myfile file, and expires 100 minutes after the time it is created. +

+
+
+ Note: You can choose to use the SAS Token in browser side, or generate a temporary SAS Token dynamically in your server side with Azure Storage C# or Node.js SDKs etc. according to your security requirements. +
+
+
+var downloadLink = fileService.getUrl('myshare', 'mydirectory', 'myfile', 'SAS_TOKEN');
+
+ +

Delete File

+

FileService provides deleteFile and deleteFileIfExists for deleting files under a file share.

+
+fileService.deleteFileIfExists('myfileshare', 'mydirectory', 'myfile', function(error, result, response) {
+    if(error) {
+        // Delete file error
+    } else {
+        // Delete file successfully
+    }
+});
+
+ +

Executable Example

+

After clicked the "Select" button on the file share list, you are able to operate with the directories and files under the selected file share.

+

    +
  • Click button to view the directories and files under your selected file share

  • +
  • Click button to create a directory share under your current directory

    +

    +
  • +
  • Click button to return to upper level directory

  • +
  • Click button to upload a local file to current directory

    +

  • +
  • Click "Delete" button to delete the directory or file

  • +
  • Click "Download" link to download a file to local

  • +
+ + Current Path: +
Uploaded Bytes:
+
+
+ 0% +
+
+
+ +

Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

+
    +
  • 1. Setting CORS rules for your selected Azure-Storage account file service.
  • +
  • 2. Including "azure-storage.common.js" in the html file.
  • +
  • 3. Including functional file(s) needed, such as "azure-storage.file.js" for file operation.
  • +
  • 4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.
  • +
  • 5. Referring to Azure Storage Node.js SDK documents for detailed API definitions which keep same with JavaScript APIs.
  • +
+

You can view the source code of this sample for detailed reference.

+
+ + + + + + + \ No newline at end of file diff --git a/node_modules/azure-storage/browser/samples/sample-queue.html b/node_modules/azure-storage/browser/samples/sample-queue.html new file mode 100644 index 000000000..2e060e4ac --- /dev/null +++ b/node_modules/azure-storage/browser/samples/sample-queue.html @@ -0,0 +1,465 @@ + + + + + + Azure Storage JavaScript Client Library Sample for Queue Operations + + + +
+
+

Azure Storage JavaScript Client Library Sample for Queue Operations

+
+

In this sample, we will demonstrate common scenarios for Azure Queue Storage that includes creating, listing and deleting queues and messages.

+
+ +

Azure Storage queue service provides cloud messaging between application components. In designing applications for scale, application components are often decoupled, so that they can scale independently. Queue storage delivers asynchronous messaging for communication between application components, whether they are running in the cloud, on the desktop, on an on-premises server, or on a mobile device. Queue storage also supports managing asynchronous tasks and building process work flows. +

+ +
+
+ Note: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB. +
+
+ +

Contents:

+ + +

Step 1: Preparing an Azure Storage account with CORS rules set

+

Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. + You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. + The "Allowed origins" could be set to "*" to allow all the origins in this sample. + For more information about CORS, see Cross-Origin Resource Sharing (CORS).

+ + +

Step 2: Importing Azure Storage JavaScript Client Library

+

+ Importing azure-storage.common.js and azure-storage.queue.js in your HTML file for queue operations, and make sure azure-storage.common.js is in front of azure-storage.queue.js. +

+

+<script src="azure-storage.common.js"></script>
+<script src="azure-storage.queue.js"></script>
+
+ +

Step 3: Creating an Azure Storage Queue Service Object

+

+ The QueueService object lets you work with queues and messages. + Following code creates a QueueService object with storage account and SAS Token. +

+
+var queueUri = 'https://' + 'STORAGE_ACCOUNT' + '.queue.core.windows.net';
+var queueService = AzureStorage.createQueueServiceWithSas(queueUri, 'SAS_TOKEN');
+
+

+ In Azure Storage JavaScript Client Library, a global variable AzureStorage is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities. +

+
+
+ How to get full detailed API definitions? Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK. + Please check API details on Azure Storage Node.js API reference documents. The JavaScript global variable AzureStorage is just like the object require('azure-storage') returns in Node.js. +
+
+
+
+ Warning: Azure Storage JavaScript Client Library also supports creating QueueService based on Storage Account Key for authentication besides SAS Token. + However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy. +
+
+ +

Step 4: Queue Operations

+

+ Azure Queue storage is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account. +

+ +

List Queues

+

QueueService provides listQueuesSegmented and listQueuesSegmentedWithPrefix for retrieving the queue list under your storage account.

+
+queueService.listQueuesSegmented(null, function (error, results) {
+    if (error) {
+        // List queue error
+    } else {
+        for (var i = 0, queue; queue = results.entries[i]; i++) {
+            // Deal with queue object
+        }
+    }
+});
+
+ +

Create Queue

+

QueueService provides createQueue and createQueueIfNotExists for creating a queue under a storage account.

+
+queueService.createQueueIfNotExists('myqueue', function(error, result) {
+    if (error) {
+        // Create queue error
+    } else {
+        // Create queue successfully
+    }
+});
+
+ +

Delete Queue

+

QueueService provides deleteQueue and deleteQueueIfExists for deleting a queue under a storage account.

+
+queueService.deleteQueueIfExists('myqueue', function(error, result) {
+    if (error) {
+        // Delete queue error
+    } else {
+        // Delete queue successfully
+    }
+});
+
+ +

Executable Example

+

The sample will try to create an Azure Storage queue service object based on SAS Token authorization. Enter your Azure Storage account name and SAS Token here. Make sure you have set the CORS rules for the Azure Storage queue service, and the SAS Token is in valid period.

+ + +

Azure Storage queue service provides plenty of interfaces for queue operations. In following example, you can try to list all the queues under your storage account, and try to create or delete one queue from your account.

+
    +
  • Click button to view the queue list under your Azure Storage account

  • +
  • Click button to create a queue under your Azure Storage account:

    +

    +
  • +
  • Click "Delete" button to delete the queue under your Azure Storage account

  • +
  • Click "Select" button to select a queue and operate with the queue messages in next step

  • +
+
+ +

Step 5: Message Operations

+

A storage Message, in any format, of up to 64 KB. The maximum time that a message can remain in the queue is 7 days.

+
+
+ Note: Azure Storage JavaScript Client Library provides var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder() which is a Base64 encoder and docoder. + If a message content string is encoded with encoder.encode(), remember to decode it with encoder.decode() after peek the message. +
+
+ +

Peek Messages

+

QueueService provides peekMessage and peekMessages for retrieving the messages list under a queue.

+
+queueService.peekMessages('myqueue', {numOfMessages: 32}, function (error, results) {
+    if (error) {
+        // Peek messages error
+    } else {
+        for (var i = 0, message; message = results[i]; i++) {
+            // Deal with message object
+        }
+    }
+});
+
+ +

Create Message

+

QueueService provides createMessage for creating a new message to a queue.

+
+var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
+queueService.createMessage('myqueue', encoder.encode('mymessage'), function (error, results, response) {
+    if (error) {
+        // Create message error
+    } else {
+        // Create message successfully
+    }
+});
+
+ +

Dequeue Message

+

QueueService provides getMessages and deleteMessage for dequeuing next message in a queue.

+
+queueService.getMessages('myqueue', function(error, result, response) {
+  if(!error){
+    // Message text is in messages[0].messageText
+    var message = result[0];
+    queueService.deleteMessage('myqueue', message.messageId, message.popReceipt, function(error, response){
+      if(!error){
+        //message deleted
+      }
+    });
+  }
+});
+
+ +

Update Message

+

QueueService provides getMessages and updateMessage for updating next message in a queue.

+
+var encoder = new AzureStorage.QueueMessageEncoder.TextBase64QueueMessageEncoder();
+queueService.getMessages('myqueue', function(error, result, response) {
+  if(!error){
+    // Got the message
+    var message = result[0];
+    queueService.updateMessage('myqueue', message.messageId, message.popReceipt, 10, {messageText: encoder.encode('new text')}, function(error, result, response){
+      if(!error){
+        // Message updated successfully
+      }
+    });
+  }
+});
+
+ +

Executable Example

+

After clicked the "Select" button on the queue list in last step, you are able to operate with the queue messages under the selected queue.

+

    +
  • Click button to refresh the message list in your selected queue

  • +
  • Click button to create a message in your selected queue:

    +

    +
  • +
  • Click button to update the top queue message in your selected queue (Dequeued messages will be invisible for 30s by default.):

    +

    +
  • +
  • Click button to dequeue the top queue message in your selected queue:

  • +
+ +
+ +

Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

+
    +
  • 1. Setting CORS rules for your selected Azure-Storage account queue service.
  • +
  • 2. Including "azure-storage.common.js" in the html file.
  • +
  • 3. Including functional file(s) needed, such as "azure-storage.queue.js" for queue operation.
  • +
  • 4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.
  • +
  • 5. Referring to Azure Storage Node.js SDK documents for detailed API definitions which keep same with JavaScript APIs.
  • +
+

You can view the source code of this sample for detailed reference.

+
+ + + + + + + \ No newline at end of file diff --git a/node_modules/azure-storage/browser/samples/sample-table.html b/node_modules/azure-storage/browser/samples/sample-table.html new file mode 100644 index 000000000..d0737bdf2 --- /dev/null +++ b/node_modules/azure-storage/browser/samples/sample-table.html @@ -0,0 +1,440 @@ + + + + + + Azure Storage JavaScript Client Library Sample for Table Operations + + + +
+
+

Azure Storage JavaScript Client Library Sample for Table Operations

+
+

In this sample, we will demonstrate common scenarios for Azure Table Storage that includes creating, listing and deleting tables and entities.

+
+ +

Azure Storage table is a service that stores structured NoSQL data in the cloud. Table storage is a key/attribute store with a schemaless design. Because Table storage is schemaless, it's easy to adapt your data as the needs of your application evolve. Access to data is fast and cost-effective for all kinds of applications. Table storage is typically significantly lower in cost than traditional SQL for similar volumes of data. +

+ +
+
+ Note: You may need set up a HTTP server to host this sample for IE browser, because IndexedDB is only available on websites with http or https URL schemes in IE. Azure Storage JavaScript Client Library currently depends on IndexedDB. +
+
+ +

Contents:

+ + +

Step 1: Preparing an Azure Storage account with CORS rules set

+

Cross-origin resource sharing, or CORS, must be configured on the Azure Storage account to be accessed directly from JavaScript in the browser. + You are able to set the CORS rules for specific Azure Storage account on the Azure Portal. + The "Allowed origins" could be set to "*" to allow all the origins in this sample. + For more information about CORS, see Cross-Origin Resource Sharing (CORS).

+ + +

Step 2: Importing Azure Storage JavaScript Client Library

+

+ Importing azure-storage.common.js and azure-storage.table.js in your HTML file for table operations, and make sure azure-storage.common.js is in front of azure-storage.table.js. +

+

+<script src="azure-storage.common.js"></script>
+<script src="azure-storage.table.js"></script>
+
+ +

Step 3: Creating an Azure Storage Table Service Object

+

+ The TableService object lets you work with table and entities. + Following code creates a TableService object with storage account and SAS Token. +

+
+var tableUri = 'https://' + 'STORAGE_ACCOUNT' + '.table.core.windows.net';
+var tableService = AzureStorage.createTableServiceWithSas(tableUri, 'SAS_TOKEN');
+
+

+ In Azure Storage JavaScript Client Library, a global variable AzureStorage is the start point where we can create service objects for blob/table/queue/file and access to the storage utilities. +

+
+
+ How to get full detailed API definitions? Currently, the JavaScript Client Library shares the same API definitions with Node.js SDK. + Please check API details on Azure Storage Node.js API reference documents. The JavaScript global variable AzureStorage is just like the object require('azure-storage') returns in Node.js. +
+
+
+
+ Warning: Azure Storage JavaScript Client Library also supports creating TableService based on Storage Account Key for authentication besides SAS Token. + However, for security concerns, we recommend use of a limited time SAS Token, generated by a backend web server using a Stored Access Policy. +
+
+ +

Step 4: Table Operations

+

+ Table: A table is a collection of entities. Tables don't enforce a schema on entities, which means a single table can contain entities that have different sets of properties. The number of tables that a storage account can contain is limited only by the storage account capacity limit. +

+ +

List Tables

+

TableService provides listTablesSegmented and listTablesSegmentedWithPrefix for retrieving the table list under your storage account.

+
+tableService.listTablesSegmented(null, {maxResults : 200}, function (error, results) {
+    if (error) {
+        // List tables error
+    } else {
+        for (var i = 0, table; table = results.entries[i]; i++) {
+            // Deal with table object
+        }
+    }
+});
+
+ +

Create Table

+

TableService provides createTable and createTableIfNotExists for creating a table under a storage account.

+
+tableService.createTableIfNotExists('mytable', function(error, result) {
+    if (error) {
+        // Create table error
+    } else {
+        // Create table successfully
+    }
+});
+
+ +

Delete Table

+

TableService provides deleteTable and deleteTableIfExists for deleting a table under a storage account.

+
+tableService.deleteTableIfExists('mytable', function(error, result) {
+    if (error) {
+        // Delete table error
+    } else {
+        // Delete table successfully
+    }
+});
+
+ +

Executable Example

+

The sample will try to create an Azure Storage table service object based on SAS Token authorization. Enter your Azure Storage account name and SAS Token here. Make sure you have set the CORS rules for the Azure Storage table service, and the SAS Token is in valid period.

+ + +

Azure Storage table service provides plenty of interfaces for table operations. In following example, you can try to list all the tables under your storage account, and try to create or delete one table from your account.

+
    +
  • Click button to view the table list under your Azure Storage account

  • +
  • Click button to create a table under your Azure Storage account

    +

    +
  • +
  • Click "Delete" button to delete the table under your Azure Storage account

  • +
  • Click "Select" button to operate with the table entities in next step

  • +
+
+ +

Step 5: Table Entities Operations

+

Entity: An entity is a set of properties, similar to a database row. An entity can be up to 1MB in size.

+

Properties: A property is a name-value pair. Each entity can include up to 252 properties to store data. Each entity also has 3 system properties that specify a partition key, a row key, and a timestamp. Entities with the same partition key can be queried more quickly, and inserted/updated in atomic operations. An entity's row key is its unique identifier within a partition.

+ +

Query Entities

+

TableService provides queryEntities for querying a table under a storage account.

+
+var tableQuery = new AzureStorage.TableQuery().top(200);
+tableService.queryEntities('mytable', tableQuery, null, function(error, result) {
+    if (error) {
+        // Query entities error
+    } else {
+        for (var i = 0, entity; entity = results.entries[i]; i++) {
+            // Deal with entity object
+        }
+    }
+});
+
+ +

Insert or Replace Entity

+

TableService provides insertEntity, insertOrReplaceEntity and insertOrMergeEntity for adding a table entity under a storage account.

+
+var insertEntity = {
+    PartitionKey: {'_': 'partitionKey'},
+    RowKey: {'_': 'rowKey'}
+};
+
+tableService.insertOrReplaceEntity('mytable', insertEntity, function(error, result, response) {
+    if(error) {
+        // Insert table entity error
+    } else {
+        // Insert table entity successfully
+    }
+});
+
+ +

Delete Entity

+

TableService provides deleteEntity for deleting a table entity under a storage account.

+
+var deleteEntity = {
+    PartitionKey: {'_': 'partitionKey'},
+    RowKey: {'_': 'rowKey'}
+};
+
+tableService.deleteEntity('mytable', deleteEntity, function(error, result, response) {
+    if(error) {
+        // Delete table entity error
+    } else {
+        // Delete table entity successfully
+    }
+});
+
+ +

Executable Example

+

After clicked the "Select" button on the table list, you are able to operate with the table entities under the selected table.

+

    +
  • Click button to refresh the entity list in your selected table

  • +
  • Click button to create an entity in your selected table. If existing entity with the sampe PartitionKey and RowKey, old entity will be merged.

    +

    + + + + +

    +
  • +
  • Click "Delete" button to delete the selected table entity in your selected table

  • +
+
+ +

Step 6: Creating your JavaScript Application based on Azure Storage JavaScript Client Library

+
    +
  • 1. Setting CORS rules for your selected Azure-Storage account table service.
  • +
  • 2. Including "azure-storage.common.js" in the html file.
  • +
  • 3. Including functional file(s) needed, such as "azure-storage.table.js" for table operation.
  • +
  • 4. Using keyword "AzureStorage" to access to Azure storage JavaScript APIs.
  • +
  • 5. Referring to Azure Storage Node.js SDK documents for detailed API definitions which keep same with JavaScript APIs.
  • +
+

You can view the source code of this sample for detailed reference.

+
+ + + + + + + + \ No newline at end of file diff --git a/node_modules/azure-storage/examples/samples/blobuploaddownloadsample.js b/node_modules/azure-storage/examples/samples/blobuploaddownloadsample.js new file mode 100644 index 000000000..be5dd70cf --- /dev/null +++ b/node_modules/azure-storage/examples/samples/blobuploaddownloadsample.js @@ -0,0 +1,246 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* 1. Demonstrates how to upload all files from a given directory in parallel +* +* 2. Demonstrates how to download all files from a given blob container to a given destination directory. +* +* 3. Demonstrate making requests using AccessConditions. +*/ + +var fs = require('fs'); + +var azure; +if (fs.existsSync('absolute path to azure-storage.js')) { + azure = require('absolute path to azure-storage'); +} else { + azure = require('azure-storage'); +} + +var container = 'updownsample3'; +var blob = 'updownsample'; +var blobAccess = 'updownaccesssample'; + +var blobService = azure.createBlobService() + .withFilter(new azure.ExponentialRetryPolicyFilter()); + +// optionally set a proxy +/*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 +}; + +blobService.setProxy(proxy); +*/ + +function uploadSample() { + var processArguments = process.argv; + if (processArguments.length !== 4) { + console.log('Incorrect number of arguments. Should be: srcPath destPath'); + process.exit(1); + } + + var srcPath = processArguments[2]; + var destPath = processArguments[3]; + + console.log('Starting blobuploaddownloadsample.'); + + // Create the container + createContainer(container, function () { + + // Demonstrates how to upload all files from a given directoy + uploadBlobs(srcPath, container, function () { + + // Demonstrates how to download all files from a given + // blob container to a given destination directory. + downloadBlobs(container, destPath, function () { + + // Demonstrate making requests using AccessConditions. + useAccessCondition(container, function () { + + // Delete the container + deleteContainer(container, function () { + console.log('Ending blobuploaddownloadsample.'); + }); + }); + }); + }); + }); +} + +function createContainer (container, callback) { + // Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + callback(); + } + }); +} + +function uploadBlobs(sourceDirectoryPath, containerName, callback) { + console.log('Entering uploadBlobs.'); + + // validate directory is valid. + if (!fs.existsSync(sourceDirectoryPath)) { + console.log(sourceDirectoryPath + ' is an invalid directory path.'); + } else { + // Search the directory and generate a list of files to upload. + walk(sourceDirectoryPath, function (error, files) { + if (error) { + console.log(error); + } else { + var finished = 0; + + // generate and schedule an upload for each file + files.forEach(function (file) { + var blobName = file.replace(/^.*[\\\/]/, ''); + + blobService.createBlockBlobFromLocalFile(containerName, blobName, file, function (error) { + finished++; + + if (error) { + console.log(error); + } else { + console.log(' Blob ' + blobName + ' upload finished.'); + + if (finished === files.length) { + // Wait until all workers complete and the blobs are uploaded to the server. + console.log('All files uploaded'); + callback(); + } + } + }); + }); + } + }); + } +} + +function downloadBlobs(containerName, destinationDirectoryPath, callback) { + console.log('Entering downloadBlobs.'); + + // Validate directory + if (!fs.existsSync(destinationDirectoryPath)) { + console.log(destinationDirectoryPath + ' does not exist. Attempting to create this directory...'); + fs.mkdirSync(destinationDirectoryPath); + console.log(destinationDirectoryPath + ' created.'); + } + + // NOTE: does not handle pagination. + blobService.listBlobsSegmented(containerName, null, function (error, result) { + if (error) { + console.log(error); + } else { + var blobs = result.entries; + var blobsDownloaded = 0; + + blobs.forEach(function (blob) { + blobService.getBlobToLocalFile(containerName, blob.name, destinationDirectoryPath + '/' + blob.name, function (error2) { + blobsDownloaded++; + + if (error2) { + console.log(error2); + } else { + console.log(' Blob ' + blob.name + ' download finished.'); + + if (blobsDownloaded === blobs.length) { + // Wait until all workers complete and the blobs are downloaded + console.log('All files downloaded'); + callback(); + } + } + }); + }); + } + }); +} + +function useAccessCondition(containerName, callback) { + console.log('Entering useAccessCondition.'); + + // Create a blob. + blobService.createBlockBlobFromText(containerName, blobAccess, 'hello', function (error, blobInformation) { + if (error) { + console.log(error); + } else { + console.log(' Created the blob ' + blobInformation.name); + console.log(' Blob Etag is: ' + blobInformation.etag); + + // Use the If-not-match ETag condition to access the blob. By + // using the IfNoneMatch condition we are asserting that the blob needs + // to have been modified in order to complete the request. In this + // sample no other client is accessing the blob, so this will fail as + // expected. + var options = { accessConditions: { EtagNonMatch: blobInformation.etag} }; + blobService.createBlockBlobFromText(containerName, blobInformation.name, 'new hello', options, function (error2) { + if (error2 && error2.statusCode === 412 && error2.code === 'ConditionNotMet') { + console.log('Attempted to recreate the blob with the if-none-match access condition and got the expected exception.'); + callback(); + } else { + console.log(' Blob was incorrectly updated'); + if (error2) { + console.log(error2); + } + } + }); + } + }); +} + +function deleteContainer (container, callback) { + // Delete the container. + blobService.deleteContainerIfExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + callback(); + } + }); +} + +// Utility function + +var walk = function (dir, done) { + var results = []; + fs.readdir(dir, function (err, list) { + if (err) return done(err); + var i = 0; + (function next() { + var file = list[i++]; + if (!file) return done(null, results); + file = dir + '/' + file; + fs.stat(file, function (err2, stat) { + if (stat && stat.isDirectory()) { + walk(file, function (err3, res) { + results = results.concat(res); + next(); + }); + } else { + results.push(file); + next(); + } + }); + })(); + }); +}; + +uploadSample(); diff --git a/node_modules/azure-storage/examples/samples/continuationsample.js b/node_modules/azure-storage/examples/samples/continuationsample.js new file mode 100644 index 000000000..fa3f2bd45 --- /dev/null +++ b/node_modules/azure-storage/examples/samples/continuationsample.js @@ -0,0 +1,159 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* This sample demonstrates how to handle continuation tokens and virtual "pages" of results when performing a listing +* operation on the blob service. +* +* This sample peformsthe following steps: +* +* 0. Create container. +* +* 1. Create 50 blobs. +* +* 2. List the first 10(page size) blobs. +* +* 3. Check whether there are more results. +* +* 4. Repeat 2 and 3 until complete. +* +*/ + +var fs = require('fs'); + +var azure; +if (fs.existsSync('absolute path to azure-storage.js')) { + azure = require('absolute path to azure-storage'); +} else { + azure = require('azure-storage'); +} + +var container = 'paginationsample'; +var blob = 'contsample'; +var blobs = []; + +var blobService = azure.createBlobService() + .withFilter(new azure.ExponentialRetryPolicyFilter()); + +// optionally set a proxy +/*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 +}; + +blobService.setProxy(proxy); +*/ + +var totalBlobsCount; +var pageSize; + +function continuationSample () { + var processArguments = process.argv; + if (processArguments.length !== 4) { + console.log('Incorrect number of arguments. Should be: numBlobs pageSize [deleteContainer]\nTry: 51 10'); + process.exit(1); + } + + totalBlobsCount = parseInt(processArguments[2], 10); + pageSize = parseInt(processArguments[3], 10); + + console.log('Starting continuationSample.'); + + // Create the container + createContainer(container, function () { + + console.log('Entering createBlobs.'); + + // Upload blobs from text. + createBlobs(totalBlobsCount, function () { + var options = { + maxResults: pageSize, + include: 'metadata', + locationMode: azure.StorageUtilities.LocationMode.PRIMARY_THEN_SECONDARY + }; + + console.log('Entering listBlobs.'); + + // List blobs using continuation tokens. + listBlobs(options, null, function () { + + // Delete the container + deleteContainer(container, function () { + console.log('Ending continuationSample.'); + }); + }); + }); + }); +} + +function createContainer (container, callback) { + // Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + callback(); + } + }); +} + +function createBlobs(currentBlobsCount, callback) { + // Upload totalBlobsCount blobs to the container. + var options = {}; + options.metadata = {'hello':'world'}; + + blobService.createBlockBlobFromText(container, blob + currentBlobsCount, 'blob' + currentBlobsCount, options, function (error) { + if (error) { + console.log(error); + } else if (currentBlobsCount > 1) { + createBlobs(--currentBlobsCount, callback); + } else { + console.log(' Created ' + totalBlobsCount + ' blobs.'); + callback(); + } + }); +} + +function listBlobs (options, token, callback) { + blobService.listBlobsSegmented(container, token, options, function(error, result) { + blobs.push.apply(blobs, result.entries); + var token = result.continuationToken; + if(token) { + console.log(' Received a page of results. There are ' + result.entries.length + ' blobs on this page.'); + listBlobs(options, token, callback); + } + else { + console.log(' Completed listing. There are ' + blobs.length + ' blobs'); + callback(); + } + }); +} + +function deleteContainer (container, callback) { + // Delete the container. + blobService.deleteContainerIfExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + callback(); + } + }); +} + +continuationSample(); diff --git a/node_modules/azure-storage/examples/samples/requestresponseeventssample.js b/node_modules/azure-storage/examples/samples/requestresponseeventssample.js new file mode 100644 index 000000000..2f73bd1e2 --- /dev/null +++ b/node_modules/azure-storage/examples/samples/requestresponseeventssample.js @@ -0,0 +1,96 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* Demonstrates how to define sendingrequest and receivedresponse event handlers. +*/ +var fs = require('fs'); + +var azure; +if (fs.existsSync('absolute path to azure-storage.js')) { + azure = require('absolute path to azure-storage'); +} else { + azure = require('azure-storage'); +} + +var container = 'sendingrequestevent3'; + +// The service object which will define the event handlers +var blobService = azure.createBlobService(); + +// optionally set a proxy +/*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 +}; + +blobService.setProxy(proxy); +blobService2.setProxy(proxy); +*/ + +// the sending request event handler +var sendingRequestHandler = function (webresource) { + webresource.withHeader('x-ms-custom-header', 'value'); + console.log(' sending request event handler called'); +}; + +// the response received event handler +var responseReceivedHandler = function (response) { + console.log(' received response event handler called'); +}; + +function eventHandlersSample () { + console.log('Starting eventHandlersSample.'); + + // set the event handlers + blobService.on('sendingRequestEvent', sendingRequestHandler); + blobService.on('receivedResponseEvent', responseReceivedHandler); + + // create and delete a container with these handlers + createContainer(container, function () { + // Delete the container + deleteContainer(container, function () { + console.log('Ending eventHandlersSample.'); + }); + }); +} + +function createContainer (container, callback) { + // Create the container. + blobService.createContainer(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + callback(); + } + }); +} + +function deleteContainer (container, callback) { + // Delete the container. + blobService.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + callback(); + } + }); +} + +eventHandlersSample(); diff --git a/node_modules/azure-storage/examples/samples/retrypolicysample.js b/node_modules/azure-storage/examples/samples/retrypolicysample.js new file mode 100644 index 000000000..b5321f0df --- /dev/null +++ b/node_modules/azure-storage/examples/samples/retrypolicysample.js @@ -0,0 +1,230 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* Demonstrates how to use pre-written retry policies and how to define a customized retry policy. +* +* In the sample for pre-written retry policies, we simply show how to use pre-written retry policies. +* +* In the sample for customized retry policy, we define a customized retry policy, +* which retries on the "The specified container is being deleted" exception besides the server exceptions. +* +* Note that only in the cloud(not the storage emulator), "The specified container is being deleted" exceptions will be +* sent if users immediately recreate a container after delete it. +*/ + +var fs = require('fs'); +if (!fs.existsSync) { + fs.existsSync = require('path').existsSync; +} + +var azure; +if (fs.existsSync('absolute path to azure-storage.js')) { + azure = require('absolute path to azure-storage'); +} else { + azure = require('azure-storage'); +} + +var RetryPolicyFilter = azure.RetryPolicyFilter; +var LocationMode = azure.StorageUtilities.LocationMode; + +var container = 'customretrypolicysample'; + +var blobService; + +/** + * Demonstrate how to use pre-written retry policies. + * By default, no retry will be performed with service instances newly created. + * Several pre-written retry policies are available with modifiable settings, + * and can be used through associating filter. + */ +function setRetries() { + console.log('Starting Sample 1 - setRetries.'); + + // By default, no retry will be performed with all kinds of services created + // by Azure storage client library for Node.js. + var blobServiceWithoutRetry = azure.createBlobService(); + console.log('BlobService instance created, no retry will be performed by default.'); + + // There are two pre-written retry policies: ExponentialRetryPolicyFilter + // and LinearRetryPolicyFilter can be used with modifiable settings. + // Use an exponential retry with customized settings. + var fileServiceWithExponentialRetry = azure.createFileService().withFilter( + new azure.ExponentialRetryPolicyFilter( + 3, // retryCount is set to 3 times. + 4000, // retryInterval is set to 4 seconds. + 3000, // minRetryInterval is set to 3 seconds. + 120000 // maxRetryInterval is set to 120 seconds. + )); + console.log('FileService instance created and associated with ExponentialRetryPolicyFilter.'); + console.log(' Retries will be performed with exponential back-off.'); + + // Use a default linear retry policy. + var tableServiceWithLinearRetry = azure.createTableService().withFilter( + new azure.LinearRetryPolicyFilter()); // By default, retryCount is set to 3 times and retryInterval is set to 30 seconds. + console.log('TableService instance created and associated with LinearRetryPolicyFilter,'); + console.log(' Retries will be performed with linear back-off.'); + + console.log('Ending Sample 1 - setRetries.'); +} + +/** + * Demonstrate how to use custom retry policy. + * Any custom retry logic may be used by simply creating and setting RetryPolicyFilter instance. + */ +function setCustomRetryPolicy() { + console.log('Starting Sample 2 - setCustomRetryPolicy.'); + + // Step 1 : Set the retry policy to customized retry policy which will + // not retry on any failing status code other than the excepted one. + var retryOnContainerBeingDeleted = new RetryPolicyFilter(); + retryOnContainerBeingDeleted.retryCount = 5; + retryOnContainerBeingDeleted.retryInterval = 5000; + + retryOnContainerBeingDeleted.shouldRetry = function (statusCode, retryData) { + console.log(' Made the request at ' + new Date().toUTCString() + ', received StatusCode: ' + statusCode); + + var retryInfo = {}; + + // retries on any bad status code other than 409 + if (statusCode >= 300 && statusCode !== 409 && statusCode !== 500) { + retryInfo.retryable = false; + } else { + var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0; + + retryInfo = { + retryInterval: this.retryInterval + 2000 * currentCount, + retryable: currentCount < this.retryCount + }; + } + + return retryInfo; + }; + + blobService = azure.createBlobService().withFilter(retryOnContainerBeingDeleted); + + // optionally set a proxy + /*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 + }; + + blobService.setProxy(proxy);*/ + + + // Step 2: Create the container + createContainer(function () { + + // Step 3: Fetch attributes from the container using LocationMode.SECONDARY_THEN_PRIMARY + fetchAttributesContainer(function () { + + // Step 4: Lease the container + leaseContainer(function () { + + // Step 5: Lease the container again, retrying until it succeeds + leaseContainer(function () { + + // Step 6: Delete the container + deleteContainer(function () { + console.log('Ending Sample 2 - setCustomRetryPolicy.'); + }); + }); + }); + }); + }); +} + +function createContainer(callback) { + console.log('Entering createContainer.'); + + // Create the container. + blobService.createContainerIfNotExists(container, function (error, containerResult) { + if (error) { + console.log(error); + } else { + console.log(' Container info '); + console.log(containerResult); + console.log('Created the container ' + container); + callback(); + } + }); +} + +function fetchAttributesContainer(callback) { + console.log('Entering fetchAttributesContainer.'); + + var options = { + locationMode: LocationMode.SECONDARY_THEN_PRIMARY + }; + + // Get the properties of the container. + blobService.getContainerProperties(container, options, function (error) { + if (error) { + console.log(error); + } else { + console.log('Downloaded container properties from ' + container); + callback(); + } + }); +} + +function leaseContainer(callback) { + console.log('Entering leaseContainer.'); + + // Try to acquire the lease. + blobService.acquireLease(container, null, {leaseDuration: 15}, function (error, lease) { + if (error) { + console.log(error); + } + else { + console.log('Acquired lease from ' + container + ' with leaseid' + lease.id); + callback(); + } + }); +} + +function deleteContainer(callback) { + console.log('Entering deleteContainer.'); + + // Break the lease. + blobService.breakLease(container, null, {leaseBreakPeriod: 0}, function (error) { + if (error) { + console.log(error); + } else { + console.log(' Broke the lease on the container ' + container); + } + + // Delete the container. + blobService.deleteContainer(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + callback(); + } + }); + }); +} + +function runAllSamples() { + console.log("Starting retrypolicySample."); + setRetries(); + setCustomRetryPolicy(); + console.log("Ending retrypolicySample."); +} + +runAllSamples(); diff --git a/node_modules/azure-storage/examples/samples/sassample.js b/node_modules/azure-storage/examples/samples/sassample.js new file mode 100644 index 000000000..7924d7b07 --- /dev/null +++ b/node_modules/azure-storage/examples/samples/sassample.js @@ -0,0 +1,218 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* In this sample, we demonstrate how to generate and use the blob level shared access signature and the container level +* shared access signature. +* +* In the blob level shared access signature sample, there are the following steps: +* +* 1. Create a container and a blob. +* +* 2. Generate a shared access signature for the blob and download the blob using it. +* +* 3. Upload a "ReadWrite" policy and a "Read" permission to the container. +* +* 4. Generate a shared access signature for the blob using the policy id and download the blob using it. +*/ + +var fs = require('fs'); +var assert = require('assert'); + +var azure; +if (fs.existsSync('../../lib/azure-storage.js')) { + azure = require('../../lib/azure-storage'); +} else { + azure = require('azure-storage'); +} +var BlobUtilities = azure.BlobUtilities; + +var container = 'container-sassample'; +var blob = 'blob-sassample'; + +var blobService = azure.createBlobService(); + +// optionally set a proxy +/*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 +}; + +blobService.setProxy(proxy); +blobService2.setProxy(proxy); +*/ + +function sasSample () { + console.log('Starting sasSample.'); + + // Create the container. + createContainer(function () { + + // Create a blob. + createBlob( function () { + + // Create a shared access signature and use it to download the blob just created. + downloadBlobUsingSharedAccessSignature(function () { + + // Add Shared Access policies to the container + createPolicies(function () { + + // Use the read policy just created + usePermissions(function () { + + // Delete the container + deleteContainer(function () { + console.log('Ending sasSample.'); + }); + }); + }); + }); + }); + }); +} + +function createContainer (callback) { + // Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + callback(); + } + }); +} + +function createBlob (callback) { + // Create the blob + blobService.createBlockBlobFromText(container, blob, 'test blob', function (error) { + if (error) { + console.log(error); + } + else { + console.log('Created the blob ' + container); + callback(); + } + }); +} + +function downloadBlobUsingSharedAccessSignature (callback) { + var startDate = new Date(); + var expiryDate = new Date(startDate); + expiryDate.setMinutes(startDate.getMinutes() + 5); + + var sharedAccessPolicy = { + AccessPolicy: { + Permissions: BlobUtilities.SharedAccessPermissions.READ, + Start: startDate, + Expiry: expiryDate + } + }; + + var sharedAccessSignatureToken = blobService.generateSharedAccessSignature(container, blob, sharedAccessPolicy); + + var sharedBlobService = azure.createBlobServiceWithSas(blobService.host, sharedAccessSignatureToken); + + // Download the blob by using the shared access signature URL. + sharedBlobService.getBlobProperties(container, blob, function (error) { + if (error) { + console.log(error); + } else { + console.log('Downloaded the blob ' + blob + ' by using the shared access signature URL: \n ' + sharedBlobService.getUrl(container, blob, sharedAccessSignatureToken)); + } + + callback(); + }); +} + +function createPolicies (callback) { + // Create a "ReadWrite" policy and a "Read" policy. + var readWriteStartDate = new Date(); + var readWriteExpiryDate = new Date(readWriteStartDate); + readWriteExpiryDate.setMinutes(readWriteStartDate.getMinutes() + 10); + + var signedIdentifiers = { + readwrite: { + Start: readWriteStartDate, + Expiry: readWriteExpiryDate, + Permissions: 'rw' + }, + read: { + Expiry: readWriteStartDate, + Permissions: 'r' + } + }; + + // Wait 30 seconds for the container acl to be processed + var func = function () { + var options = { publicAccessLevel: BlobUtilities.BlobContainerPublicAccessType.CONTAINER }; + blobService.setContainerAcl(container, signedIdentifiers, options, function(error) { + if (error) { + console.log(error); + } else { + console.log('Uploaded the permissions for the container ' + container); + callback(); + } + }); + }; + + setTimeout(func, 30000); +} + +function usePermissions (callback) { + // Read, write the blob using the shared access signature from "ReadWrite" policy. + var readWriteAccessPolicy = { + Id: 'readwrite' + }; + + var headers = { + cacheControl: 'no-transform', + contentDisposition: 'attachment', + contentEncoding: 'gzip', + contentLanguage: 'tr,en', + contentType: 'text/html' + }; + + var sharedAccessSignatureToken = blobService.generateSharedAccessSignature(container, null, {Id: 'readwrite'}, headers); + + var sharedBlobService = azure.createBlobServiceWithSas(blobService.host, sharedAccessSignatureToken); + + sharedBlobService.getBlobProperties(container, blob, function (error, result) { + if (error) { + console.log(error); + } else { + console.log('Downloaded the blob ' + blob + ' by using the shared access signature URL: \n ' + sharedBlobService.getUrl(container, blob, sharedAccessSignatureToken)); + + } + + callback(); + }); +} + +function deleteContainer (callback) { + // Delete the container. + blobService.deleteContainerIfExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + callback(); + } + }); +} + +sasSample(); diff --git a/node_modules/azure-storage/examples/samples/snapshotsample.js b/node_modules/azure-storage/examples/samples/snapshotsample.js new file mode 100644 index 000000000..766a8727e --- /dev/null +++ b/node_modules/azure-storage/examples/samples/snapshotsample.js @@ -0,0 +1,219 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* This sample is used to provide an overview of blob snapshots and how to work with them. +* +* 1. Upload blocks and commit them. +* +* 2. Take a snapshot for that blob. +* +* 3. Re-upload one of the three blocks and commit them. +* +* 4. Get the snapshot. +* +* 5. List blobs including snapshots. +* +* 6. Delete the snapshot. +*/ + +var fs = require('fs'); + +var azure; +if (fs.existsSync('absolute path to azure-storage.js')) { + azure = require('absolute path to azure-storage'); +} else { + azure = require('azure-storage'); +} + +var BlobUtilities = azure.BlobUtilities; + +var container = 'snapshotsample'; +var blob = 'snapshotsample'; + +var blockList = ['b1', 'b2', 'b3']; +var blockContent = ['content1', 'content2', 'content3']; +var blockContentAlternative2 = 'alternative2'; + +var blobService = azure.createBlobService(); + +// optionally set a proxy +/*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 +}; + +blobService.setProxy(proxy);*/ + +function snapshotSample () { + var processArguments = process.argv; + if (processArguments.length !== 2) { + console.log('Incorrect number of arguments. No arguments should be given.'); + process.exit(1); + } + + console.log('Starting snapshotSample.'); + + // Create the container + createContainer(function () { + + // Upload a blob + uploadBlockBlob(function () { + + // Create a snapshot of the blob + createSnapshot(function (snapshot) { + + // Update the blob + blockContent[1] = blockContentAlternative2; + uploadBlockBlob(function () { + + // Create a snapshot of the modified blob + getSnapshotToText(snapshot, function () { + + // List the blob and its snapshots + listSnapshots(function () { + + // Delete the snapshots + deleteSnapshots(function () { + + // Delete the container + deleteContainer(function () { + console.log('Ending snapshotSample.'); + }); + }); + }); + }); + }); + }); + }); + }); +} + +function createContainer (callback) { + // Create the container. + blobService.createContainerIfNotExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Created the container ' + container); + callback(); + } + }); +} + +function uploadBlockBlob(callback) { + // Upload 3 blocks and commit them. + var blocks = 0; + var blobCallbackCounter = function (block) { + ++blocks; + if (blocks === blockList.length) { + console.log(' Created ' + blocks + ' blocks.'); + + blobService.commitBlocks(container, blob, {LatestBlocks: blockList}, function (error4) { + if (error4) { + console.log(error4); + } + else { + console.log('Committed the blob ' + blob); + callback(); + } + }); + } + } + + for(var i = 0; i < blockList.length; i++) { + console.log(' Uploading a block. ID: ' + blockList[i] + ' Content: ' + blockContent[i]); + blobService.createBlockFromText(blockList[i], container, blob, blockContent[i], blockContent[i].length, function (error) { + if (error) { + console.log(error); + } else { + blobCallbackCounter(); + } + }); + } +} + +function createSnapshot(callback) { + // Creates a snapshot. + blobService.createBlobSnapshot(container, blob, function (error, snapshot) { + if (error) { + console.log(error); + } else { + console.log('Created a snapshot for the blob ' + blob); + callback(snapshot); + } + }); +} + +function getSnapshotToText(snapshot, callback) { + // Gets a snapshot. + blobService.getBlobToText(container, blob, {snapshotId: snapshot}, function (error, text) { + if (error) { + console.log(error); + } else { + console.log('Snapshot ' + blob + '?' + snapshot + ' text: ' + text); + callback(); + } + }); +} + +function listSnapshots (callback) { + // List the blobs, including snapshots + blobService.listBlobsSegmented(container, null, { include: BlobUtilities.BlobListingDetails.SNAPSHOTS }, function (error, results) { + if (error) { + console.log(error); + } else { + console.log('Listing the blobs under the container ' + container); + + results.entries.forEach(function (blob) { + var snapshot = ''; + if (blob.snapshot) { + snapshot = '; BlobSnapshot: ' + blob.snapshot; + } + console.log(' BlobName: ' + blob.name + snapshot); + }); + + callback(); + } + }); +}; + +function deleteSnapshots (callback) { + // Delete the snapshot. + blobService.deleteBlob(container, blob, { deleteSnapshots: BlobUtilities.SnapshotDeleteOptions.SNAPSHOTS_ONLY }, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the snapshots.'); + callback(); + } + }); +}; + +function deleteContainer (callback) { + // Delete the container. + blobService.deleteContainerIfExists(container, function (error) { + if (error) { + console.log(error); + } else { + console.log('Deleted the container ' + container); + callback(); + } + }); +} + +snapshotSample(); diff --git a/node_modules/azure-storage/examples/samples/tablequerysample.js b/node_modules/azure-storage/examples/samples/tablequerysample.js new file mode 100644 index 000000000..d91e4fffc --- /dev/null +++ b/node_modules/azure-storage/examples/samples/tablequerysample.js @@ -0,0 +1,165 @@ +var fs = require('fs'); +var assert = require('assert'); +var util = require('util'); +var http = require('http'); + +var azure; +if (fs.existsSync('absolute path to azure-storage.js')) { + azure = require('absolute path to azure-storage'); +} else { + azure = require('azure-storage'); +} + +var TableQuery = azure.TableQuery; +var TableUtilities = azure.TableUtilities; +var eg = TableUtilities.entityGenerator; + +var tableName = 'tablequerysample'; +var tableService = azure.createTableService(); + +// optionally set a proxy +/*var proxy = { + protocol: 'http:', + host: '127.0.0.1', + port: 8888 +}; + +tableService.setProxy(proxy);*/ + +var entity1 = { + PartitionKey: eg.String('partition1'), + RowKey: eg.String('row1'), + integerfield: eg.Int32(1), + stringfield: eg.String('stringfield value'), + longfield: eg.Int64('92233720368547758') +}; + +var entity2 = { + PartitionKey: eg.String('partition1'), + RowKey: eg.String('row2'), + stringfield: eg.String('stringfield value'), + longfield: eg.Int64('8547758') +}; + +function performTableQuery() { + // Create the table + tableService.createTable(tableName, function (error1) { + assert.equal(error1, null); + + // Insert the entities + insertEntities(function() { + + // Return all entities + queryAllEntities(function () { + + // Return entities Where certain conditions are met + queryEntitiesWhere(function () { + + // Return the Top n entities + queryEntitiesTop(function () { + + // Return Select fields from entities + queryEntitiesSelect(function () { + + // Delete the table + tableService.deleteTable(tableName, function (error2) { + assert.equal(error2, null); + }); + }); + }); + }); + }); + }); + }); +} + +function insertEntities(callback) { + // insert the entities + tableService.insertEntity(tableName, entity1, function (error1) { + assert.equal(error1, null); + tableService.insertEntity(tableName, entity2, function (error2) { + assert.equal(error2, null); + callback(); + }); + }); +} + +function queryAllEntities(callback) { + // Select all fields + tableService.queryEntities(tableName, null, null, function (error, result) { + assert.equal(error, null); + assert.notEqual(result, null); + assert.notEqual(result.entries, null); + + var entities = result.entries; + assert.equal(entities.length, 2); + var entityResult = entities[0]; + assert.equal(entityResult.stringfield._, entity1.stringfield._); + assert.equal(entityResult.longfield._, entity1.longfield._); + + callback(); + }); +} + +function queryEntitiesWhere(callback) { + // Select only the entries where the longfield is great than 10,000,000 + + // equivalently: var tableQuery = new TableQuery().where('longfield == ?int64?', '10000000'); + var tableQuery = new TableQuery().where(TableQuery.int64Filter('longfield', TableUtilities.QueryComparisons.GREATER_THAN, '10000000')); + + tableService.queryEntities(tableName, tableQuery, null, function (error, result) { + assert.equal(error, null); + assert.notEqual(result, null); + assert.notEqual(result.entries, null); + + var entities = result.entries; + assert.equal(entities.length, 1); + + var entityResult = entities[0]; + assert.equal(entityResult.longfield._, entity1.longfield._); + + callback(); + }); +} + +function queryEntitiesTop(callback) { + // Select only the top entry + var tableQuery = new TableQuery().top(1); + + tableService.queryEntities(tableName, tableQuery, null, function (error, result) { + assert.equal(error, null); + assert.notEqual(result, null); + assert.notEqual(result.entries, null); + + var entities = result.entries; + assert.equal(entities.length, 1); + + var entityResult = entities[0]; + assert.equal(entityResult.integerfield._, entity1.integerfield._); + assert.equal(entityResult.longfield._, entity1.longfield._); + + callback(); + }); +} + +function queryEntitiesSelect(callback) { + // Select specific field + var tableQuery = new TableQuery().select('integerfield'); + + tableService.queryEntities(tableName, tableQuery, null, function (error, result) { + assert.equal(error, null); + assert.notEqual(result, null); + assert.notEqual(result.entries, null); + + var entities = result.entries; + assert.equal(entities.length, 2); + + var entityResult = entities[0]; + assert.equal(entityResult.integerfield._, entity1.integerfield._); + assert.equal(entityResult.longfield, undefined); + + callback(); + }); +} + +performTableQuery(); \ No newline at end of file diff --git a/node_modules/azure-storage/gruntfile.js b/node_modules/azure-storage/gruntfile.js new file mode 100644 index 000000000..e11772016 --- /dev/null +++ b/node_modules/azure-storage/gruntfile.js @@ -0,0 +1,106 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +module.exports = function(grunt) { + //init stuff + grunt.initConfig({ + + nsp: { + package: grunt.file.readJSON('package.json') + }, + + mochaTest: { + test: { + options: { + reporter: 'spec', + quiet: false, + clearRequireCache: false, + timeout: 100000 + }, + src: ['test/**/*.js'] + } + }, + + //jsdoc config + jsdoc: { + dist: { + src: [ + 'README.md', + 'lib/azure-storage.js', + 'lib/common/filters/retrypolicyfilter.js', + 'lib/common/filters/linearretrypolicyfilter.js', + 'lib/common/filters/exponentialretrypolicyfilter.js', + 'lib/common/services/storageutilities.js', + 'lib/services/blob/blobservice.core.js', + 'lib/services/blob/blobservice.node.js', + 'lib/services/blob/blobservice.browser.js', + 'lib/services/blob/models/blobresult.js', + 'lib/services/blob/models/containerresult.js', + 'lib/services/blob/models/leaseresult.js', + 'lib/services/blob/blobutilities.js', + 'lib/services/queue/queueservice.js', + 'lib/services/queue/queuemessageencoder.js', + 'lib/services/queue/queueutilities.js', + 'lib/services/queue/models/queueresult.js', + 'lib/services/queue/models/queuemessageresult.js', + 'lib/services/table/tableservice.js', + 'lib/services/table/tablebatch.js', + 'lib/services/table/tablequery.js', + 'lib/services/table/tableutilities.js', + 'lib/services/file/fileservice.core.js', + 'lib/services/file/fileservice.node.js', + 'lib/services/file/fileservice.browser.js', + 'lib/services/file/fileutilities.js', + 'lib/services/file/models/shareresult.js', + 'lib/services/file/models/directoryresult.js', + 'lib/services/file/models/fileresult.js', + 'lib/common/services/storageserviceclient.js', + 'lib/common/diagnostics/logger.js' + ], + options: { + destination: 'docs', + template: 'node_modules/ink-docstrap/template', + configure: 'jsdoc/jsdoc.json' + } + } + }, + + // devserver config + devserver: { + server : {}, + options: { + 'base': 'docs' + } + }, + + jshint: { + all: ['Gruntfile.js', 'lib/**/*.js'], + options: { + jshintrc: true + } + } + }); + + grunt.loadNpmTasks('grunt-jsdoc'); + grunt.loadNpmTasks('grunt-mocha-test'); + grunt.loadNpmTasks('grunt-devserver'); + grunt.loadNpmTasks('grunt-nsp'); + grunt.loadNpmTasks('grunt-contrib-jshint'); + + grunt.registerTask('doc', ['jsdoc', 'devserver']); + grunt.registerTask('validate', ['jshint', 'nsp']); + grunt.registerTask('default', ['validate', 'mochaTest']); +}; \ No newline at end of file diff --git a/node_modules/azure-storage/jsdoc/jsdoc.json b/node_modules/azure-storage/jsdoc/jsdoc.json new file mode 100644 index 000000000..cf86e1209 --- /dev/null +++ b/node_modules/azure-storage/jsdoc/jsdoc.json @@ -0,0 +1,27 @@ +{ + "tags" : { + "allowUnknownTags" : true + }, + "plugins" : ["plugins/markdown"], + + "templates" : { + "cleverLinks" : false, + "monospaceLinks" : false, + "dateFormat" : "ddd MMM Do YYYY", + "outputSourceFiles" : true, + "outputSourcePath" : true, + "systemName" : "Microsoft Azure Storage Client Library for node.js", + "footer" : "", + "navType" : "vertical", + "theme" : "cosmo", + "linenums" : true, + "collapseSymbols" : false, + "inverseNav" : true, + "highlightTutorialCode" : false, + "protocol": "fred://" + }, + "markdown" : { + "parser" : "gfm", + "hardwrap" : true + } +} \ No newline at end of file diff --git a/node_modules/azure-storage/lib/azure-storage.js b/node_modules/azure-storage/lib/azure-storage.js new file mode 100644 index 000000000..813e3c414 --- /dev/null +++ b/node_modules/azure-storage/lib/azure-storage.js @@ -0,0 +1,369 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var exports = module.exports; + +/** +* Creates a connection string that can be used to create a service which runs on the storage emulator. The emulator must be downloaded separately. +* +* @param {string} [proxyUri] The proxyUri. By default, http://127.0.0.1 +* @return {string} A connection string representing the development storage credentials. +* @example +* var azure = require('azure-storage'); +* var devStoreCreds = azure.generateDevelopmentStorageCredentials(); +* var blobService = azure.createBlobService(devStoreCreds); +*/ +exports.generateDevelopmentStorageCredentials = function (proxyUri) { + var devStore = 'UseDevelopmentStorage=true;'; + if(proxyUri){ + devStore += 'DevelopmentStorageProxyUri=' + proxyUri; + } + + return devStore; +}; + +/** + * Table client exports. + * @ignore + */ +var TableService = require('./services/table/tableservice'); + +exports.TableService = TableService; +exports.TableQuery = require('./services/table/tablequery'); +exports.TableBatch = require('./services/table/tablebatch'); +exports.TableUtilities = require('./services/table/tableutilities'); + +/** +* Creates a new {@link TableService} object. +* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY +* environment variables will be used. +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @return {TableService} A new TableService object. +* +*/ +exports.createTableService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new TableService(storageAccountOrConnectionString, storageAccessKey, host); +}; + +/** +* Creates a new {@link TableService} object using the host Uri and the SAS credentials provided. +* +* @param {string|object} host The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} sasToken The Shared Access Signature token. +* @return {TableService} A new TableService object with the SAS credentials. +*/ +exports.createTableServiceWithSas = function (hostUri, sasToken) { + return new TableService(null, null, hostUri, sasToken); +}; + +/** + * Blob client exports. + * @ignore + */ +var BlobService = require('./services/blob/blobservice.node'); + +exports.BlobService = BlobService; +exports.BlobUtilities = require('./services/blob/blobutilities'); + +/** +* Creates a new {@link BlobService} object. +* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY +* environment variables will be used. +* +* @param {string} storageAccountOrConnectionString The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @return {BlobService} A new BlobService object. +*/ +exports.createBlobService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new BlobService(storageAccountOrConnectionString, storageAccessKey, host, null); +}; + +/** +* Creates a new {@link BlobService} object using the host Uri and the SAS credentials provided. +* +* @param {string|object} host The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} sasToken The Shared Access Signature token. +* @return {BlobService} A new BlobService object with the SAS credentials. +*/ +exports.createBlobServiceWithSas = function (host, sasToken) { + return new BlobService(null, null, host, sasToken); +}; + +/** +* Creates a new {@link BlobService} object using the host uri and anonymous access. +* +* @param {string|object} host The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @return {BlobService} A new BlobService object with the anonymous credentials. +*/ +exports.createBlobServiceAnonymous = function (host) { + return new BlobService(null, null, host, null); +}; + +/** + * File client exports. + * @ignore + */ +var FileService = require('./services/file/fileservice.node'); + +exports.FileService = FileService; +exports.FileUtilities = require('./services/file/fileutilities'); + +/** +* Creates a new {@link FileService} object. +* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY +* environment variables will be used. +* +* @param {string} storageAccountOrConnectionString The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @return {FileService} A new FileService object. +*/ +exports.createFileService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new FileService(storageAccountOrConnectionString, storageAccessKey, host); +}; + +/** +* Creates a new {@link FileService} object using the host Uri and the SAS credentials provided. +* +* @param {string|object} host The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} sasToken The Shared Access Signature token. +* @return {FileService} A new FileService object with the SAS credentials. +*/ +exports.createFileServiceWithSas = function (hostUri, sasToken) { + return new FileService(null, null, hostUri, sasToken); +}; + +/** + * Queue client exports. + * @ignore + */ +var QueueService = require('./services/queue/queueservice'); + +exports.QueueService = QueueService; +exports.QueueUtilities = require('./services/queue/queueutilities'); +exports.QueueMessageEncoder = require('./services/queue/queuemessageencoder'); + +/** +* Creates a new {@link QueueService} object. +* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY +* environment variables will be used. +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @return {QueueService} A new QueueService object. +*/ +exports.createQueueService = function (storageAccountOrConnectionString, storageAccessKey, host) { + return new QueueService(storageAccountOrConnectionString, storageAccessKey, host); +}; + +/** +* Creates a new {@link QueueService} object using the host Uri and the SAS credentials provided. +* +* @param {string|object} host The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} sasToken The Shared Access Signature token. +* @return {QueueService} A new QueueService object with the SAS credentials. +*/ +exports.createQueueServiceWithSas = function(hostUri, sasToken) { + return new QueueService(null, null, hostUri, sasToken); +}; + +/** +* Account SAS +* @ignore +*/ + +var azureCommon = require('./common/common.node'); +var StorageServiceClient = azureCommon.StorageServiceClient; +var SharedKey = azureCommon.SharedKey; +/** +* Generates an account shared access signature token +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {SharedAccessServices} sharedAccessPolicy.AccessPolicy.Services The services (blob, file, queue, table) for a shared access signature associated with this shared access policy. +* Refer to `Constants.AccountSasConstants.Services`. +* @param {SharedAccessResourceTypes} sharedAccessPolicy.AccessPolicy.ResourceTypes The resource type for a shared access signature associated with this shared access policy. +* Refer to `Constants.AccountSasConstants.ResourceTypes`. +* @param {SharedAccessPermissions} sharedAccessPolicy.AccessPolicy.Permissions The permissions for a shared access signature. +* Refer to `Constants.AccountSasConstants.Permissions`. +* @param {date} sharedAccessPolicy.AccessPolicy.Start The time at which the Shared Access Signature becomes valid. +* @param {date} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired. +* @param {string} sharedAccessPolicy.AccessPolicy.IPAddressOrRange The permission type. Refer to `Constants.AccountSasConstants.ResourceTypes`. +* @param {string} sharedAccessPolicy.AccessPolicy.Protocols The possible protocols. Refer to `Constants.AccountSasConstants.ResourceTypes`. +*/ +exports.generateAccountSharedAccessSignature = function(storageAccountOrConnectionString, storageAccessKey, sharedAccessAccountPolicy) +{ + var storageSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey); + var sharedKey = new SharedKey(storageSettings._name, storageSettings._key); + + return sharedKey.generateAccountSignedQueryString(sharedAccessAccountPolicy); +}; + + +/** +* A callback that returns a response object. +* @callback errorOrResponse +* @param {object} error If an error occurs, will contain information about the error. +* @param {object} response Contains information about the response returned for the operation. +* For example, HTTP status codes and headers. +*/ + +/** +* A callback that returns result and response objects. +* @callback errorOrResult +* @param {object} error If an error occurs, will contain information about the error. +* @param {object} result The result of the operation. +* @param {object} response Contains information about the response returned for the operation. +* For example, HTTP status codes and headers. +*/ + + +/** +* Specifying conditional headers for blob service operations. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information. +* @typedef {object} AccessConditions +* @property {string} EtagMatch If the ETag for the blob matches the specified ETag. +* Specify the wildcard character (*) to perform the operation only if the resource does exist, and fail the operation if it does not exist. +* @property {string} EtagNonMatch If the ETag for the blob does not match the specified ETag. +* Specify the wildcard character (*) to perform the operation only if the resource does not exist, and fail the operation if it does exist. +* @property {Date|string} DateModifedSince If the blob has been modified since the specified date. +* @property {Date|string} DateUnModifiedSince If the blob has not been modified since the specified date. +* @property {Number|string} SequenceNumberLessThanOrEqual If the blob's sequence number is less than or equal to the specified value. +* For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information. +* @property {Number|string} SequenceNumberLessThan If the blob's sequence number is less than the specified value. +* For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information. +* @property {Number|string} SequenceNumberEqual If the blob's sequence number is equal to the specified value. +* For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information. +* @property {Number|string} MaxBlobSize If the Append Block operation would cause the blob to exceed that limit or if the blob size is already greater than the specified value. +* For Append Block operation only. See https://msdn.microsoft.com/en-us/library/mt427365.aspx for more information. +* @property {Number|string} MaxAppendPosition If the append position is equal to the specified value. +* For Append Block operation only. See https://msdn.microsoft.com/en-us/library/mt427365.aspx for more information. +*/ + +/** +* The properties of a storage service, including properties of Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. +* @typedef {object} ServiceProperties +* @property {string} DefaultServiceVersion The default version of Storage Analytics currently in use. +* @property {LoggingProperties} Logging The Logging settings. +* @property {MetricsProperties} HourMetrics The HourMetrics settings provide a summary of request statistics grouped by API in hourly aggregates. +* @property {MetricsProperties} MinuteMetrics The HourMetrics settings provide request statistics grouped by API for each minute. +* @property {object} Cors Groups all CORS rules. +* @property {CorsRule[]} Cors.CorsRules Groups settings for a `[CORS rule]{@link CorsRule}`. +*/ + +/** +* The Azure Analytics logging settings. +* @typedef {object} LoggingProperties +* @property {string} Version The version of Storage Analytics currently in use for logging. +* @property {boolean} Delete Indicates whether delete requests are being logged. +* @property {boolean} Read Indicates whether read requests are being logged. +* @property {boolean} Write Indicates whether write requests are being logged. +* @property {RetentionPolicy} RetentionPolicy The retention policy of the log data. +*/ + +/** +* The setting of Azure Analytics summary of request stastics. +* @typedef {object} MetricsProperties +* @property {string} Version The version of Storage Analytics currently in use for hour metrics. +* @property {string} Enabled Indicates whether metrics are enabled +* @property {boolean} IncludeAPIs Indicates whether metrics generate summary statistics for called API operations. +* @property {RetentionPolicy} RetentionPolicy The retention policy of the metrics data. +*/ + +/** +* The CORS rule of a storage service. +* @typedef {object} CorsRule +* @property {string[]} AllowedMethods A list of HTTP methods that are allowed to be executed by the origin. For Azure Storage, permitted methods are DELETE, GET, HEAD, MERGE, POST, OPTIONS or PUT. +* @property {string[]} AllowedOrigins A list of origin domains that are allowed via CORS, or "*" if all domains are allowed. +* @property {string[]} AllowedHeaders A list of headers allowed to be part of the cross-origin request. +* @property {string[]} ExposedHeaders A list of response headers to expose to CORS clients. +* @property {number} MaxAgeInSeconds The number of seconds that the client/browser should cache a preflight response. +*/ + +/** +* The Azure Analytics logging or metrics retention policy. +* @typedef {object} RetentionPolicy +* @property {boolean} Enabled Indicates whether a retention policy is enabled for the storage service. +* @property {number} Days Indicates the number of days that logging data is retained. All data older than this value will be deleted. +*/ + +/** +* The access policy. +* @typedef {object} AccessPolicy +* @property {string} Permissions The permission type. +* @property {Date} Start The time at which the access policy becomes valid. +* @property {Date} Expiry The time at which the access policy becomes expired. +* @property {string} IPAddressOrRange An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @property {string} Protocols The protocols permitted for a request made with the SAS. +* @property {string} Services The services (blob, file, queue, table) for a shared access signature associated with this shared access policy. +* @property {string} ResourceTypes The resource type for a shared access signature associated with this shared access policy. +*/ + +/** +* The service statistics. +* @typedef {object} ServiceStats +* @property {object} GeoReplication The geo replication stastics. +* @property {string} GeoReplication.Status The status of the secondary location. +* @property {Date} GeoReplication.LastSyncTime A GMT date/time value, to the second. +* All primary writes preceding this value are guaranteed to be available for read operations at the secondary. +* Primary writes after this point in time may or may not be available for reads. +*/ + +/** +* The range. +* @typedef {object} Range +* @property {number} start The start of the range. +* @property {number} end The end of the range. +*/ + +/** +* The range diff. Refer to https://msdn.microsoft.com/en-us/library/azure/mt736912.aspx +* @typedef {object} RangeDiff +* @property {number} start The start of the range. +* @property {number} end The end of the range. +* @property {boolean} isCleared If the range is cleared or not. + +*/ + +exports.Constants = azureCommon.Constants; +exports.StorageUtilities = azureCommon.StorageUtilities; +exports.AccessCondition = azureCommon.AccessCondition; + +exports.SR = azureCommon.SR; +exports.StorageServiceClient = StorageServiceClient; +exports.Logger = azureCommon.Logger; +exports.WebResource = azureCommon.WebResource; +exports.Validate = azureCommon.validate; +exports.date = azureCommon.date; + +// Other filters +exports.LinearRetryPolicyFilter = azureCommon.LinearRetryPolicyFilter; +exports.ExponentialRetryPolicyFilter = azureCommon.ExponentialRetryPolicyFilter; +exports.RetryPolicyFilter = azureCommon.RetryPolicyFilter; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/common.browser.js b/node_modules/azure-storage/lib/common/common.browser.js new file mode 100644 index 000000000..320738c6e --- /dev/null +++ b/node_modules/azure-storage/lib/common/common.browser.js @@ -0,0 +1,21 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var azureCommon = require('./common.core'); + +azureCommon.BrowserFileReadStream = require('./streams/browserfilereadstream'); + +module.exports = azureCommon; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/common.core.js b/node_modules/azure-storage/lib/common/common.core.js new file mode 100644 index 000000000..3331d7f2a --- /dev/null +++ b/node_modules/azure-storage/lib/common/common.core.js @@ -0,0 +1,67 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var exports = module.exports; + +var azureutil = require('./util/util'); + +require('./util/patch-xmlbuilder'); + +var nodeVersion = azureutil.getNodeVersion(); +if (nodeVersion.major === 0 && nodeVersion.minor > 8 && !(nodeVersion.minor > 10 || (nodeVersion.minor === 10 && nodeVersion.patch >= 3))) { + throw new Error('The Microsoft Azure node SDK does not work with node versions > 0.9.0 and < 0.10.3. Please upgrade to node >= 0.10.3'); +} + +exports.xmlbuilder = require('xmlbuilder'); +exports.xml2js = require('xml2js'); + +exports.Logger = require('./diagnostics/logger'); +exports.WebResource = require('./http/webresource'); + +// Services +exports.StorageServiceClient = require('./services/storageserviceclient'); + +// Models +exports.ServicePropertiesResult = require('./models/servicepropertiesresult'); +exports.ServiceStatsParser = require('./models/servicestatsparser'); +exports.AclResult = require('./models/aclresult'); + +// Filters +exports.LinearRetryPolicyFilter = require('./filters/linearretrypolicyfilter'); +exports.ExponentialRetryPolicyFilter = require('./filters/exponentialretrypolicyfilter'); +exports.RetryPolicyFilter = require('./filters/retrypolicyfilter'); + +// Signing +exports.SharedAccessSignature = require('./signing/sharedaccesssignature'); +exports.SharedKey = require('./signing/sharedkey'); + +// Streams +exports.BatchOperation = require('./streams/batchoperation'); +exports.ChunkAllocator = require('./streams/chunkallocator'); +exports.ChunkStream = require('./streams/chunkstream'); +exports.ChunkStreamWithStream = require('./streams/chunkstreamwithstream'); +exports.SpeedSummary = require('./streams/speedsummary'); +exports.BufferStream = require('./streams/bufferstream'); + +// Utilities +exports.Constants = require('./util/constants'); +exports.SR = require('./util/sr'); +exports.date = require('./util/date'); +exports.ISO8061Date = require('./util/iso8061date'); +exports.util = require('./util/util'); +exports.validate = require('./util/validate'); +exports.StorageUtilities = require('./util/storageutilities'); +exports.AccessCondition = require('./util/accesscondition'); \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/common.node.js b/node_modules/azure-storage/lib/common/common.node.js new file mode 100644 index 000000000..1b9bfa93b --- /dev/null +++ b/node_modules/azure-storage/lib/common/common.node.js @@ -0,0 +1,22 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var azureCommon = require('./common.core'); + +// Streams +azureCommon.FileReadStream = require('./streams/filereadstream'); + +module.exports = azureCommon; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/diagnostics/logger.js b/node_modules/azure-storage/lib/common/diagnostics/logger.js new file mode 100644 index 000000000..7526e63a7 --- /dev/null +++ b/node_modules/azure-storage/lib/common/diagnostics/logger.js @@ -0,0 +1,148 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* Creates a new Logger object +* @class +* The Logger class is used to write log information. +* +* @constructor +* +* @param {string} [level] The log level. Refer to Logger.LogLevels. +* @param {object} [loggerFunction] The function to write log information. +*/ +function Logger(level, loggerFunction) { + /** + * The log level. Refer to the Logger.LogLevels for available log levels. + * @name Logger#level + * @type {string} + * @see Logger.LogLevels + */ + this.level = level; + + this.loggerFunction = loggerFunction; + + if (!this.loggerFunction) { + this.loggerFunction = this.defaultLoggerFunction; + } +} + +/** +* The available log levels. +* +* @const +* @enum {string} +*/ +Logger.LogLevels = { + /** + * System is unusable. + */ + EMERGENCY: 'emergency', + + /** + * Action must be taken immediately. + */ + ALERT : 'alert', + + /** + * Critical condition. + */ + CRITICAL : 'critical', + + /** + * Error condition. + */ + ERROR : 'error', + + /** + * Warning condition. + */ + WARNING : 'warning', + + /** + * Normal but significant condition. + */ + NOTICE : 'notice', + + /** + * Purely informational message. + */ + INFO : 'info', + + /** + * Application debug messages. + */ + DEBUG : 'debug' +}; + +Logger.logPriority = [ + Logger.LogLevels.EMERGENCY, + Logger.LogLevels.ALERT, + Logger.LogLevels.CRITICAL, + Logger.LogLevels.ERROR, + Logger.LogLevels.WARNING, + Logger.LogLevels.NOTICE, + Logger.LogLevels.INFO, + Logger.LogLevels.DEBUG +]; + +Logger.prototype.log = function (level, msg) { + this.loggerFunction(level, msg); +}; + +Logger.prototype.emergency = function(msg) { + this.log(Logger.LogLevels.EMERGENCY, msg); +}; + +Logger.prototype.critical = function(msg) { + this.log(Logger.LogLevels.CRITICAL, msg); +}; + +Logger.prototype.alert = function(msg) { + this.log(Logger.LogLevels.ALERT, msg); +}; + +Logger.prototype.error = function(msg) { + this.log(Logger.LogLevels.ERROR, msg); +}; + +Logger.prototype.warn = function(msg) { + this.log(Logger.LogLevels.WARNING, msg); +}; + +Logger.prototype.notice = function(msg) { + this.log(Logger.LogLevels.NOTICE, msg); +}; + +Logger.prototype.info = function(msg) { + this.log(Logger.LogLevels.INFO, msg); +}; + +Logger.prototype.debug = function(msg) { + this.log(Logger.LogLevels.DEBUG, msg); +}; + +Logger.prototype.defaultLoggerFunction = function(logLevel , msg) { + var currentLevelIndex = Logger.logPriority.indexOf(this.level); + var logLevelIndex = Logger.logPriority.indexOf(logLevel); + var time = new Date(); + var timeStamp = time.toISOString(); + if (logLevelIndex <= currentLevelIndex) { + console.log('[' + timeStamp + ']' + this.level + ' : ' + msg); + } +}; + +module.exports = Logger; diff --git a/node_modules/azure-storage/lib/common/errors/errors.js b/node_modules/azure-storage/lib/common/errors/errors.js new file mode 100644 index 000000000..c1f2e71af --- /dev/null +++ b/node_modules/azure-storage/lib/common/errors/errors.js @@ -0,0 +1,68 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var util = require('util'); +var _ = require('underscore'); + +function captureStackTrace(targetObject, constructorOpt) { + if (Error.captureStackTrace) { + Error.captureStackTrace(targetObject, constructorOpt); + } +} + +function ArgumentError(argumentName, message) { + captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.argumentName = argumentName; + this.message = message || util.format('Invalid or missing argument supplied: %s', argumentName); +} +util.inherits(ArgumentError, Error); + +function ArgumentNullError(argumentName, message) { + captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.argumentName = argumentName; + this.message = message || util.format('Missing argument: %s', argumentName); +} + +util.inherits(ArgumentNullError, Error); + +function StorageError(message, properties) { + captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.message = message; + + if(properties){ + _.extend(this, properties); + } +} + +util.inherits(StorageError, Error); + +function TimeoutError(message) { + captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.message = message; +} + +util.inherits(TimeoutError, Error); + +module.exports.ArgumentError = ArgumentError; +module.exports.ArgumentNullError = ArgumentNullError; +module.exports.StorageError = StorageError; +module.exports.TimeoutError = TimeoutError; +module.exports.captureStackTrace = captureStackTrace; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js b/node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js new file mode 100644 index 000000000..a6fe63f24 --- /dev/null +++ b/node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js @@ -0,0 +1,95 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +'use strict'; + +var RetryPolicyFilter = require('./retrypolicyfilter'); +/** +* Creates a new 'ExponentialRetryPolicyFilter' instance. +* @class +* The ExponentialRetryPolicyFilter allows you to retry operations, +* using an exponential back-off interval between retries. +* To apply a filter to service operations, use `withFilter` +* and specify the filter to be used when creating a service. +* @constructor +* @param {number} [retryCount=3] The client retry count. +* @param {number} [retryInterval=30000] The client retry interval, in milliseconds. +* @param {number} [minRetryInterval=3000] The minimum retry interval, in milliseconds. +* @param {number} [maxRetryInterval=90000] The maximum retry interval, in milliseconds. +* +* @example +* var azure = require('azure-storage'); +* var retryOperations = new azure.ExponentialRetryPolicyFilter(); +* var blobService = azure.createBlobService().withFilter(retryOperations) +*/ +function ExponentialRetryPolicyFilter(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { + this.retryCount = retryCount ? retryCount : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = retryInterval ? retryInterval : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL; + this.minRetryInterval = minRetryInterval ? minRetryInterval : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + this.maxRetryInterval = maxRetryInterval ? maxRetryInterval : ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; +} + +/** +* Represents the default client retry interval, in milliseconds. +*/ +ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; + +/** +* Represents the default client retry count. +*/ +ExponentialRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT = 3; + +/** +* Represents the default maximum retry interval, in milliseconds. +*/ +ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; + +/** +* Represents the default minimum retry interval, in milliseconds. +*/ +ExponentialRetryPolicyFilter.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; + +/** + * Determines if the operation should be retried and how long to wait until the next retry. + * + * @param {number} statusCode The HTTP status code. + * @param {object} requestOptions The request options. + * @return {retryInfo} Information about whether the operation qualifies for a retry and the retryInterval. + */ +ExponentialRetryPolicyFilter.prototype.shouldRetry = function (statusCode, requestOptions) { + var retryData = (requestOptions && requestOptions.retryContext) ? requestOptions.retryContext : {}; + + // Adjust retry interval + var incrementDelta = Math.pow(2, retryData.retryCount) - 1; + var boundedRandDelta = this.retryInterval * 0.8 + Math.floor(Math.random() * (this.retryInterval * 1.2 - this.retryInterval * 0.8)); + incrementDelta *= boundedRandDelta; + + retryData.retryInterval = Math.min(this.minRetryInterval + incrementDelta, this.maxRetryInterval); + + return RetryPolicyFilter._shouldRetryOnError(statusCode, requestOptions); +}; + +/** +* Handles an operation with an exponential retry policy. +* +* @param {Object} requestOptions The original request options. +* @param {function} next The next filter to be handled. +*/ +ExponentialRetryPolicyFilter.prototype.handle = function (requestOptions, next) { + RetryPolicyFilter._handle(this, requestOptions, next); +}; + +module.exports = ExponentialRetryPolicyFilter; diff --git a/node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js b/node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js new file mode 100644 index 000000000..3bbe6d0e5 --- /dev/null +++ b/node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js @@ -0,0 +1,75 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// +'use strict'; + +var RetryPolicyFilter = require('./retrypolicyfilter'); + +/** +* Creates a new LinearRetryPolicyFilter instance. +* @class +* The LinearRetryPolicyFilter allows you to retry operations, +* using an linear back-off interval between retries. +* To apply a filter to service operations, use `withFilter` +* and specify the filter to be used when creating a service. +* @constructor +* @param {number} [retryCount=3] The client retry count. +* @param {number} [retryInterval=30000] The client retry interval, in milliseconds. +* +* @example +* var azure = require('azure-storage'); +* var retryOperations = new azure.LinearRetryPolicyFilter(); +* var blobService = azure.createBlobService().withFilter(retryOperations) +*/ +function LinearRetryPolicyFilter(retryCount, retryInterval) { + this.retryCount = retryCount ? retryCount : LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = retryInterval ? retryInterval : LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL; +} + +/** +* Represents the default client retry interval, in milliseconds. +*/ +LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; + +/** +* Represents the default client retry count. +*/ +LinearRetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT = 3; + +/** +* Determines if the operation should be retried and how long to wait until the next retry. +* + * @param {number} statusCode The HTTP status code. + * @param {object} requestOptions The request options. + * @return {retryInfo} Information about whether the operation qualifies for a retry and the retryInterval. +*/ +LinearRetryPolicyFilter.prototype.shouldRetry = function (statusCode, requestOptions) { + var retryData = (requestOptions && requestOptions.retryContext) ? requestOptions.retryContext : {}; + retryData.retryInterval = this.retryInterval; + + return RetryPolicyFilter._shouldRetryOnError(statusCode, requestOptions); +}; + +/** +* Handles an operation with a linear retry policy. +* +* @param {Object} requestOptions The original request options. +* @param {function} next The next filter to be handled. +*/ +LinearRetryPolicyFilter.prototype.handle = function (requestOptions, next) { + RetryPolicyFilter._handle(this, requestOptions, next); +}; + +module.exports = LinearRetryPolicyFilter; diff --git a/node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js b/node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js new file mode 100644 index 000000000..2e7e7c2a9 --- /dev/null +++ b/node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js @@ -0,0 +1,233 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var azureutil = require('../util/util'); +var Constants = require('../util/constants'); +var StorageUtilities = require('../util/storageutilities'); +var extend = require('util')._extend; + +/** +* Creates a new RetryPolicyFilter instance. +* @class +* The RetryPolicyFilter allows you to retry operations, +* using a custom retry policy. Users are responsible to +* define the shouldRetry method. +* To apply a filter to service operations, use `withFilter` +* and specify the filter to be used when creating a service. +* @constructor +* @param {number} [retryCount=30000] The client retry count. +* @param {number} [retryInterval=3] The client retry interval, in milliseconds. +* +* @example +* var azure = require('azure-storage'); +* var retryPolicy = new azure.RetryPolicyFilter(); +* retryPolicy.retryCount = 3; +* retryPolicy.retryInterval = 3000; +* retryPolicy.shouldRetry = function(statusCode, retryContext) { +* +* }; +* var blobService = azure.createBlobService().withFilter(retryPolicy); +*/ +function RetryPolicyFilter(retryCount, retryInterval) { + this.retryCount = retryCount ? retryCount : RetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = retryInterval ? retryInterval : RetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL; +} + +/** +* Represents the default client retry interval, in milliseconds. +*/ +RetryPolicyFilter.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; + +/** +* Represents the default client retry count. +*/ +RetryPolicyFilter.DEFAULT_CLIENT_RETRY_COUNT = 3; + +/** +* Handles an operation with a retry policy. +* +* @param {Object} requestOptions The original request options. +* @param {function} next The next filter to be handled. +*/ +RetryPolicyFilter.prototype.handle = function (requestOptions, next) { + RetryPolicyFilter._handle(this, requestOptions, next); +}; + +/** +* Handles an operation with a retry policy. +* +* @param {Object} requestOptions The original request options. +* @param {function} next The next filter to be handled. +*/ +RetryPolicyFilter._handle = function (self, requestOptions, next) { + + var retryRequestOptions = extend({}, requestOptions); + retryRequestOptions.retryInterval = 0; + + // Initialize retryContext because that will be passed to the shouldRetry method which users will implement + retryRequestOptions.retryContext = { + retryCount: 0, + error: null, + retryInterval: retryRequestOptions.retryInterval, + locationMode: retryRequestOptions.locationMode, + currentLocation: retryRequestOptions.currentLocation + }; + + var lastPrimaryAttempt; + var lastSecondaryAttempt; + var operation = function () { + // retry policies dont really do anything to the request options + // so move on to next + if (next) { + next(retryRequestOptions, function (returnObject, finalCallback, nextPostCallback) { + // Previous operation ended so update the retry data + if (returnObject.error) { + if (retryRequestOptions.retryContext.error) { + returnObject.error.innerError = retryRequestOptions.retryContext.error; + } + + retryRequestOptions.retryContext.error = returnObject.error; + } + + // If a request sent to the secondary location fails with 404 (Not Found), it is possible + // that the resource replication is not finished yet. So, in case of 404 only in the secondary + // location, the failure should still be retryable. + var secondaryNotFound = (retryRequestOptions.currentLocation === Constants.StorageLocation.SECONDARY) && ((returnObject.response && returnObject.response.statusCode === 404) || (returnObject.error && returnObject.error.code === 'ENOTFOUND')); + + var notExceedMaxRetryCount = retryRequestOptions.retryContext.retryCount ? retryRequestOptions.retryContext.retryCount <= self.retryCount : true; + var retryInfo = self.shouldRetry(secondaryNotFound ? 500 : (azureutil.objectIsNull(returnObject.response) ? 306 : returnObject.response.statusCode), retryRequestOptions); + retryRequestOptions.retryContext.retryCount++; + + if (retryInfo.ignore) { + returnObject.error = null; + } + + // If the custom retry logic(shouldRetry) does not return a targetLocation, calculate based on the previous location and locationMode. + if(azureutil.objectIsNull(retryInfo.targetLocation)) { + retryInfo.targetLocation = azureutil.getNextLocation(retryRequestOptions.currentLocation, retryRequestOptions.locationMode); + } + + // If the custom retry logic(shouldRetry) does not return a retryInterval, try to set it to the value on the instance if it is available. Otherwise, the default(30000) will be used. + if(azureutil.objectIsNull(retryInfo.retryInterval)) { + retryInfo.retryInterval = self.retryInterval; + } + + // Only in the case of success from server but client side failure like MD5 or length mismatch, returnObject.retryable has a value(we explicitly set it to false). + // In this case, we should not retry the request. + // If the output stream already get sent to server and get error back, + // we should NOT retry within the SDK as the stream data is not valid anymore if we retry directly. + if ( + !returnObject.outputStreamSent && returnObject.error && azureutil.objectIsNull(returnObject.retryable) && notExceedMaxRetryCount && + ( + (!azureutil.objectIsNull(returnObject.response) && retryInfo.retryable) || + ( + returnObject.error.code === 'ECONNREFUSED' || + returnObject.error.code === 'ETIMEDOUT' || + returnObject.error.code === 'ESOCKETTIMEDOUT' || + returnObject.error.code === 'ECONNRESET' || + returnObject.error.code === 'EAI_AGAIN' + ) + ) + ) { + if (retryRequestOptions.currentLocation === Constants.StorageLocation.PRIMARY) { + lastPrimaryAttempt = returnObject.operationEndTime; + } else { + lastSecondaryAttempt = returnObject.operationEndTime; + } + + // Moreover, in case of 404 when trying the secondary location, instead of retrying on the + // secondary, further requests should be sent only to the primary location, as it most + // probably has a higher chance of succeeding there. + if (secondaryNotFound && (retryRequestOptions.locationMode !== StorageUtilities.LocationMode.SECONDARY_ONLY)) + { + retryInfo.locationMode = StorageUtilities.LocationMode.PRIMARY_ONLY; + retryInfo.targetLocation = Constants.StorageLocation.PRIMARY; + } + + // Now is the time to calculate the exact retry interval. ShouldRetry call above already + // returned back how long two requests to the same location should be apart from each other. + // However, for the reasons explained above, the time spent between the last attempt to + // the target location and current time must be subtracted from the total retry interval + // that ShouldRetry returned. + var lastAttemptTime = retryInfo.targetLocation === Constants.StorageLocation.PRIMARY ? lastPrimaryAttempt : lastSecondaryAttempt; + if (!azureutil.objectIsNull(lastAttemptTime)) { + var sinceLastAttempt = new Date().getTime() - lastAttemptTime.getTime(); + if (sinceLastAttempt < 0) { + sinceLastAttempt = 0; + } + + retryRequestOptions.retryInterval = retryInfo.retryInterval - sinceLastAttempt; + } + else { + retryRequestOptions.retryInterval = 0; + } + + if(!azureutil.objectIsNull(retryInfo.locationMode)) { + retryRequestOptions.locationMode = retryInfo.locationMode; + } + + retryRequestOptions.currentLocation = retryInfo.targetLocation; + operation(); + } else { + if (nextPostCallback) { + nextPostCallback(returnObject); + } else if (finalCallback) { + finalCallback(returnObject); + } + } + }); + } + }; + + operation(); +}; + +RetryPolicyFilter._shouldRetryOnError = function (statusCode, requestOptions) { + var retryInfo = (requestOptions && requestOptions.retryContext) ? requestOptions.retryContext : {}; + + // Non-timeout Cases + if (statusCode >= 300 && statusCode != 408) { + // Always no retry on "not implemented" and "version not supported" + if (statusCode == 501 || statusCode == 505) { + retryInfo.retryable = false; + return retryInfo; + } + + // When absorbConditionalErrorsOnRetry is set (for append blob) + if (requestOptions && requestOptions.absorbConditionalErrorsOnRetry) { + if (statusCode == 412) { + // When appending block with precondition failure and their was a server error before, we ignore the error. + if (retryInfo.lastServerError) { + retryInfo.ignore = true; + retryInfo.retryable = true; + } else { + retryInfo.retryable = false; + } + } else if (retryInfo.retryable && statusCode >= 500 && statusCode < 600) { + // Retry on the server error + retryInfo.retryable = true; + retryInfo.lastServerError = true; + } + } else if (statusCode < 500) { + // No retry on the client error + retryInfo.retryable = false; + } + } + + return retryInfo; +}; + +module.exports = RetryPolicyFilter; diff --git a/node_modules/azure-storage/lib/common/http/webresource.js b/node_modules/azure-storage/lib/common/http/webresource.js new file mode 100644 index 000000000..4fa76c7db --- /dev/null +++ b/node_modules/azure-storage/lib/common/http/webresource.js @@ -0,0 +1,324 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureutil = require('../util/util'); +var SR = require('../util/sr'); +var Constants = require('../util/constants'); +var errors = require('../errors/errors'); +var ArgumentError = errors.ArgumentError; +var HeaderConstants = Constants.HeaderConstants; +var HttpConstants = Constants.HttpConstants; +var HttpConstants = Constants.HttpConstants; +var HttpVerbs = HttpConstants.HttpVerbs; + +function encodeSpecialCharacters(path) { + return path.replace(/'/g, '%27'); +} + +/** +* Creates a new WebResource object. +* +* This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary +* properties to initiate a request. +* +* @constructor +*/ +function WebResource() { + this.rawResponse = false; + this.queryString = {}; +} + +/** +* Creates a new put request web resource. +* +* @param {string} path The path for the put operation. +* @return {WebResource} A new webresource with a put operation for the given path. +*/ +WebResource.put = function (path) { + var webResource = new WebResource(); + webResource.path = path ? encodeSpecialCharacters(path) : null; + webResource.method = HttpConstants.HttpVerbs.PUT; + return webResource; +}; + +/** +* Creates a new get request web resource. +* +* @param {string} path The path for the get operation. +* @return {WebResource} A new webresource with a get operation for the given path. +*/ +WebResource.get = function (path) { + var webResource = new WebResource(); + webResource.path = path ? encodeSpecialCharacters(path) : null; + webResource.method = HttpConstants.HttpVerbs.GET; + return webResource; +}; + +/** +* Creates a new head request web resource. +* +* @param {string} path The path for the head operation. +* @return {WebResource} A new webresource with a head operation for the given path. +*/ +WebResource.head = function (path) { + var webResource = new WebResource(); + webResource.path = path ? encodeSpecialCharacters(path) : null; + webResource.method = HttpConstants.HttpVerbs.HEAD; + return webResource; +}; + +/** +* Creates a new delete request web resource. +* +* @param {string} path The path for the delete operation. +* @return {WebResource} A new webresource with a delete operation for the given path. +*/ +WebResource.del = function (path) { + var webResource = new WebResource(); + webResource.path = path ? encodeSpecialCharacters(path) : null; + webResource.method = HttpConstants.HttpVerbs.DELETE; + return webResource; +}; + +/** +* Creates a new post request web resource. +* +* @param {string} path The path for the post operation. +* @return {WebResource} A new webresource with a post operation for the given path. +*/ +WebResource.post = function (path) { + var webResource = new WebResource(); + webResource.path = path ? encodeSpecialCharacters(path) : null; + webResource.method = HttpConstants.HttpVerbs.POST; + return webResource; +}; + +/** +* Creates a new merge request web resource. +* +* @param {string} path The path for the merge operation. +* @return {WebResource} A new webresource with a merge operation for the given path. +*/ +WebResource.merge = function (path) { + var webResource = new WebResource(); + webResource.path = path ? encodeSpecialCharacters(path) : null; + webResource.method = HttpConstants.HttpVerbs.MERGE; + return webResource; +}; + +/** +* Specifies a custom property in the web resource. +* +* @param {string} name The property name. +* @param {string} value The property value. +* @return {WebResource} The webresource. +*/ +WebResource.prototype.withProperty = function (name, value) { + if (!this.properties) { + this.properties = {}; + } + + this.properties[name] = value; + + return this; +}; + +/** +* Specifies if the response should be parsed or not. +* +* @param {bool} rawResponse true if the response should not be parsed; false otherwise. +* @return {WebResource} The webresource. +*/ +WebResource.prototype.withRawResponse = function (rawResponse) { + this.rawResponse = rawResponse; + + if (azureutil.objectIsNull(this.rawResponse)) { + this.rawResponse = true; + } + + return this; +}; + +WebResource.prototype.withHeadersOnly = function (headersOnly) { + if (headersOnly !== undefined) { + this.headersOnly = headersOnly; + } else { + this.headersOnly = true; + } + + return this; +}; + +/** +* Adds an optional query string parameter. +* +* @param {Object} name The name of the query string parameter. +* @param {Object} value The value of the query string parameter. +* @param {Object} defaultValue The default value for the query string parameter to be used if no value is passed. +* @return {Object} The web resource. +*/ +WebResource.prototype.withQueryOption = function (name, value, defaultValue) { + if (!azureutil.objectIsNull(value)) { + this.queryString[name] = value; + } else if (defaultValue) { + this.queryString[name] = defaultValue; + } + + return this; +}; + +/** +* Adds optional query string parameters. +* +* Additional arguments will be the needles to search in the haystack. +* +* @param {Object} object The haystack of query string parameters. +* @return {Object} The web resource. +*/ +WebResource.prototype.withQueryOptions = function (object) { + if (object) { + for (var i = 1; i < arguments.length; i++) { + if (object[arguments[i]]) { + this.withQueryOption(arguments[i], object[arguments[i]]); + } + } + } + + return this; +}; + +/** +* Adds an optional header parameter. +* +* @param {Object} name The name of the header parameter. +* @param {Object} value The value of the header parameter. +* @return {Object} The web resource. +*/ +WebResource.prototype.withHeader = function (name, value) { + if (!this.headers) { + this.headers = {}; + } + + if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(value)) { + value = value instanceof Date ? value.toUTCString() : value; + + this.headers[name] = value; + } + + return this; +}; + +/** +* Adds an optional body. +* +* @param {Object} body The request body. +* @return {Object} The web resource. +*/ +WebResource.prototype.withBody = function (body) { + this.body = body; + return this; +}; + +/** +* Adds optional query string parameters. +* +* Additional arguments will be the needles to search in the haystack. +* +* @param {Object} object The haystack of headers. +* @return {Object} The web resource. +*/ +WebResource.prototype.withHeaders = function (object) { + if (object) { + for (var i = 1; i < arguments.length; i++) { + if (object[arguments[i]]) { + this.withHeader(arguments[i], object[arguments[i]]); + } + } + } + + return this; +}; + +WebResource.prototype.addOptionalMetadataHeaders = function (metadata) { + var self = this; + + if (metadata) { + Object.keys(metadata).forEach(function (metadataKey) { + if (azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(metadataKey)) { + throw new ArgumentError('metadata', SR.METADATA_KEY_INVALID); + } + + var value = metadata[metadataKey]; + if (azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(value)) { + throw new ArgumentError('metadata', SR.METADATA_VALUE_INVALID); + } + + var metadataHeaderName = HeaderConstants.PREFIX_FOR_STORAGE_METADATA + metadataKey; + var existingMetadataHeaderName = ''; + var headers = self.headers ? self.headers : {}; + if (Object.keys(headers).some(function (headerName) { + existingMetadataHeaderName = headerName; + return headerName.toString().toLowerCase() === metadataHeaderName.toLowerCase(); + })) { + self.withHeader(existingMetadataHeaderName, self.headers[existingMetadataHeaderName] + ',' + value); + } else { + self.withHeader(metadataHeaderName, value); + } + }); + } + + return this; +}; + +/** +* Determines if a status code corresponds to a valid response according to the WebResource's expected status codes. +* +* @param {int} statusCode The response status code. +* @return true if the response is valid; false otherwise. +*/ +WebResource.validResponse = function (statusCode) { + if (statusCode >= 200 && statusCode < 300) { + return true; + } + + return false; +}; + +function isMethodWithBody(verb) { + return verb === HttpVerbs.PUT || + verb === HttpVerbs.POST || + verb === HttpVerbs.MERGE; +} + +/** +* Hook up the given input stream to a destination output stream if the WebResource method +* requires a request body and a body is not already set. +* +* @param {Stream} inputStream the stream to pipe from +* @param {Stream} outputStream the stream to pipe to +* +* @return destStream +*/ +WebResource.prototype.pipeInput = function(inputStream, destStream) { + if (isMethodWithBody(this.method) && !this.hasOwnProperty('body')) { + inputStream.pipe(destStream); + } + + return destStream; +}; + +module.exports = WebResource; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/md5-wrapper/md5.browser.js b/node_modules/azure-storage/lib/common/md5-wrapper/md5.browser.js new file mode 100644 index 000000000..9aea459ea --- /dev/null +++ b/node_modules/azure-storage/lib/common/md5-wrapper/md5.browser.js @@ -0,0 +1,26 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var MD5 = require('md5.js'); + +var Md5Wrapper = function () { +}; + +Md5Wrapper.prototype.createMd5Hash = function() { + return new MD5(); +}; + +module.exports = Md5Wrapper; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/md5-wrapper/md5.node.js b/node_modules/azure-storage/lib/common/md5-wrapper/md5.node.js new file mode 100644 index 000000000..eb28fb1df --- /dev/null +++ b/node_modules/azure-storage/lib/common/md5-wrapper/md5.node.js @@ -0,0 +1,26 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var crypto = require('crypto'); + +var Md5Wrapper = function () { +}; + +Md5Wrapper.prototype.createMd5Hash = function() { + return crypto.createHash('md5'); +}; + +module.exports = Md5Wrapper; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/md5-wrapper/package.json b/node_modules/azure-storage/lib/common/md5-wrapper/package.json new file mode 100644 index 000000000..b05289c5b --- /dev/null +++ b/node_modules/azure-storage/lib/common/md5-wrapper/package.json @@ -0,0 +1,7 @@ +{ + "name": "azure-storage-md5-wrapper", + "author": "Microsoft Corporation", + "license": "Apache-2.0", + "main": "md5.node.js", + "browser": "md5.browser.js" +} \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/models/aclresult.js b/node_modules/azure-storage/lib/common/models/aclresult.js new file mode 100644 index 000000000..abe4906d3 --- /dev/null +++ b/node_modules/azure-storage/lib/common/models/aclresult.js @@ -0,0 +1,122 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); +var xmlbuilder = require('xmlbuilder'); + +var azureutil = require('../util/util'); +var ISO8061Date = require('../util/iso8061date'); +var Constants = require('../util/constants'); +var AclConstants = Constants.AclConstants; + +exports = module.exports; + +/** +* Builds an XML representation for container acl permissions. +* +* @param {Object.} entity The signed identifiers. +* @return {string} The XML container acl permissions. +*/ +exports.serialize = function (signedIdentifiersJs) { + var doc = xmlbuilder.create(); + doc = doc.begin(AclConstants.SIGNED_IDENTIFIERS_ELEMENT, { version: '1.0', encoding: 'utf-8' }); + + var keys = Object.keys(signedIdentifiersJs); + if (keys.length > 0) { + keys.forEach(function (key) { + var accessPolicy = signedIdentifiersJs[key]; + doc = doc + .ele(AclConstants.SIGNED_IDENTIFIER_ELEMENT) + .ele(AclConstants.ID) + .txt(key) + .up() + .ele(AclConstants.ACCESS_POLICY); + + if (accessPolicy.Start) { + var startIsoString = accessPolicy.Start; + if (!_.isDate(startIsoString)) { + startIsoString = new Date(startIsoString); + } + + // Convert to expected ISO 8061 date format + startIsoString = ISO8061Date.format(startIsoString); + + doc = doc + .ele(AclConstants.START) + .txt(startIsoString) + .up(); + } + + if (accessPolicy.Expiry) { + var expiryIsoString = accessPolicy.Expiry; + if (!_.isDate(expiryIsoString)) { + expiryIsoString = new Date(expiryIsoString); + } + + // Convert to expected ISO 8061 date format + expiryIsoString = ISO8061Date.format(expiryIsoString); + + doc = doc + .ele(AclConstants.EXPIRY) + .txt(expiryIsoString) + .up(); + } + + if (accessPolicy.Permissions) { + doc = doc + .ele(AclConstants.PERMISSION) + .txt(accessPolicy.Permissions) + .up(); + } + + doc = doc.up().up(); + }); + } + return doc.doc().toString(); +}; + +exports.parse = function (signedIdentifiersXml) { + var signedIdentifiers = {}; + + signedIdentifiersXml = azureutil.tryGetValueChain(signedIdentifiersXml, [ 'SignedIdentifiers', 'SignedIdentifier' ]); + if (signedIdentifiersXml) { + if (!_.isArray(signedIdentifiersXml)) { + signedIdentifiersXml = [ signedIdentifiersXml ]; + } + + signedIdentifiersXml.forEach(function (signedIdentifier) { + var accessPolicy = {}; + if (signedIdentifier.AccessPolicy) { + if (signedIdentifier.AccessPolicy.Start) { + accessPolicy.Start = ISO8061Date.parse(signedIdentifier.AccessPolicy.Start); + } + + if (signedIdentifier.AccessPolicy.Expiry) { + accessPolicy.Expiry = ISO8061Date.parse(signedIdentifier.AccessPolicy.Expiry); + } + + if (signedIdentifier.AccessPolicy.Permission) { + accessPolicy.Permissions = signedIdentifier.AccessPolicy.Permission; + } + } + + signedIdentifiers[signedIdentifier.Id] = accessPolicy; + }); + } + + return signedIdentifiers; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/models/servicepropertiesresult.js b/node_modules/azure-storage/lib/common/models/servicepropertiesresult.js new file mode 100644 index 000000000..01095d8d9 --- /dev/null +++ b/node_modules/azure-storage/lib/common/models/servicepropertiesresult.js @@ -0,0 +1,427 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); +var xmlbuilder = require('xmlbuilder'); + +var Constants = require('../util/constants'); +var ServicePropertiesConstants = Constants.ServicePropertiesConstants; + +exports = module.exports; + +function serializeRetentionPolicy(doc, policy) { + if (policy !== null) { + if (typeof policy === 'undefined') { + policy = {}; + } + + doc = doc.ele(ServicePropertiesConstants.RETENTION_POLICY_ELEMENT); + if (typeof policy.Enabled !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT) + .txt(policy.Enabled) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT) + .txt(false) + .up(); + } + + if (typeof policy.Days !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.DAYS_ELEMENT) + .txt(policy.Days) + .up(); + } else if (policy.Enabled === true) { + doc = doc.ele(ServicePropertiesConstants.DAYS_ELEMENT) + .txt(1) + .up(); + } + + doc = doc.up(); + } +} + +function serializeDeleteRetentionPolicy(doc, policy) { + if (policy !== null) { + if (typeof policy === 'undefined') { + policy = {}; + } + + if (typeof policy.Enabled !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT) + .txt(policy.Enabled) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT) + .txt(false) + .up(); + } + + if (typeof policy.Days !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.DAYS_ELEMENT) + .txt(policy.Days) + .up(); + } else if (policy.Enabled === true) { + doc = doc.ele(ServicePropertiesConstants.DAYS_ELEMENT) + .txt(1) + .up(); + } + + doc = doc.up(); + } +} + +function serializeLogging(doc, logging) { + if (typeof logging.Version !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT) + .txt(logging.Version) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT) + .txt(ServicePropertiesConstants.DEFAULT_ANALYTICS_VERSION) + .up(); + } + + if (typeof logging.Delete !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.DELETE_ELEMENT) + .txt(logging.Delete) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.DELETE_ELEMENT) + .txt(false) + .up(); + } + + if (typeof logging.Read !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.READ_ELEMENT) + .txt(logging.Read) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.READ_ELEMENT) + .txt(false) + .up(); + } + + if (typeof logging.Write !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.WRITE_ELEMENT) + .txt(logging.Write) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.WRITE_ELEMENT) + .txt(false) + .up(); + } + + serializeRetentionPolicy(doc, logging.RetentionPolicy); + + doc = doc.up(); +} + +function serializeMetrics(doc, metrics) { + if (typeof metrics.Version !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT) + .txt(metrics.Version) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.VERSION_ELEMENT) + .txt(ServicePropertiesConstants.DEFAULT_ANALYTICS_VERSION) + .up(); + } + + if (typeof metrics.Enabled !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT) + .txt(metrics.Enabled) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.ENABLED_ELEMENT) + .txt(false) + .up(); + } + + if (metrics.Enabled) { + if (typeof metrics.IncludeAPIs !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.INCLUDE_APIS_ELEMENT) + .txt(metrics.IncludeAPIs) + .up(); + } else if (metrics.Enabled === true) { + doc = doc.ele(ServicePropertiesConstants.INCLUDE_APIS_ELEMENT) + .txt(false) + .up(); + } + } + serializeRetentionPolicy(doc, metrics.RetentionPolicy); +} + +function serializeCorsRules(doc, rules) { + if (typeof rules !== 'undefined' && rules !== null && _.isArray(rules)) { + rules.forEach(function (rule) { + doc = doc.ele(ServicePropertiesConstants.CORS_RULE_ELEMENT); + + if (typeof rule.AllowedMethods !== 'undefined' && _.isArray(rule.AllowedMethods)) { + doc = doc.ele(ServicePropertiesConstants.ALLOWED_METHODS_ELEMENT) + .txt(rule.AllowedMethods.join(',')) + .up(); + } + + if (typeof rule.AllowedOrigins !== 'undefined' && _.isArray(rule.AllowedOrigins)) { + doc = doc.ele(ServicePropertiesConstants.ALLOWED_ORIGINS_ELEMENT) + .txt(rule.AllowedOrigins.join(',')) + .up(); + } + + if (typeof rule.AllowedHeaders !== 'undefined' && _.isArray(rule.AllowedHeaders)) { + doc = doc.ele(ServicePropertiesConstants.ALLOWED_HEADERS_ELEMENT) + .txt(rule.AllowedHeaders.join(',')) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.ALLOWED_HEADERS_ELEMENT) + .txt('') + .up(); + } + + if (typeof rule.ExposedHeaders !== 'undefined' && _.isArray(rule.ExposedHeaders)) { + doc = doc.ele(ServicePropertiesConstants.EXPOSED_HEADERS_ELEMENT) + .txt(rule.ExposedHeaders.join(',')) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.EXPOSED_HEADERS_ELEMENT) + .txt('') + .up(); + } + + if (typeof rule.MaxAgeInSeconds !== 'undefined') { + doc = doc.ele(ServicePropertiesConstants.MAX_AGE_IN_SECONDS_ELEMENT) + .txt(rule.MaxAgeInSeconds) + .up(); + } else { + doc = doc.ele(ServicePropertiesConstants.MAX_AGE_IN_SECONDS_ELEMENT) + .txt('0') + .up(); + } + + doc = doc.up(); + }); + } +} + +exports.serialize = function (servicePropertiesJs) { + var doc = xmlbuilder.create(); + doc = doc.begin(ServicePropertiesConstants.STORAGE_SERVICE_PROPERTIES_ELEMENT, { version: '1.0', encoding: 'utf-8' }); + + if (servicePropertiesJs.Logging) { + doc = doc.ele(ServicePropertiesConstants.LOGGING_ELEMENT); + serializeLogging(doc, servicePropertiesJs.Logging); + doc = doc.up(); + } + + if (servicePropertiesJs.HourMetrics) { + doc = doc.ele(ServicePropertiesConstants.HOUR_METRICS_ELEMENT); + serializeMetrics(doc, servicePropertiesJs.HourMetrics); + doc = doc.up(); + } + + if (servicePropertiesJs.MinuteMetrics) { + doc = doc.ele(ServicePropertiesConstants.MINUTE_METRICS_ELEMENT); + serializeMetrics(doc, servicePropertiesJs.MinuteMetrics); + doc = doc.up(); + } + + if (servicePropertiesJs.Cors) { + doc = doc.ele(ServicePropertiesConstants.CORS_ELEMENT); + serializeCorsRules(doc, servicePropertiesJs.Cors.CorsRule); + doc = doc.up(); + } + + if (servicePropertiesJs.DefaultServiceVersion) { + doc = doc.ele(ServicePropertiesConstants.DEFAULT_SERVICE_VERSION_ELEMENT) + .txt(servicePropertiesJs.DefaultServiceVersion) + .up(); + } + + if (servicePropertiesJs.DeleteRetentionPolicy) { + doc = doc.ele(ServicePropertiesConstants.DEFAULT_DELETE_RETENTION_POLICY_ELEMENT); + serializeDeleteRetentionPolicy(doc, servicePropertiesJs.DeleteRetentionPolicy); + doc = doc.up(); + } + + return doc.doc().toString(); +}; + +function parseRetentionPolicy(policyXml) { + var policy = {}; + + if (typeof policyXml.Enabled !== 'undefined') { + policy.Enabled = policyXml.Enabled === 'true'; + } + + if (typeof policyXml.Days !== 'undefined') { + policy.Days = parseInt(policyXml.Days, 10); + } + + return policy; +} + +function parseLogging(loggingXml) { + var logging = {}; + + if (typeof loggingXml.Version !== 'undefined') { + logging.Version = loggingXml.Version; + } + + if (typeof loggingXml.Delete !== 'undefined') { + logging.Delete = loggingXml.Delete === 'true'; + } + + if (typeof loggingXml.Read !== 'undefined') { + logging.Read = loggingXml.Read === 'true'; + } + + if (typeof loggingXml.Write !== 'undefined') { + logging.Write = loggingXml.Write === 'true'; + } + + if (typeof loggingXml.RetentionPolicy !== 'undefined') { + logging.RetentionPolicy = parseRetentionPolicy(loggingXml.RetentionPolicy); + } + + return logging; +} + +function parseMetrics(metricsXml) { + var metrics = {}; + + if (typeof metricsXml.Version !== 'undefined') { + metrics.Version = metricsXml.Version; + } + + if (typeof metricsXml.Enabled !== 'undefined') { + metrics.Enabled = metricsXml.Enabled === 'true'; + } + + if (typeof metricsXml.IncludeAPIs !== 'undefined') { + metrics.IncludeAPIs = metricsXml.IncludeAPIs === 'true'; + } + + if (typeof metricsXml.RetentionPolicy !== 'undefined') { + metrics.RetentionPolicy = parseRetentionPolicy(metricsXml.RetentionPolicy); + } + + return metrics; +} + +function parseCors(corsXml) { + var cors = {}; + + if (typeof corsXml.CorsRule !== 'undefined') { + var rulesXml = corsXml.CorsRule; + if (!_.isArray(rulesXml)) { + rulesXml = [rulesXml]; + } + + cors.CorsRule = []; + rulesXml.forEach(function (ruleXml) { + var rule = {}; + + if (typeof ruleXml.AllowedMethods !== 'undefined') { + if (ruleXml.AllowedMethods !== '') { + rule.AllowedMethods = ruleXml.AllowedMethods.split(','); + } + else { + rule.AllowedMethods = []; + } + } + + if (typeof ruleXml.AllowedOrigins !== 'undefined') { + if (ruleXml.AllowedOrigins !== '') { + rule.AllowedOrigins = ruleXml.AllowedOrigins.split(','); + } + else { + rule.AllowedOrigins = []; + } + } + + if (typeof ruleXml.AllowedHeaders !== 'undefined') { + if (ruleXml.AllowedHeaders !== '') { + rule.AllowedHeaders = ruleXml.AllowedHeaders.split(','); + } + else { + rule.AllowedHeaders = []; + } + } + + if (typeof ruleXml.ExposedHeaders !== 'undefined') { + if (ruleXml.ExposedHeaders !== '') { + rule.ExposedHeaders = ruleXml.ExposedHeaders.split(','); + } + else { + rule.ExposedHeaders = []; + } + } + + if (typeof ruleXml.MaxAgeInSeconds !== 'undefined') { + rule.MaxAgeInSeconds = parseInt(ruleXml.MaxAgeInSeconds, 10); + } + + cors.CorsRule.push(rule); + }); + } + + return cors; +} + +function parseDeleteRetentionPolicy(deleteRetentionPolicyXml) { + var deleteRetentionPolicy = {}; + + if (typeof deleteRetentionPolicyXml.Enabled !== 'undefined') { + deleteRetentionPolicy.Enabled = deleteRetentionPolicyXml.Enabled === 'true'; + } + + if (typeof deleteRetentionPolicyXml.Days !== 'undefined') { + deleteRetentionPolicy.Days = deleteRetentionPolicyXml.Days; + } + + return deleteRetentionPolicy; +} + +exports.parse = function (servicePropertiesXml) { + var serviceProperties = {}; + + if (typeof servicePropertiesXml.Logging !== 'undefined') { + serviceProperties.Logging = parseLogging(servicePropertiesXml.Logging); + } + + if (typeof servicePropertiesXml.HourMetrics !== 'undefined') { + serviceProperties.HourMetrics = parseMetrics(servicePropertiesXml.HourMetrics); + } + + if (typeof servicePropertiesXml.MinuteMetrics !== 'undefined') { + serviceProperties.MinuteMetrics = parseMetrics(servicePropertiesXml.MinuteMetrics); + } + + if (typeof servicePropertiesXml.Cors !== 'undefined') { + serviceProperties.Cors = parseCors(servicePropertiesXml.Cors); + } + + if (typeof servicePropertiesXml.DefaultServiceVersion !== 'undefined') { + serviceProperties.DefaultServiceVersion = servicePropertiesXml.DefaultServiceVersion; + } + + if (typeof servicePropertiesXml.DeleteRetentionPolicy !== 'undefined') { + serviceProperties.DeleteRetentionPolicy = parseDeleteRetentionPolicy(servicePropertiesXml.DeleteRetentionPolicy); + } + + return serviceProperties; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/models/servicestatsparser.js b/node_modules/azure-storage/lib/common/models/servicestatsparser.js new file mode 100644 index 000000000..b2060ae9b --- /dev/null +++ b/node_modules/azure-storage/lib/common/models/servicestatsparser.js @@ -0,0 +1,34 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// +exports = module.exports; + +exports.parse = function (serviceStatsXml) { + var serviceStats = {}; + + if (typeof serviceStatsXml.GeoReplication !== 'undefined') { + serviceStats.GeoReplication = {}; + + if (typeof serviceStatsXml.GeoReplication.Status !== 'undefined') { + serviceStats.GeoReplication.Status = serviceStatsXml.GeoReplication.Status; + } + + if (typeof serviceStatsXml.GeoReplication.LastSyncTime !== 'undefined' && serviceStatsXml.GeoReplication.LastSyncTime !== '') { + serviceStats.GeoReplication.LastSyncTime = new Date(serviceStatsXml.GeoReplication.LastSyncTime); + } + } + + return serviceStats; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/request-wrapper/package.json b/node_modules/azure-storage/lib/common/request-wrapper/package.json new file mode 100644 index 000000000..c5ece1e1e --- /dev/null +++ b/node_modules/azure-storage/lib/common/request-wrapper/package.json @@ -0,0 +1,7 @@ +{ + "name": "azure-storage-request-wrapper", + "author": "Microsoft Corporation", + "license": "Apache-2.0", + "main": "request.node.js", + "browser": "request.browser.js" +} \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/request-wrapper/request.browser.js b/node_modules/azure-storage/lib/common/request-wrapper/request.browser.js new file mode 100644 index 000000000..df893b919 --- /dev/null +++ b/node_modules/azure-storage/lib/common/request-wrapper/request.browser.js @@ -0,0 +1,258 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var azureCommon = require('../common.browser'); +var Duplex = require('stream').Duplex; +var extend = require('extend'); +var http = require('http'); +var https = require('https'); +var url = require('url'); +var util = require('util'); + +/** +* Creates a new Request object. +* +* @constructor +* @param {object} options The options for a Request object. +* @param {function} callback Callback +*/ +function Request(options, callback) { + Duplex.call(this); + + this._init(options, callback); + this._send(); +} + +util.inherits(Request, Duplex); + +Request.prototype._init = function (options, callback) { + this.callback = callback; + + var nonReservedProperties = azureCommon.util.filterOutNonReservedProperties(this, options); + extend(this, nonReservedProperties); + + this.agent = this.agent || false; + this.timeout = this.timeout || Math.pow(2, 32) * 1000; + + this._initUri(); + this._initHeaders(); +}; + +Request.prototype._initUri = function () { + if (!this.uri) { + return this.emit('error', new Error('options.uri is a required argument')); + } + + if (typeof this.uri === 'string') { + this.uri = url.parse(this.uri); + } + + if (!this.uri.href) { + this.uri.href = url.format(this.uri); + } +}; + +Request.prototype._initHeaders = function () { + this.headers = this.headers || {}; + this.headers['content-length'] = this.headers['content-length'] || 0; +}; + +Request.prototype._send = function () { + this._sent = true; + + var protocol = this.uri.protocol || ''; + var iface = (protocol === 'https:' ? https : http); + + var options = { + scheme: protocol.replace(/:$/, ''), + method: this.method, + host: this.uri.hostname, + port: Number(this.uri.port) || (protocol === 'https:' ? 443 : 80), + path: this.uri.path, + agent: this.agent, + headers: this.headers, + withCredentials: this.withCredentials, + localAddress: this.localAddress, + mode: this.mode + }; + + if (protocol === 'https:') { + options.pfx = this.pfx; + options.key = this.key; + options.cert = this.cert; + options.ca = this.ca; + options.ciphers = this.ciphers; + options.rejectUnauthorized = this.rejectUnauthorized; + options.secureProtocol = this.secureProtocol; + } + + var httpRequest = iface.request(options); + if (this.timeout && httpRequest.setTimeout) { + httpRequest.setTimeout(this.timeout); + } + + this.httpRequest = httpRequest; + this.emit('request', httpRequest); + + this._sendBody(); + this._listenHttpResponse(); + this._listenHttpError(); + + return httpRequest; +}; + +Request.prototype._sendBody = function () { + if (this.body) { + this.httpRequest.write(this.body); + this.httpRequest.end(); + return; + } + + if (this.headers['content-length'] == '0') { + this.httpRequest.end(); + return; + } +}; + +Request.prototype._listenHttpError = function() { + var self = this; + + self.httpRequest.on('error', function(error) { + self.emit('error', error); + }); + + self.on('error', function(error) { + if (self.callback) { + self.callback(error); + } + }); +}; + +Request.prototype._listenHttpResponse = function () { + var self = this; + + self.httpRequest.on('response', function (response) { + var buffers = []; + var bufferLength = 0; + + self.response = response; + + response.on('data', function (chunk) { + self.push(chunk); + buffers.push(chunk); + bufferLength += chunk.length; + }); + + response.on('error', function (error) { + self.emit('error', error); + }); + + response.on('end', function () { + self.push(null); + + response.body = ''; + if (bufferLength > 0) { + response.body = Buffer.concat(buffers, bufferLength); + } + + if (self.encoding !== null) { + response.body = response.body.toString(self.encoding); + } + + if (self.callback) { + self.callback(null, response); + } + }); + + self.emit('response', response); + }); +}; + +/** +* Set a Request header. +* +* @param {string} key The user provided header key. +* @param {string} value The valid header value. +*/ +Request.prototype.setHeader = function (key, value) { + if (this._sent) { + throw new Error('Request already sent'); + } + + this.headers[key] = value; + return this; +}; + +/** +* Set a Request URI. +* +* @param {string} uri The user provided uri. +*/ +Request.prototype.setLocation = function (uri) { + this.uri = uri; + return this; +}; + +Request.prototype.end = function (chunk) { + if (chunk) { + this.httpRequest.write(chunk); + } + + this.httpRequest.end(); +}; + +Request.prototype._write = function (chunk, encoding, callback) { + this.httpRequest.write(chunk); + callback(); +}; + +Request.prototype._read = function () { +}; + +/** +* Create a Request object +* @ignore +* +* @param {object} options Options +* @param {function} callback Callback +* @return {Request} The created request object. +*/ +function req(optionsOrCallback, callback) { + var reqDefaults = req.defaults(); + return reqDefaults(optionsOrCallback, callback); +} + +/** +* Create a Request creator with default options +* @ignore +* +* @param {object} defaultOptions Default options +* @return {function} +*/ +req.defaults = function (defaultOptions) { + return function (optionsOrCallback, callback) { + var options; + azureCommon.util.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + var nonReservedProperties = azureCommon.util.filterOutNonReservedProperties(options, defaultOptions); + extend(options, nonReservedProperties); + + var request = new Request(options, callback); + return request; + }; +}; + +module.exports = req; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/request-wrapper/request.node.js b/node_modules/azure-storage/lib/common/request-wrapper/request.node.js new file mode 100644 index 000000000..c49e60366 --- /dev/null +++ b/node_modules/azure-storage/lib/common/request-wrapper/request.node.js @@ -0,0 +1,17 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +module.exports = require('request'); \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/services/servicesettings.js b/node_modules/azure-storage/lib/common/services/servicesettings.js new file mode 100644 index 000000000..d5c64bfed --- /dev/null +++ b/node_modules/azure-storage/lib/common/services/servicesettings.js @@ -0,0 +1,262 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var util = require('util'); + +var azureUtil = require('../util/util'); +var errors = require('../errors/errors'); +var SR = require('../util/sr'); +var Constants = require('../util/constants'); + +exports = module.exports; + +/** +* The default protocol. +*/ +exports.DEFAULT_PROTOCOL = Constants.HTTPS; + +var NoMatchError = function (msg, constr) { + errors.captureStackTrace(this, constr || this); + this.message = msg || 'Error'; +}; + +util.inherits(NoMatchError, Error); +NoMatchError.prototype.name = 'NoMatchError'; + +exports.NoMatchError = NoMatchError; + +/** +* Throws an exception if the connection string format does not match any of the +* available formats. +* +* @param {string} connectionString The invalid formatted connection string. +* @return none +*/ +exports.noMatchConnectionString = function (connectionString) { + throw new NoMatchError('The provided connection string "' + connectionString + '" does not have complete configuration settings.'); +}; + +/** +* Throws an exception if the settings dont match any of the +* available formats. +* +* @param {object} settings The invalid settings. +* @return none +*/ +exports.noMatchSettings = function (settings) { + throw new NoMatchError('The provided settings ' + JSON.stringify(settings) + ' are not complete.'); +}; + +/** +* Parses the connection string and then validate that the parsed keys belong to +* the validSettingKeys +* +* @param {string} connectionString The user provided connection string. +* @param {array} validKeys The valid keys. +* @return {array} The tokenized connection string keys. +*/ +exports.parseAndValidateKeys = function (connectionString, validKeys) { + var parsedConnectionString = { }; + + // parse key/value pairs from connection string + var pairs = connectionString.split(';'); + for (var m = 0; m < pairs.length; m++) { + if (pairs[m].length === 0) { + continue; + } + + var equalDex = pairs[m].indexOf('='); + if (equalDex < 0) { + throw new SyntaxError(SR.INVALID_CONNECTION_STRING); + } else if (equalDex === 0) { + // empty key name. + throw new SyntaxError(SR.INVALID_CONNECTION_STRING_EMPTY_KEY); + } + + var key = pairs[m].substring(0, equalDex); + + // assure that all given keys are valid. + if (!azureUtil.inArrayInsensitive(key, validKeys)) { + throw new SyntaxError(util.format(SR.INVALID_CONNECTION_STRING_BAD_KEY, key)); + } + + var value = pairs[m].substring(equalDex + 1); + + if(typeof parsedConnectionString[key] === 'undefined'){ + parsedConnectionString[key] = value; + } else { + // duplicate key name + throw new SyntaxError(util.format(SR.INVALID_CONNECTION_STRING_DUPLICATE_KEY, key)); + } + } + + return parsedConnectionString; +}; + +/** +* Creates an anonymous function that acts as predicate to perform a validation. +* +* @param array {requirements} The array of conditions to satisfy. +* @param boolean {isRequired} Either these conditions are all required or all +* optional. +* @param boolean {atLeastOne} Indicates that at least one requirement must +* succeed. +* @return {function} +*/ +exports.getValidator = function (requirements, isRequired, atLeastOne) { + return function (userSettings) { + var oneFound = false; + var result = { }; + + for (var key in userSettings) { + if (userSettings.hasOwnProperty(key)) { + result[key.toLowerCase()] = userSettings[key]; + } + } + + for (var requirement in requirements) { + if (requirements.hasOwnProperty(requirement)) { + var settingName = requirements[requirement].SettingName.toLowerCase(); + + // Check if the setting name exists in the provided user settings. + if (result[settingName]) { + // Check if the provided user setting value is valid. + var validationFunc = requirements[requirement].SettingConstraint; + var isValid = validationFunc(result[settingName]); + + if (isValid) { + // Remove the setting as indicator for successful validation. + delete result[settingName]; + oneFound = true; + } + } else if (isRequired) { + // If required then fail because the setting does not exist + return null; + } + } + } + + if (atLeastOne) { + // At least one requirement must succeed, otherwise fail. + return oneFound ? result : null; + } else { + return result; + } + }; +}; + +/** +* Creates a setting value condition that validates it is one of the +* passed valid values. +* +* @param {string} name The setting key name. +* @return {array} +*/ +exports.setting = function (name) { + var validValues = Array.prototype.slice.call(arguments, 1, arguments.length); + + var predicate = function (settingValue) { + var validValuesString = JSON.stringify(validValues); + if (validValues.length === 0) { + // No restrictions, succeed. + return true; + } + + // Check to find if the settingValue is valid or not. + for (var index = 0; index < validValues.length; index++) { + if (settingValue.toString() == validValues[index].toString()) { + // SettingValue is found in valid values set, succeed. + return true; + } + } + + // settingValue is missing in valid values set, fail. + throw new RangeError('The provided config value ' + settingValue + ' does not belong to the valid values subset:\n' + validValuesString); + }; + + return exports.settingWithFunc(name, predicate); +}; + +/** +* Creates an "at lease one" predicate for the provided list of requirements. +* +* @return callable +*/ +exports.atLeastOne = function () { + var allSettings = arguments; + return exports.getValidator(allSettings, false, true); +}; + +/** +* Creates an optional predicate for the provided list of requirements. +* +* @return {function} +*/ +exports.optional = function () { + var optionalSettings = arguments; + return exports.getValidator(optionalSettings, false, false); +}; + +/** +* Creates an required predicate for the provided list of requirements. +* +* @return {function} +*/ +exports.allRequired = function () { + var requiredSettings = arguments; + return exports.getValidator(requiredSettings, true, false); +}; + +/** +* Creates a setting value condition using the passed predicate. +* +* @param {string} name The setting key name. +* @param {function} predicate The setting value predicate. +* @return {array} +*/ +exports.settingWithFunc = function (name, predicate) { + var requirement = {}; + requirement.SettingName = name; + requirement.SettingConstraint = predicate; + + return requirement; +}; + + +/** +* Tests to see if a given list of settings matches a set of filters exactly. +* +* @param array $settings The settings to check. +* @return boolean If any filter returns null, false. If there are any settings +* left over after all filters are processed, false. Otherwise true. +*/ +exports.matchedSpecification = function (settings) { + var constraints = Array.prototype.slice.call(arguments, 1, arguments.length); + + for (var constraint in constraints) { + if (constraints.hasOwnProperty(constraint)) { + var remainingSettings = constraints[constraint](settings); + + if (!remainingSettings) { + return false; + } else { + settings = remainingSettings; + } + } + } + + return azureUtil.objectKeysLength(settings) === 0; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/services/storageserviceclient.js b/node_modules/azure-storage/lib/common/services/storageserviceclient.js new file mode 100644 index 000000000..629233e0a --- /dev/null +++ b/node_modules/azure-storage/lib/common/services/storageserviceclient.js @@ -0,0 +1,1355 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var request = require('../request-wrapper'); +var url = require('url'); +var qs = require('querystring'); +var util = require('util'); +var xml2js = require('xml2js'); +var events = require('events'); +var _ = require('underscore'); +var guid = require('uuid'); +var os = require('os'); +var extend = require('extend'); +var Parser = require('json-edm-parser'); + +var Md5Wrapper = require('../md5-wrapper'); +var azureutil = require('../util/util'); +var validate = require('../util/validate'); +var SR = require('../util/sr'); +var WebResource = require('../http/webresource'); +var BufferStream = require('../streams/bufferstream.js'); + +var ServiceSettings = require('./servicesettings'); +var StorageServiceSettings = require('./storageservicesettings'); +var Constants = require('../util/constants'); +var StorageUtilities = require('../util/storageutilities'); +var ServicePropertiesResult = require('../models/servicepropertiesresult'); +var TableUtilities = require('../../services/table/tableutilities'); + +var SharedKey = require('../signing/sharedkey'); +var SharedAccessSignature = require('../signing/sharedaccesssignature'); + +var HeaderConstants = Constants.HeaderConstants; +var QueryStringConstants = Constants.QueryStringConstants; +var HttpResponseCodes = Constants.HttpConstants.HttpResponseCodes; +var StorageServiceClientConstants = Constants.StorageServiceClientConstants; +var defaultRequestLocationMode = Constants.RequestLocationMode.PRIMARY_ONLY; +var RequestLocationMode = Constants.RequestLocationMode; + +var Logger = require('../diagnostics/logger'); +var errors = require('../errors/errors'); +var ArgumentError = errors.ArgumentError; +var ArgumentNullError = errors.ArgumentNullError; +var TimeoutError = errors.TimeoutError; +var StorageError = errors.StorageError; + +/** +* Creates a new StorageServiceClient object. +* +* @class +* The StorageServiceClient class is the base class of all the service classes. +* @constructor +* @param {string} storageAccount The storage account. +* @param {string} storageAccessKey The storage access key. +* @param {object} host The host for the service. +* @param {bool} usePathStyleUri Boolean value indicating wether to use path style uris. +* @param {string} sasToken The Shared Access Signature token. +*/ +function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, sasToken) { + StorageServiceClient['super_'].call(this); + + if(storageAccount && storageAccessKey) { + // account and key + this.storageAccount = storageAccount; + this.storageAccessKey = storageAccessKey; + this.storageCredentials = new SharedKey(this.storageAccount, this.storageAccessKey, usePathStyleUri); + } else if (sasToken) { + // sas + this.sasToken = sasToken; + this.storageCredentials = new SharedAccessSignature(sasToken); + } else { + // anonymous + this.anonymous = true; + this.storageCredentials = { + signRequest: function(webResource, callback){ + // no op, anonymous access + callback(null); + } + }; + } + + if(host){ + this.setHost(host); + } + + this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION; + this.usePathStyleUri = usePathStyleUri; + + this._initDefaultFilter(); + + /** + * The logger of the service. To change the log level of the services, set the `[logger.level]{@link Logger#level}`. + * @name StorageServiceClient#logger + * @type Logger + * */ + this.logger = new Logger(Logger.LogLevels.INFO); + + this._setDefaultProxy(); + + this.xml2jsSettings = StorageServiceClient._getDefaultXml2jsSettings(); + this.defaultLocationMode = StorageUtilities.LocationMode.PRIMARY_ONLY; +} + +util.inherits(StorageServiceClient, events.EventEmitter); + +/** +* Gets the default xml2js settings. +* @ignore +* @return {object} The default settings +*/ +StorageServiceClient._getDefaultXml2jsSettings = function() { + var xml2jsSettings = _.clone(xml2js.defaults['0.2']); + + // these determine what happens if the xml contains attributes + xml2jsSettings.attrkey = Constants.TableConstants.XML_METADATA_MARKER; + xml2jsSettings.charkey = Constants.TableConstants.XML_VALUE_MARKER; + + // from xml2js guide: always put child nodes in an array if true; otherwise an array is created only if there is more than one. + xml2jsSettings.explicitArray = false; + + return xml2jsSettings; +}; + +/** +* Sets a host for the service. +* @ignore +* @param {string} host The host for the service. +*/ +StorageServiceClient.prototype.setHost = function (host) { + var parseHost = function(hostUri){ + var parsedHost; + if(!azureutil.objectIsNull(hostUri)) { + if(hostUri.indexOf('http') === -1 && hostUri.indexOf('//') !== 0){ + hostUri = '//' + hostUri; + } + parsedHost = url.parse(hostUri, false, true); + + if(!parsedHost.protocol){ + parsedHost.protocol = ServiceSettings.DEFAULT_PROTOCOL; + } + + if (!parsedHost.port) { + if (parsedHost.protocol === Constants.HTTPS) { + parsedHost.port = Constants.DEFAULT_HTTPS_PORT; + } else { + parsedHost.port = Constants.DEFAULT_HTTP_PORT; + } + } + + parsedHost = url.format({ + protocol: parsedHost.protocol, + port: parsedHost.port, + hostname: parsedHost.hostname, + pathname: parsedHost.pathname + }); + } + + return parsedHost; + }; + + validate.isValidHost(host); + + this.host = { + primaryHost: parseHost(host.primaryHost), + secondaryHost: parseHost(host.secondaryHost) + }; +}; + +/** +* Performs a REST service request through HTTP expecting an input stream. +* @ignore +* +* @param {WebResource} webResource The webresource on which to perform the request. +* @param {string} outputData The outgoing request data as a raw string. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {function} callback The response callback function. +*/ +StorageServiceClient.prototype.performRequest = function (webResource, outputData, options, callback) { + this._performRequest(webResource, { outputData: outputData }, options, callback); +}; + +/** +* Performs a REST service request through HTTP expecting an input stream. +* @ignore +* +* @param {WebResource} webResource The webresource on which to perform the request. +* @param {Stream} outputStream The outgoing request data as a stream. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {function} callback The response callback function. +*/ +StorageServiceClient.prototype.performRequestOutputStream = function (webResource, outputStream, options, callback) { + this._performRequest(webResource, { outputStream: outputStream }, options, callback); +}; + +/** +* Performs a REST service request through HTTP expecting an input stream. +* @ignore +* +* @param {WebResource} webResource The webresource on which to perform the request. +* @param {string} outputData The outgoing request data as a raw string. +* @param {Stream} inputStream The ingoing response data as a stream. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {function} callback The response callback function. +*/ +StorageServiceClient.prototype.performRequestInputStream = function (webResource, outputData, inputStream, options, callback) { + this._performRequest(webResource, { outputData: outputData, inputStream: inputStream }, options, callback); +}; + +/** +* Performs a REST service request through HTTP. +* @ignore +* +* @param {WebResource} webResource The webresource on which to perform the request. +* @param {object} body The request body. +* @param {string} [body.outputData] The outgoing request data as a raw string. +* @param {Stream} [body.outputStream] The outgoing request data as a stream. +* @param {Stream} [body.inputStream] The ingoing response data as a stream. +* @param {object} [options] The request options. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {function} callback The response callback function. +*/ +StorageServiceClient.prototype._performRequest = function (webResource, body, options, callback) { + var self = this; + + // Sets a requestId on the webResource + if(!options.clientRequestId) { + options.clientRequestId = guid.v1(); + } + + webResource.withHeader(HeaderConstants.CLIENT_REQUEST_ID, options.clientRequestId); + + // Sets the user-agent string + var userAgentComment = util.format('(NODE-VERSION %s; %s %s)', process.version, os.type(), os.release()); + webResource.withHeader(HeaderConstants.USER_AGENT, Constants.USER_AGENT_PRODUCT_NAME + '/' + Constants.USER_AGENT_PRODUCT_VERSION + ' ' + userAgentComment); + + // Initialize the location that the request is going to be sent to. + if(azureutil.objectIsNull(options.locationMode)) { + options.locationMode = this.defaultLocationMode; + } + + // Initialize the location that the request can be sent to. + if(azureutil.objectIsNull(options.requestLocationMode)) { + options.requestLocationMode = defaultRequestLocationMode; + } + + // Initialize whether nagling is used or not. + if(azureutil.objectIsNull(options.useNagleAlgorithm)) { + options.useNagleAlgorithm = this.useNagleAlgorithm; + } + + this._initializeLocation(options); + + // Initialize the operationExpiryTime + this._setOperationExpiryTime(options); + + // If the output stream already got sent to server and got error back, + // we should NOT retry within the SDK as the stream data is not valid anymore if we retry directly. + // And it's very hard for SDK to re-wind the stream. + // + // If users want to retry on this kind of error, they can implement their own logic to parse the response and + // determine if they need to re-prepare a stream and call our SDK API to retry. + // + // Currently for blobs/files with size greater than 32MB (DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES), + // we'll send the steam by chunk buffers which doesn't have this issue. + var outputStreamSent = false; + + var operation = function (options, next) { + self._validateLocation(options); + var currentLocation = options.currentLocation; + self._buildRequestOptions(webResource, body, options, function (err, finalRequestOptions) { + if (err) { + callback({ error: err, response: null }, function (finalRequestOptions, finalCallback) { + finalCallback(finalRequestOptions); + }); + } else { + self.logger.log(Logger.LogLevels.DEBUG, 'FINAL REQUEST OPTIONS:\n' + util.inspect(finalRequestOptions)); + + if(self._maximumExecutionTimeExceeded(Date.now(), options.operationExpiryTime)) { + callback({ error: new TimeoutError(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION), response: null }, function (finalRequestOptions, finalCallback) { + finalCallback(finalRequestOptions); + }); + } else { + var processResponseCallback = function (error, response) { + var responseObject; + + if (error) { + responseObject = { error: error, response: null }; + } else { + responseObject = self._processResponse(webResource, response, options); + responseObject.contentMD5 = response.contentMD5; + responseObject.length = response.length; + } + + responseObject.operationEndTime = new Date(); + // Required for listing operations to make sure successive operations go to the same location. + responseObject.targetLocation = currentLocation; + responseObject.outputStreamSent = outputStreamSent; + + callback(responseObject, next); + }; + + var endResponse; + var buildRequest = function (headersOnly, inputStream) { + // Build request (if body was set before, request will process immediately, if not it'll wait for the piping to happen + var requestStream; + + var requestWithDefaults; + + if(self.proxy) { + if(requestWithDefaults === undefined) { + requestWithDefaults = request.defaults({'proxy':self.proxy}); + } + } else { + requestWithDefaults = request; + } + + if (headersOnly) { + requestStream = requestWithDefaults(finalRequestOptions); + + requestStream.on('error', processResponseCallback); + requestStream.on('response', function (response) { + var isValid = WebResource.validResponse(response.statusCode); + if (!isValid) { + // When getting invalid response, try to get the error message for future steps to extract the detailed error information + var contentLength = parseInt(response.headers['content-length']); + var errorMessageBuffer; + var index = 0; + if (contentLength !== undefined) { + errorMessageBuffer = new Buffer(contentLength); + } + + requestStream.on('data', function (data) { + if (contentLength !== undefined) { + data.copy(errorMessageBuffer, index); + index += data.length; + } else { + if (!errorMessageBuffer) { + errorMessageBuffer = data; + } else { + errorMessageBuffer = Buffer.concat([errorMessageBuffer, data]); + } + } + }); + requestStream.on('end', function () { + if (errorMessageBuffer) { + // Strip the UTF8 BOM following the same ways as 'request' module + if (errorMessageBuffer.length > 3 && + errorMessageBuffer[0] === 239 && + errorMessageBuffer[1] === 187 && + errorMessageBuffer[2] === 191) { + response.body = errorMessageBuffer.toString('utf8', 3); + } else { + response.body = errorMessageBuffer.toString('utf8'); + } + } + processResponseCallback(null, response); + }); + } else { + // Only pipe to the destination stream when we get a valid response from service + // Error message should NOT be piped to the destination stream + if (inputStream) { + requestStream.pipe(inputStream); + } + + var responseLength = 0; + var internalHash = new Md5Wrapper().createMd5Hash(); + response.on('data', function(data) { + responseLength += data.length; + internalHash.update(data); + }); + + response.on('end', function () { + // Calculate and set MD5 here + if(azureutil.objectIsNull(options.disableContentMD5Validation) || options.disableContentMD5Validation === false) { + response.contentMD5 = internalHash.digest('base64'); + } + + response.length = responseLength; + endResponse = response; + }); + } + }); + } else { + requestStream = requestWithDefaults(finalRequestOptions, processResponseCallback); + } + + //If useNagleAlgorithm is not set or the value is set and is false, setNoDelay is set to true. + if (azureutil.objectIsNull(options.useNagleAlgorithm) || options.useNagleAlgorithm === false) { + requestStream.on('request', function(httpRequest) { + httpRequest.setNoDelay(true); + }); + } + + // Workaround to avoid request from potentially setting unwanted (rejected) headers by the service + var oldEnd = requestStream.end; + requestStream.end = function () { + if (finalRequestOptions.headers['content-length']) { + requestStream.headers['content-length'] = finalRequestOptions.headers['content-length']; + } else if (requestStream.headers['content-length']) { + delete requestStream.headers['content-length']; + } + + oldEnd.call(requestStream); + }; + + // Bubble events up -- This is when the request is going to be made. + requestStream.on('response', function (response) { + self.emit('receivedResponseEvent', response); + }); + + return requestStream; + }; + + if (body && body.outputData) { + if (!azureutil.isBrowser() && Buffer.isBuffer(body.outputData)) { + // Request module will take 200MB additional memory when we pass a 100MB buffer as body + // Transfer buffer to stream will highly reduce the memory used by request module + finalRequestOptions.body = new BufferStream(body.outputData); + } else { + finalRequestOptions.body = body.outputData; + } + } + + // Pipe any input / output streams + if (body && body.inputStream) { + body.inputStream.on('close', function () { + if (endResponse) { + processResponseCallback(null, endResponse); + endResponse = null; + } + }); + body.inputStream.on('end', function () { + if (endResponse) { + processResponseCallback(null, endResponse); + endResponse = null; + } + }); + body.inputStream.on('finish', function () { + if (endResponse) { + processResponseCallback(null, endResponse); + endResponse = null; + } + }); + buildRequest(true, body.inputStream); + } else if (body && body.outputStream) { + var sendUnchunked = function () { + var size = finalRequestOptions.headers['content-length'] ? + finalRequestOptions.headers['content-length'] : + Constants.BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES; + + var concatBuf = new Buffer(size); + var index = 0; + + body.outputStream.on('data', function (d) { + outputStreamSent = true; + if(self._maximumExecutionTimeExceeded(Date.now(), options.operationExpiryTime)) { + processResponseCallback(new TimeoutError(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION)); + } else { + d.copy(concatBuf, index); + index += d.length; + } + }).on('end', function () { + var requestStream = buildRequest(); + requestStream.write(concatBuf); + requestStream.end(); + }); + if (azureutil.isStreamPaused(body.outputStream)) { + body.outputStream.resume(); + } + }; + + var sendStream = function () { + // NOTE: workaround for an unexpected EPIPE exception when piping streams larger than 29 MB + if (!azureutil.objectIsNull(finalRequestOptions.headers['content-length']) && finalRequestOptions.headers['content-length'] < 29 * 1024 * 1024) { + body.outputStream.pipe(buildRequest()); + outputStreamSent = true; + + if (azureutil.isStreamPaused(body.outputStream)) { + body.outputStream.resume(); + } + } else { + sendUnchunked(); + } + }; + + if (!body.outputStream.readable) { + // if the content length is zero, build the request and don't send a body + if (finalRequestOptions.headers['content-length'] === 0) { + buildRequest(); + } else { + // otherwise, wait until we know the readable stream is actually valid before piping + body.outputStream.on('open', function () { + sendStream(); + }); + } + } else { + sendStream(); + } + + // This catches any errors that happen while creating the readable stream (usually invalid names) + body.outputStream.on('error', function (error) { + processResponseCallback(error); + }); + } else { + buildRequest(); + } + } + } + }); + }; + + // The filter will do what it needs to the requestOptions and will provide a + // function to be handled after the reply + self.filter(options, function (postFiltersRequestOptions, nextPostCallback) { + if(self._maximumExecutionTimeExceeded(Date.now() + postFiltersRequestOptions.retryInterval, postFiltersRequestOptions.operationExpiryTime)) { + callback({ error: new TimeoutError(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION), response: null}, function (postFiltersRequestOptions, finalCallback) { + finalCallback(postFiltersRequestOptions); + }); + } else { + // If there is a filter, flow is: + // filter -> operation -> process response + if(postFiltersRequestOptions.retryContext) { + var func = function() { + operation(postFiltersRequestOptions, nextPostCallback); + }; + + // Sleep for retryInterval before making the request + setTimeout(func, postFiltersRequestOptions.retryInterval); + } else { + // No retry policy filter specified + operation(postFiltersRequestOptions, nextPostCallback); + } + } + }); +}; + + +/** +* Builds the request options to be passed to the http.request method. +* @ignore +* @param {WebResource} webResource The webresource where to build the options from. +* @param {object} options The request options. +* @param {function(error, requestOptions)} callback The callback function. +*/ +StorageServiceClient.prototype._buildRequestOptions = function (webResource, body, options, callback) { + webResource.withHeader(HeaderConstants.STORAGE_VERSION, this.apiVersion); + webResource.withHeader(HeaderConstants.MS_DATE, new Date().toUTCString()); + if (!webResource.headers[HeaderConstants.ACCEPT]) { + webResource.withHeader(HeaderConstants.ACCEPT, 'application/atom+xml,application/xml'); + } + webResource.withHeader(HeaderConstants.ACCEPT_CHARSET, 'UTF-8'); + + // Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE' after Azure Storage 'Authorization header' calculation, + // which may result in a 403 authorization error. So add timestamp to GET/HEAD request URLs thus avoid the browser cache. + if (azureutil.isBrowser() && ( + webResource.method === Constants.HttpConstants.HttpVerbs.GET || + webResource.method === Constants.HttpConstants.HttpVerbs.HEAD)) { + webResource.withQueryOption(HeaderConstants.FORCE_NO_CACHE_IN_BROWSER, new Date().getTime()); + } + + if(azureutil.objectIsNull(options.timeoutIntervalInMs)) { + options.timeoutIntervalInMs = this.defaultTimeoutIntervalInMs; + } + + if(azureutil.objectIsNull(options.clientRequestTimeoutInMs)) { + options.clientRequestTimeoutInMs = this.defaultClientRequestTimeoutInMs; + } + + if(!azureutil.objectIsNull(options.timeoutIntervalInMs) && options.timeoutIntervalInMs > 0) { + webResource.withQueryOption(QueryStringConstants.TIMEOUT, Math.ceil(options.timeoutIntervalInMs / 1000)); + } + + if(options.accessConditions) { + webResource.withHeader(HeaderConstants.IF_MATCH, options.accessConditions.EtagMatch); + webResource.withHeader(HeaderConstants.IF_MODIFIED_SINCE, options.accessConditions.DateModifedSince); + webResource.withHeader(HeaderConstants.IF_NONE_MATCH, options.accessConditions.EtagNonMatch); + webResource.withHeader(HeaderConstants.IF_UNMODIFIED_SINCE, options.accessConditions.DateUnModifiedSince); + webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER_EQUAL, options.accessConditions.SequenceNumberEqual); + webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER_LESS_THAN, options.accessConditions.SequenceNumberLessThan); + webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL, options.accessConditions.SequenceNumberLessThanOrEqual); + webResource.withHeader(HeaderConstants.BLOB_CONDITION_MAX_SIZE, options.accessConditions.MaxBlobSize); + webResource.withHeader(HeaderConstants.BLOB_CONDITION_APPEND_POSITION, options.accessConditions.MaxAppendPosition); + } + + if(options.sourceAccessConditions) { + webResource.withHeader(HeaderConstants.SOURCE_IF_MATCH, options.sourceAccessConditions.EtagMatch); + webResource.withHeader(HeaderConstants.SOURCE_IF_MODIFIED_SINCE, options.sourceAccessConditions.DateModifedSince); + webResource.withHeader(HeaderConstants.SOURCE_IF_NONE_MATCH, options.sourceAccessConditions.EtagNonMatch); + webResource.withHeader(HeaderConstants.SOURCE_IF_UNMODIFIED_SINCE, options.sourceAccessConditions.DateUnModifiedSince); + } + + if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_TYPE] === undefined) { + // work around to add an empty content type header to prevent the request module from magically adding a content type. + webResource.headers[HeaderConstants.CONTENT_TYPE] = ''; + } else if (webResource.headers && webResource.headers[HeaderConstants.CONTENT_TYPE] === null) { + delete webResource.headers[HeaderConstants.CONTENT_TYPE]; + } + + if (!webResource.headers || webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) { + if (body && body.outputData) { + webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body.outputData, 'UTF8')); + } else if (webResource.headers[HeaderConstants.CONTENT_LENGTH] === undefined) { + webResource.withHeader(HeaderConstants.CONTENT_LENGTH, 0); + } + } else if (webResource.headers && webResource.headers[HeaderConstants.CONTENT_LENGTH] === null) { + delete webResource.headers[HeaderConstants.CONTENT_LENGTH]; + } + + // Sets the request url in the web resource. + this._setRequestUrl(webResource, options); + + this.emit('sendingRequestEvent', webResource); + + // Now that the web request is finalized, sign it + this.storageCredentials.signRequest(webResource, function (error) { + var requestOptions = null; + + if (!error) { + var targetUrl = webResource.uri; + + requestOptions = { + uri: url.format(targetUrl), + method: webResource.method, + headers: webResource.headers, + mode: 'disable-fetch' + }; + + if (options) { + //set encoding of response data. If set to null, the body is returned as a Buffer + requestOptions.encoding = options.responseEncoding; + } + + if (options && options.clientRequestTimeoutInMs) { + requestOptions.timeout = options.clientRequestTimeoutInMs; + } else { + requestOptions.timeout = Constants.DEFAULT_CLIENT_REQUEST_TIMEOUT_IN_MS; // 2 minutes + } + + requestOptions.forever = true; + } + + callback(error, requestOptions); + }); +}; + +/** +* Process the response. +* @ignore +* +* @param {WebResource} webResource The web resource that made the request. +* @param {Response} response The response object. +* @param {Options} options The response parsing options. +* @param {String} options.payloadFormat The payload format. +* @return The normalized responseObject. +*/ +StorageServiceClient.prototype._processResponse = function (webResource, response, options) { + var self = this; + + function convertRawHeadersToHeaders(rawHeaders) { + var headers = {}; + if(!rawHeaders) { + return undefined; + } + + for(var i = 0; i < rawHeaders.length; i++) { + var headerName; + if (rawHeaders[i].indexOf(HeaderConstants.PREFIX_FOR_STORAGE_METADATA) === 0) { + headerName = rawHeaders[i]; + } else { + headerName = rawHeaders[i].toLowerCase(); + } + headers[headerName] = rawHeaders[++i]; + } + + return headers; + } + + var validResponse = WebResource.validResponse(response.statusCode); + var rsp = StorageServiceClient._buildResponse(validResponse, response.body, convertRawHeadersToHeaders(response.rawHeaders) || response.headers, response.statusCode, response.md5); + var responseObject; + + if (validResponse && webResource.rawResponse) { + responseObject = { error: null, response: rsp }; + } else { + // attempt to parse the response body, errors will be returned in rsp.error without modifying the body + rsp = StorageServiceClient._parseResponse(rsp, self.xml2jsSettings, options); + + if (validResponse && !rsp.error) { + responseObject = { error: null, response: rsp }; + } else { + rsp.isSuccessful = false; + + if (response.statusCode < 400 || response.statusCode >= 500) { + this.logger.log(Logger.LogLevels.DEBUG, + 'ERROR code = ' + response.statusCode + ' :\n' + util.inspect(rsp.body)); + } + + // responseObject.error should contain normalized parser errors if they occured in _parseResponse + // responseObject.response.body should contain the raw response body in that case + var errorBody = rsp.body; + if(rsp.error) { + errorBody = rsp.error; + delete rsp.error; + } + + if (!errorBody) { + var code = Object.keys(HttpResponseCodes).filter(function (name) { + if (HttpResponseCodes[name] === rsp.statusCode) { + return name; + } + }); + + errorBody = { error: { code: code[0] } }; + } + + var normalizedError = StorageServiceClient._normalizeError(errorBody, response); + responseObject = { error: normalizedError, response: rsp }; + } + } + + this.logger.log(Logger.LogLevels.DEBUG, 'RESPONSE:\n' + util.inspect(responseObject)); + + return responseObject; +}; + +/** +* Associate a filtering operation with this StorageServiceClient. Filtering operations +* can include logging, automatically retrying, etc. Filter operations are objects +* that implement a method with the signature: +* +* "function handle (requestOptions, next)". +* +* After doing its preprocessing on the request options, the method needs to call +* "next" passing a callback with the following signature: +* signature: +* +* "function (returnObject, finalCallback, next)" +* +* In this callback, and after processing the returnObject (the response from the +* request to the server), the callback needs to either invoke next if it exists to +* continue processing other filters or simply invoke finalCallback otherwise to end +* up the service invocation. +* +* @param {Object} filter The new filter object. +* @return {StorageServiceClient} A new service client with the filter applied. +*/ +StorageServiceClient.prototype.withFilter = function (newFilter) { + // Create a new object with the same members as the current service + var derived = _.clone(this); + + // If the current service has a filter, merge it with the new filter + // (allowing us to effectively pipeline a series of filters) + var parentFilter = this.filter; + var mergedFilter = newFilter; + if (parentFilter !== undefined) { + // The parentFilterNext is either the operation or the nextPipe function generated on a previous merge + // Ordering is [f3 pre] -> [f2 pre] -> [f1 pre] -> operation -> [f1 post] -> [f2 post] -> [f3 post] + mergedFilter = function (originalRequestOptions, parentFilterNext) { + newFilter.handle(originalRequestOptions, function (postRequestOptions, newFilterCallback) { + // handle parent filter pre and get Parent filter post + var next = function (postPostRequestOptions, parentFilterCallback) { + // The parentFilterNext is the filter next to the merged filter. + // For 2 filters, that'd be the actual operation. + parentFilterNext(postPostRequestOptions, function (responseObject, responseCallback, finalCallback) { + parentFilterCallback(responseObject, finalCallback, function (postResponseObject) { + newFilterCallback(postResponseObject, responseCallback, finalCallback); + }); + }); + }; + + parentFilter(postRequestOptions, next); + }); + }; + } + + // Store the filter so it can be applied in performRequest + derived.filter = mergedFilter; + return derived; + }; + +/* +* Builds a response object with normalized key names. +* @ignore +* +* @param {Bool} isSuccessful Boolean value indicating if the request was successful +* @param {Object} body The response body. +* @param {Object} headers The response headers. +* @param {int} statusCode The response status code. +* @param {string} md5 The response's content md5 hash. +* @return {Object} A response object. +*/ +StorageServiceClient._buildResponse = function (isSuccessful, body, headers, statusCode, md5) { + var response = { + isSuccessful: isSuccessful, + statusCode: statusCode, + body: body, + headers: headers, + md5: md5 + }; + + if (!azureutil.objectIsNull(headers)) { + if (headers[HeaderConstants.REQUEST_SERVER_ENCRYPTED] !== undefined) { + response.requestServerEncrypted = (headers[HeaderConstants.REQUEST_SERVER_ENCRYPTED] === 'true'); + } + } + + return response; +}; + +/** +* Parses a server response body from XML or JSON into a JS object. +* This is done using the xml2js library. +* @ignore +* +* @param {object} response The response object with a property "body" with a XML or JSON string content. +* @param {object} xml2jsSettings The XML to json settings. +* @param {Options} options The response parsing options. +* @param {String} options.payloadFormat The payload format. +* @return {object} The same response object with the body part as a JS object instead of a XML or JSON string. +*/ +StorageServiceClient._parseResponse = function (response, xml2jsSettings, options) { + function parseXml(body) { + var parsed; + var parser = new xml2js.Parser(xml2jsSettings); + parser.parseString(azureutil.removeBOM(body.toString()), function (err, parsedBody) { + if (err) { + var xmlError = new SyntaxError('EXMLFORMAT'); + xmlError.innerError = err; + throw xmlError; + } else { parsed = parsedBody; } + }); + + return parsed; + } + + if (response.body && Buffer.byteLength(response.body.toString()) > 0) { + var contentType = ''; + if (response.headers && response.headers['content-type']) { + contentType = response.headers['content-type'].toLowerCase(); + } + + try { + if (contentType.indexOf('application/json') !== -1) { + if (options && options.payloadFormat && options.payloadFormat !== TableUtilities.PayloadFormat.NO_METADATA) { + var parser = new Parser(); + parser.onValue = function (value) { + response.body = value; + }; + parser.write(response.body); + } else { + response.body = JSON.parse(response.body); + } + } else if (contentType.indexOf('application/xml') !== -1 || contentType.indexOf('application/atom+xml') !== -1) { + response.body = parseXml(response.body); + } else if (contentType.indexOf('text/html') !== -1) { + response.body = response.body; + } else { + response.body = parseXml(response.body); + // throw new SyntaxError(SR.CONTENT_TYPE_MISSING, null); + } + } catch (e) { + response.error = e; + } + } + + return response; +}; + +/** +* Gets the storage settings. +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string} [host] The host address. +* @param {object} [sasToken] The sas token. +* +* @return {StorageServiceSettings} +*/ +StorageServiceClient.getStorageSettings = function (storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) { + var storageServiceSettings; + if (storageAccountOrConnectionString && !storageAccessKey && !sasToken) { + // If storageAccountOrConnectionString was passed and no accessKey was passed, assume connection string + storageServiceSettings = StorageServiceSettings.createFromConnectionString(storageAccountOrConnectionString); + } else if ((storageAccountOrConnectionString && storageAccessKey) || sasToken || host) { + // Account and key or credentials or anonymous + storageServiceSettings = StorageServiceSettings.createExplicitly(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix); + } else { + // Use environment variables + storageServiceSettings = StorageServiceSettings.createFromEnvironment(); + } + + return storageServiceSettings; +}; + +/** +* Sets the webResource's requestUrl based on the service client settings. +* @ignore +* +* @param {WebResource} webResource The web resource where to set the request url. +*/ +StorageServiceClient.prototype._setRequestUrl = function (webResource, options) { + // Normalize the path + // Backup the original path of the webResource to make sure it works fine even this function get executed multiple times - like RetryFilter + webResource.originalPath = webResource.originalPath || webResource.path; + webResource.path = this._getPath(webResource.originalPath); + + if(!this.host){ + throw new ArgumentNullError('this.host', SR.STORAGE_HOST_LOCATION_REQUIRED); + } + + var host = this.host.primaryHost; + + if(!azureutil.objectIsNull(options) && options.currentLocation === Constants.StorageLocation.SECONDARY) { + host = this.host.secondaryHost; + } + + if(host && host.lastIndexOf('/') !== (host.length - 1)){ + host = host + '/'; + } + + var fullPath = url.format({pathname: webResource.path, query: webResource.queryString}); + webResource.uri = url.resolve(host, fullPath); + webResource.path = url.parse(webResource.uri).pathname; +}; + +/** +* Retrieves the normalized path to be used in a request. +* It also removes any leading "/" of the path in case +* it's there before. +* @ignore +* @param {string} path The path to be normalized. +* @return {string} The normalized path. +*/ +StorageServiceClient.prototype._getPath = function (path) { + if (path === null || path === undefined) { + path = ''; + } else if (path.indexOf('/') === 0) { + path = path.substring(1); + } + + return path; +}; + +/** + * Get the url of a given path + */ +StorageServiceClient.prototype._getUrl = function (path, sasToken, primary) { + var host; + if (!azureutil.objectIsNull(primary) && primary === false) { + host = this.host.secondaryHost; + } else { + host = this.host.primaryHost; + } + + host = azureutil.trimPortFromUri(host); + if(host && host.lastIndexOf('/') !== (host.length - 1)){ + host = host + '/'; + } + + var query = qs.parse(sasToken); + var fullPath = url.format({ pathname: this._getPath(path), query: query }); + return url.resolve(host, fullPath); +}; + +/** +* Initializes the default filter. +* This filter is responsible for chaining the pre filters request into the operation and, after processing the response, +* pass it to the post processing filters. This method should only be invoked by the StorageServiceClient constructor. +* @ignore +* +*/ +StorageServiceClient.prototype._initDefaultFilter = function () { + this.filter = function (requestOptions, nextPreCallback) { + if (nextPreCallback) { + // Handle the next pre callback and pass the function to be handled as post call back. + nextPreCallback(requestOptions, function (returnObject, finalCallback, nextPostCallback) { + if (nextPostCallback) { + nextPostCallback(returnObject); + } else if (finalCallback) { + finalCallback(returnObject); + } + }); + } + }; +}; + +/** +* Retrieves the metadata headers from the response headers. +* @ignore +* +* @param {object} headers The metadata headers. +* @return {object} An object with the metadata headers (without the "x-ms-" prefix). +*/ +StorageServiceClient.prototype.parseMetadataHeaders = function (headers) { + var metadata = {}; + + if (!headers) { + return metadata; + } + + for (var header in headers) { + if (header.indexOf(HeaderConstants.PREFIX_FOR_STORAGE_METADATA) === 0) { + var key = header.substr(HeaderConstants.PREFIX_FOR_STORAGE_METADATA.length, header.length - HeaderConstants.PREFIX_FOR_STORAGE_METADATA.length); + metadata[key] = headers[header]; + } + } + + return metadata; +}; + +/** +* Gets the properties of a storage account’s service, including Azure Storage Analytics. +* @ignore +* +* @this {StorageServiceClient} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the properties +* and `response` will contain information related to this operation. +*/ +StorageServiceClient.prototype.getAccountServiceProperties = function (optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getServiceProperties', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var webResource = WebResource.get() + .withQueryOption(QueryStringConstants.COMP, 'properties') + .withQueryOption(QueryStringConstants.RESTYPE, 'service'); + + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.servicePropertiesResult = null; + if (!responseObject.error) { + responseObject.servicePropertiesResult = ServicePropertiesResult.parse(responseObject.response.body.StorageServiceProperties); + } + + // function to be called after all filters + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.servicePropertiesResult, returnObject.response); + }; + + // call the first filter + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets the properties of a storage account’s service, including Azure Storage Analytics. +* You can also use this operation to set the default request version for all incoming requests that do not have a version specified. +* +* @this {StorageServiceClient} +* @param {object} serviceProperties The service properties. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise, `response` +* will contain information related to this operation. +*/ +StorageServiceClient.prototype.setAccountServiceProperties = function (serviceProperties, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setServiceProperties', function (v) { + v.object(serviceProperties, 'serviceProperties'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var servicePropertiesXml = ServicePropertiesResult.serialize(serviceProperties); + + var webResource = WebResource.put() + .withQueryOption(QueryStringConstants.COMP, 'properties') + .withQueryOption(QueryStringConstants.RESTYPE, 'service') + .withHeader(HeaderConstants.CONTENT_TYPE, 'application/xml;charset="utf-8"') + .withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(servicePropertiesXml)) + .withBody(servicePropertiesXml); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +// Other functions + +/** +* Processes the error body into a normalized error object with all the properties lowercased. +* +* Error information may be returned by a service call with additional debugging information: +* http://msdn.microsoft.com/en-us/library/windowsazure/dd179382.aspx +* +* Table services returns these properties lowercased, example, "code" instead of "Code". So that the user +* can always expect the same format, this method lower cases everything. +* +* @ignore +* +* @param {Object} error The error object as returned by the service and parsed to JSON by the xml2json. +* @return {Object} The normalized error object with all properties lower cased. +*/ +StorageServiceClient._normalizeError = function (error, response) { + if (azureutil.objectIsString(error)) { + return new StorageError(error, null); + } else if (error) { + var normalizedError = {}; + + // blob/queue errors should have error.Error, table errors should have error['odata.error'] + var errorProperties = error.Error || error.error || error['odata.error'] || error['m:error'] || error; + normalizedError.code = errorProperties.message; // The message exists when there is error.Error. + + for (var property in errorProperties) { + if (errorProperties.hasOwnProperty(property)) { + var key = property.toLowerCase(); + if(key.indexOf('m:') === 0) { + key = key.substring(2); + } + + normalizedError[key] = errorProperties[property]; + + // if this is a table error, message is an object - flatten it to normalize with blob/queue errors + // ex: "message":{"lang":"en-US","value":"The specified resource does not exist."} becomes message: "The specified resource does not exist." + if (key === 'message' && _.isObject(errorProperties[property])) { + if (errorProperties[property]['value']) { + normalizedError[key] = errorProperties[property]['value']; + } + } + } + } + + // add status code and server request id if available + if (response) { + if (response.statusCode) { + normalizedError.statusCode = response.statusCode; + } + + if (response.headers && response.headers['x-ms-request-id']) { + normalizedError.requestId = response.headers['x-ms-request-id']; + } + } + + var errorObject = new StorageError(normalizedError.code, normalizedError); + return errorObject; + } + + return null; +}; + +/** +* Sets proxy object specified by caller. +* +* @param {object} proxy proxy to use for tunneling +* { +* host: hostname +* port: port number +* proxyAuth: 'user:password' for basic auth +* headers: {...} headers for proxy server +* key: key for proxy server +* ca: ca for proxy server +* cert: cert for proxy server +* } +* if null or undefined, clears proxy +*/ +StorageServiceClient.prototype.setProxy = function (proxy) { + if (proxy) { + this.proxy = proxy; + } else { + this.proxy = null; + } +}; + +/** +* Sets the service host default proxy from the environment. +* Can be overridden by calling _setProxyUrl or _setProxy +* +*/ +StorageServiceClient.prototype._setDefaultProxy = function () { + var proxyUrl = StorageServiceClient._loadEnvironmentProxyValue(); + if (proxyUrl) { + var parsedUrl = url.parse(proxyUrl); + if (!parsedUrl.port) { + parsedUrl.port = 80; + } + this.setProxy(parsedUrl); + } else { + this.setProxy(null); + } +}; + +/* +* Loads the fields "useProxy" and respective protocol, port and url +* from the environment values HTTPS_PROXY and HTTP_PROXY +* in case those are set. +* @ignore +* +* @return {string} or null +*/ +StorageServiceClient._loadEnvironmentProxyValue = function () { + var proxyUrl = null; + if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY]) { + proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY]; + } else if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY.toLowerCase()]) { + proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTPS_PROXY.toLowerCase()]; + } else if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY]) { + proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY]; + } else if (process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY.toLowerCase()]) { + proxyUrl = process.env[StorageServiceClientConstants.EnvironmentVariables.HTTP_PROXY.toLowerCase()]; + } + + return proxyUrl; +}; + +/** +* Initializes the location to which the operation is being sent to. +*/ +StorageServiceClient.prototype._initializeLocation = function (options) { + if(!azureutil.objectIsNull(options.locationMode)) { + switch(options.locationMode) { + case StorageUtilities.LocationMode.PRIMARY_ONLY: + case StorageUtilities.LocationMode.PRIMARY_THEN_SECONDARY: + options.currentLocation = Constants.StorageLocation.PRIMARY; + break; + case StorageUtilities.LocationMode.SECONDARY_ONLY: + case StorageUtilities.LocationMode.SECONDARY_THEN_PRIMARY: + options.currentLocation = Constants.StorageLocation.SECONDARY; + break; + default: + throw new RangeError(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'locationMode', options.locationMode)); + } + } else { + options.locationMode = StorageUtilities.LocationMode.PRIMARY_ONLY; + options.currentLocation = Constants.StorageLocation.PRIMARY; + } +}; + +/** +* Validates the location to which the operation is being sent to. +*/ +StorageServiceClient.prototype._validateLocation = function (options) { + if(this._invalidLocationMode(options.locationMode)) { + throw new ArgumentNullError('host', SR.STORAGE_HOST_MISSING_LOCATION); + } + + switch(options.requestLocationMode) { + case Constants.RequestLocationMode.PRIMARY_ONLY: + if(options.locationMode === StorageUtilities.LocationMode.SECONDARY_ONLY) { + throw new ArgumentError('host.primaryHost', SR.PRIMARY_ONLY_COMMAND); + } + + options.currentLocation = Constants.StorageLocation.PRIMARY; + options.locationMode = StorageUtilities.LocationMode.PRIMARY_ONLY; + break; + + case Constants.RequestLocationMode.SECONDARY_ONLY: + if(options.locationMode === StorageUtilities.LocationMode.PRIMARY_ONLY) { + throw new ArgumentError('host.secondaryHost', SR.SECONDARY_ONLY_COMMAND); + } + + options.currentLocation = Constants.StorageLocation.SECONDARY; + options.locationMode = StorageUtilities.LocationMode.SECONDARY_ONLY; + break; + + default: + // no op + } +}; + +/** +* Checks whether we have the relevant host information based on the locationMode. +*/ +StorageServiceClient.prototype._invalidLocationMode = function (locationMode) { + switch(locationMode) { + case StorageUtilities.LocationMode.PRIMARY_ONLY: + return azureutil.objectIsNull(this.host.primaryHost); + case StorageUtilities.LocationMode.SECONDARY_ONLY: + return azureutil.objectIsNull(this.host.secondaryHost); + default: + return (azureutil.objectIsNull(this.host.primaryHost) || azureutil.objectIsNull(this.host.secondaryHost)); + } +}; + +/** +* Checks to see if the maximum execution timeout provided has been exceeded. +*/ +StorageServiceClient.prototype._maximumExecutionTimeExceeded = function (currentTime, expiryTime) { + if(!azureutil.objectIsNull(expiryTime) && currentTime > expiryTime) { + return true; + } else { + return false; + } +}; + +/** +* Sets the operation expiry time. +*/ +StorageServiceClient.prototype._setOperationExpiryTime = function (options) { + if(azureutil.objectIsNull(options.operationExpiryTime)) { + if(!azureutil.objectIsNull(options.maximumExecutionTimeInMs)) { + options.operationExpiryTime = Date.now() + options.maximumExecutionTimeInMs; + } else if(this.defaultMaximumExecutionTimeInMs) { + options.operationExpiryTime = Date.now() + this.defaultMaximumExecutionTimeInMs; + } + } +}; + +module.exports = StorageServiceClient; diff --git a/node_modules/azure-storage/lib/common/services/storageservicesettings.js b/node_modules/azure-storage/lib/common/services/storageservicesettings.js new file mode 100644 index 000000000..aec29473d --- /dev/null +++ b/node_modules/azure-storage/lib/common/services/storageservicesettings.js @@ -0,0 +1,420 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +'use strict'; + +var _ = require('underscore'); +var url = require('url'); + +var util = require('../util/util'); +var ServiceSettings = require('./servicesettings'); +var Constants = require('../util/constants'); +var StorageServiceClientConstants = Constants.StorageServiceClientConstants; +var ConnectionStringKeys = Constants.ConnectionStringKeys; +var Validate = require('../util/validate'); +var SR = require('../util/sr'); + +var useDevelopmentStorageSetting = ServiceSettings.setting(ConnectionStringKeys.USE_DEVELOPMENT_STORAGE_NAME, true); +var developmentStorageProxyUriSetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME, Validate.isValidUri); +var defaultEndpointsProtocolSetting = ServiceSettings.setting(ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME, 'http', 'https'); +var accountNameSetting = ServiceSettings.setting(ConnectionStringKeys.ACCOUNT_NAME_NAME); +var accountKeySetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.ACCOUNT_KEY_NAME, Validate.isBase64Encoded); +var sasSetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME, _.isString); + +var blobEndpointSetting = ServiceSettings.settingWithFunc( + ConnectionStringKeys.BLOB_ENDPOINT_NAME, + Validate.isValidHost +); + +var queueEndpointSetting = ServiceSettings.settingWithFunc( + ConnectionStringKeys.QUEUE_ENDPOINT_NAME, + Validate.isValidHost +); + +var tableEndpointSetting = ServiceSettings.settingWithFunc( + ConnectionStringKeys.TABLE_ENDPOINT_NAME, + Validate.isValidHost +); + +var fileEndpointSetting = ServiceSettings.settingWithFunc( + ConnectionStringKeys.FILE_ENDPOINT_NAME, + Validate.isValidHost +); + +var endpointSuffixSetting = ServiceSettings.settingWithFunc( + ConnectionStringKeys.ENDPOINT_SUFFIX_NAME, + Validate.isValidHost +); + +var validKeys = [ + ConnectionStringKeys.USE_DEVELOPMENT_STORAGE_NAME, + ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME, + ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME, + ConnectionStringKeys.ACCOUNT_NAME_NAME, + ConnectionStringKeys.ACCOUNT_KEY_NAME, + ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME, + ConnectionStringKeys.BLOB_ENDPOINT_NAME, + ConnectionStringKeys.QUEUE_ENDPOINT_NAME, + ConnectionStringKeys.TABLE_ENDPOINT_NAME, + ConnectionStringKeys.FILE_ENDPOINT_NAME, + ConnectionStringKeys.ENDPOINT_SUFFIX_NAME +]; + +/** +* Creates new storage service settings instance. +* +* @param {string} name The storage service name. +* @param {string} key The storage service key. +* @param {string} sasToken The storage service shared access signature token. +* @param {string} blobEndpoint The storage service blob endpoint. +* @param {string} queueEndpoint The storage service queue endpoint. +* @param {string} tableEndpoint The storage service table endpoint. +* @param {string} fileEndpoint The storage service file endpoint. +* @param {bool} usePathStyleUri Boolean value indicating wether to use path style uri or not. +*/ +function StorageServiceSettings(name, key, sasToken, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, usePathStyleUri) { + this._name = name; + this._key = key; + + if (sasToken && sasToken[0] === '?') { + this._sasToken = sasToken.slice(1); + } else { + this._sasToken = sasToken; + } + + this._blobEndpoint = blobEndpoint; + this._queueEndpoint = queueEndpoint; + this._tableEndpoint = tableEndpoint; + this._fileEndpoint = fileEndpoint; + + if (usePathStyleUri) { + this._usePathStyleUri = usePathStyleUri; + } else { + this._usePathStyleUri = false; + } +} + +/** +* Creates a StorageServiceSettings object from the given connection string. +* +* @param {string} connectionString The storage settings connection string. +* @return {StorageServiceSettings} +*/ +StorageServiceSettings.createFromConnectionString = function (connectionString) { + var tokenizedSettings = ServiceSettings.parseAndValidateKeys(connectionString, validKeys); + + try { + return StorageServiceSettings.createFromSettings(tokenizedSettings); + } catch (e) { + if (e instanceof ServiceSettings.NoMatchError) { + // Replace no match settings exception by no match connection string one. + ServiceSettings.noMatchConnectionString(connectionString); + } else { + throw e; + } + } +}; + +StorageServiceSettings.createExplicitly = function (storageAccount, storageAccessKey, host, sasToken, endpointSuffix) { + var settings = {}; + function addIfNotNullOrEmpty(key, value){ + if(typeof value === 'string' && !util.stringIsEmpty(value)){ + settings[key] = value; + } else if (typeof value == 'object' && !util.objectIsNull(value)) { + settings[key] = value; + } + } + + // Endpoints + if (host) { + addIfNotNullOrEmpty('blobendpoint', host); + addIfNotNullOrEmpty('tableendpoint', host); + addIfNotNullOrEmpty('queueendpoint', host); + addIfNotNullOrEmpty('fileendpoint', host); + } else { + addIfNotNullOrEmpty('defaultendpointsprotocol', ServiceSettings.DEFAULT_PROTOCOL.split(':', 1)[0]); + } + + addIfNotNullOrEmpty('accountname', storageAccount); + addIfNotNullOrEmpty('accountkey', storageAccessKey); + addIfNotNullOrEmpty('sharedaccesssignature', sasToken); + addIfNotNullOrEmpty('endpointsuffix', endpointSuffix); + + return StorageServiceSettings.createFromSettings(settings); +}; + +StorageServiceSettings.createFromEnvironment = function () { + var emulated = process.env[StorageServiceClientConstants.EnvironmentVariables.EMULATED]; + if (emulated) { + return StorageServiceSettings.getDevelopmentStorageAccountSettings(); + } + + var connectionString = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_CONNECTION_STRING]; + if (connectionString) { + return StorageServiceSettings.createFromConnectionString(connectionString); + } + + var storageAccount = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCOUNT]; + var storageAccessKey = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY]; + if(storageAccount && storageAccessKey){ + return StorageServiceSettings.createExplicitly(storageAccount, storageAccessKey, null, null, null); + } + + throw new Error(SR.NO_CREDENTIALS_PROVIDED); +}; + +/** +* Creates a StorageServiceSettings object from a set of settings. +* +* @param {object} settings The settings object. +* @return {StorageServiceSettings} +*/ +StorageServiceSettings.createFromSettings = function (settings) { + // Devstore case + var matchedSpecs = ServiceSettings.matchedSpecification( + settings, + ServiceSettings.allRequired(useDevelopmentStorageSetting), + ServiceSettings.optional(developmentStorageProxyUriSetting) + ); + + if (matchedSpecs) { + var proxyUri = util.tryGetValueInsensitive( + ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME, + settings + ); + + return this.getDevelopmentStorageAccountSettings(proxyUri); + } + + // Account/Key automatic case + matchedSpecs = ServiceSettings.matchedSpecification( + settings, + ServiceSettings.allRequired( + defaultEndpointsProtocolSetting, + accountNameSetting, + accountKeySetting + ), + ServiceSettings.optional( + blobEndpointSetting, + queueEndpointSetting, + tableEndpointSetting, + fileEndpointSetting, + endpointSuffixSetting + ) + ); + + if (matchedSpecs) { + return this._createStorageServiceSettings(settings); + } + + // Account/Key explicit case + matchedSpecs = ServiceSettings.matchedSpecification( + settings, + ServiceSettings.allRequired( + accountNameSetting, + accountKeySetting + ), + ServiceSettings.atLeastOne( + blobEndpointSetting, + queueEndpointSetting, + tableEndpointSetting, + fileEndpointSetting, + endpointSuffixSetting + ) + ); + + if (matchedSpecs) { + return this._createStorageServiceSettings(settings); + } + + // SAS case + matchedSpecs = ServiceSettings.matchedSpecification( + settings, + ServiceSettings.allRequired( + sasSetting + ), + ServiceSettings.atLeastOne( + blobEndpointSetting, + queueEndpointSetting, + tableEndpointSetting, + fileEndpointSetting, + endpointSuffixSetting + ) + ); + + if(matchedSpecs) { + return this._createStorageServiceSettings(settings); + } + + // anonymous explicit case + // Only blob anonymous access is valid. + matchedSpecs = ServiceSettings.matchedSpecification( + settings, + ServiceSettings.allRequired( + blobEndpointSetting + ), + ServiceSettings.optional( + fileEndpointSetting, + queueEndpointSetting, + tableEndpointSetting, + endpointSuffixSetting + ) + ); + + if(matchedSpecs) { + return this._createStorageServiceSettings(settings); + } + + ServiceSettings.noMatchSettings(settings); +}; + +/** +* Returns a StorageServiceSettings with development storage credentials using +* the specified proxy Uri. +* +* @param {string} proxyUri The proxy endpoint to use. +* @return {StorageServiceSettings} +*/ +StorageServiceSettings.getDevelopmentStorageAccountSettings = function (proxyUri) { + if (!proxyUri) { + proxyUri = StorageServiceClientConstants.DEV_STORE_URI; + } + + var parsedUri = url.parse(proxyUri); + var scheme = parsedUri.protocol; + var host = parsedUri.host; + var prefix = scheme + '//' + host; + + var blobEndpoint = { + primaryHost: prefix + ':10000' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, + secondaryHost: prefix + ':10000' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary' + }; + + var queueEndpoint = { + primaryHost: prefix + ':10001' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, + secondaryHost: prefix + ':10001' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary' + }; + + var tableEndpoint = { + primaryHost: prefix + ':10002' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, + secondaryHost: prefix + ':10002' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary' + }; + + return new StorageServiceSettings( + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT, + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY, + null, + blobEndpoint, + queueEndpoint, + tableEndpoint, + null, + true + ); +}; + +/** +* Creates StorageServiceSettings object given endpoints uri. +* +* @ignore +* @param {array} settings The service settings. +* @param {string} blobEndpointUri The blob endpoint uri. +* @param {string} queueEndpointUri The queue endpoint uri. +* @param {string} tableEndpointUri The table endpoint uri. +* @param {string} fileEndpointUri The file endpoint uri. +* @return {StorageServiceSettings} +*/ +StorageServiceSettings._createStorageServiceSettings = function (settings) { + var standardizeHost = function (host, accountName, scheme, dns){ + var storageHost; + if (host) { + storageHost = {}; + storageHost.primaryHost = _.isString(host) ? host : host.primaryHost; + storageHost.secondaryHost = _.isString(host) ? undefined : host.secondaryHost; + } + + if (scheme && accountName && dns) { + storageHost = storageHost ? storageHost : {}; + storageHost.primaryHost = storageHost.primaryHost ? storageHost.primaryHost : url.format({ protocol: scheme, hostname: accountName + '.' + dns}); + storageHost.secondaryHost = storageHost.secondaryHost ? storageHost.secondaryHost : url.format({ protocol: scheme, hostname: accountName + '-secondary.' + dns}); + } + + return storageHost; + }; + + var scheme = util.tryGetValueInsensitive( + ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME, + settings + ); + + var accountName = util.tryGetValueInsensitive( + ConnectionStringKeys.ACCOUNT_NAME_NAME, + settings + ); + + var accountKey = util.tryGetValueInsensitive( + ConnectionStringKeys.ACCOUNT_KEY_NAME, + settings + ); + + var sasToken = util.tryGetValueInsensitive( + ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME, + settings + ); + + var endpointSuffix = util.tryGetValueInsensitive( + ConnectionStringKeys.ENDPOINT_SUFFIX_NAME, + settings + ); + + var blobEndpoint = standardizeHost( + util.tryGetValueInsensitive(ConnectionStringKeys.BLOB_ENDPOINT_NAME, settings), + accountName, + scheme, + endpointSuffix ? 'blob.' + endpointSuffix : StorageServiceClientConstants.CLOUD_BLOB_HOST); + + var queueEndpoint = standardizeHost( + util.tryGetValueInsensitive(ConnectionStringKeys.QUEUE_ENDPOINT_NAME, settings), + accountName, + scheme, + endpointSuffix ? 'queue.' + endpointSuffix : StorageServiceClientConstants.CLOUD_QUEUE_HOST); + + var tableEndpoint = standardizeHost( + util.tryGetValueInsensitive(ConnectionStringKeys.TABLE_ENDPOINT_NAME, settings), + accountName, + scheme, + endpointSuffix ? 'table.' + endpointSuffix : StorageServiceClientConstants.CLOUD_TABLE_HOST); + + var fileEndpoint = standardizeHost( + util.tryGetValueInsensitive(ConnectionStringKeys.FILE_ENDPOINT_NAME, settings), + accountName, + scheme, + endpointSuffix ? 'file.' + endpointSuffix : StorageServiceClientConstants.CLOUD_FILE_HOST); + + + return new StorageServiceSettings( + accountName, + accountKey, + sasToken, + blobEndpoint, + queueEndpoint, + tableEndpoint, + fileEndpoint + ); +}; + +StorageServiceSettings.validKeys = validKeys; + +exports = module.exports = StorageServiceSettings; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/signing/hmacsha256sign.js b/node_modules/azure-storage/lib/common/signing/hmacsha256sign.js new file mode 100644 index 000000000..e1f7f099a --- /dev/null +++ b/node_modules/azure-storage/lib/common/signing/hmacsha256sign.js @@ -0,0 +1,43 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var crypto = require('crypto'); + +/** +* Creates a new HmacSHA256Sign object. +* +* @constructor +*/ +function HmacSha256Sign(accessKey) { + this._accessKey = accessKey; + this._decodedAccessKey = new Buffer(this._accessKey, 'base64'); +} + +/** +* Computes a signature for the specified string using the HMAC-SHA256 algorithm. +* +* @param {string} stringToSign The UTF-8-encoded string to sign. +* @return A String that contains the HMAC-SHA256-encoded signature. +*/ +HmacSha256Sign.prototype.sign = function (stringToSign) { + // Encoding the Signature + // Signature=Base64(HMAC-SHA256(UTF8(StringToSign))) + + return crypto.createHmac('sha256', this._decodedAccessKey).update(stringToSign, 'utf-8').digest('base64'); +}; + +module.exports = HmacSha256Sign; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js b/node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js new file mode 100644 index 000000000..9acfc8b97 --- /dev/null +++ b/node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js @@ -0,0 +1,56 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// +var HmacSha256Sign = require('./hmacsha256sign'); +var Constants = require('./../util/constants'); +var SR = require('./../util/sr'); + +/** +* Creates a new SharedAccessSignature object. +* +* @constructor +* @param {string} sasToken The sasToken. +*/ +function SharedAccessSignature(sasToken) { + this.sasToken = sasToken; + this.signer = new HmacSha256Sign(sasToken); +} + +/** +* Signs a request with the signature header. +* +* @this {SharedAccessSignature} +* @param {WebResource} The webresource to be signed. +* @param {function(error)} callback The callback function. +*/ +SharedAccessSignature.prototype.signRequest = function (webResource, callback) { + if (webResource.uri.indexOf('?') === -1) { + webResource.uri += '?'; + } else { + webResource.uri += '&'; + } + + webResource.uri += this.sasToken; + + // Add the api-version + if (this.sasToken.indexOf('api-version') == -1) { + webResource.uri += '&' + Constants.QueryStringConstants.API_VERSION + '=' + Constants.HeaderConstants.TARGET_STORAGE_VERSION; + } else { + throw new SyntaxError(SR.INVALID_SAS_TOKEN); + } + callback(null); +}; + +module.exports = SharedAccessSignature; diff --git a/node_modules/azure-storage/lib/common/signing/sharedkey.js b/node_modules/azure-storage/lib/common/signing/sharedkey.js new file mode 100644 index 000000000..1eceb6ace --- /dev/null +++ b/node_modules/azure-storage/lib/common/signing/sharedkey.js @@ -0,0 +1,500 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); +var qs = require('querystring'); + +var azureutil = require('../util/util'); +var HmacSha256Sign = require('./hmacsha256sign'); +var SR = require('../util/sr'); +var errors = require('../errors/errors'); +var ArgumentError = errors.ArgumentError; + +var Constants = require('../util/constants'); +var HeaderConstants = Constants.HeaderConstants; +var QueryStringConstants = Constants.QueryStringConstants; +var HeaderConstants = Constants.HeaderConstants; +var CompatibleVersionConstants = Constants.CompatibleVersionConstants; + +/** +* Creates a new SharedKey object. +* +* @constructor +* @param {string} storageAccount The storage account. +* @param {string} storageAccessKey The storage account's access key. +* @param {bool} usePathStyleUri Boolean value indicating if the path, or the hostname, should include the storage account. +*/ +function SharedKey(storageAccount, storageAccessKey, usePathStyleUri) { + this.storageAccount = storageAccount; + this.storageAccessKey = storageAccessKey; + this.usePathStyleUri = usePathStyleUri; + this.signer = new HmacSha256Sign(storageAccessKey); +} + +/** +* Generates the shared access signature for a account. +* For more detailed information, refer to https://msdn.microsoft.com/en-us/library/azure/mt584140.aspx +* +* @param {object} sharedAccessPolicy The shared access policy. +* @param {SharedAccessServices} sharedAccessPolicy.AccessPolicy.Services The services (blob, file, queue, table) for a shared access signature associated with this shared access policy. +* Refer to `Constants.AccountSasConstants.Services`. +* @param {SharedAccessResourceTypes} sharedAccessPolicy.AccessPolicy.ResourceTypes The resource type for a shared access signature associated with this shared access policy. +* Refer to `Constants.AccountSasConstants.ResourceTypes`. +* @param {SharedAccessPermissions} sharedAccessPolicy.AccessPolicy.Permissions The permissions for a shared access signature. +* Refer to `Constants.AccountSasConstants.Permissions`. +* @param {date} sharedAccessPolicy.AccessPolicy.Start The time at which the Shared Access Signature becomes valid. +* @param {date} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired. +* @param {string} sharedAccessPolicy.AccessPolicy.IPAddressOrRange An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} sharedAccessPolicy.AccessPolicy.Protocols The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* Refer to `Constants.AccountSasConstants.Protocols`. +* @return {string} The shared access signature. +*/ +SharedKey.prototype.generateAccountSignedQueryString = function (sharedAccessPolicy) { + var addIfNotNull = function (queryString, name, value) { + if (!azureutil.objectIsNull(name) && !azureutil.objectIsNull(value)) { + queryString[name] = value; + } + }; + + var formatAccessPolicyDates = function (accessPolicy) { + if (!azureutil.objectIsNull(accessPolicy.Start)) { + if (!_.isDate(accessPolicy.Start)) { + accessPolicy.Start = new Date(accessPolicy.Start); + } + + accessPolicy.Start = azureutil.truncatedISO8061Date(accessPolicy.Start); + } + + if (!azureutil.objectIsNull(accessPolicy.Expiry)) { + if (!_.isDate(accessPolicy.Expiry)) { + accessPolicy.Expiry = new Date(accessPolicy.Expiry); + } + + accessPolicy.Expiry = azureutil.truncatedISO8061Date(accessPolicy.Expiry); + } + }; + + var queryString = {}; + + addIfNotNull(queryString, QueryStringConstants.SIGNED_VERSION, HeaderConstants.TARGET_STORAGE_VERSION); + + // add shared access policy params + if (sharedAccessPolicy.AccessPolicy) { + formatAccessPolicyDates(sharedAccessPolicy.AccessPolicy); + + addIfNotNull(queryString, QueryStringConstants.SIGNED_SERVICES, sharedAccessPolicy.AccessPolicy.Services); + addIfNotNull(queryString, QueryStringConstants.SIGNED_RESOURCE_TYPES, sharedAccessPolicy.AccessPolicy.ResourceTypes); + addIfNotNull(queryString, QueryStringConstants.SIGNED_PERMISSIONS, sharedAccessPolicy.AccessPolicy.Permissions); + addIfNotNull(queryString, QueryStringConstants.SIGNED_START, sharedAccessPolicy.AccessPolicy.Start); + addIfNotNull(queryString, QueryStringConstants.SIGNED_EXPIRY, sharedAccessPolicy.AccessPolicy.Expiry); + addIfNotNull(queryString, QueryStringConstants.SIGNED_IP, sharedAccessPolicy.AccessPolicy.IPAddressOrRange); + addIfNotNull(queryString, QueryStringConstants.SIGNED_PROTOCOL, sharedAccessPolicy.AccessPolicy.Protocols); + } + + // add signature + addIfNotNull(queryString, QueryStringConstants.SIGNATURE, this._generateAccountSharedAccessSignature(sharedAccessPolicy)); + + return qs.stringify(queryString); +}; + + +/** +* Generates the signature part of the shared access signature for a account. +* For more detailed information, refer to https://msdn.microsoft.com/en-us/library/azure/mt584140.aspx +* +* @param {object} sharedAccessPolicy The shared access policy. +* @param {SharedAccessServices} sharedAccessPolicy.AccessPolicy.Services The services (blob, file, queue, table) for a shared access signature associated with this shared access policy. +* Refer to `Constants.AccountSasConstants.Services`. +* @param {SharedAccessResourceTypes} sharedAccessPolicy.AccessPolicy.ResourceTypes The resource type for a shared access signature associated with this shared access policy. +* Refer to `Constants.AccountSasConstants.ResourceTypes`. +* @param {SharedAccessPermissions} sharedAccessPolicy.AccessPolicy.Permissions The permissions for a shared access signature. +* Refer to `Constants.AccountSasConstants.Permissions`. +* @param {date} sharedAccessPolicy.AccessPolicy.Start The time at which the Shared Access Signature becomes valid. +* @param {date} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired. +* @param {string} sharedAccessPolicy.AccessPolicy.IPAddressOrRange An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} sharedAccessPolicy.AccessPolicy.Protocols The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* Refer to `Constants.AccountSasConstants.Protocols`. +* @return {string} The signature part of the shared access signature. +*/ +SharedKey.prototype._generateAccountSharedAccessSignature = function(sharedAccessPolicy){ + var getvalueToAppend = function (value, noNewLine) { + var returnValue = ''; + if (!azureutil.objectIsNull(value)) { + returnValue = value; + } + + if (noNewLine !== true) { + returnValue += '\n'; + } + + return returnValue; + }; + + var stringToSign = getvalueToAppend(this.storageAccount) + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Permissions : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Services : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.ResourceTypes : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Start : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Expiry : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.IPAddressOrRange : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Protocols : '') + + getvalueToAppend(HeaderConstants.TARGET_STORAGE_VERSION); + + return this.signer.sign(stringToSign); +}; + +/** +* Signs a request with the Authentication header. +* +* @param {WebResource} The webresource to be signed. +* @param {function(error)} callback The callback function. +*/ +SharedKey.prototype.signRequest = function (webResource, callback) { + var getvalueToAppend = function (value, headerName) { + // Do not sign content-length 0 in 2014-08-16 and later + if (headerName === HeaderConstants.CONTENT_LENGTH && (azureutil.objectIsNull(value[headerName]) || value[headerName].toString() === '0')) { + return '\n'; + } else if (azureutil.objectIsNull(value) || azureutil.objectIsNull(value[headerName])) { + return '\n'; + } else { + return value[headerName] + '\n'; + } + }; + + var stringToSign = + webResource.method + '\n' + + getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_ENCODING) + + getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_LANGUAGE) + + getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_LENGTH) + + getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_MD5) + + getvalueToAppend(webResource.headers, HeaderConstants.CONTENT_TYPE) + + getvalueToAppend(webResource.headers, HeaderConstants.DATE) + + getvalueToAppend(webResource.headers, HeaderConstants.IF_MODIFIED_SINCE) + + getvalueToAppend(webResource.headers, HeaderConstants.IF_MATCH) + + getvalueToAppend(webResource.headers, HeaderConstants.IF_NONE_MATCH) + + getvalueToAppend(webResource.headers, HeaderConstants.IF_UNMODIFIED_SINCE) + + getvalueToAppend(webResource.headers, HeaderConstants.RANGE) + + this._getCanonicalizedHeaders(webResource) + + this._getCanonicalizedResource(webResource); + + var signature = this.signer.sign(stringToSign); + + webResource.withHeader(HeaderConstants.AUTHORIZATION, 'SharedKey ' + this.storageAccount + ':' + signature); + callback(null); +}; + +/* +* Retrieves the webresource's canonicalized resource string. +* @param {WebResource} webResource The webresource to get the canonicalized resource string from. +* @return {string} The canonicalized resource string. +*/ +SharedKey.prototype._getCanonicalizedResource = function (webResource) { + var path = '/'; + if (webResource.path) { + path = webResource.path; + } + + var canonicalizedResource = '/' + this.storageAccount + path; + + // Get the raw query string values for signing + var queryStringValues = webResource.queryString; + + // Build the canonicalized resource by sorting the values by name. + if (queryStringValues) { + var paramNames = []; + Object.keys(queryStringValues).forEach(function (n) { + paramNames.push(n); + }); + + paramNames = paramNames.sort(); + Object.keys(paramNames).forEach(function (name) { + canonicalizedResource += '\n' + paramNames[name] + ':' + queryStringValues[paramNames[name]]; + }); + } + + return canonicalizedResource; +}; + +/* +* Constructs the Canonicalized Headers string. +* +* To construct the CanonicalizedHeaders portion of the signature string, +* follow these steps: 1. Retrieve all headers for the resource that begin +* with x-ms-, including the x-ms-date header. 2. Convert each HTTP header +* name to lowercase. 3. Sort the headers lexicographically by header name, +* in ascending order. Each header may appear only once in the +* string. 4. Unfold the string by replacing any breaking white space with a +* single space. 5. Trim any white space around the colon in the header. 6. +* Finally, append a new line character to each canonicalized header in the +* resulting list. Construct the CanonicalizedHeaders string by +* concatenating all headers in this list into a single string. +* +* @param {object} The webresource object. +* @return {string} The canonicalized headers. +*/ +SharedKey.prototype._getCanonicalizedHeaders = function (webResource) { + // Build canonicalized headers + var canonicalizedHeaders = ''; + if (webResource.headers) { + var canonicalizedHeadersArray = []; + for (var header in webResource.headers) { + if (header.indexOf(HeaderConstants.PREFIX_FOR_STORAGE) === 0) { + var headerItem = { canonicalized: header.toLowerCase(), original: header }; + canonicalizedHeadersArray.push(headerItem); + } + } + + canonicalizedHeadersArray.sort(function(a, b) { return a.canonicalized.localeCompare(b.canonicalized); }); + + _.each(canonicalizedHeadersArray, function (currentHeaderItem) { + var value = webResource.headers[currentHeaderItem.original]; + if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(value)) { + canonicalizedHeaders += currentHeaderItem.canonicalized + ':' + value + '\n'; + } else { + canonicalizedHeaders += currentHeaderItem.canonicalized + ':\n'; + } + }); + } + + return canonicalizedHeaders; +}; + +/** +* Generates the query string for a shared access signature signing. +* +* @this {SharedAccessSignature} +* @param {string} serviceType The service type. +* @param {string} path The path to the resource. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {string} [sharedAccessPolicy.Id] The signed identifier. +* @param {SharedAccessPermissions} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. +* @param {date} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid. +* @param {date} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired. +* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} [sharedAccessPolicy.AccessPolicy.Protocols] The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* @param {string} sasVersion A string indicating the desired SAS Version to use, in storage service version format. Value must be 2012-02-12 or later. +* @parma {ResourceTypes} [args.resourceType] The resource type, if the resource is a blob or container. Null if the resource is a queue or table. +* @parma {ResourceTypes} [args.tableName] The table name, if the resource is a table. Null if the resource is a blob orqueue. +* @parma {ResourceTypes} [args.queryString] The query string, if additional parameters are desired. +* @param {object} [args.headers] The optional header values to set for a blob returned wth this SAS. +* @param {string} [args.headers.CacheControl] The value of the Cache-Control response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentType] The value of the Content-Type response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentEncoding] The value of the Content-Encoding response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentLanguage] The value of the Content-Language response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentDisposition] The value of the Content-Disposition response header to be returned when this SAS is used. +* @return {object} The shared access signature query string. +*/ +SharedKey.prototype.generateSignedQueryString = function (serviceType, path, sharedAccessPolicy, sasVersion, args) { + var addIfNotNull = function (queryString, name, value) { + if (!azureutil.objectIsNull(name) && !azureutil.objectIsNull(value)) { + queryString[name] = value; + } + }; + + var validateVersion = function (sasVersion) { + // validate and add version + if (azureutil.objectIsNull(sasVersion)) { + return HeaderConstants.TARGET_STORAGE_VERSION; + } else { + var values = _.values(CompatibleVersionConstants); + if (values.some(function(version) { + return version.toLowerCase() === sasVersion.toLowerCase(); + })) { + return sasVersion; + } else { + throw new ArgumentError('sasVersion', azureutil.stringFormat(SR.INVALID_SAS_VERSION, sasVersion, values)); + } + } + }; + + var formatAccessPolicyDates = function (accessPolicy) { + if (!azureutil.objectIsNull(accessPolicy.Start)) { + if (!_.isDate(accessPolicy.Start)) { + accessPolicy.Start = new Date(accessPolicy.Start); + } + + accessPolicy.Start = azureutil.truncatedISO8061Date(accessPolicy.Start); + } + + if (!azureutil.objectIsNull(accessPolicy.Expiry)) { + if (!_.isDate(accessPolicy.Expiry)) { + accessPolicy.Expiry = new Date(accessPolicy.Expiry); + } + + accessPolicy.Expiry = azureutil.truncatedISO8061Date(accessPolicy.Expiry); + } + }; + + // set up optional args + var queryString; + var resourceType; + var headers; + var tableName; + + if(args) { + queryString = args.queryString; + resourceType = args.resourceType; + tableName = args.tableName; + headers = args.headers; + } + + if(!queryString) { + queryString = {}; + } + + // add shared access policy params + if (sharedAccessPolicy.AccessPolicy) { + formatAccessPolicyDates(sharedAccessPolicy.AccessPolicy); + + addIfNotNull(queryString, QueryStringConstants.SIGNED_START, sharedAccessPolicy.AccessPolicy.Start); + addIfNotNull(queryString, QueryStringConstants.SIGNED_EXPIRY, sharedAccessPolicy.AccessPolicy.Expiry); + addIfNotNull(queryString, QueryStringConstants.SIGNED_PERMISSIONS, sharedAccessPolicy.AccessPolicy.Permissions); + addIfNotNull(queryString, QueryStringConstants.SIGNED_IP, sharedAccessPolicy.AccessPolicy.IPAddressOrRange); + addIfNotNull(queryString, QueryStringConstants.SIGNED_PROTOCOL, sharedAccessPolicy.AccessPolicy.Protocols); + + // tables only + addIfNotNull(queryString, QueryStringConstants.STARTPK, sharedAccessPolicy.AccessPolicy.StartPk); + addIfNotNull(queryString, QueryStringConstants.ENDPK, sharedAccessPolicy.AccessPolicy.EndPk); + addIfNotNull(queryString, QueryStringConstants.STARTRK, sharedAccessPolicy.AccessPolicy.StartRk); + addIfNotNull(queryString, QueryStringConstants.ENDRK, sharedAccessPolicy.AccessPolicy.EndRk); + } + + // validate and add version + var validatedSASVersionString = validateVersion(sasVersion); + addIfNotNull(queryString, QueryStringConstants.SIGNED_VERSION, validatedSASVersionString); + + // add signed identifier + addIfNotNull(queryString, QueryStringConstants.SIGNED_IDENTIFIER, sharedAccessPolicy.Id); + + // blobs only + addIfNotNull(queryString, QueryStringConstants.SIGNED_RESOURCE, resourceType); + if (headers) { + addIfNotNull(queryString, QueryStringConstants.CACHE_CONTROL, headers.cacheControl); + addIfNotNull(queryString, QueryStringConstants.CONTENT_TYPE, headers.contentType); + addIfNotNull(queryString, QueryStringConstants.CONTENT_ENCODING, headers.contentEncoding); + addIfNotNull(queryString, QueryStringConstants.CONTENT_LANGUAGE, headers.contentLanguage); + addIfNotNull(queryString, QueryStringConstants.CONTENT_DISPOSITION, headers.contentDisposition); + } + + // tables only + addIfNotNull(queryString, QueryStringConstants.TABLENAME, tableName); + + // add signature + addIfNotNull(queryString, QueryStringConstants.SIGNATURE, this._generateSignature(serviceType, path, sharedAccessPolicy, validatedSASVersionString, {resourceType: resourceType, headers: headers, tableName: tableName})); + + return qs.stringify(queryString); +}; + +/** +* Generates the shared access signature for a resource. +* +* @this {SharedAccessSignature} +* @param {string} serviceType The service type. +* @param {string} path The path to the resource. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {string} [sharedAccessPolicy.Id] The signed identifier. +* @param {SharedAccessPermissions} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. +* @param {date} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid. +* @param {date} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired. +* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} [sharedAccessPolicy.AccessPolicy.Protocols] The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* @param {string} sasVersion A string indicating the desired SAS Version to use, in storage service version format. Value must be 2012-02-12 or later. +* @parma {ResourceTypes} [args.resourceType] The resource type, if the resource is a blob or container. Null if the resource is a queue or table. +* @parma {ResourceTypes} [args.tableName] The table name, if the resource is a table. Null if the resource is a blob or queue. +* @param {object} [args.headers] The optional header values to set for a blob returned wth this SAS. +* @param {string} [args.headers.CacheControl] The value of the Cache-Control response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentType] The value of the Content-Type response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentEncoding] The value of the Content-Encoding response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentLanguage] The value of the Content-Language response header to be returned when this SAS is used. +* @param {string} [args.headers.ContentDisposition] The value of the Content-Disposition response header to be returned when this SAS is used. +* @return {string} The shared access signature. +*/ +SharedKey.prototype._generateSignature = function (serviceType, path, sharedAccessPolicy, sasVersion, args) { + var getvalueToAppend = function (value, noNewLine) { + var returnValue = ''; + if (!azureutil.objectIsNull(value)) { + returnValue = value; + } + + if (noNewLine !== true) { + returnValue += '\n'; + } + + return returnValue; + }; + + // set up optional args + var resourceType; + var tableName; + var headers; + if(args) { + resourceType = args.resourceType; + tableName = args.tableName; + headers = args.headers; + } + + // Add leading slash to path + if (path.substr(0, 1) !== '/') { + path = '/' + path; + } + + var canonicalizedResource; + if (sasVersion === CompatibleVersionConstants.FEBRUARY_2012 || sasVersion === CompatibleVersionConstants.AUGUST_2013) { + // Do not prepend service name for older versions + canonicalizedResource = '/' + this.storageAccount + path; + } else { + canonicalizedResource = '/' + serviceType + '/' + this.storageAccount + path; + } + + var stringToSign = getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Permissions : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Start : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Expiry : '') + + getvalueToAppend(canonicalizedResource) + + getvalueToAppend(sharedAccessPolicy.Id) + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.IPAddressOrRange : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.Protocols : '') + + sasVersion; + + if(sasVersion == CompatibleVersionConstants.FEBRUARY_2012) { + if(headers) { + throw new ArgumentError('args.headers', SR.INVALID_HEADERS); + } + } else if (resourceType) { + stringToSign += '\n' + + getvalueToAppend(headers ? headers.cacheControl : '') + + getvalueToAppend(headers ? headers.contentDisposition : '') + + getvalueToAppend(headers ? headers.contentEncoding : '') + + getvalueToAppend(headers ? headers.contentLanguage : '') + + getvalueToAppend(headers ? headers.contentType : '', true); + } + + if(tableName) { + stringToSign += '\n' + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.StartPk : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.StartRk : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.EndPk : '') + + getvalueToAppend(sharedAccessPolicy.AccessPolicy ? sharedAccessPolicy.AccessPolicy.EndRk : '', true); + } + + return this.signer.sign(stringToSign); +}; + +module.exports = SharedKey; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/streams/batchoperation.js b/node_modules/azure-storage/lib/common/streams/batchoperation.js new file mode 100644 index 000000000..612d7eb0b --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/batchoperation.js @@ -0,0 +1,425 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var util = require('util'); +var http = require('http'); +var https = require('https'); +var EventEmitter = require('events').EventEmitter; +var os = require('os'); + +var azureutil = require('../util/util'); +var Logger = require('../diagnostics/logger'); +var Constants = require('../util/constants'); +var errors = require('../errors/errors'); +var ArgumentError = errors.ArgumentError; + +var DEFAULT_OPERATION_MEMORY_USAGE = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; +var DEFAULT_CRITICAL_MEMORY_LIMITATION_32_IN_BYTES = Constants.BlobConstants.DEFAULT_CRITICAL_MEMORY_LIMITATION_32_IN_BYTES; +var DEFAULT_CRITICAL_MEMORY_LIMITATION_BROWSER_IN_BYTES = Constants.BlobConstants.DEFAULT_CRITICAL_MEMORY_LIMITATION_BROWSER_IN_BYTES; +var DEFAULT_MINIMUM_MEMORY_USAGE_BROWSER_IN_BYTES = Constants.BlobConstants.DEFAULT_MINIMUM_MEMORY_USAGE_BROWSER_IN_BYTES; +var DEFAULT_GLOBAL_CONCURRENCY = 5; //Default http connection limitation for nodejs + +var SystemTotalMemory = os.totalmem(); +var CriticalFreeMemory = 0.1 * SystemTotalMemory; +var nodeVersion = azureutil.getNodeVersion(); + +/** +* Concurrently execute batch operations and call operation callback randomly or in sequence. +* Random mode is for uploading. +* 1. Fire user callback when the operation is done. +* Sequence mode is for downloading. +* 1. Fire user callback when the operation is done and all previous operations and callback has finished. +* 2. BatchOperation guarantees the user callback is fired one by one. +* 3. The next user callback can't be fired until the current one is completed. +*/ +function BatchOperation(name, options) { + if (!options) { + options = {}; + } + + this.name = name; + this.logger = options.logger || new Logger(Logger.LogLevels.INFO); + this.operationMemoryUsage = options.operationMemoryUsage || DEFAULT_OPERATION_MEMORY_USAGE; + this.callbackInOrder = options.callbackInOrder === true; + this.callInOrder = options.callInOrder === true; + this._currentOperationId = this.callbackInOrder ? 1 : -1; + this.concurrency = DEFAULT_GLOBAL_CONCURRENCY; + this.enableReuseSocket = (nodeVersion.major > 0 || nodeVersion.minor >= 10) && options.enableReuseSocket; + + this._emitter = new EventEmitter(); + this._enableComplete = false; + this._ended = false; + this._error = null; + this._paused = false; + + //Total operations count(queued and active and connected) + this._totalOperation = 0; + + //Action operations count(The operations which are connecting to remote or executing callback or queued for executing) + this._activeOperation = 0; + + //Queued operations count(The operations which are connecting to remote or queued for executing) + this._queuedOperation = 0; + + //finished operation should be removed from this array + this._operations = []; +} + +/** +* Operation state +*/ +var OperationState = { + INITED : 'inited', + QUEUED : 'queued', + RUNNING : 'running', + COMPLETE : 'complete', + CALLBACK : 'callback', + ERROR : 'error' +}; + +BatchOperation.OperationState = OperationState; + +/** +* Set batch operation concurrency +*/ +BatchOperation.prototype.setConcurrency = function(concurrency) { + if (concurrency) { + this.concurrency = concurrency; + http.Agent.maxSockets = this.concurrency; + https.Agent.maxSockets = this.concurrency; + } +}; + +/** +* Is the workload heavy and It can be used to determine whether we could queue operations +*/ +BatchOperation.prototype.IsWorkloadHeavy = function() { + //Only support one batch operation for now. + //In order to work with the multiple batch operation, we can use global operation track objects + //BatchOperation acquire a bunch of operation ids from global and allocated ids to RestOperation + //RestOperation start to run in order of id + var sharedRequest = 1; + if(this.enableReuseSocket && !this.callInOrder) { + sharedRequest = 2; + } + return this._activeOperation >= sharedRequest * this.concurrency || this._isLowMemory(); +}; + +/** +* Get the approximate memory usage for batch operation. +*/ +BatchOperation.prototype._getApproximateMemoryUsage = function() { + var currentUsage = azureutil.isBrowser() ? DEFAULT_MINIMUM_MEMORY_USAGE_BROWSER_IN_BYTES : process.memoryUsage().rss; // Currently, we cannot get memory usage in browsers + var futureUsage = this._queuedOperation * this.operationMemoryUsage; + return currentUsage + futureUsage; +}; + +/** +* Return whether in a low memory situation. +*/ +BatchOperation.prototype._isLowMemory = function() { + var approximateMemoryUsage = this._getApproximateMemoryUsage(); + return os.freemem() < CriticalFreeMemory || + (this._activeOperation >= this.concurrency && approximateMemoryUsage > 0.5 * SystemTotalMemory) || + (azureutil.is32() && approximateMemoryUsage > DEFAULT_CRITICAL_MEMORY_LIMITATION_32_IN_BYTES) || + (azureutil.isBrowser() && approximateMemoryUsage > DEFAULT_CRITICAL_MEMORY_LIMITATION_BROWSER_IN_BYTES); +}; + +/** +* Add a operation into batch operation +*/ +BatchOperation.prototype.addOperation = function(operation) { + this._operations.push(operation); + operation.status = OperationState.QUEUED; + operation.operationId = ++this._totalOperation; + this._queuedOperation++; + this.logger.debug(util.format('Add operation %d into batch operation %s. Active: %s; Queued: %s', operation.operationId, this.name, this._activeOperation, this._queuedOperation)); + //Immediately start the idle operation if workload isn't heavy + this._runOperation(operation); + return this.IsWorkloadHeavy(); +}; + +/** +* Enable batch operation complete when there is no operation to run. +*/ +BatchOperation.prototype.enableComplete = function() { + this._enableComplete = true; + this.logger.debug(util.format('Enable batch operation %s complete', this.name)); + this._tryEmitEndEvent(); +}; + +/** +* Stop firing user call back +*/ +BatchOperation.prototype.pause = function () { + this._paused = true; +}; + +/** +* Start firing user call back +*/ +BatchOperation.prototype.resume = function () { + if (this._paused) { + this._paused = false; + this._fireOperationUserCallback(); + } +}; + +/** +* Add event listener +*/ +BatchOperation.prototype.on = function(event, listener) { + // only emit end if the batch has completed all operations + if(this._ended && event === 'end') { + listener(); + } else { + this._emitter.on(event, listener); + } +}; + +/** +* Run operation +*/ +BatchOperation.prototype._runOperation = function (operation) { + this.logger.debug(util.format('Operation %d start to run', operation.operationId)); + var cb = this.getBatchOperationCallback(operation); + + if(this._error) { + cb(this._error);//Directly call the callback with previous error. + } else { + operation.run(cb); + } + + this._activeOperation++; +}; + +/** +* Return an general operation call back. +* This callback is used to update the internal status and fire user's callback when operation is complete. +*/ +BatchOperation.prototype.getBatchOperationCallback = function (operation) { + var self = this; + return function (error) { + self._queuedOperation--; + if (error) { + operation.status = OperationState.ERROR; + self.logger.debug(util.format('Operation %d failed. Error %s', operation.operationId, error)); + self._error = error; + } else { + operation.status = OperationState.CALLBACK; + self.logger.debug(util.format('Operation %d succeed', operation.operationId)); + } + + operation._callbackArguments = arguments; + if (self._paused) { + operation.status = OperationState.CALLBACK; + self.logger.debug(util.format('Batch operation paused and Operation %d wait for firing callback', operation.operationId)); + } else if (self.callbackInOrder) { + operation.status = OperationState.CALLBACK; + if (self._currentOperationId === operation.operationId) { + self._fireOperationUserCallback(operation); + } else if (self._currentOperationId > operation.operationId) { + throw new Error('Debug error: current callback operation id cannot be larger than operation id'); + } else { + self.logger.debug(util.format('Operation %d is waiting for firing callback %s', operation.operationId, self._currentOperationId)); + } + } else { + self._fireOperationUserCallback(operation); + } + + self._tryEmitDrainEvent(); + operation = null; + self = null; + }; +}; + +/** +* Fire user's call back +*/ +BatchOperation.prototype._fireOperationUserCallback = function (operation) { + var index = this._getCallbackOperationIndex(); + if (!operation && index != -1) { + operation = this._operations[index]; + } + + if (operation && !this._paused) { + // fire the callback, if exists + if (operation._userCallback) { + this.logger.debug(util.format('Fire user call back for operation %d', operation.operationId)); + // make sure UserCallback is a sync operation in sequence mode. + // both async and sync operations are available for random mode. + operation._fireUserCallback(); + } + + // remove the operation from the array and decrement the counter + this._operations.splice(index, 1); + this._activeOperation--; + operation.status = OperationState.COMPLETE; + index = operation = null; + + if (this.callbackInOrder) { + this._currentOperationId++; + } + + this._fireOperationUserCallback(); + } else if (this._paused) { + this._tryEmitDrainEvent(); + } else { + // check if batch has ended and if so emit end event + this._tryEmitEndEvent(); + } +}; + +/** +* Try to emit the BatchOperation end event +* End event means all the operation and callback already finished. +*/ +BatchOperation.prototype._tryEmitEndEvent = function () { + if(this._enableComplete && this._activeOperation === 0 && this._operations.length === 0) { + this._ended = true; + this.logger.debug(util.format('Batch operation %s emits the end event', this.name)); + this._emitter.emit('end', this._error, null); + return true; + } + + // Workaround to recover from the 'hang' edge case. _tryEmitEndEvent function is not supposed to be called if the bacth is not really completed. + this._tryEmitDrainEvent(); + return false; +}; + +/** +* Try to emit the drain event +*/ +BatchOperation.prototype._tryEmitDrainEvent = function () { + if (!this._emitter) return false; + if(!this.IsWorkloadHeavy() || this._activeOperation < this.concurrency) { + this._emitter.emit('drain'); + return true; + } + return false; +}; + +/** +* Get the current active operation index. +* Only the active operation could call user's callback in sequence model. +* The other finished but not active operations should wait for wake up. +*/ +BatchOperation.prototype._getCallbackOperationIndex = function () { + var operation = null; + for (var i = 0; i < this._operations.length; i++) { + operation = this._operations[i]; + if (this.callbackInOrder) { + //Sequence mode + if (operation.operationId == this._currentOperationId) { + if (operation.status === OperationState.CALLBACK) { + return i; + } else { + return -1; + } + } + } else { + //Random mode + if (operation.status === OperationState.CALLBACK) { + return i; + } + } + } + return -1; +}; + +/** +* Do nothing and directly call the callback. +* In random mode, the user callback will be called immediately +* In sequence mode, the user callback will be called after the previous callback has been called +*/ +BatchOperation.noOperation = function (cb) { + cb(); +}; + +/** +* Rest operation in sdk +*/ +function RestOperation(serviceClient, operation) { + this.status = OperationState.Inited; + this.operationId = -1; + this._callbackArguments = null; + + // setup callback and args + this._userCallback = arguments[arguments.length - 1]; + var sliceEnd = arguments.length; + if(azureutil.objectIsFunction(this._userCallback)) { + sliceEnd--; + } else { + this._userCallback = null; + } + var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd); + + this.run = function(cb) { + var func = serviceClient[operation]; + if(!func) { + throw new ArgumentError('operation', util.format('Unknown operation %s in serviceclient', operation)); + } else { + if(!cb) cb = this._userCallback; + operationArguments.push(cb); + this.status = OperationState.RUNNING; + func.apply(serviceClient, operationArguments); + operationArguments = operation = null; + } + }; + + this._fireUserCallback = function () { + if(this._userCallback) { + this._userCallback.apply(null, this._callbackArguments); + } + }; +} + +BatchOperation.RestOperation = RestOperation; + +/** +* Common operation wrapper +*/ +function CommonOperation(operationFunc, callback) { + this.status = OperationState.Inited; + this.operationId = -1; + this._callbackArguments = null; + var sliceStart = 2; + if (azureutil.objectIsFunction(callback)) { + this._userCallback = callback; + } else { + this._userCallback = null; + sliceStart = 1; + } + var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart); + this.run = function (cb) { + if (!cb) cb = this._userCallback; + operationArguments.push(cb); + this.status = OperationState.RUNNING; + operationFunc.apply(null, operationArguments); + operationArguments = operationFunc = null; + }; + + this._fireUserCallback = function () { + if (this._userCallback) { + this._userCallback.apply(null, this._callbackArguments); + } + this._userCallback = this._callbackArguments = null; + }; +} + +BatchOperation.CommonOperation = CommonOperation; + +module.exports = BatchOperation; diff --git a/node_modules/azure-storage/lib/common/streams/browserfilereadstream.js b/node_modules/azure-storage/lib/common/streams/browserfilereadstream.js new file mode 100644 index 000000000..c20340b4c --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/browserfilereadstream.js @@ -0,0 +1,61 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var buffer = require('buffer').Buffer; +var stream = require('stream'); +var util = require('util'); + +var Constants = require('../util/constants'); +var bufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + +function BrowserFileReadStream(file, options) { + stream.Readable.call(this, options); + + if (!options) { + options = {}; + } + + this._fileReader = new FileReader(file); // HTML FileReader + this._file = file; + this._size = file.size; + this._highWaterMark = options.highWaterMark || bufferSize; + this._offset = 0; + var self = this; + + this._fileReader.onloadend = function (event) { + var data = event.target.result; + var buf = buffer.from(data); + self.push(buf); + }; + + this._fileReader.onerror = function (error) { + self.emit('error', error); + }; +} +util.inherits(BrowserFileReadStream, stream.Readable); + +BrowserFileReadStream.prototype._read = function() { + if (this._offset >= this._size) { + this.push(null); + } else { + var end = this._offset + this._highWaterMark; + var slice = this._file.slice(this._offset, end); + this._fileReader.readAsArrayBuffer(slice); + this._offset = end; + } +}; + +module.exports = BrowserFileReadStream; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/streams/bufferstream.js b/node_modules/azure-storage/lib/common/streams/bufferstream.js new file mode 100644 index 000000000..c1df94661 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/bufferstream.js @@ -0,0 +1,50 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var stream = require('stream'); +var util = require('util'); + +function BufferStream(buffer, options) { + stream.Readable.call(this, options); + + this._buffer = buffer; + this._offset = 0; + this._chunkSize = 4 * 1024 * 1024; + this._bufferSize = buffer.length; +} + +util.inherits(BufferStream, stream.Readable); + +BufferStream.prototype._read = function () { + while (this.push(this._readNextChunk())) { + continue; + } +}; + +BufferStream.prototype._readNextChunk = function () { + var data = null; + + if (this._offset < this._bufferSize) { + var end = this._offset + this._chunkSize; + end = end > this._bufferSize ? this._bufferSize : end; + data = this._buffer.slice(this._offset, end); + this._offset = end; + } + + return data; +}; + +module.exports = BufferStream; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/streams/chunkallocator.js b/node_modules/azure-storage/lib/common/streams/chunkallocator.js new file mode 100644 index 000000000..1d5e2b48e --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/chunkallocator.js @@ -0,0 +1,128 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// +/** +* Chunked memory pool allocator. +* It could dramatically reduce the memory usage. +* However, it can't dramatically reduce the CPU time since GC in v8 is very efficient. +*/ +function ChunkAllocator(chunkSize, maxCount) { + // Track the unused buffers and number of used buffers + this._pool = []; + this._inuse = 0; + + // Buffer size + this._chunkSize = chunkSize; + + // If total memory is larger than this._chunkSize * this._maxCount, the buffer pool is not used. + this._maxCount = maxCount || 10; + + // Immediately add a buffer to the pool. + this._extendMemoryPool(); +} + +/** +* Synchronously require a buffer +* Caller should be aware of that the content of buffer is random since the Buffer.fill is Time-consumed opreation. +*/ +ChunkAllocator.prototype.getBuffer = function(size) { + var buffer = this._getBufferFromPool(size); + if (buffer === null) { + // Either the total memory is larger than this._chunkSize * this._maxCount + // Or, the size does not match the chunk size of the pool + buffer = new Buffer(size); + } + + this._inuse++; + return buffer; +}; + +/** +* Get buffer from the current memory pool. +*/ +ChunkAllocator.prototype._getBufferFromPool = function(size) { + // Return null if the given size does not match the chunk size of the buffer pool. + if(size !== this._chunkSize) { + return null; + } + + // Extend the memory pool if it is empty. + if(this._pool.length === 0) { + this._extendMemoryPool(); + } + + // If the pool is not empty, return a buffer. + if(this._pool.length !== 0) { + return this._pool.pop(); + } else { + return null; + } +}; + +/** +* Extend the memory pool if the maximum size has not been reached. +*/ +ChunkAllocator.prototype._extendMemoryPool = function() { + var total = this._pool.length + this._inuse; + + // If the total is larger than the max, do not allocate more memory. + if(total >= this._maxCount) return; + + // Calculate the new number of buffers, equal to the total*2 bounded by 1 and the maxCount + var nextSize = Math.min(total * 2, this._maxCount) || 1; + + // Add more buffers. + var increment = nextSize - total; + for(var i = 0; i < increment; i++) { + var buffer = new Buffer(this._chunkSize); + this._pool.push(buffer); + } +}; + +/** +* Release the buffer. +*/ +ChunkAllocator.prototype.releaseBuffer = function(buffer) { + if(buffer.length !== this._chunkSize) { + // Directly delete the buffer if bufferSize is invalid and wait for GC. + buffer = null; + return; + } + + // Add the buffer to the pool if it is not full, otherwise delete it + if (this._pool.length < this._maxCount) { + this._pool.push(buffer); + } else { + buffer = null; + } + + // Decrement _inuse + this._inuse--; + + // _inuse could be below zero if a buffer is released which was not returned by getBuffer + if(this._inuse < 0) { + this._inuse = 0; + } +}; + +/** +* Destroy ChunkAllocator. +*/ +ChunkAllocator.prototype.destroy = function() { + this._pool = []; + this._inuse = 0; +}; + +module.exports = ChunkAllocator; diff --git a/node_modules/azure-storage/lib/common/streams/chunkstream.js b/node_modules/azure-storage/lib/common/streams/chunkstream.js new file mode 100644 index 000000000..3475aa3f4 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/chunkstream.js @@ -0,0 +1,321 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var stream = require('stream'); +var util = require('util'); + +var azureutil = require('../util/util'); +var Md5Wrapper = require('../md5-wrapper'); +var Constants = require('../util/constants'); +var bufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + +/** +* Chunk stream +* 1. Calculate md5 +* 2. Track reading offset +* 3. Work with customize memory allocator +* 4. Buffer data from stream. +* @param {object} options stream.Readable options +*/ +function ChunkStream(options) { + stream.Stream.call(this); + this.writable = this.readable = true; + + if (!options) { + options = {}; + } + + this._highWaterMark = options.highWaterMark || bufferSize; + + this._paused = undefined; //True/false is the external status from users. + + this._isStreamOpened = false; + this._offset = 0; + this._allocator = options.allocator; + this._streamEnded = false; + this._md5hash = null; + this._buffer = null; + this._internalBufferSize = 0; + this._outputLengthLimit = 0; + this._md5sum = undefined; + + if (options.calcContentMd5) { + this._md5hash = new Md5Wrapper().createMd5Hash(); + } +} + +util.inherits(ChunkStream, stream.Stream); + +/** +* Set the memory allocator. +*/ +ChunkStream.prototype.setMemoryAllocator = function(allocator) { + this._allocator = allocator; +}; + +/** +* Set the output length. +*/ +ChunkStream.prototype.setOutputLength = function(length) { + if (length) { + this._outputLengthLimit = length; + } +}; + +/** +* Internal stream ended +*/ +ChunkStream.prototype.end = function (chunk, encoding, cb) { + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk) { + this.write(chunk, encoding); + } + + this._streamEnded = true; + this._flushInternalBuffer(); + + if (cb) { + this.once('end', cb); + } + + this.emit('end'); +}; + +ChunkStream.prototype.finish = function () { + this.emit('finish'); + + this.destroy(); +}; + +ChunkStream.prototype.error = function () { + this.emit('error'); + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function () { + this.writable = this.readable = false; + + if (this._allocator && azureutil.objectIsFunction(this._allocator.destroy)) { + this._allocator.destroy(); + } + + this.emit('close'); +}; + +ChunkStream.prototype.stop = function () { + this.destroy(); + this._streamEnded = true; + this.emit('end'); +}; + +/** +* Add event listener +*/ +ChunkStream.prototype.write = function (chunk, encoding) { + if (!this._isStreamOpened) { + this._isStreamOpened = true; + } + + this._buildChunk(chunk, encoding); + + return !this._paused; +}; + +/** +* Buffer the data into a chunk and emit it +*/ +ChunkStream.prototype._buildChunk = function (data) { + if (typeof data == 'string') { + data = new Buffer(data); + } + var dataSize = data.length; + var dataOffset = 0; + do { + var buffer = null; + var targetSize = this._internalBufferSize + dataSize; + + if (targetSize < this._highWaterMark) { + // add the data to the internal buffer and return as it is not yet full + this._copyToInternalBuffer(data, dataOffset, data.length); + return; + } else if (targetSize == this._highWaterMark){ + var canReleaseInnerStreamBuffer = this._stream && this._stream._allocator && this._stream._allocator.releaseBuffer; + if(this._internalBufferSize === 0 && data.length === this._highWaterMark && !canReleaseInnerStreamBuffer) { + // set the buffer to the data passed in to avoid creating a new buffer + buffer = data; + } else { + // add the data to the internal buffer and pop that buffer + this._copyToInternalBuffer(data, dataOffset, data.length); + buffer = this._popInternalBuffer(); + } + dataSize = 0; + } else { + // add data to the internal buffer until its full, then return it + // set the dataSize parameter so that additional data is not lost + var copySize = this._highWaterMark - this._internalBufferSize; + this._copyToInternalBuffer(data, dataOffset, dataOffset + copySize); + dataSize -= copySize; + dataOffset += copySize; + buffer = this._popInternalBuffer(); + } + this._emitBufferData(buffer); + } while(dataSize > 0); +}; + +/** +* Emit the buffer +*/ +ChunkStream.prototype._emitBufferData = function(buffer) { + var newOffset = this._offset + buffer.length; + var range = { + start : this._offset, + end : newOffset - 1, + size : buffer.length + }; + + this._offset = newOffset; + + if (this._outputLengthLimit > 0) { + // When the start postion is larger than the limit, no data will be consumed though there is an event to be emitted. + // So the buffer should not be calculated. + if (range.start <= this._outputLengthLimit) { + if (this._offset > this._outputLengthLimit) { + // Don't use negative end parameter which means the index starting from the end of the buffer + // to be compatible with node 0.8. + buffer = buffer.slice(0, buffer.length - (this._offset - this._outputLengthLimit)); + } + if (this._md5hash) { + this._md5hash.update(buffer); + } + } + } else if (this._md5hash) { + this._md5hash.update(buffer); + } + + this.emit('data', buffer, range); +}; + +/** +* Copy data into internal buffer +*/ +ChunkStream.prototype._copyToInternalBuffer = function(data, start, end) { + if(start === undefined) start = 0; + if(end === undefined) end = data.length; + if (!this._buffer) { + this._buffer = this._allocateNewBuffer(); + this._internalBufferSize = 0; + } + var copied = data.copy(this._buffer, this._internalBufferSize, start, end); + this._internalBufferSize += copied; + + if (this._stream && this._stream._allocator && this._stream._allocator.releaseBuffer) { + this._stream._allocator.releaseBuffer(data); + } + + if(copied != (end - start)) { + throw new Error('Can not copy entire data to buffer'); + } +}; + +/** +* Flush internal buffer +*/ +ChunkStream.prototype._flushInternalBuffer = function() { + var buffer = this._popInternalBuffer(); + if (buffer) { + this._emitBufferData(buffer); + } +}; + +/** +* Pop internal buffer +*/ +ChunkStream.prototype._popInternalBuffer = function () { + var buf = null; + if (!this._buffer || this._internalBufferSize === 0) { + buf = null; + } else if(this._internalBufferSize == this._highWaterMark) { + buf = this._buffer; + } else { + buf = this._buffer.slice(0, this._internalBufferSize); + } + + this._buffer = null; + this._internalBufferSize = 0; + + return buf; +}; + +/** +* Allocate a buffer +*/ +ChunkStream.prototype._allocateNewBuffer = function() { + var size = this._highWaterMark; + if(this._allocator && azureutil.objectIsFunction(this._allocator.getBuffer)) { + return this._allocator.getBuffer(size); + } else { + var buffer = new Buffer(size); + return buffer; + } +}; + +/** +* Get file content md5 when read completely. +*/ +ChunkStream.prototype.getContentMd5 = function(encoding) { + if (!encoding) encoding = 'base64'; + if(!this._md5hash) { + throw new Error('Can\'t get content md5, please set the calcContentMd5 option for FileReadStream.'); + } else { + if (this._streamEnded) { + if (!this._md5sum) { + this._md5sum = this._md5hash.digest(encoding); + } + return this._md5sum; + } else { + throw new Error('Stream has not ended.'); + } + } +}; + +/** +* Pause chunk stream +*/ +ChunkStream.prototype.pause = function() { + this._paused = true; +}; + +/** +* Resume read stream +*/ +ChunkStream.prototype.resume = function() { + if (this._paused) { + this._paused = false; + + this.emit('drain'); + } +}; + +module.exports = ChunkStream; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js b/node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js new file mode 100644 index 000000000..af3727158 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js @@ -0,0 +1,103 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var ChunkStream = require('./chunkstream'); +var EventEmitter = require('events').EventEmitter; +var util = require('util'); +var azureutil = require('./../util/util'); + +/** +* Chunk stream +* 1. Calculate md5 +* 2. Track reading offset +* 3. Work with customize memory allocator +* 4. Buffer data from stream. +* @param {object} options stream.Readable options +*/ +function ChunkStreamWithStream(stream, options) { + ChunkStream.call(this, options); + + stream.pause(); // Pause stream and wait for data listener. It's useful for node v0.8 + this._stream = stream; + this._stream.on('end', this.end.bind(this)); // Should catch the end event for node v0.8 +} + +util.inherits(ChunkStreamWithStream, ChunkStream); + +/** +* Add event listener +*/ +ChunkStreamWithStream.prototype.on = function(event, listener) { + if(event === 'end' && this._streamEnded) { + listener(); //Directly call the end event when stream already ended + } else { + EventEmitter.prototype.on.call(this, event, listener); + } + + if (event === 'data') { + if (!this._isStreamOpened) { + this._isStreamOpened = true; + this._stream.on('data', this._buildChunk.bind(this)); + } + if (this._paused === undefined) { + this._stream.resume(); + } + } + + return this; +}; + +/** +* Stop stream from external +*/ +ChunkStreamWithStream.prototype.stop = function (chunk, encoding, cb) { + if (azureutil.objectIsFunction(this._stream.destroy)) { + this._stream.destroy(); + } else { + this.pause(); + } + ChunkStream.prototype.end.call(this, chunk, encoding, cb); +}; + +/** +* Pause chunk stream +*/ +ChunkStreamWithStream.prototype.pause = function () { + ChunkStream.prototype.pause.call(this); + + this._stream.pause(); +}; + +/** +* Resume read stream +*/ +ChunkStreamWithStream.prototype.resume = function() { + ChunkStream.prototype.resume.call(this); + + this._stream.resume(); +}; + +ChunkStreamWithStream.prototype.finish = function () { + ChunkStream.prototype.finish.call(this); + this._stream.emit.call(this._stream, 'finish'); +}; + +ChunkStreamWithStream.prototype.destroy = function () { + ChunkStream.prototype.destroy.call(this); + this._stream.emit.call(this._stream, 'close'); +}; + +module.exports = ChunkStreamWithStream; diff --git a/node_modules/azure-storage/lib/common/streams/filereadstream.js b/node_modules/azure-storage/lib/common/streams/filereadstream.js new file mode 100644 index 000000000..2b32bc046 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/filereadstream.js @@ -0,0 +1,261 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var stream = require('stream'); +var util = require('util'); +var fs = require('fs'); +var validator = require('validator'); + +var Md5Wrapper = require('../md5-wrapper'); +var Constants = require('../util/constants'); +var bufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + +var EventEmitter = require('events').EventEmitter; + +/** +* File read stream +* 1. Calculate md5 +* 2. Track reading offset +* 3. Work with customize memory allocator +* 4. Buffer data from stream. +* @param {object} options stream.Readable options +*/ +function FileReadStream(path, options) { + stream.Stream.call(this); + this.readable = true; + + if(!options) { + options = {}; + } + + this._destroyed = false; + this._streamEnded = false; + this._fd = null; + this._fileName = undefined; + this._highWaterMark = options.highWaterMark || bufferSize; + this._offset = 0; + this._paused = undefined; + this._allocator = options.allocator; + this._fileName = path; + + this._md5hash = null; + this._md5sum = undefined; + + if (options.calcContentMd5) { + this._md5hash = new Md5Wrapper().createMd5Hash(); + } + + this._open(); +} + +util.inherits(FileReadStream, stream.Stream); + +/** +* Open file +*/ +FileReadStream.prototype._open = function () { + var flags = 'r'; + var self = this; + fs.open(this._fileName, flags, function(error, fd) { + if (error) { + self.emit('error', error); + } else { + self._fd = fd; + self.emit('open', fd); + } + }); +}; + +/** +* Add event listener +*/ +FileReadStream.prototype.on = function(event, listener) { + if (event === 'data' && this._paused === undefined) { + this._paused = false; + this._emitData(); + } + + return EventEmitter.prototype.on.call(this, event, listener); +}; + +/** +* Set memory allocator +*/ +FileReadStream.prototype.setMemoryAllocator = function(allocator) { + this._allocator = allocator; +}; + +/** +* Get buffer +*/ +FileReadStream.prototype._getBuffer = function(size) { + if(this._allocator && this._allocator.getBuffer) { + return this._allocator.getBuffer(size); + } else { + var buffer = new Buffer(size); + return buffer; + } +}; + +/** +* Release buffer +*/ +FileReadStream.prototype._releaseBuffer = function(buffer) { + if(this._allocator && this._allocator.releaseBuffer) { + this._allocator.releaseBuffer(buffer); + } +}; + +/** +* Emit the data from file +*/ +FileReadStream.prototype._emitData = function() { + var self = this; + if(!this._fd) { + this.once('open', function() { + self._emitData(); + }); + return; + } + + if (this._paused || this._streamEnded) { + return; + } + var buffer = this._getBuffer(this._highWaterMark); + fs.read(this._fd, buffer, 0, this._highWaterMark, this._offset, function(error, bytesRead, readBuffer) { + if (error) { + self.emit('error', error); + return; + } + + if(bytesRead === 0) { + if(!self._streamEnded) { + self._streamEnded = true; + self.emit('end'); + } + return; + } + + var range = { + start : self._offset, + end : self._offset + bytesRead - 1, + size : bytesRead + }; + + var data; + if(bytesRead == self._highWaterMark) { + data = readBuffer; + } else { + data = readBuffer.slice(0, bytesRead); + //Release the current buffer since we created a new one + self._releaseBuffer(readBuffer); + } + + if(self._md5hash) { + self._md5hash.update(data); + } + + self.emit('data', data, range); + + // cleanup + self._offset += bytesRead; + buffer = readBuffer = data = null; + self._emitData(); + }); +}; + +/** +* Get file content md5 when read completely. +*/ +FileReadStream.prototype.getContentMd5 = function(encoding) { + if (!encoding) encoding = 'base64'; + if(!this._md5hash) { + throw new Error('Can\'t get content md5, please set the calcContentMd5 option for FileReadStream.'); + } else { + if (this._streamEnded) { + if (!this._md5sum) { + this._md5sum = this._md5hash.digest(encoding); + } + return this._md5sum; + } else { + throw new Error('FileReadStream has not ended.'); + } + } +}; + +/** +* Pause chunk stream +*/ +FileReadStream.prototype.pause = function() { + this._paused = true; +}; + +/** +* Resume read stream +*/ +FileReadStream.prototype.resume = function() { + var previousState = this._paused; + if (this._paused) { + this._paused = false; + + if(previousState === true) { + //Only start to emit data when it's in pause state + this._emitData(); + } + } +}; + +FileReadStream.prototype.finish = function () { + this.destroy(); +}; + +FileReadStream.prototype.destroy = function () { + if (this._destroyed) { + return; + } + + var self = this; + this.readable = false; + + function close(fd) { + fs.close(fd || self._fd, function(err) { + if (err) { + self.emit('error', err); + } + else { + self.emit('close'); + } + }); + self._fd = null; + self._destroyed = true; + } + + // when the stream is closed immediately after creating it + if (!validator.isInt(this._fd)) { + this.once('open', close); + return; + } + + close(); +}; + +FileReadStream.prototype.stop = function () { + this.destroy(); + this._streamEnded = true; + this.emit('end'); +}; + +module.exports = FileReadStream; diff --git a/node_modules/azure-storage/lib/common/streams/rangestream.js b/node_modules/azure-storage/lib/common/streams/rangestream.js new file mode 100644 index 000000000..130a4bde3 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/rangestream.js @@ -0,0 +1,293 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var azureCommon = require('./../common.core'); +var azureutil = azureCommon.util; +var Constants = require('./../util/constants'); +var EventEmitter = require('events').EventEmitter; + +/** +* Range stream +*/ +function RangeStream(serviceClient, container, blob, options) { + this.serviceClient = serviceClient; + this._emitter = new EventEmitter(); + this._paused = false; + this._emittedAll = false; + this._emittedRangeIndex = 0; + this._rangelist = []; + this._resourcePath = []; + this._isEmitting = false; + this._rangeStreamEnded = false; + this._lengthHeader = Constants.HeaderConstants.CONTENT_LENGTH; + this._minRangeSize = Constants.BlobConstants.MIN_WRITE_PAGE_SIZE_IN_BYTES; + this._maxRangeSize = Constants.BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES; + if (options.rangeStart) { + this._startOffset = options.rangeStart; + } else { + this._startOffset = 0; + } + this._dataOffset = this._startOffset; + if (options.rangeEnd) { + this._endOffset = options.rangeEnd; + } else { + this._endOffset = Number.MAX_VALUE; + } + if (container) { + this._resourcePath.push(container); + } + if (blob) { + this._resourcePath.push(blob); + } +} + +/** +* Get range list +*/ +RangeStream.prototype.list = function (options, callback) { + var start = this._startOffset; + var end; + var singleRangeSize = Constants.BlobConstants.MAX_SINGLE_GET_PAGE_RANGE_SIZE; + + if (this._listFunc === undefined) { + // the default function puts the whole blob into a single list item + this._listFunc = this._defaultListFunc; + end = this._endOffset; + } else { + end = Math.min(this._startOffset + singleRangeSize - 1, this._endOffset); + } + options.rangeStart = start; + if (end != Number.MAX_VALUE) { + options.rangeEnd = end; + } + + var self = this; + var onList = function (error, ranges, response) { + if (error) { + callback(error); + } else { + if (self._rangeStreamEnded) { + return; + } + + var totalSize = parseInt(response.headers[self._lengthHeader], 10); + var endOffset = Math.min(totalSize - 1, self._endOffset); + var rangeEnd = Math.min(end, endOffset); + + if (!ranges.length) { + // convert single object to range + // start >= end means there is no valid regions + ranges.push({ start : start, end : rangeEnd, dataSize: 0 }); + } else if (ranges[ranges.length - 1].end !== rangeEnd) { + // don't forget the zero chunk at the end of range + ranges.push({ start : ranges[ranges.length - 1].end + 1, end : rangeEnd, dataSize: 0 }); + } + + if (end >= endOffset) { + self._rangeStreamEnded = true; + } + self.resizeAndSaveRanges(ranges); + self._startOffset += singleRangeSize; + self._emitRange(); + + // This is only valid when listing pages because when listing with the default function, the "endOffset" will always equal to or greater than the "end". + if (end < endOffset && !self._rangeStreamEnded) { + process.nextTick(function () { + ranges = null; + self.list(options, callback); + self = null; + }); + } + } + }; + + var callArguments = Array.prototype.slice.call(this._resourcePath); + callArguments.push(options); + callArguments.push(onList); + this._listFunc.apply(this.serviceClient, callArguments); +}; + +/** +* Resize regions: +* 1. Merge small pieces into a range no less than this._minRangeSize +* 2. Split large pieces into ranges no more than this._maxRangeSize +*/ +RangeStream.prototype.resizeAndSaveRanges = function (ranges) { + var rangeList = this._rangelist; + var holdingRange = { type : 'range', size : 0, dataSize : 0, start : this._startOffset, end : -1 }; + var readingRange = null; + var rangeSize = 0; + + for (var index = 0; index < ranges.length; index++) { + readingRange = ranges[index]; + rangeSize = readingRange.end - holdingRange.start + 1; + + if (rangeSize < this._minRangeSize) { + // merge fragment ranges + this.mergeRanges(holdingRange, readingRange); + } else { + if (holdingRange.end != -1) { + // save the holding range list and hold the reading range + this.splitAndSaveRanges(holdingRange, rangeList); + holdingRange = readingRange; + } + + if (this._dataOffset != readingRange.start) { + // padding zero for empty range and hold the reading range + this.putZeroRange(this._dataOffset, readingRange.start - 1, rangeList); + holdingRange = readingRange; + } else if (holdingRange.end == -1) { + // if holdingRange is never set, it means readingRange exceeds MIN_WRITE_FILE_SIZE_IN_BYTES + this.splitAndSaveRanges(readingRange, rangeList); + // reading range has been saved, offset the holding start position for calculating the range size in next loop + holdingRange.start = readingRange.end + 1; + } + } + + // If it is the last range, put the holding range into list anyway + if (index == ranges.length - 1 && holdingRange.end > holdingRange.start) { + this.splitAndSaveRanges(holdingRange, rangeList); + } + + this._dataOffset = readingRange.end + 1; + } +}; + +/** +* Put a zero range into range list +*/ +RangeStream.prototype.putZeroRange = function (startOffset, endOffset, rangeList) { + var zeroDataRange = { type : 'range', size : -1, dataSize : 0, start : startOffset, end : endOffset }; + this.splitAndSaveRanges(zeroDataRange, rangeList); +}; + +/** +* Merge small ranges +*/ +RangeStream.prototype.mergeRanges = function (holdingRange, readingRange) { + holdingRange.size = readingRange.end - holdingRange.start + 1; + holdingRange.dataSize += readingRange.dataSize; + holdingRange.end = readingRange.end; + return holdingRange; +}; + +/** +* Split range into small pieces with maximum _maxRangeSize and minimum _minRangeSize size. +* For example, [0, 10G - 1] => [0, 4MB - 1], [4MB, 8MB - 1] ... [10GB - 4MB, 10GB - 1] +*/ +RangeStream.prototype.splitAndSaveRanges = function (range, rangeList) { + var rangeSize = range.end - range.start + 1; + var offset = range.start; + var limitedSize = 0; + + while (rangeSize > 0) { + var newRange = { type : 'range', size : 0, dataSize : 0, start : -1, end : -1 }; + limitedSize = Math.min(rangeSize, this._maxRangeSize); + newRange.start = offset; + newRange.size = limitedSize; + if (range.dataSize === 0) { + newRange.dataSize = 0; + } else { + newRange.dataSize = limitedSize; + } + offset += limitedSize; + newRange.end = offset - 1; + rangeList.push(newRange); + rangeSize -= limitedSize; + } +}; + +/** +* Emit a range +*/ +RangeStream.prototype._emitRange = function () { + if (this._paused || this._emittedAll || this._isEmitting) return; + this._isEmitting = true; + try { + for (; this._emittedRangeIndex < this._rangelist.length; this._emittedRangeIndex++) { + if (this._paused) { + return; + } + var range = this._rangelist[this._emittedRangeIndex]; + this._emitter.emit('range', range); + this._rangelist[this._emittedRangeIndex] = null; + } + + if (this._rangeStreamEnded) { + this._rangelist = null; + this._emittedAll = true; + this._emitter.emit('end'); + } + } finally { + this._isEmitting = false; + } +}; + +/** +* The Default list function which puts the whole blob into one range. +*/ +RangeStream.prototype._defaultListFunc = function (container, blob, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + this.getBlobProperties(container, blob, options, function (error, result, response) { + if (error) { + callback(error); + } else { + var range = [{}]; + range[0].start = options.rangeStart ? Math.max(options.rangeStart, 0) : 0; + range[0].end = options.rangeEnd ? Math.min(options.rangeEnd, result.contentLength - 1) : result.contentLength - 1; + range[0].size = range[0].end - range[0].start + 1; + range[0].dataSize = range[0].size; + callback(error, range, response); + } + }); +}; + +/** +* Add event listener +*/ +RangeStream.prototype.on = function (event, listener) { + this._emitter.on(event, listener); +}; + +/** +* Pause the stream +*/ +RangeStream.prototype.pause = function () { + this._paused = true; +}; + +/** +* Resume the stream +*/ +RangeStream.prototype.resume = function () { + this._paused = false; + if (!this._isEmitting) { + this._emitRange(); + } +}; + +/** +* Stop the stream +*/ +RangeStream.prototype.stop = function () { + this.pause(); + this._emittedAll = true; + this._emitter.emit('end'); +}; + +module.exports = RangeStream; diff --git a/node_modules/azure-storage/lib/common/streams/readablefs.js b/node_modules/azure-storage/lib/common/streams/readablefs.js new file mode 100644 index 000000000..933336562 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/readablefs.js @@ -0,0 +1,32 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var rs = require('readable-stream').Readable; +var fs = require('fs'); + +/* +* As far as streams support goes, we can get the node 0.10 stream API in node 0.8. +* Use the readable-stream module (https://www.npmjs.org/package/readable-stream) which is +* essentially a copy of the stream modules from core node 0.10 and it just works on both 0.8 and 0.10. +*/ + +exports.createReadStream = function(path, options) { + var stream = fs.createReadStream(path, options); + if (/^v0\.8\./.test(process.version)) { + stream = rs().wrap(stream); + } + return stream; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/streams/speedsummary.js b/node_modules/azure-storage/lib/common/streams/speedsummary.js new file mode 100644 index 000000000..9d724f488 --- /dev/null +++ b/node_modules/azure-storage/lib/common/streams/speedsummary.js @@ -0,0 +1,205 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var util = require('util'); +var azureutil = require('../util/util'); + +/** +* Blob upload/download speed summary +*/ +function SpeedSummary (name) { + this.name = name; + this._startTime = Date.now(); + this._timeWindowInSeconds = 10; + this._timeWindow = this._timeWindowInSeconds * 1000; + this._totalWindowSize = 0; + this._speedTracks = new Array(this._timeWindowInSeconds); + this._speedTrackPtr = 0; + this.totalSize = undefined; + this.completeSize = 0; +} + +/** +* Convert the size to human readable size +*/ +function toHumanReadableSize(size, len) { + if(!size) return '0B'; + if (!len || len <= 0) { + len = 2; + } + var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + var i = Math.floor( Math.log(size) / Math.log(1024)); + return (size/Math.pow(1024, i)).toFixed(len) + units[i]; +} + +/** +* Get running seconds +*/ +SpeedSummary.prototype.getElapsedSeconds = function(humanReadable) { + var now = Date.now(); + var seconds = parseInt((now - this._startTime) / 1000, 10); + if (humanReadable !== false) { + var s = parseInt(seconds % 60, 10); + seconds /= 60; + var m = Math.floor(seconds % 60); + seconds /= 60; + var h = Math.floor(seconds); + seconds = util.format('%s:%s:%s', azureutil.zeroPaddingString(h, 2), azureutil.zeroPaddingString(m, 2), azureutil.zeroPaddingString(s, 2)); + } + return seconds; +}; + +/** +* Get complete percentage +* @param {int} len The number of digits after the decimal point. +*/ +SpeedSummary.prototype.getCompletePercent = function(len) { + if (this.totalSize) { + if(!len || len <= 0) { + len = 1; + } + return (this.completeSize * 100 / this.totalSize).toFixed(len); + } else { + if(this.totalSize === 0) { + return 100; + } else { + return 0; + } + } +}; + +/** +* Get average upload/download speed +*/ +SpeedSummary.prototype.getAverageSpeed = function(humanReadable) { + var elapsedTime = this.getElapsedSeconds(false); + return this._getInternalSpeed(this.completeSize, elapsedTime, humanReadable); +}; + +/** +* Get instant speed +*/ +SpeedSummary.prototype.getSpeed = function(humanReadable) { + this._refreshSpeedTracks(); + var elapsedTime = this.getElapsedSeconds(false); + elapsedTime = Math.min(elapsedTime, this._timeWindowInSeconds); + return this._getInternalSpeed(this._totalWindowSize, elapsedTime, humanReadable); +}; + +/** +* Get internal speed +*/ +SpeedSummary.prototype._getInternalSpeed = function(totalSize, elapsedTime, humanReadable) { + if (elapsedTime <= 0) { + elapsedTime = 1; + } + var speed = totalSize / elapsedTime; + if(humanReadable !== false) { + speed = toHumanReadableSize(speed) + '/s'; + } + return speed; +}; + +/** +* Refresh speed tracks +*/ +SpeedSummary.prototype._refreshSpeedTracks = function() { + var now = Date.now(); + var totalSize = 0; + for(var i = 0; i < this._speedTracks.length; i++) { + if(!this._speedTracks[i]) continue; + if(now - this._speedTracks[i].timeStamp <= this._timeWindow) { + totalSize += this._speedTracks[i].size; + } else { + this._speedTracks[i] = null; + } + } + this._totalWindowSize = totalSize; +}; + +/** +* Increment the complete data size +*/ +SpeedSummary.prototype.increment = function(len) { + this.completeSize += len; + this._recordSpeed(len); + return this.completeSize; +}; + +/** +* record complete size into speed tracks +*/ +SpeedSummary.prototype._recordSpeed = function(completeSize) { + var now = Date.now(); + var track = this._speedTracks[this._speedTrackPtr]; + if(track) { + var timeDiff = now - track.timeStamp; + if(timeDiff > this._timeWindow) { + track.timeStamp = now; + track.size = completeSize; + } else if(timeDiff <= 1000) { //1 seconds + track.size += completeSize; + } else { + this._speedTrackPtr = (this._speedTrackPtr + 1) % this._timeWindowInSeconds; + this._recordSpeed(completeSize); + } + } else { + track = {timeStamp : now, size: completeSize}; + this._speedTracks[this._speedTrackPtr] = track; + } +}; + +/** +* Get auto increment function +*/ +SpeedSummary.prototype.getAutoIncrementFunction = function(size) { + var self = this; + return function(error, retValue) { + if(!error) { + var doneSize = 0; + if((!retValue && retValue !== 0) || isNaN(retValue)) { + doneSize = size; + } else { + doneSize = retValue; + } + self.increment(doneSize); + } + }; +}; + +/** +* Get total size +*/ +SpeedSummary.prototype.getTotalSize = function(humanReadable) { + if (humanReadable !== false) { + return toHumanReadableSize(this.totalSize); + } else { + return this.totalSize; + } +}; + +/** +* Get completed data size +*/ +SpeedSummary.prototype.getCompleteSize = function(humanReadable) { + if (humanReadable !== false) { + return toHumanReadableSize(this.completeSize); + } else { + return this.completeSize; + } +}; + +module.exports = SpeedSummary; diff --git a/node_modules/azure-storage/lib/common/util/accesscondition.js b/node_modules/azure-storage/lib/common/util/accesscondition.js new file mode 100644 index 000000000..342621221 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/accesscondition.js @@ -0,0 +1,166 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'AccessCondition'. + +/** +* Defines constants, enums, and utility functions for use with storage access condition. +* @namespace +*/ + +'use strict'; + +exports = module.exports; + +/** +* Constructs an empty access condition. +* +* @return {object} An empty AccessCondition object +*/ +exports.generateEmptyCondition = function () { + return {}; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource does not exist on the service +* +* Setting this access condition modifies the request to include the HTTP If-None-Match conditional header + +* @return {AccessConditions} An AccessCondition object that represents a condition that checks for nonexistence +*/ +exports.generateIfNotExistsCondition = function () { + var accessCondition = {}; + accessCondition.EtagNonMatch = '*'; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource exists on the service +* +* Setting this access condition modifies the request to include the HTTP If-Match conditional header + +* @return {AccessConditions} An AccessCondition object that represents a condition that checks for existence +*/ +exports.generateIfExistsCondition = function () { + var accessCondition = {}; + accessCondition.EtagMatch = '*'; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource's ETag value +* does not match the specified ETag value +* +* Setting this access condition modifies the request to include the HTTP If-None-Match conditional header +* +* @param {string} etag The ETag value to check against the resource's ETag +* @return {AccessConditions} An AccessCondition object that represents the If-None-Match condition +*/ +exports.generateIfNoneMatchCondition = function (etag) { + var accessCondition = {}; + accessCondition.EtagNonMatch = etag; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource's ETag value +* matches the specified ETag value +* +* Setting this access condition modifies the request to include the HTTP If-Match conditional header +* +* @param {string} etag The ETag value to check against the resource's ETag +* @return {AccessConditions} An AccessCondition object that represents the If-Match condition +*/ +exports.generateIfMatchCondition = function (etag) { + var accessCondition = {}; + accessCondition.EtagMatch = etag; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource has been +* modified since the specified time +* +* Setting this access condition modifies the request to include the HTTP If-Modified-Since conditional header +* +* @param {Date|string} time A date object specifying the time since which the resource must have been modified +* @return {AccessConditions} An AccessCondition object that represents the If-Modified-Since condition +*/ +exports.generateIfModifiedSinceCondition = function (time) { + var accessCondition = {}; + accessCondition.DateModifedSince = time; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource has not been +* modified since the specified time +* +* Setting this access condition modifies the request to include the HTTP If-Unmodified-Since conditional header +* +* @param {Date|string} time A date object specifying the time since which the resource must have not been modified +* @return {AccessConditions} An AccessCondition object that represents the If-Unmodified-Since condition +*/ +exports.generateIfNotModifiedSinceCondition = function (time) { + var accessCondition = {}; + accessCondition.DateUnModifiedSince = time; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource's sequence number +* is equal to the specified value +* +* Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-eq conditional header +* +* @param {Number|string} sequenceNumber A date object specifying the time since which the resource must have not been modified +* @return {AccessConditions} An AccessCondition object that represents the If-Unmodified-Since condition +*/ +exports.generateSequenceNumberEqualCondition = function (sequenceNumber) { + var accessCondition = {}; + accessCondition.SequenceNumberEqual = sequenceNumber; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource's sequence number +* is less than the specified value +* +* Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-lt conditional header +* +* @param {Number|string} sequenceNumber A date object specifying the time since which the resource must have not been modified +* @return {AccessConditions} An AccessCondition object that represents the If-Unmodified-Since condition +*/ +exports.generateSequenceNumberLessThanCondition = function (sequenceNumber) { + var accessCondition = {}; + accessCondition.SequenceNumberLessThan = sequenceNumber; + return accessCondition; +}; + +/** +* Constructs an access condition such that an operation will be performed only if the resource's sequence number +* is less than or equal to the specified value +* +* Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-le conditional header +* +* @param {Number|string} sequenceNumber A date object specifying the time since which the resource must have not been modified +* @return {AccessConditions} An AccessCondition object that represents the If-Unmodified-Since condition +*/ +exports.generateSequenceNumberLessThanOrEqualCondition = function (sequenceNumber) { + var accessCondition = {}; + accessCondition.SequenceNumberLessThanOrEqual = sequenceNumber; + return accessCondition; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/constants.js b/node_modules/azure-storage/lib/common/util/constants.js new file mode 100644 index 000000000..3fe628099 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/constants.js @@ -0,0 +1,2536 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'Constants'. +exports = module.exports; + +var storageDnsSuffix = process.env.AZURE_STORAGE_DNS_SUFFIX || 'core.windows.net'; + +/** +* Defines constants. +*/ +var Constants = { + /* + * Specifies the value to use for UserAgent header. + * + * @const + * @type {string} + */ + USER_AGENT_PRODUCT_NAME: 'Azure-Storage', + + /* + * Specifies the value to use for UserAgent header. + * + * @const + * @type {string} + */ + USER_AGENT_PRODUCT_VERSION: '2.8.0', + + /** + * The number of default concurrent requests for parallel operation. + * + * @const + * @type {int} + */ + DEFAULT_PARALLEL_OPERATION_THREAD_COUNT: 5, + + /** + * The value of default socket reuse for batch operation. + * + * @const + * @type {boolean} + */ + DEFAULT_ENABLE_REUSE_SOCKET: true, + + /** + * Constant representing a kilobyte (Non-SI version). + * + * @const + * @type {int} + */ + KB: 1024, + + /** + * Constant representing a megabyte (Non-SI version). + * + * @const + * @type {int} + */ + MB: 1024 * 1024, + + /** + * Constant representing a gigabyte (Non-SI version). + * + * @const + * @type {int} + */ + GB: 1024 * 1024 * 1024, + + /** + * Specifies HTTP. + * + * @const + * @type {string} + */ + HTTP: 'http:', + + /** + * Specifies HTTPS. + * + * @const + * @type {string} + */ + HTTPS: 'https:', + + /** + * Default HTTP port. + * + * @const + * @type {int} + */ + DEFAULT_HTTP_PORT: 80, + + /** + * Default HTTPS port. + * + * @const + * @type {int} + */ + DEFAULT_HTTPS_PORT: 443, + + /** + * Default client request timeout in milliseconds. + * Integer containing the number of milliseconds to wait for a server to send response headers (and start the response body) before aborting the request. + * 2 minutes by default. + * + * @const + * @type {int} + */ + DEFAULT_CLIENT_REQUEST_TIMEOUT_IN_MS: 120000, + + /** + * Marker for atom metadata. + * + * @const + * @type {string} + */ + XML_METADATA_MARKER: '$', + + /** + * Marker for atom value. + * + * @const + * @type {string} + */ + XML_VALUE_MARKER: '_', + + /** + * Defines the service types indicators. + * + * @const + * @enum {string} + */ + ServiceType: { + Blob: 'blob', + Queue: 'queue', + Table: 'table', + File: 'file' + }, + + /** + * Specifies the location used to indicate which location the operation can be performed against. + * + * @const + * @enum {int} + */ + RequestLocationMode: { + PRIMARY_ONLY: 0, + SECONDARY_ONLY: 1, + PRIMARY_OR_SECONDARY: 2 + }, + + /** + * Represents a storage service location. + * + * @const + * @enum {int} + */ + StorageLocation: { + PRIMARY: 0, + SECONDARY: 1 + }, + + /** + * Defines constants for use with account SAS. + */ + AccountSasConstants:{ + /** + * Permission types. + * + * @const + * @enum {string} + */ + Permissions: { + READ: 'r', + ADD: 'a', + CREATE: 'c', + UPDATE: 'u', + PROCESS: 'p', + WRITE: 'w', + DELETE: 'd', + LIST: 'l' + }, + + /** + * Services types. + * + * @const + * @enum {string} + */ + Services: { + BLOB: 'b', + FILE: 'f', + QUEUE: 'q', + TABLE: 't' + }, + + /** + * Resources types. + * + * @const + * @enum {string} + */ + Resources: { + SERVICE: 's', + CONTAINER: 'c', + OBJECT: 'o' + }, + + /** + * Protocols types. + * + * @const + * @enum {string} + */ + Protocols: { + HTTPSONLY: 'https', + HTTPSORHTTP: 'https,http' + } + }, + + /** + * Defines constants for use with shared access policies. + */ + AclConstants: { + /** + * XML element for an access policy. + * + * @const + * @type {string} + */ + ACCESS_POLICY: 'AccessPolicy', + + /** + * XML element for the end time of an access policy. + * + * @const + * @type {string} + */ + EXPIRY: 'Expiry', + + /** + * XML attribute for IDs. + * + * @const + * @type {string} + */ + ID: 'Id', + + /** + * XML element for the permission of an access policy. + * + * @const + * @type {string} + */ + PERMISSION: 'Permission', + + /** + * XML element for a signed identifier. + * + * @const + * @type {string} + */ + SIGNED_IDENTIFIER_ELEMENT: 'SignedIdentifier', + + /** + * XML element for signed identifiers. + * + * @const + * @type {string} + */ + SIGNED_IDENTIFIERS_ELEMENT: 'SignedIdentifiers', + + /** + * XML element for the start time of an access policy. + * + * @const + * @type {string} + */ + START: 'Start' + }, + + /** + * Defines constants for use with service properties. + */ + ServicePropertiesConstants: { + /** + * XML element for storage service properties. + * + * @const + * @type {string} + */ + STORAGE_SERVICE_PROPERTIES_ELEMENT: 'StorageServiceProperties', + + /** + * Default analytics version to send for logging, hour metrics and minute metrics. + * + * @const + * @type {string} + */ + DEFAULT_ANALYTICS_VERSION: '1.0', + + /** + * XML element for logging. + * + * @const + * @type {string} + */ + LOGGING_ELEMENT: 'Logging', + + /** + * XML element for version. + * + * @const + * @type {string} + */ + VERSION_ELEMENT: 'Version', + + /** + * XML element for delete. + * + * @const + * @type {string} + */ + DELETE_ELEMENT: 'Delete', + + /** + * XML element for read. + * + * @const + * @type {string} + */ + READ_ELEMENT: 'Read', + + /** + * XML element for write. + * + * @const + * @type {string} + */ + WRITE_ELEMENT: 'Write', + + /** + * XML element for retention policy. + * + * @const + * @type {string} + */ + RETENTION_POLICY_ELEMENT: 'RetentionPolicy', + + /** + * XML element for enabled. + * + * @const + * @type {string} + */ + ENABLED_ELEMENT: 'Enabled', + + /** + * XML element for days. + * + * @const + * @type {string} + */ + DAYS_ELEMENT: 'Days', + + /** + * XML element for HourMetrics. + * + * @const + * @type {string} + */ + HOUR_METRICS_ELEMENT: 'HourMetrics', + + /** + * XML element for MinuteMetrics. + * + * @const + * @type {string} + */ + MINUTE_METRICS_ELEMENT: 'MinuteMetrics', + + /** + * XML element for Cors. + * + * @const + * @type {string} + */ + CORS_ELEMENT: 'Cors', + + /** + * XML element for CorsRule. + * + * @const + * @type {string} + */ + CORS_RULE_ELEMENT: 'CorsRule', + + /** + * XML element for AllowedOrigins. + * + * @const + * @type {string} + */ + ALLOWED_ORIGINS_ELEMENT: 'AllowedOrigins', + + /** + * XML element for AllowedMethods. + * + * @const + * @type {string} + */ + ALLOWED_METHODS_ELEMENT: 'AllowedMethods', + + /** + * XML element for MaxAgeInSeconds. + * + * @const + * @type {string} + */ + MAX_AGE_IN_SECONDS_ELEMENT: 'MaxAgeInSeconds', + + /** + * XML element for ExposedHeaders. + * + * @const + * @type {string} + */ + EXPOSED_HEADERS_ELEMENT: 'ExposedHeaders', + + /** + * XML element for AllowedHeaders. + * + * @const + * @type {string} + */ + ALLOWED_HEADERS_ELEMENT: 'AllowedHeaders', + + /** + * XML element for IncludeAPIs. + * + * @const + * @type {string} + */ + INCLUDE_APIS_ELEMENT: 'IncludeAPIs', + + /** + * XML element for DefaultServiceVersion. + * + * @const + * @type {string} + */ + DEFAULT_SERVICE_VERSION_ELEMENT: 'DefaultServiceVersion', + + /** + * XML element for DeleteRetentionPolicy. + * + * @const + * @type {string} + */ + DEFAULT_DELETE_RETENTION_POLICY_ELEMENT: 'DeleteRetentionPolicy' + }, + + /** + * Defines constants for use with blob operations. + */ + BlobConstants: { + /** + * XML element for the latest. + * + * @const + * @type {string} + */ + LATEST_ELEMENT: 'Latest', + + /** + * XML element for uncommitted blocks. + * + * @const + * @type {string} + */ + UNCOMMITTED_ELEMENT: 'Uncommitted', + + /** + * XML element for a block list. + * + * @const + * @type {string} + */ + BLOCK_LIST_ELEMENT: 'BlockList', + + /** + * XML element for committed blocks. + * + * @const + * @type {string} + */ + COMMITTED_ELEMENT: 'Committed', + + /** + * The default write page size, in bytes, used by blob streams. + * + * @const + * @type {int} + */ + DEFAULT_WRITE_PAGE_SIZE_IN_BYTES: 4 * 1024 * 1024, + + /** + * The minimum write page size, in bytes, used by blob streams. + * + * @const + * @type {int} + */ + MIN_WRITE_PAGE_SIZE_IN_BYTES: 2 * 1024 * 1024, + + /** + * The default maximum size, in bytes, of a blob before it must be separated into blocks. + * + * @const + * @type {int} + */ + DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES: 32 * 1024 * 1024, + + /** + * The default write block size, in bytes, used by blob streams. + * + * @const + * @type {int} + */ + DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES: 4 * 1024 * 1024, + + /** + * The default critical memory limitation in 32bit Node.js environment, in bytes. + * + * @const + * @type {int} + */ + DEFAULT_CRITICAL_MEMORY_LIMITATION_32_IN_BYTES: 800 * 1024 * 1024, + + /** + * The default critical memory limitation in browser environment, in bytes. + * + * @const + * @type {int} + */ + DEFAULT_CRITICAL_MEMORY_LIMITATION_BROWSER_IN_BYTES: 1 * 1024 * 1024 * 1024, + + /** + * The default minimum memory usage in browser environment, in bytes. + * + * @const + * @type {int} + */ + DEFAULT_MINIMUM_MEMORY_USAGE_BROWSER_IN_BYTES: 4 * 1024 * 1024, + + /** + * The maximum size of a single block of block blob. + * + * @const + * @type {int} + */ + MAX_BLOCK_BLOB_BLOCK_SIZE: 100 * 1024 * 1024, + + /** + * The maximum size of a single block of append blob. + * + * @const + * @type {int} + */ + MAX_APPEND_BLOB_BLOCK_SIZE: 4 * 1024 * 1024, + + /** + * The maximum size, in bytes, of a blob before it must be separated into blocks. + * + * @const + * @type {int} + */ + MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES: 64 * 1024 * 1024, + + /** + * The maximum range get size when requesting for a contentMD5. + * + * @const + * @type {int} + */ + MAX_RANGE_GET_SIZE_WITH_MD5 : 4 * 1024 * 1024, + + /** + * The maximum page range size for a page update operation. + * + * @const + * @type {int} + */ + MAX_UPDATE_PAGE_SIZE : 4 * 1024 * 1024, + + /** + * The maximum buffer size for writing a stream buffer. + * + * @const + * @type {int} + */ + MAX_QUEUED_WRITE_DISK_BUFFER_SIZE : 64 * 1024 * 1024, + + /** + * Max size for single get page range. The max value should be 150MB. + * http://blogs.msdn.com/b/windowsazurestorage/archive/2012/03/26/getting-the-page-ranges-of-a-large-page-blob-in-segments.aspx + * + * @const + * @type {int} + */ + MAX_SINGLE_GET_PAGE_RANGE_SIZE : 37 * 4 * 1024 * 1024, + + /** + * The size of a page, in bytes, in a page blob. + * + * @const + * @type {int} + */ + PAGE_SIZE: 512, + + /** + * Resource types. + * + * @const + * @enum {string} + */ + ResourceTypes: { + CONTAINER: 'c', + BLOB: 'b' + }, + + /** + * List blob types. + * + * @const + * @enum {string} + */ + ListBlobTypes: { + Blob: 'b', + Directory: 'd' + }, + + /** + * Put page write options + * + * @const + * @enum {string} + */ + PageWriteOptions: { + UPDATE: 'update', + CLEAR: 'clear' + }, + + /** + * Blob types + * + * @const + * @enum {string} + */ + BlobTypes: { + BLOCK: 'BlockBlob', + PAGE: 'PageBlob', + APPEND: 'AppendBlob' + }, + + /** + * Blob lease constants + * + * @const + * @enum {string} + */ + LeaseOperation: { + ACQUIRE: 'acquire', + RENEW: 'renew', + CHANGE: 'change', + RELEASE: 'release', + BREAK: 'break' + } + }, + + /** + * Defines constants for use with file operations. + */ + FileConstants: { + /** + * The default write size, in bytes, used by file streams. + * + * @const + * @type {int} + */ + DEFAULT_WRITE_SIZE_IN_BYTES: 4 * 1024 * 1024, + + /** + * The maximum range size when requesting for a contentMD5. + * + * @const + * @type {int} + */ + MAX_RANGE_GET_SIZE_WITH_MD5 : 4 * 1024 * 1024, + + /** + * The maximum range size for a file update operation. + * + * @const + * @type {int} + */ + MAX_UPDATE_FILE_SIZE : 4 * 1024 * 1024, + + /** + * The default minimum size, in bytes, of a file when it must be separated into ranges. + * + * @const + * @type {int} + */ + DEFAULT_SINGLE_FILE_GET_THRESHOLD_IN_BYTES: 32 * 1024 * 1024, + + /** + * The minimum write file size, in bytes, used by file streams. + * + * @const + * @type {int} + */ + MIN_WRITE_FILE_SIZE_IN_BYTES: 2 * 1024 * 1024, + + /** + * Put range write options + * + * @const + * @enum {string} + */ + RangeWriteOptions: { + UPDATE: 'update', + CLEAR: 'clear' + }, + + /** + * Resource types. + * + * @const + * @enum {string} + */ + ResourceTypes: { + SHARE: 's', + FILE: 'f' + } + }, + + /** + * Defines constants for use with queue storage. + */ + QueueConstants: { + /** + * XML element for QueueMessage. + * + * @const + * @type {string} + */ + QUEUE_MESSAGE_ELEMENT: 'QueueMessage', + + /** + * XML element for MessageText. + * + * @const + * @type {string} + */ + MESSAGE_TEXT_ELEMENT: 'MessageText' + }, + + /** + * Defines constants for use with table storage. + */ + TableConstants: { + /** + * The changeset response delimiter. + * + * @const + * @type {string} + */ + CHANGESET_DELIMITER: '--changesetresponse_', + + /** + * The batch response delimiter. + * + * @const + * @type {string} + */ + BATCH_DELIMITER: '--batchresponse_', + + /** + * The next continuation row key token. + * + * @const + * @type {string} + */ + CONTINUATION_NEXT_ROW_KEY: 'x-ms-continuation-nextrowkey', + + /** + * The next continuation partition key token. + * + * @const + * @type {string} + */ + CONTINUATION_NEXT_PARTITION_KEY: 'x-ms-continuation-nextpartitionkey', + + /** + * The next continuation table name token. + * + * @const + * @type {string} + */ + CONTINUATION_NEXT_TABLE_NAME: 'x-ms-continuation-nexttablename', + + /** + * The next row key query string argument. + * + * @const + * @type {string} + */ + NEXT_ROW_KEY: 'NextRowKey', + + /** + * The next partition key query string argument. + * + * @const + * @type {string} + */ + NEXT_PARTITION_KEY: 'NextPartitionKey', + + /** + * The next table name query string argument. + * + * @const + * @type {string} + */ + NEXT_TABLE_NAME: 'NextTableName', + + /** + * Prefix of the odata properties returned in a JSON query. + * + * @const + * @type {string} + */ + ODATA_PREFIX: 'odata.', + + /** + * Constant representing the string following a type annotation in a JSON table query. + * + * @const + * @type {string} + */ + ODATA_TYPE_SUFFIX: '@odata.type', + + /** + * Constant representing the property where the odata metadata elements are stored. + * + * @const + * @type {string} + */ + ODATA_METADATA_MARKER: '.metadata', + + /** + * Constant representing the value for an entity property. + * + * @const + * @type {string} + */ + ODATA_VALUE_MARKER: '_', + + /** + * Constant representing the type for an entity property. + * + * @const + * @type {string} + */ + ODATA_TYPE_MARKER: '$', + + /** + * The value to set the maximum data service version header. + * + * @const + * @type {string} + */ + DEFAULT_DATA_SERVICE_VERSION: '3.0;NetFx', + + /** + * The name of the property that stores the table name. + * + * @const + * @type {string} + */ + TABLE_NAME: 'TableName', + + /** + * The name of the special table used to store tables. + * + * @const + * @type {string} + */ + TABLE_SERVICE_TABLE_NAME: 'Tables', + + /** + * Operations. + * + * @const + * @enum {string} + */ + Operations: { + RETRIEVE: 'RETRIEVE', + INSERT: 'INSERT', + REPLACE: 'REPLACE', + MERGE: 'MERGE', + DELETE: 'DELETE', + INSERT_OR_REPLACE: 'INSERT_OR_REPLACE', + INSERT_OR_MERGE: 'INSERT_OR_MERGE' + } + }, + + /** + * Defines constants for use with HTTP headers. + */ + HeaderConstants: { + /** + * The accept ranges header. + * + * @const + * @type {string} + */ + ACCEPT_RANGES: 'accept_ranges', + + /** + * The content transfer encoding header. + * + * @const + * @type {string} + */ + CONTENT_TRANSFER_ENCODING: 'content-transfer-encoding', + + /** + * The transfer encoding header. + * + * @const + * @type {string} + */ + TRANSFER_ENCODING: 'transfer-encoding', + + /** + * The server header. + * + * @const + * @type {string} + */ + SERVER: 'server', + + /** + * The location header. + * + * @const + * @type {string} + */ + LOCATION: 'location', + + /** + * The Last-Modified header + * + * @const + * @type {string} + */ + LAST_MODIFIED: 'Last-Modified', + + /** + * The data service version. + * + * @const + * @type {string} + */ + DATA_SERVICE_VERSION: 'dataserviceversion', + + /** + * The maximum data service version. + * + * @const + * @type {string} + */ + MAX_DATA_SERVICE_VERSION: 'maxdataserviceversion', + + /** + * The master Windows Azure Storage header prefix. + * + * @const + * @type {string} + */ + PREFIX_FOR_STORAGE: 'x-ms-', + + /** + * The client request Id header. + * + * @const + * @type {string} + */ + CLIENT_REQUEST_ID: 'x-ms-client-request-id', + + /** + * The header that specifies the approximate message count of a queue. + * + * @const + * @type {string} + */ + APPROXIMATE_MESSAGES_COUNT: 'x-ms-approximate-messages-count', + + /** + * The Authorization header. + * + * @const + * @type {string} + */ + AUTHORIZATION: 'authorization', + + /** + * The header that is used to avoid browser cache. + * + * @const + * @type {string} + */ + FORCE_NO_CACHE_IN_BROWSER: '_', + + /** + * The header that specifies public access to blobs. + * + * @const + * @type {string} + */ + BLOB_PUBLIC_ACCESS: 'x-ms-blob-public-access', + + /** + * The header for the blob type. + * + * @const + * @type {string} + */ + BLOB_TYPE: 'x-ms-blob-type', + + /** + * The header for the type. + * + * @const + * @type {string} + */ + TYPE: 'x-ms-type', + + /** + * Specifies the block blob type. + * + * @const + * @type {string} + */ + BLOCK_BLOB: 'blockblob', + + /** + * The CacheControl header. + * + * @const + * @type {string} + */ + CACHE_CONTROL: 'cache-control', + + /** + * The header that specifies blob caching control. + * + * @const + * @type {string} + */ + BLOB_CACHE_CONTROL: 'x-ms-blob-cache-control', + + /** + * The header that specifies caching control. + * + * @const + * @type {string} + */ + FILE_CACHE_CONTROL: 'x-ms-cache-control', + + /** + * The copy status. + * + * @const + * @type {string} + */ + COPY_STATUS: 'x-ms-copy-status', + + /** + * The copy completion time + * + * @const + * @type {string} + */ + COPY_COMPLETION_TIME: 'x-ms-copy-completion-time', + + /** + * The copy status message + * + * @const + * @type {string} + */ + COPY_STATUS_DESCRIPTION: 'x-ms-copy-status-description', + + /** + * The copy identifier. + * + * @const + * @type {string} + */ + COPY_ID: 'x-ms-copy-id', + + /** + * Progress of any copy operation + * + * @const + * @type {string} + */ + COPY_PROGRESS: 'x-ms-copy-progress', + + /** + * The copy action. + * + * @const + * @type {string} + */ + COPY_ACTION: 'x-ms-copy-action', + + /** + * Flag if the blob is incremental copy blob. + * + * @const + * @type {string} + */ + INCREMENTAL_COPY: 'x-ms-incremental-copy', + + /** + * Snapshot time of the last successful incremental copy snapshot for this blob. + * + * @const + * @type {string} + */ + COPY_DESTINATION_SNAPSHOT: 'x-ms-copy-destination-snapshot', + + /** + * The ContentID header. + * + * @const + * @type {string} + */ + CONTENT_ID: 'content-id', + + /** + * The ContentEncoding header. + * + * @const + * @type {string} + */ + CONTENT_ENCODING: 'content-encoding', + + /** + * The header that specifies blob content encoding. + * + * @const + * @type {string} + */ + BLOB_CONTENT_ENCODING: 'x-ms-blob-content-encoding', + + /** + * The header that specifies content encoding. + * + * @const + * @type {string} + */ + FILE_CONTENT_ENCODING: 'x-ms-content-encoding', + + /** + * The ContentLangauge header. + * + * @const + * @type {string} + */ + CONTENT_LANGUAGE: 'content-language', + + /** + * The header that specifies blob content language. + * + * @const + * @type {string} + */ + BLOB_CONTENT_LANGUAGE: 'x-ms-blob-content-language', + + /** + * The header that specifies content language. + * + * @const + * @type {string} + */ + FILE_CONTENT_LANGUAGE: 'x-ms-content-language', + + /** + * The ContentLength header. + * + * @const + * @type {string} + */ + CONTENT_LENGTH: 'content-length', + + /** + * The header that specifies blob content length. + * + * @const + * @type {string} + */ + BLOB_CONTENT_LENGTH: 'x-ms-blob-content-length', + + /** + * The header that specifies content length. + * + * @const + * @type {string} + */ + FILE_CONTENT_LENGTH: 'x-ms-content-length', + + /** + * The ContentDisposition header. + * @const + * @type {string} + */ + CONTENT_DISPOSITION: 'content-disposition', + + /** + * The header that specifies blob content disposition. + * + * @const + * @type {string} + */ + BLOB_CONTENT_DISPOSITION: 'x-ms-blob-content-disposition', + + /** + * The header that specifies content disposition. + * + * @const + * @type {string} + */ + FILE_CONTENT_DISPOSITION: 'x-ms-content-disposition', + + /** + * The ContentMD5 header. + * + * @const + * @type {string} + */ + CONTENT_MD5: 'content-md5', + + /** + * The header that specifies blob content MD5. + * + * @const + * @type {string} + */ + BLOB_CONTENT_MD5: 'x-ms-blob-content-md5', + + /** + * The header that specifies content MD5. + * + * @const + * @type {string} + */ + FILE_CONTENT_MD5: 'x-ms-content-md5', + + /** + * The ContentRange header. + * + * @const + * @type {string} + */ + CONTENT_RANGE: 'cache-range', + + /** + * The ContentType header. + * + * @const + * @type {string} + */ + CONTENT_TYPE: 'content-type', + + /** + * The header that specifies blob content type. + * + * @const + * @type {string} + */ + BLOB_CONTENT_TYPE: 'x-ms-blob-content-type', + + /** + * The header that specifies content type. + * + * @const + * @type {string} + */ + FILE_CONTENT_TYPE: 'x-ms-content-type', + + /** + * The header for copy source. + * + * @const + * @type {string} + */ + COPY_SOURCE: 'x-ms-copy-source', + + /** + * The header that specifies the date. + * + * @const + * @type {string} + */ + DATE: 'date', + + /** + * The header that specifies the date. + * + * @const + * @type {string} + */ + MS_DATE: 'x-ms-date', + + /** + * The header to delete snapshots. + * + * @const + * @type {string} + */ + DELETE_SNAPSHOT: 'x-ms-delete-snapshots', + + /** + * The ETag header. + * + * @const + * @type {string} + */ + ETAG: 'etag', + + /** + * The IfMatch header. + * + * @const + * @type {string} + */ + IF_MATCH: 'if-match', + + /** + * The IfModifiedSince header. + * + * @const + * @type {string} + */ + IF_MODIFIED_SINCE: 'if-modified-since', + + /** + * The IfNoneMatch header. + * + * @const + * @type {string} + */ + IF_NONE_MATCH: 'if-none-match', + + /** + * The IfUnmodifiedSince header. + * + * @const + * @type {string} + */ + IF_UNMODIFIED_SINCE: 'if-unmodified-since', + + /** + * Specifies snapshots are to be included. + * + * @const + * @type {string} + */ + INCLUDE_SNAPSHOTS_VALUE: 'include', + + /** + * Specifies that the content-type is JSON. + * + * @const + * @type {string} + */ + JSON_CONTENT_TYPE_VALUE: 'application/json;', + + + /** + * The header that specifies lease ID. + * + * @const + * @type {string} + */ + LEASE_ID: 'x-ms-lease-id', + + /** + * The header that specifies the lease break period. + * + * @const + * @type {string} + */ + LEASE_BREAK_PERIOD: 'x-ms-lease-break-period', + + /** + * The header that specifies the proposed lease identifier. + * + * @const + * @type {string} + */ + PROPOSED_LEASE_ID: 'x-ms-proposed-lease-id', + + /** + * The header that specifies the lease duration. + * + * @const + * @type {string} + */ + LEASE_DURATION: 'x-ms-lease-duration', + + /** + * The header that specifies the source lease ID. + * + * @const + * @type {string} + */ + SOURCE_LEASE_ID: 'x-ms-source-lease-id', + + /** + * The header that specifies lease time. + * + * @const + * @type {string} + */ + LEASE_TIME: 'x-ms-lease-time', + + /** + * The header that specifies lease status. + * + * @const + * @type {string} + */ + LEASE_STATUS: 'x-ms-lease-status', + + /** + * The header that specifies lease state. + * + * @const + * @type {string} + */ + LEASE_STATE: 'x-ms-lease-state', + + /** + * Specifies the page blob type. + * + * @const + * @type {string} + */ + PAGE_BLOB: 'PageBlob', + + /** + * The header that specifies page write mode. + * + * @const + * @type {string} + */ + PAGE_WRITE: 'x-ms-page-write', + + /** + * The header that specifies file range write mode. + * + * @const + * @type {string} + */ + FILE_WRITE: 'x-ms-write', + + /** + * The header that specifies whether the response should include the inserted entity. + * + * @const + * @type {string} + */ + PREFER: 'Prefer', + + /** + * The header value which specifies that the response should include the inserted entity. + * + * @const + * @type {string} + */ + PREFER_CONTENT: 'return-content', + + /** + * The header value which specifies that the response should not include the inserted entity. + * + * @const + * @type {string} + */ + PREFER_NO_CONTENT: 'return-no-content', + + /** + * The header prefix for metadata. + * + * @const + * @type {string} + */ + PREFIX_FOR_STORAGE_METADATA: 'x-ms-meta-', + + /** + * The header prefix for properties. + * + * @const + * @type {string} + */ + PREFIX_FOR_STORAGE_PROPERTIES: 'x-ms-prop-', + + /** + * The Range header. + * + * @const + * @type {string} + */ + RANGE: 'Range', + + /** + * The header that specifies if the request will populate the ContentMD5 header for range gets. + * + * @const + * @type {string} + */ + RANGE_GET_CONTENT_MD5: 'x-ms-range-get-content-md5', + + /** + * The format string for specifying ranges. + * + * @const + * @type {string} + */ + RANGE_HEADER_FORMAT: 'bytes:%d-%d', + + /** + * The header that indicates the request ID. + * + * @const + * @type {string} + */ + REQUEST_ID: 'x-ms-request-id', + + /** + * The header for specifying the sequence number. + * + * @const + * @type {string} + */ + SEQUENCE_NUMBER: 'x-ms-blob-sequence-number', + + /** + * The header for specifying the If-Sequence-Number-EQ condition. + * + * @const + * @type {string} + */ + SEQUENCE_NUMBER_EQUAL: 'x-ms-if-sequence-number-eq', + + /** + * The header for specifying the If-Sequence-Number-LT condition. + * + * @const + * @type {string} + */ + SEQUENCE_NUMBER_LESS_THAN: 'x-ms-if-sequence-number-lt', + + /** + * The header for specifying the If-Sequence-Number-LE condition. + * + * @const + * @type {string} + */ + SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL: 'x-ms-if-sequence-number-le', + + /** + * The header that specifies sequence number action. + * + * @const + * @type {string} + */ + SEQUENCE_NUMBER_ACTION: 'x-ms-sequence-number-action', + + /** + * The header for the blob content length. + * + * @const + * @type {string} + */ + SIZE: 'x-ms-blob-content-length', + + /** + * The header for snapshots. + * + * @const + * @type {string} + */ + SNAPSHOT: 'x-ms-snapshot', + + /** + * Specifies only snapshots are to be included. + * + * @const + * @type {string} + */ + SNAPSHOTS_ONLY_VALUE: 'only', + + /** + * The header for the If-Match condition. + * + * @const + * @type {string} + */ + SOURCE_IF_MATCH: 'x-ms-source-if-match', + + /** + * The header for the If-Modified-Since condition. + * + * @const + * @type {string} + */ + SOURCE_IF_MODIFIED_SINCE: 'x-ms-source-if-modified-since', + + /** + * The header for the If-None-Match condition. + * + * @const + * @type {string} + */ + SOURCE_IF_NONE_MATCH: 'x-ms-source-if-none-match', + + /** + * The header for the If-Unmodified-Since condition. + * + * @const + * @type {string} + */ + SOURCE_IF_UNMODIFIED_SINCE: 'x-ms-source-if-unmodified-since', + + /** + * The header for data ranges. + * + * @const + * @type {string} + */ + STORAGE_RANGE: 'x-ms-range', + + /** + * The header for storage version. + * + * @const + * @type {string} + */ + STORAGE_VERSION: 'x-ms-version', + + /** + * The current storage version header value. + * + * @const + * @type {string} + */ + TARGET_STORAGE_VERSION: '2017-07-29', + + /** + * The UserAgent header. + * + * @const + * @type {string} + */ + USER_AGENT: 'user-agent', + + /** + * The pop receipt header. + * + * @const + * @type {string} + */ + POP_RECEIPT: 'x-ms-popreceipt', + + /** + * The time next visibile header. + * + * @const + * @type {string} + */ + TIME_NEXT_VISIBLE: 'x-ms-time-next-visible', + + /** + * The approximate message counter header. + * + * @const + * @type {string} + */ + APPROXIMATE_MESSAGE_COUNT: 'x-ms-approximate-message-count', + + /** + * The lease action header. + * + * @const + * @type {string} + */ + LEASE_ACTION: 'x-ms-lease-action', + + /** + * The accept header. + * + * @const + * @type {string} + */ + ACCEPT: 'accept', + + /** + * The accept charset header. + * + * @const + * @type {string} + */ + ACCEPT_CHARSET: 'Accept-Charset', + + /** + * The host header. + * + * @const + * @type {string} + */ + HOST: 'host', + + /** + * The correlation identifier header. + * + * @const + * @type {string} + */ + CORRELATION_ID: 'x-ms-correlation-id', + + /** + * The group identifier header. + * + * @const + * @type {string} + */ + GROUP_ID: 'x-ms-group-id', + + /** + * The share quota header. + * + * @const + * @type {string} + */ + SHARE_QUOTA: 'x-ms-share-quota', + + /** + * The max blob size header. + * + * @const + * @type {string} + */ + BLOB_CONDITION_MAX_SIZE: 'x-ms-blob-condition-maxsize', + + /** + * The append blob position header. + * + * @const + * @type {string} + */ + BLOB_CONDITION_APPEND_POSITION: 'x-ms-blob-condition-appendpos', + + /** + * The append blob append offset header. + * + * @const + * @type {string} + */ + BLOB_APPEND_OFFSET: 'x-ms-blob-append-offset', + + /** + * The append blob committed block header. + * + * @const + * @type {string} + */ + BLOB_COMMITTED_BLOCK_COUNT: 'x-ms-blob-committed-block-count', + + /** + * If the contents of the request have been successfully encrypted using the specified algorithm. + * + * @const + * @type {string} + */ + REQUEST_SERVER_ENCRYPTED: 'x-ms-request-server-encrypted', + + /** + * If the data and application metadata are completely encrypted using the specified algorithm. + * + * @const + * @type {string} + */ + SERVER_ENCRYPTED: 'x-ms-server-encrypted', + + /** + * Header indicates the resulting tier of the blob. + * + * @const + * @type {string} + */ + ACCESS_TIER: 'x-ms-access-tier', + + /** + * This is the datetime of when the last time tier was changed on the blob. + * + * @const + * @type {string} + */ + ACCESS_TIER_CHANGE_TIME: 'x-ms-access-tier-change-time', + + /** + * If the access tier is not explicitly set on the blob, + * the tier is inferred based on its content length + * and this header will be returned with true value. + * + * @const + * @type {string} + */ + ACCESS_TIER_INFERRED: 'x-ms-access-tier-inferred', + + /** + * For BlobStorage accounts, the header is returned if archive tier is set + * and rehydrate operation is pending for the request version is 2017-04-17 or later. + * The valid values are rehydrate-pending-to-hot or rehydrate-pending-to-cool. + * + * @const + * @type {string} + */ + ARCHIVE_STATUS: 'x-ms-archive-status' + }, + + QueryStringConstants: { + + /** + * Query component for SAS API version. + * @const + * @type {string} + */ + API_VERSION: 'api-version', + + /** + * The Comp value. + * + * @const + * @type {string} + */ + COMP: 'comp', + + /** + * The Res Type. + * + * @const + * @type {string} + */ + RESTYPE: 'restype', + + /** + * The copy Id. + * @const + * @type {string} + */ + COPY_ID: 'copyid', + + /** + * The snapshot value. + * + * @const + * @type {string} + */ + SNAPSHOT: 'snapshot', + + /** + * The share snapshot value. + * + * @const + * @type {string} + */ + SHARE_SNAPSHOT: 'sharesnapshot', + + /** + * The previous snapshot value. + * + * @const + * @type {string} + */ + PREV_SNAPSHOT: 'prevsnapshot', + + /** + * The timeout value. + * + * @const + * @type {string} + */ + TIMEOUT: 'timeout', + + /** + * The signed start time query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_START: 'st', + + /** + * The signed expiry time query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_EXPIRY: 'se', + + /** + * The signed resource query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_RESOURCE: 'sr', + + /** + * The signed permissions query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_PERMISSIONS: 'sp', + + /** + * The signed services query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_SERVICES: 'ss', + + /** + * The signed resource types query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_RESOURCE_TYPES: 'srt', + + /** + * The signed IP query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_IP: 'sip', + + /** + * The signed protocol query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_PROTOCOL: 'spr', + + /** + * The signed identifier query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_IDENTIFIER: 'si', + + /** + * The signature query string argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNATURE: 'sig', + + /** + * The signed version argument for shared access signature. + * + * @const + * @type {string} + */ + SIGNED_VERSION: 'sv', + + /** + * The cache control argument for shared access signature. + * + * @const + * @type {string} + */ + CACHE_CONTROL: 'rscc', + + /** + * The content type argument for shared access signature. + * + * @const + * @type {string} + */ + CONTENT_TYPE: 'rsct', + + /** + * The content encoding argument for shared access signature. + * + * @const + * @type {string} + */ + CONTENT_ENCODING: 'rsce', + + /** + * The content language argument for shared access signature. + * + * @const + * @type {string} + */ + CONTENT_LANGUAGE: 'rscl', + + /** + * The content disposition argument for shared access signature. + * + * @const + * @type {string} + */ + CONTENT_DISPOSITION: 'rscd', + + /** + * The block identifier query string argument for blob service. + * + * @const + * @type {string} + */ + BLOCK_ID: 'blockid', + + /** + * The block list type query string argument for blob service. + * + * @const + * @type {string} + */ + BLOCK_LIST_TYPE: 'blocklisttype', + + /** + * The prefix query string argument for listing operations. + * + * @const + * @type {string} + */ + PREFIX: 'prefix', + + /** + * The marker query string argument for listing operations. + * + * @const + * @type {string} + */ + MARKER: 'marker', + + /** + * The maxresults query string argument for listing operations. + * + * @const + * @type {string} + */ + MAX_RESULTS: 'maxresults', + + /** + * The delimiter query string argument for listing operations. + * + * @const + * @type {string} + */ + DELIMITER: 'delimiter', + + /** + * The include query string argument for listing operations. + * + * @const + * @type {string} + */ + INCLUDE: 'include', + + /** + * The peekonly query string argument for queue service. + * + * @const + * @type {string} + */ + PEEK_ONLY: 'peekonly', + + /** + * The numofmessages query string argument for queue service. + * + * @const + * @type {string} + */ + NUM_OF_MESSAGES: 'numofmessages', + + /** + * The popreceipt query string argument for queue service. + * + * @const + * @type {string} + */ + POP_RECEIPT: 'popreceipt', + + /** + * The visibilitytimeout query string argument for queue service. + * + * @const + * @type {string} + */ + VISIBILITY_TIMEOUT: 'visibilitytimeout', + + /** + * The messagettl query string argument for queue service. + * + * @const + * @type {string} + */ + MESSAGE_TTL: 'messagettl', + + /** + * The select query string argument. + * + * @const + * @type {string} + */ + SELECT: '$select', + + /** + * The filter query string argument. + * + * @const + * @type {string} + */ + FILTER: '$filter', + + /** + * The top query string argument. + * + * @const + * @type {string} + */ + TOP: '$top', + + /** + * The skip query string argument. + * + * @const + * @type {string} + */ + SKIP: '$skip', + + /** + * The next partition key query string argument for table service. + * + * @const + * @type {string} + */ + NEXT_PARTITION_KEY: 'NextPartitionKey', + + /** + * The next row key query string argument for table service. + * + * @const + * @type {string} + */ + NEXT_ROW_KEY: 'NextRowKey', + + /** + * The lock identifier for service bus messages. + * + * @const + * @type {string} + */ + LOCK_ID: 'lockid', + + /** + * The table name for table SAS URI's. + * + * @const + * @type {string} + */ + TABLENAME: 'tn', + + /** + * The starting Partition Key for tableSAS URI's. + * + * @const + * @type {string} + */ + STARTPK: 'spk', + + /** + * The starting Partition Key for tableSAS URI's. + * + * @const + * @type {string} + */ + STARTRK: 'srk', + + /** + * The ending Partition Key for tableSAS URI's. + * + * @const + * @type {string} + */ + ENDPK: 'epk', + + /** + * The ending Partition Key for tableSAS URI's. + * + * @const + * @type {string} + */ + ENDRK: 'erk' + }, + + StorageServiceClientConstants: { + /** + * The default protocol. + * + * @const + * @type {string} + */ + DEFAULT_PROTOCOL: 'https:', + + /* + * Used environment variables. + * + * @const + * @enum {string} + */ + EnvironmentVariables: { + AZURE_STORAGE_ACCOUNT: 'AZURE_STORAGE_ACCOUNT', + AZURE_STORAGE_ACCESS_KEY: 'AZURE_STORAGE_ACCESS_KEY', + AZURE_STORAGE_DNS_SUFFIX: 'AZURE_STORAGE_DNS_SUFFIX', + AZURE_STORAGE_CONNECTION_STRING: 'AZURE_STORAGE_CONNECTION_STRING', + HTTP_PROXY: 'HTTP_PROXY', + HTTPS_PROXY: 'HTTPS_PROXY', + EMULATED: 'EMULATED' + }, + + /** + * Default credentials. + */ + DEVSTORE_STORAGE_ACCOUNT: 'devstoreaccount1', + DEVSTORE_STORAGE_ACCESS_KEY: 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==', + + /** + * The development store URI. + * + * @const + * @type {string} + */ + DEV_STORE_URI: 'http://127.0.0.1', + + /** + * Development ServiceClient URLs. + */ + DEVSTORE_DEFAULT_PROTOCOL: 'http://', + DEVSTORE_BLOB_HOST: '127.0.0.1:10000', + DEVSTORE_QUEUE_HOST: '127.0.0.1:10001', + DEVSTORE_TABLE_HOST: '127.0.0.1:10002', + + /** + * Production ServiceClient URLs. + */ + CLOUD_BLOB_HOST: 'blob.' + storageDnsSuffix, + CLOUD_QUEUE_HOST: 'queue.' + storageDnsSuffix, + CLOUD_TABLE_HOST: 'table.' + storageDnsSuffix, + CLOUD_FILE_HOST: 'file.' + storageDnsSuffix + }, + + HttpConstants: { + /** + * Http Verbs + * + * @const + * @enum {string} + */ + HttpVerbs: { + PUT: 'PUT', + GET: 'GET', + DELETE: 'DELETE', + POST: 'POST', + MERGE: 'MERGE', + HEAD: 'HEAD' + }, + + /** + * Response codes. + * + * @const + * @enum {int} + */ + HttpResponseCodes: { + Ok: 200, + Created: 201, + Accepted: 202, + NoContent: 204, + PartialContent: 206, + BadRequest: 400, + Unauthorized: 401, + Forbidden: 403, + NotFound: 404, + Conflict: 409, + LengthRequired: 411, + PreconditionFailed: 412 + } + }, + + CompatibleVersionConstants: { + /** + * Constant for the 2013-08-15 version. + * + * @const + * @type {string} + */ + AUGUST_2013: '2013-08-15', + + /** + * Constant for the 2012-02-12 version. + * + * @const + * @type {string} + */ + FEBRUARY_2012: '2012-02-12' + }, + + BlobErrorCodeStrings: { + INVALID_BLOCK_ID: 'InvalidBlockId', + BLOB_NOT_FOUND: 'BlobNotFound', + BLOB_ALREADY_EXISTS: 'BlobAlreadyExists', + CONTAINER_ALREADY_EXISTS: 'ContainerAlreadyExists', + CONTAINER_NOT_FOUND: 'ContainerNotFound', + INVALID_BLOB_OR_BLOCK: 'InvalidBlobOrBlock', + INVALID_BLOCK_LIST: 'InvalidBlockList' + }, + + FileErrorCodeStrings: { + SHARE_ALREADY_EXISTS: 'ShareAlreadyExists', + SHARE_NOT_FOUND: 'ShareNotFound', + FILE_NOT_FOUND: 'FileNotFound' + }, + + QueueErrorCodeStrings: { + QUEUE_NOT_FOUND: 'QueueNotFound', + QUEUE_DISABLED: 'QueueDisabled', + QUEUE_ALREADY_EXISTS: 'QueueAlreadyExists', + QUEUE_NOT_EMPTY: 'QueueNotEmpty', + QUEUE_BEING_DELETED: 'QueueBeingDeleted', + POP_RECEIPT_MISMATCH: 'PopReceiptMismatch', + INVALID_PARAMETER: 'InvalidParameter', + MESSAGE_NOT_FOUND: 'MessageNotFound', + MESSAGE_TOO_LARGE: 'MessageTooLarge', + INVALID_MARKER: 'InvalidMarker' + }, + + /** + * Constants for storage error strings + * + * More details are at: http://msdn.microsoft.com/en-us/library/azure/dd179357.aspx + */ + StorageErrorCodeStrings: { + // Not Modified (304): The condition specified in the conditional header(s) was not met for a read operation. + // Precondition Failed (412): The condition specified in the conditional header(s) was not met for a write operation. + CONDITION_NOT_MET: 'ConditionNotMet', + // Bad Request (400): A required HTTP header was not specified. + MISSING_REQUIRED_HEADER: 'MissingRequiredHeader', + // Bad Request (400): A required XML node was not specified in the request body. + MISSING_REQUIRED_XML_NODE: 'MissingRequiredXmlNode', + // Bad Request (400): One of the HTTP headers specified in the request is not supported. + UNSUPPORTED_HEADER: 'UnsupportedHeader', + // Bad Request (400): One of the XML nodes specified in the request body is not supported. + UNSUPPORTED_XML_NODE: 'UnsupportedXmlNode', + // Bad Request (400): The value provided for one of the HTTP headers was not in the correct format. + INVALID_HEADER_VALUE: 'InvalidHeaderValue', + // Bad Request (400): The value provided for one of the XML nodes in the request body was not in the correct format. + INVALID_XML_NODE_VALUE: 'InvalidXmlNodeValue', + // Bad Request (400): A required query parameter was not specified for this request. + MISSING_REQUIRED_QUERY_PARAMETER: 'MissingRequiredQueryParameter', + // Bad Request (400): One of the query parameters specified in the request URI is not supported. + UNSUPPORTED_QUERY_PARAMETER: 'UnsupportedQueryParameter', + // Bad Request (400): An invalid value was specified for one of the query parameters in the request URI. + INVALID_QUERY_PARAMETER_VALUE: 'InvalidQueryParameterValue', + // Bad Request (400): A query parameter specified in the request URI is outside the permissible range. + OUT_OF_RANGE_QUERY_PARAMETER_VALUE: 'OutOfRangeQueryParameterValue', + // Bad Request (400): The url in the request could not be parsed. + REQUEST_URL_FAILED_TO_PARSE: 'RequestUrlFailedToParse', + // Bad Request (400): The requested URI does not represent any resource on the server. + INVALID_URI: 'InvalidUri', + // Bad Request (400): The HTTP verb specified was not recognized by the server. + INVALID_HTTP_VERB: 'InvalidHttpVerb', + // Bad Request (400): The key for one of the metadata key-value pairs is empty. + EMPTY_METADATA_KEY: 'EmptyMetadataKey', + // Bad Request (400): The specified XML is not syntactically valid. + INVALID_XML_DOCUMENT: 'InvalidXmlDocument', + // Bad Request (400): The MD5 value specified in the request did not match the MD5 value calculated by the server. + MD5_MISMATCH: 'Md5Mismatch', + // Bad Request (400): The MD5 value specified in the request is invalid. The MD5 value must be 128 bits and Base64-encoded. + INVALID_MD5: 'InvalidMd5', + // Bad Request (400): One of the request inputs is out of range. + OUT_OF_RANGE_INPUT: 'OutOfRangeInput', + // Bad Request (400): The authentication information was not provided in the correct format. Verify the value of Authorization header. + INVALID_AUTHENTICATION_INFO: 'InvalidAuthenticationInfo', + // Bad Request (400): One of the request inputs is not valid. + INVALID_INPUT: 'InvalidInput', + // Bad Request (400): The specified metadata is invalid. It includes characters that are not permitted. + INVALID_METADATA: 'InvalidMetadata', + // Bad Request (400): The specifed resource name contains invalid characters. + INVALID_RESOURCE_NAME: 'InvalidResourceName', + // Bad Request (400): The size of the specified metadata exceeds the maximum size permitted. + METADATA_TOO_LARGE: 'MetadataTooLarge', + // Bad Request (400): Condition headers are not supported. + CONDITION_HEADER_NOT_SUPPORTED: 'ConditionHeadersNotSupported', + // Bad Request (400): Multiple condition headers are not supported. + MULTIPLE_CONDITION_HEADER_NOT_SUPPORTED: 'MultipleConditionHeadersNotSupported', + // Forbidden (403): Server failed to authenticate the request. Make sure the value of the Authorization header is formed correctly including the signature. + AUTHENTICATION_FAILED: 'AuthenticationFailed', + // Forbidden (403): Read-access geo-redundant replication is not enabled for the account. + // Forbidden (403): Write operations to the secondary location are not allowed. + // Forbidden (403): The account being accessed does not have sufficient permissions to execute this operation. + INSUFFICIENT_ACCOUNT_PERMISSIONS: 'InsufficientAccountPermissions', + // Not Found (404): The specified resource does not exist. + RESOURCE_NOT_FOUND: 'ResourceNotFound', + // Forbidden (403): The specified account is disabled. + ACCOUNT_IS_DISABLED: 'AccountIsDisabled', + // Method Not Allowed (405): The resource doesn't support the specified HTTP verb. + UNSUPPORTED_HTTP_VERB: 'UnsupportedHttpVerb', + // Conflict (409): The specified account already exists. + ACCOUNT_ALREADY_EXISTS: 'AccountAlreadyExists', + // Conflict (409): The specified account is in the process of being created. + ACCOUNT_BEING_CREATED: 'AccountBeingCreated', + // Conflict (409): The specified resource already exists. + RESOURCE_ALREADY_EXISTS: 'ResourceAlreadyExists', + // Conflict (409): The specified resource type does not match the type of the existing resource. + RESOURCE_TYPE_MISMATCH: 'ResourceTypeMismatch', + // Length Required (411): The Content-Length header was not specified. + MISSING_CONTENT_LENGTH_HEADER: 'MissingContentLengthHeader', + // Request Entity Too Large (413): The size of the request body exceeds the maximum size permitted. + REQUEST_BODY_TOO_LARGE: 'RequestBodyTooLarge', + // Requested Range Not Satisfiable (416): The range specified is invalid for the current size of the resource. + INVALID_RANGE: 'InvalidRange', + // Internal Server Error (500): The server encountered an internal error. Please retry the request. + INTERNAL_ERROR: 'InternalError', + // Internal Server Error (500): The operation could not be completed within the permitted time. + OPERATION_TIMED_OUT: 'OperationTimedOut', + // Service Unavailable (503): The server is currently unable to receive requests. Please retry your request. + SERVER_BUSY: 'ServerBusy', + + // Legacy error code strings + UPDATE_CONDITION_NOT_SATISFIED: 'UpdateConditionNotSatisfied', + CONTAINER_NOT_FOUND: 'ContainerNotFound', + CONTAINER_ALREADY_EXISTS: 'ContainerAlreadyExists', + CONTAINER_DISABLED: 'ContainerDisabled', + CONTAINER_BEING_DELETED: 'ContainerBeingDeleted' + }, + + TableErrorCodeStrings: { + XMETHOD_NOT_USING_POST: 'XMethodNotUsingPost', + XMETHOD_INCORRECT_VALUE: 'XMethodIncorrectValue', + XMETHOD_INCORRECT_COUNT: 'XMethodIncorrectCount', + TABLE_HAS_NO_PROPERTIES: 'TableHasNoProperties', + DUPLICATE_PROPERTIES_SPECIFIED: 'DuplicatePropertiesSpecified', + TABLE_HAS_NO_SUCH_PROPERTY: 'TableHasNoSuchProperty', + DUPLICATE_KEY_PROPERTY_SPECIFIED: 'DuplicateKeyPropertySpecified', + TABLE_ALREADY_EXISTS: 'TableAlreadyExists', + TABLE_NOT_FOUND: 'TableNotFound', + ENTITY_NOT_FOUND: 'EntityNotFound', + ENTITY_ALREADY_EXISTS: 'EntityAlreadyExists', + PARTITION_KEY_NOT_SPECIFIED: 'PartitionKeyNotSpecified', + OPERATOR_INVALID: 'OperatorInvalid', + UPDATE_CONDITION_NOT_SATISFIED: 'UpdateConditionNotSatisfied', + PROPERTIES_NEED_VALUE: 'PropertiesNeedValue', + PARTITION_KEY_PROPERTY_CANNOT_BE_UPDATED: 'PartitionKeyPropertyCannotBeUpdated', + TOO_MANY_PROPERTIES: 'TooManyProperties', + ENTITY_TOO_LARGE: 'EntityTooLarge', + PROPERTY_VALUE_TOO_LARGE: 'PropertyValueTooLarge', + INVALID_VALUE_TYPE: 'InvalidValueType', + TABLE_BEING_DELETED: 'TableBeingDeleted', + TABLE_SERVER_OUT_OF_MEMORY: 'TableServerOutOfMemory', + PRIMARY_KEY_PROPERTY_IS_INVALID_TYPE: 'PrimaryKeyPropertyIsInvalidType', + PROPERTY_NAME_TOO_LONG: 'PropertyNameTooLong', + PROPERTY_NAME_INVALID: 'PropertyNameInvalid', + BATCH_OPERATION_NOT_SUPPORTED: 'BatchOperationNotSupported', + JSON_FORMAT_NOT_SUPPORTED: 'JsonFormatNotSupported', + METHOD_NOT_ALLOWED: 'MethodNotAllowed', + NOT_IMPLEMENTED: 'NotImplemented' + }, + + ConnectionStringKeys: { + USE_DEVELOPMENT_STORAGE_NAME: 'UseDevelopmentStorage', + DEVELOPMENT_STORAGE_PROXY_URI_NAME: 'DevelopmentStorageProxyUri', + DEFAULT_ENDPOINTS_PROTOCOL_NAME: 'DefaultEndpointsProtocol', + ACCOUNT_NAME_NAME: 'AccountName', + ACCOUNT_KEY_NAME: 'AccountKey', + BLOB_ENDPOINT_NAME: 'BlobEndpoint', + FILE_ENDPOINT_NAME: 'FileEndpoint', + QUEUE_ENDPOINT_NAME: 'QueueEndpoint', + TABLE_ENDPOINT_NAME: 'TableEndpoint', + SHARED_ACCESS_SIGNATURE_NAME: 'SharedAccessSignature', + ENDPOINT_SUFFIX_NAME: 'EndpointSuffix', + BLOB_BASE_DNS_NAME: 'blob.core.windows.net', + FILE_BASE_DNS_NAME: 'file.core.windows.net', + QUEUE_BASE_DNS_NAME: 'queue.core.windows.net', + TABLE_BASE_DNS_NAME: 'table.core.windows.net' + } +}; + +module.exports = Constants; diff --git a/node_modules/azure-storage/lib/common/util/date.js b/node_modules/azure-storage/lib/common/util/date.js new file mode 100644 index 000000000..b2e5f06a4 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/date.js @@ -0,0 +1,69 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +/** +* Date/time related helper functions +* @module date +* +*/ + +/** +* Generates a Date object which is in the given days from now. +* +* @param {int} days The days timespan. +* @return {Date} +*/ +exports.daysFromNow = function (days) { + var date = new Date(); + date.setDate(date.getDate() + days); + return date; +}; + +/** +* Generates a Date object which is in the given hours from now. +* +* @param {int} hours The hours timespan. +* @return {Date} +*/ +exports.hoursFromNow = function (hours) { + var date = new Date(); + date.setHours(date.getHours() + hours); + return date; +}; + +/** +* Generates a Date object which is in the given minutes from now. +* +* @param {int} minutes The minutes timespan. +* @return {Date} +*/ +exports.minutesFromNow = function (minutes) { + var date = new Date(); + date.setMinutes(date.getMinutes() + minutes); + return date; +}; + +/** +* Generates a Date object which is in the given seconds from now. +* +* @param {int} seconds The seconds timespan. +* @return {Date} +*/ +exports.secondsFromNow = function (seconds) { + var date = new Date(); + date.setSeconds(date.getSeconds() + seconds); + return date; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/iso8061date.js b/node_modules/azure-storage/lib/common/util/iso8061date.js new file mode 100644 index 000000000..69541fe02 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/iso8061date.js @@ -0,0 +1,66 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var rightPad = function (n, number) { + var currentN = '' + n; + while (currentN.length < number) { + currentN = currentN + '0'; + } + + return currentN; +}; + +/** +* Formats a date into an iso 8061 string. +* +* @param {date} date The date to format. +* @param {bool} skipMilliseconds Boolean value indicating if the miliseconds part of the date should not be included. +* @param {integer} millisecondsPading Number of digits to left pad the miliseconds. +* @return {string} The date formated in the ISO 8061 date format. +*/ +exports.format = function (date) { + var dateString = date.toISOString(); + return dateString.substring(0, dateString.length - 1) + '0000Z'; +}; + +/** +* Parses an ISO 8061 date string into a date object. +* +* @param {string} stringDateTime The string with the date to parse in the ISO 8061 format. +* @return {date} The parsed date. +*/ +exports.parse = function (stringDateTime) { + var parts = stringDateTime.split('T'); + var ymd = parts[0].split('-'); + var time = parts[1].split('.'); + var hms = time[0].split(':'); + var ms = 0; + if (time[1]) { + ms = time[1].split('Z'); + } + + var date = new Date(Date.UTC( + parseInt(ymd[0], 10), + parseInt(ymd[1], 10) - 1, + parseInt(ymd[2], 10), + parseInt(hms[0], 10), + parseInt(hms[1], 10), + parseInt(hms[2], 10), + Math.round(parseInt(rightPad(ms[0], 7), 10) / 10000) + )); + + return date; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js b/node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js new file mode 100644 index 000000000..06f6e1295 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js @@ -0,0 +1,31 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +'use strict'; + +var XMLBuilder = require('xmlbuilder/lib/XMLBuilder'); + +// Patch xmlbuilder to allow Unicode surrogate pair code +// points in XML bodies + +XMLBuilder.prototype.assertLegalChar = function(str) { + var chars, chr; + chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/; + chr = str.match(chars); + if (chr) { + throw new Error('Invalid character (' + chr + ') in string: ' + str); + } +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/sr.js b/node_modules/azure-storage/lib/common/util/sr.js new file mode 100644 index 000000000..e0b112b8c --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/sr.js @@ -0,0 +1,76 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +exports = module.exports; + +var SR = { + ANONYMOUS_ACCESS_BLOBSERVICE_ONLY: 'Anonymous access is only valid for the BlobService.', + ARGUMENT_NULL_OR_EMPTY: 'The argument must not be null or an empty string. Argument name: %s.', + ARGUMENT_NULL_OR_UNDEFINED: 'The argument must not be null or undefined. Argument name: %s.', + ARGUMENT_OUT_OF_RANGE_ERROR: 'The argument is out of range. Argument name: %s, Value passed: %s.', + BATCH_ONE_PARTITION_KEY: 'All entities in the batch must have the same PartitionKey value.', + BATCH_ONE_RETRIEVE: 'If a retrieve operation is part of a batch, it must be the only operation in the batch.', + BATCH_TOO_LARGE: 'Batches must not contain more than 100 operations.', + BLOB_INVALID_SEQUENCE_NUMBER: 'The sequence number may not be specified for an increment operation.', + BLOB_TYPE_MISMATCH: 'Blob type of the blob reference doesn\'t match blob type of the blob.', + CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY: 'Cannot create Shared Access Signature unless the Account Name and Key are used to create the ServiceClient.', + CONTENT_LENGTH_MISMATCH: 'An incorrect number of bytes was read from the connection. The connection may have been closed.', + CONTENT_TYPE_MISSING: 'Content-Type response header is missing or invalid.', + EMPTY_BATCH: 'Batch must not be empty.', + EXCEEDED_SIZE_LIMITATION: 'Upload exceeds the size limitation. Max size is %s but the current size is %s', + HASH_MISMATCH: 'Hash mismatch (integrity check failed), Expected value is %s, retrieved %s.', + INCORRECT_ENTITY_KEYS: 'PartitionKey and RowKey must be specified as strings in the entity object.', + INVALID_BLOB_LENGTH: 'createBlockBlobFromText requires the size of text to be less than 64MB. Please use createBlockBlobFromLocalFile or createBlockBlobFromStream to upload large blobs.', + INVALID_CONNECTION_STRING: 'Connection strings must be of the form "key1=value1;key2=value2".', + INVALID_CONNECTION_STRING_BAD_KEY: 'Connection string contains unrecognized key: "%s"', + INVALID_CONNECTION_STRING_DUPLICATE_KEY: 'Connection string contains duplicate key: "%s"', + INVALID_CONNECTION_STRING_EMPTY_KEY: 'Connection strings must not contain empty keys.', + INVALID_DELETE_SNAPSHOT_OPTION: 'The deleteSnapshots option cannot be included when deleting a specific snapshot using the snapshotId option.', + INVALID_EDM_TYPE: 'The value \'%s\' does not match the type \'%s\'.', + INVALID_FILE_LENGTH: 'createFileFromText requires the size of text to be less than 4MB. Please use createFileFromLocalFile or createFileFromStream to upload large files.', + INVALID_FILE_RANGE_FOR_UPDATE: 'Range size should be less than 4MB for a file range update operation.', + INVALID_HEADERS: 'Headers are not supported in the 2012-02-12 version.', + INVALID_MESSAGE_ID: 'Message ID cannot be null or undefined for deleteMessage and updateMessage operations.', + INVALID_PAGE_BLOB_LENGTH: 'Page blob length must be multiple of 512.', + INVALID_PAGE_END_OFFSET: 'Page end offset must be multiple of 512.', + INVALID_PAGE_RANGE_FOR_UPDATE: 'Page range size should be less than 4MB for a page update operation.', + INVALID_PAGE_START_OFFSET: 'Page start offset must be multiple of 512.', + INVALID_POP_RECEIPT: 'Pop Receipt cannot be null or undefined for deleteMessage and updateMessage operations.', + INVALID_PROPERTY_RESOLVER: 'The specified property resolver returned an invalid type. %s:{_:%s,$:%s }', + INVALID_RANGE_FOR_MD5: 'The requested range should be less than 4MB when contentMD5 is expected from the server', + INVALID_SAS_VERSION: 'SAS Version ? is invalid. Valid versions include: ?.', + INVALID_SAS_TOKEN: 'The SAS token should not contain api-version.', + INVALID_SIGNED_IDENTIFIERS: 'Signed identifiers need to be a hash object with key as the id and the value as the access policy.', + INVALID_STREAM_LENGTH: 'The length of the provided stream is invalid.', + INVALID_STRING_ERROR: 'Invalid string error.', + INVALID_TABLE_OPERATION: 'Operation not found: %s', + INVALID_TEXT_LENGTH: 'The length of the provided text is invalid.', + MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION: 'The client could not finish the operation within specified maximum execution timeout.', + MD5_NOT_POSSIBLE: 'MD5 cannot be calculated for an existing blob because it would require reading the existing data. Please disable storeBlobContentMD5.', + MD5_NOT_PRESENT_ERROR: 'MD5 does not exist. If you do not want to force validation, please disable useTransactionalMD5.', + METADATA_KEY_INVALID: 'The key for one of the metadata key-value pairs is null, empty, or whitespace.', + METADATA_VALUE_INVALID: 'The value for one of the metadata key-value pairs is null, empty, or whitespace.', + NO_CREDENTIALS_PROVIDED: 'Credentials must be provided when creating a service client.', + PRIMARY_ONLY_COMMAND: 'This operation can only be executed against the primary storage location.', + QUERY_OPERATOR_REQUIRES_WHERE: '%s operator needs to be used after where.', + SECONDARY_ONLY_COMMAND: 'This operation can only be executed against the secondary storage location.', + STORAGE_HOST_LOCATION_REQUIRED: 'The host for the storage service must be specified.', + STORAGE_HOST_MISSING_LOCATION: 'The host for the target storage location is not specified. Please consider changing the request\'s location mode.', + TYPE_NOT_SUPPORTED: 'Type not supported when sending data to the service: ', + MAX_BLOB_SIZE_CONDITION_NOT_MEET: 'Append block data should not exceed the maximum blob size condition value.', +}; + +module.exports = SR; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/storageutilities.js b/node_modules/azure-storage/lib/common/util/storageutilities.js new file mode 100644 index 000000000..0c5caa3a2 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/storageutilities.js @@ -0,0 +1,42 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'StorageUtilities'. + +/** +* Defines constants, enums, and utility functions for use with storage. +* @namespace +*/ +var StorageUtilities = { + /** + * Specifies the location mode used to decide which location the request should be sent to. + * + * @const + * @enum {number} + */ + LocationMode: { + /** The primary location only */ + PRIMARY_ONLY: 0, + /** The primary location first, then the secondary */ + PRIMARY_THEN_SECONDARY: 1, + /** The secondary location only */ + SECONDARY_ONLY: 2, + /** The secondary location first, then the primary */ + SECONDARY_THEN_PRIMARY: 3 + } +}; + +module.exports = StorageUtilities; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/util.js b/node_modules/azure-storage/lib/common/util/util.js new file mode 100644 index 000000000..dddc47f21 --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/util.js @@ -0,0 +1,618 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var _ = require('underscore'); +var util = require('util'); +var url = require('url'); +var stream = require('stream'); +var Constants = require('./constants'); +var Md5Wrapper = require('../md5-wrapper'); +var StorageUtilities = require('./storageutilities'); +var SR = require('./sr'); + +/** +* Trim the default port in the url. +* +* @param {string} uri The URI to be encoded. +* @return {string} The URI without defualt port. +*/ +exports.trimPortFromUri = function (uri) { + var uri = url.parse(uri); + if ((uri.protocol === Constants.HTTPS && uri.port == Constants.DEFAULT_HTTPS_PORT) || (uri.protocol === Constants.HTTP && uri.port == Constants.DEFAULT_HTTP_PORT)) { + uri.host = uri.hostname; + } + return url.format(uri); +}; + +/** +* Returns the number of keys (properties) in an object. +* +* @param {object} value The object which keys are to be counted. +* @return {number} The number of keys in the object. +*/ +exports.objectKeysLength = function (value) { + if (!value) { + return 0; + } + + return _.keys(value).length; +}; + +/** +* Checks if in a browser environment. +* +* @return {bool} True if in a browser environment, false otherwise. +*/ +exports.isBrowser = function () { + return typeof window !== 'undefined'; +}; + +/** +* Checks if in IE. +* +* @return {bool} True if in IE, false otherwise. +*/ +exports.isIE = function () { + if (!exports.isBrowser()) { + return false; + } + + var ua = window.navigator.userAgent; + var msie = ua.indexOf('MSIE '); + var trident = ua.indexOf('Trident/'); + return msie > 0 || trident > 0; +}; + +/** +* Checks if in a 32bit Node.js environment. +* +* @return {bool} True if in a 32bit Node.js environment, false otherwise. +*/ +exports.is32 = function () { + return !exports.isBrowser() && process.arch === 'ia32'; +}; + +/** +* Checks if a value is null or undefined. +* +* @param {object} value The value to check for null or undefined. +* @return {bool} True if the value is null or undefined, false otherwise. +*/ +exports.objectIsNull = function (value) { + return _.isNull(value) || _.isUndefined(value); +}; + +/** +* Checks if an object is empty. +* +* @param {object} object The object to check if it is null. +* @return {bool} True if the object is empty, false otherwise. +*/ +exports.objectIsEmpty = function (object) { + return _.isEmpty(object); +}; + +/** +* Determines if an object contains an integer number. +* +* @param {object} value The object to assert. +* @return {bool} True if the object contains an integer number; false otherwise. +*/ +exports.objectIsInt = function (value) { + return typeof value === 'number' && parseFloat(value) == parseInt(value, 10) && !isNaN(value); +}; + +/** +* Determines if an object is a NaN. +* +* @param {object} value The object to assert. +* @return {bool} True if the object is a NaN; false otherwise. +*/ +exports.objectIsNaN = function (value) { + return typeof(value) === 'number' && isNaN(value); +}; + +/** +* Checks if an object is a string. +* +* @param {object} object The object to check if it is a string. +* @return {bool} True if the object is a string, false otherwise. +*/ +exports.objectIsString = function (object) { + return _.isString(object); +}; + +/** +* Check if an object is a function +* @param {object} object The object to check whether it is function +* @return {bool} True if the specified object is function, otherwise false +*/ +exports.objectIsFunction = function (object) { + return _.isFunction(object); +}; + + +/** +* Front zero padding of string to sepcified length +*/ +exports.zeroPaddingString = function(str, len) { + var paddingStr = '0000000000' + str; + if(paddingStr.length < len) { + return exports.zeroPaddingString(paddingStr, len); + } else { + return paddingStr.substr(-1 * len); + } +}; + +/** +* Checks if a value is an empty string, null or undefined. +* +* @param {object} value The value to check for an empty string, null or undefined. +* @return {bool} True if the value is an empty string, null or undefined, false otherwise. +*/ +exports.stringIsEmpty = function (value) { + return _.isNull(value) || _.isUndefined(value) || value === ''; +}; + +/** +* Checks if a value is null, empty, undefined or consists only of white-space characters. +* +* @param {object} value The value to check for null, empty, undefined and white-space only characters. +* @return {bool} True if the value is an empty string, null, undefined, or consists only of white-space characters, false otherwise. +*/ +exports.IsNullOrEmptyOrUndefinedOrWhiteSpace = function (value) { + if(_.isNull(value) || _.isUndefined(value) || value === '') { + return true; + } + + if(_.isString(value) && value.trim().length === 0) { + return true; + } + + return false; +}; + +/** +* Formats a text replacing '?' by the arguments. +* +* @param {string} text The string where the ? should be replaced. +* @param {array} arguments Value(s) to insert in question mark (?) parameters. +* @return {string} +*/ +exports.stringFormat = function (text) { + if (arguments.length > 1) { + for (var i = 1; text.indexOf('?') !== -1; i++) { + text = text.replace('?', arguments[i]); + } + } + + return text; +}; + +/** +* Determines if a string starts with another. +* +* @param {string} text The string to assert. +* @param {string} prefix The string prefix. +* @return {Bool} True if the string starts with the prefix; false otherwise. +*/ +exports.stringStartsWith = function (text, prefix) { + if (_.isNull(prefix)) { + return true; + } + + return text.substr(0, prefix.length) === prefix; +}; + +/** +* Determines if a string ends with another. +* +* @param {string} text The string to assert. +* @param {string} suffix The string suffix. +* @return {Bool} True if the string ends with the suffix; false otherwise. +*/ +exports.stringEndsWith = function (text, suffix) { + if (_.isNull(suffix)) { + return true; + } + + return text.substr(text.length - suffix.length) === suffix; +}; + +/** +* Removes the BOM from a string. +* +* @param {string} str The string from where the BOM is to be removed +* @return {string} The string without the BOM. +*/ +exports.removeBOM = function (str) { + if (str.charCodeAt(0) === 0xfeff || str.charCodeAt(0) === 0xffef) { + str = str.substring(1); + } + + return str; +}; + +/** +* Merges multiple objects. +* +* @param {object} object The objects to be merged +* @return {object} The merged object. +*/ +exports.merge = function () { + return _.extend.apply(this, arguments); +}; + +/** +* Checks if a value exists in an array. The comparison is done in a case +* insensitive manner. +* +* @param {string} needle The searched value. +* @param {array} haystack The array. +* +* @static +* +* @return {boolean} +*/ +exports.inArrayInsensitive = function (needle, haystack) { + return _.contains(_.map(haystack, function (h) { return h.toLowerCase(); }), needle.toLowerCase()); +}; + +/** +* Returns the specified value of the key passed from object and in case that +* this key doesn't exist, the default value is returned. The key matching is +* done in a case insensitive manner. +* +* @param {string} key The array key. +* @param {object} haystack The object to be used. +* @param {mix} default The value to return if $key is not found in $array. +* +* @static +* +* @return mix +*/ +exports.tryGetValueInsensitive = function (key, haystack, defaultValue) { + if (haystack) { + for (var i in haystack) { + if (haystack.hasOwnProperty(i) && i.toString().toLowerCase() === key.toString().toLowerCase()) { + return haystack[i]; + } + } + } + + return defaultValue; +}; + +/** +* Returns the value in a chained object. +* +* @param {object} object The object with the values. +* @param {array} keys The keys. +* @param {mix} default The value to return if $key is not found in $array. +* +* @static +* +* @return mix +*/ +exports.tryGetValueChain = function (object, keys, defaultValue) { + if (keys.length === 0) { + return object; + } + + var currentKey = keys.shift(); + if (object && object[currentKey] !== undefined) { + return exports.tryGetValueChain(object[currentKey], keys, defaultValue); + } + + return defaultValue; +}; + +/** +* Set the value of an inner property of an object. +* +* @param {object} object The target object. +* @param {array} keys The property chain keys. +* @param {mix} object The value to be set. +* +* @static + +* @example +* // Set targetObject.propA.propB to 'testValue' +* var targetObject = {}; +* util.setObjectInnerPropertyValue(targetObject, ['propA', 'propB'], 'testValue'); +*/ +exports.setObjectInnerPropertyValue = function(object, propertyChainKeys, value){ + if(!object || propertyChainKeys.length < 1) { + return; + } + + var currentKey = propertyChainKeys.shift(); + if(propertyChainKeys.length === 0) { + object[currentKey] = value; + return; + } + + if (!object[currentKey]) { + object[currentKey] = {}; + } + + exports.setObjectInnerPropertyValue(object[currentKey], propertyChainKeys, value); +}; + +/** +* Rounds a date off to seconds. +* +* @param {Date} a date +* @return {string} the date in ISO8061 format, with no milliseconds component +*/ +exports.truncatedISO8061Date = function (date) { + var dateString = date.toISOString(); + return dateString.substring(0, dateString.length - 5) + 'Z'; +}; + +exports.normalizeArgs = function (optionsOrCallback, callback, result) { + var options = {}; + if(_.isFunction(optionsOrCallback) && !callback) { + callback = optionsOrCallback; + } else if (optionsOrCallback) { + options = optionsOrCallback; + } + + result(options, callback); +}; + +exports.getNodeVersion = function () { + var parsedVersion = process.version.split('.'); + return { + major: parseInt(parsedVersion[0].substr(1), 10), + minor: parseInt(parsedVersion[1], 10), + patch: parseInt(parsedVersion[2], 10) + }; +}; + +/** +* Calculate md5sum for the stream +* @ignore +*/ +exports.calculateMD5 = function(readStream, bufferLength, options, callback) { + var internalBuff = new Buffer(bufferLength); + var index = 0; + var internalHash = new Md5Wrapper().createMd5Hash(); + readStream.on('data', function(data) { + if (index + data.length > bufferLength) { + var copyLength = bufferLength - index; + if (copyLength > 0) { + data = data.slice(0, copyLength); + data.copy(internalBuff, index); + internalHash.update(data); + index += copyLength; + } + readStream.emit('end'); + } else { + data.copy(internalBuff, index); + internalHash.update(data); + index += data.length; + } + }).on('end', function() { + if (!readStream.endEmitted) { + internalBuff = internalBuff.slice(0, index); + var contentMD5 = internalHash.digest('base64'); + // Set the flag to be compatible with Nodejs 0.10 which will keep emitting data from + // the file stream when the read stream has emitted the end event from its listner. + readStream.endEmitted = true; + callback(internalBuff, contentMD5); + } + }); +}; + +/** +* Whether the content of buffer is all zero +*/ +exports.isBufferAllZero = function (buffer) { + for(var i = 0, len = buffer.length; i < len; i++) { + if (buffer[i] !== 0) { + return false; + } + } + return true; +}; + +/** +* Write zero to stream +*/ +var zeroBuffer = null; +exports.writeZerosToStream = function (stream, length, md5Hash, progressCallback, callback) { + var defaultBufferSize = Constants.BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + var bufferSize = Math.min(defaultBufferSize, length); + var remaining = length - bufferSize; + var buffer = null; + if (bufferSize == defaultBufferSize) { + if (!zeroBuffer) { + zeroBuffer = new Buffer(defaultBufferSize); + zeroBuffer.fill(0); + } + buffer = zeroBuffer; + } else { + buffer = new Buffer(bufferSize); + buffer.fill(0); + } + if (md5Hash) { + md5Hash.update(buffer); + } + //We can only write the entire buffer to stream instead of part of buffer. + return stream.write(buffer, function () { + if (exports.objectIsFunction(progressCallback)) { + progressCallback(null, buffer.length); + } + buffer = null; + if (remaining > 0) { + exports.writeZerosToStream(stream, remaining, md5Hash, progressCallback, callback); + } else if (exports.objectIsFunction(callback)) { + callback(null, null); + } + }); +}; + +/** +* Calculate md5sum for the content +*/ +exports.getContentMd5 = function (content, encoding) { + if (!encoding) encoding = 'base64'; + var internalHash = new Md5Wrapper().createMd5Hash(); + internalHash.update(content, 'utf8'); + return internalHash.digest(encoding); +}; + +exports.getNextLocation = function(lastLocation, locationMode) { + switch(locationMode) { + case StorageUtilities.LocationMode.PRIMARY_ONLY: + return Constants.StorageLocation.PRIMARY; + case StorageUtilities.LocationMode.SECONDARY_ONLY: + return Constants.StorageLocation.SECONDARY; + case StorageUtilities.LocationMode.PRIMARY_THEN_SECONDARY: + case StorageUtilities.LocationMode.SECONDARY_THEN_PRIMARY: + return (lastLocation === Constants.StorageLocation.PRIMARY) ? Constants.StorageLocation.SECONDARY : Constants.StorageLocation.PRIMARY; + default: + throw new RangeError(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'locationMode', locationMode)); + } +}; + +exports.getNextListingLocationMode = function (token) { + if(_.isNull(token) || _.isUndefined(token)) { + return Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + } + else { + switch (token.targetLocation) { + case Constants.StorageLocation.PRIMARY: + return Constants.RequestLocationMode.PRIMARY_ONLY; + case Constants.StorageLocation.SECONDARY: + return Constants.RequestLocationMode.SECONDARY_ONLY; + default: + throw new RangeError(util.format(SR.ARGUMENT_OUT_OF_RANGE_ERROR, 'targetLocation', token.targetLocation)); + } + } +}; + +exports.isStreamPaused = function (object) { + if (object instanceof stream) { + return object._paused === true || (object._readableState && object._readableState.flowing === false); + } + return false; +}; + +/** +* Parse copy progress string in the format of bytesCopied/totalBytes +*/ +exports.parseCopyProgress = function (progress) { + if (typeof progress != 'string' || progress.indexOf('/') === -1) { + return {}; + } + + var progressInfo = progress.split('/'); + return { bytesCopied: progressInfo[0], totalBytes: progressInfo[1] }; +}; + +/** +* The list of the properties should be normalized with explicit mapping +*/ +var normalizePropertyNameExceptionList = { + 'x-ms-blob-sequence-number': 'sequenceNumber', + 'content-Type': 'contentSettings.contentType', + 'content-Encoding': 'contentSettings.contentEncoding', + 'content-Language': 'contentSettings.contentLanguage', + 'cache-Control': 'contentSettings.cacheControl', + 'content-Disposition': 'contentSettings.contentDisposition', + 'content-MD5': 'contentSettings.contentMD5', + 'leaseId': 'lease.id', + 'leaseStatus': 'lease.status', + 'leaseDuration': 'lease.duration', + 'leaseState': 'lease.state', + 'copyId': 'copy.id', + 'copyStatus': 'copy.status', + 'copySource': 'copy.source', + 'copyProgress': 'copy.progress', + 'copyCompletionTime': 'copy.completionTime', + 'copyStatusDescription': 'copy.statusDescription', + 'copyDestinationSnapshot': 'copy.destinationSnapshot', + 'publicAccess': 'publicAccessLevel', + 'incrementalCopy': 'isIncrementalCopy' +}; + +/** +* Normalize the property name from XML to keep consistent with +* the name defined in the property headers +*/ +exports.normalizePropertyNameFromXML = function (propertyName) { + if (this.IsNullOrEmptyOrUndefinedOrWhiteSpace(propertyName)) { + return ''; + } + + propertyName = propertyName.trim(); + propertyName = propertyName[0].toLowerCase() + propertyName.substring(1); + // So far the cases are: + // for the 'last-modified' property in listing resources + // for the 'content-*' properties in listing resources + // for the 'cache-control' property in listing blobs + // for the 'x-ms-blob-sequence-number' in listing blobs + if (propertyName in normalizePropertyNameExceptionList) { + return normalizePropertyNameExceptionList[propertyName]; + } else if (propertyName.toLowerCase().indexOf('-') != -1) { + return propertyName.replace('-', ''); + } else { + return propertyName; + } +}; + +/** +* Set the property value from XML +*/ +exports.setPropertyValueFromXML = function (result, xmlNode, toNormalize) { + for (var subPropertyName in xmlNode) { + if (xmlNode.hasOwnProperty(subPropertyName)) { + if (toNormalize) { + var propertyChain = this.normalizePropertyNameFromXML(subPropertyName).split('.'); + exports.setObjectInnerPropertyValue(result, propertyChain, xmlNode[subPropertyName]); + } else { + result[subPropertyName.toLowerCase()] = xmlNode[subPropertyName]; + } + + if (subPropertyName.toLowerCase() === 'copyprogress') { + var info = this.parseCopyProgress(xmlNode[subPropertyName]); + exports.setObjectInnerPropertyValue(result, ['copy', 'bytesCopied'], parseInt(info.bytesCopied)); + exports.setObjectInnerPropertyValue(result, ['copy', 'totalBytes'], parseInt(info.totalBytes)); + } + } + } +}; + +/** + * Filter out non-reserved properties from options + */ +exports.filterOutNonReservedProperties = function (reserved, options) { + var nonReservedProperties = {}; + if (options) { + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + var isReserved = reserved.hasOwnProperty(prop); + var isFunction = typeof options[prop] === 'function'; + if (!isReserved && !isFunction) { + nonReservedProperties[prop] = options[prop]; + } + } + } + } + return nonReservedProperties; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/common/util/validate.js b/node_modules/azure-storage/lib/common/util/validate.js new file mode 100644 index 000000000..2128caa6a --- /dev/null +++ b/node_modules/azure-storage/lib/common/util/validate.js @@ -0,0 +1,560 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var _ = require('underscore'); +var util = require('util'); + +var constants = require('./../util/constants'); +var blobConstants = constants.BlobConstants; +var BlobUtilities = require('./../../services/blob/blobutilities'); +var FileUtilities = require('./../../services/file/fileutilities'); +var azureutil = require('./util'); +var SR = require('./sr'); +var check = require('validator'); +var errors = require('../errors/errors'); +var ArgumentError = errors.ArgumentError; +var ArgumentNullError = errors.ArgumentNullError; + +exports = module.exports; + +function initCallback(callbackParam, resultsCb) { + var fail; + if (callbackParam) { + fail = function (err) { + callbackParam(err); + return false; + }; + } else { + fail = function (err) { + throw err; + }; + callbackParam = function () {}; + } + + resultsCb(fail, callbackParam); +} + +/** +* Checks if the given value is a valid enumeration or not. +* +* @param {object} value The value to validate. +* @param {object} list The enumeration values. +* @return {boolean} +*/ +exports.isValidEnumValue = function (value, list, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (!list.some(function (current) { + return current.toLowerCase() === value.toLowerCase(); + })) { + return fail(new RangeError(util.format('Invalid value: %s. Options are: %s.', value, list))); + } + + callback(); + return true; +}; + +/** +* Creates a anonymous function that check if the given uri is valid or not. +* +* @param {string} uri The uri to validate. +* @return {boolean} +*/ +exports.isValidUri = function (uri) { + if (!check.isURL(uri)){ + throw new URIError('The provided URI "' + uri + '" is invalid.'); + } + return true; +}; + +/** +* Checks if the given host is valid or not. +* +* @param {string|object} host The host to validate. +* @return {boolean} +*/ +exports.isValidHost= function (host) { + if (azureutil.objectIsNull(host)) { + throw new ArgumentNullError('host', SR.STORAGE_HOST_LOCATION_REQUIRED); + } else { + var storageHost = {}; + storageHost.primaryHost = _.isString(host) ? host : host.primaryHost; + if (storageHost.primaryHost && !check.isURL(storageHost.primaryHost)){ + throw new URIError('The provided URI "' + storageHost.primaryHost + '" is invalid.'); + } + + storageHost.secondaryHost = _.isString(host) ? undefined : host.secondaryHost; + if (storageHost.secondaryHost && !check.isURL(storageHost.secondaryHost)){ + throw new URIError('The provided URI "' + storageHost.secondaryHost + '" is invalid.'); + } + + if (!storageHost.primaryHost && !storageHost.secondaryHost) { + throw new ArgumentNullError('host', SR.STORAGE_HOST_LOCATION_REQUIRED); + } + } + + return true; +}; + +/** +* Checks if the given value is a valid UUID or not. +* +* @param {string|object} uuid The uuid to validate. +* @return {boolean} +*/ +exports.isValidUuid = function(uuid, callback) { + var validUuidRegex = /^[a-zA-Z0-9]{8}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{4}\-[a-zA-Z0-9]{12}$/; + + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (!validUuidRegex.test(uuid)) { + return fail(new SyntaxError('The value is not a valid UUID format.')); + } + + callback(); + return true; +}; + +/** +* Creates a anonymous function that check if a given key is base 64 encoded. +* +* @param {string} key The key to validate. +* @return {function} +*/ +exports.isBase64Encoded = function (key) { + var isValidBase64String = key.match(/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/); + + if (isValidBase64String) { + return true; + } else { + throw new SyntaxError('The provided account key ' + key + ' is not a valid base64 string.'); + } +}; + +/** +* Validates a function. +* +* @param {object} function The function to validate. +* @return {function} +*/ +exports.isValidFunction = function (functionObject, functionName) { + if (!functionObject) { + throw new ArgumentNullError('functionObject', functionName + ' must be specified.'); + } + if(!_.isFunction(functionObject)){ + throw new TypeError(functionName + ' specified should be a function.'); + } + return true; +}; + +var getNameError = function(name, typeName) { + // checks if name is null, undefined or empty + if (azureutil.stringIsEmpty(name)) { + return new ArgumentNullError('name', util.format('%s name must be a non empty string.', typeName)); + } + + // check if name is between 3 and 63 characters + if (name.length < 3 || name.length > 63) { + return new ArgumentError('name', util.format('%s name must be between 3 and 63 characters long.', typeName)); + } + + // check if name follows naming rules + if (name.match(/^([a-z0-9]+(-[a-z0-9]+)*)$/) === null) { + return new SyntaxError(util.format('%s name format is incorrect.', typeName)); + } + + return null; +}; + +/** +* Validates a container name. +* +* @param {string} containerName The container name. +*/ +exports.containerNameIsValid = function (containerName, callback) { + var fail; + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + var nameError = getNameError(containerName, 'Container'); + + if (!nameError || containerName.match(/^(\$root|\$logs)$/)) { + callback(); + return true; + } else { + return fail(nameError); + } +}; + +/** +* Validates a blob name. +* +* @param {string} containerName The container name. +* @param {string} blobname The blob name. +*/ +exports.blobNameIsValid = function (containerName, blobName, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (!blobName) { + return fail(new ArgumentNullError('blobName', 'Blob name is not specified.')); + } + + if (containerName === '$root' && blobName.indexOf('/') !== -1) { + return fail(new SyntaxError('Blob name format is incorrect.')); + } + + callback(); + return true; +}; + +/** +* Validates a blob tier name. +* +* @param {string} blobTier The blob tier name. +*/ +exports.blobTierNameIsValid = function (blobTier, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (!blobTier) { + return fail(new ArgumentNullError('blobTier', 'Blob tier is not specified.')); + } + + if (!_.chain(_.union( + _.values(BlobUtilities.BlobTier.PremiumPageBlobTier), + _.values(BlobUtilities.BlobTier.StandardBlobTier) + )) + .map(function (val) { return val.toString().toUpperCase(); }) + .contains(blobTier.toString().toUpperCase()) + .value()) { + return fail(new SyntaxError('Blob tier is incorrect. Refer to BlobUtilities.BlobTier for possible values.')); + } + + callback(); + return true; +}; + +/** +* Validates a share name. +* +* @param {string} shareName The share name. +*/ +exports.shareNameIsValid = function (shareName, callback) { + var fail; + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + var nameError = getNameError(shareName, 'Share'); + + if (!nameError) { + callback(); + return true; + } else { + return fail(nameError); + } +}; + +/** +* Validates a queue name. +* +* @param {string} queueName The queue name. +*/ +exports.queueNameIsValid = function (queueName, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + var nameError = getNameError(queueName, 'Queue'); + + if (!nameError) { + callback(); + return true; + } else { + return fail(nameError); + } +}; + +/** +* Validates a table name. +* +* @param {string} table The table name. +*/ +exports.tableNameIsValid = function (table, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (azureutil.stringIsEmpty(table)) { + return fail(new ArgumentNullError('table', 'Table name must be a non empty string.')); + } + + if (table.length < 3 || table.length > 63) { + return fail(new ArgumentError('table', 'Table name must be between 3 and 63 characters long.')); + } + + if(table.toLowerCase() === 'tables') { + return fail(new RangeError('Table name cannot be \'Tables\'.')); + } + + if (table.match(/^([A-Za-z][A-Za-z0-9]{2,62})$/) !== null || table === '$MetricsCapacityBlob' || table.match(/^(\$Metrics(HourPrimary|MinutePrimary|HourSecondary|MinuteSecondary)?(Transactions)(Blob|Queue|Table|File))$/) !== null) + { + callback(); + return true; + } else { + return fail(new SyntaxError('Table name format is incorrect.')); + } +}; + +/** +* Validates an HTML File object. +* +* @param {File} browserFile The HTML File object. +*/ +exports.browserFileIsValid = function (browserFile, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + // IE doesn't support File.constructor.name + if (!azureutil.isBrowser() || + !browserFile || + !browserFile.constructor || + (!azureutil.isIE() && !browserFile.constructor.name) || + (!azureutil.isIE() && browserFile.constructor.name !== 'File' && browserFile.constructor.name !== 'Blob') || + !azureutil.objectIsInt(browserFile.size)) { + return fail(new ArgumentError('type', 'Invalid HTML File object.')); + } else { + callback(); + return true; + } +}; + +/** +* Validates page ranges. +* +* @param {int} rangeStart The range starting position. +* @param {int} rangeEnd The range ending position. +* @param {int} writeBlockSizeInBytes The block size. +*/ +exports.pageRangesAreValid = function (rangeStart, rangeEnd, writeBlockSizeInBytes, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (rangeStart % 512 !== 0) { + return fail(new RangeError('Start byte offset must be a multiple of 512.')); + } + + var size = null; + if (!azureutil.objectIsNull(rangeEnd)) { + if ((rangeEnd + 1) % 512 !== 0) { + return fail(new RangeError('End byte offset must be a multiple of 512 minus 1.')); + } + + size = (rangeEnd - rangeStart) + 1; + if (size > writeBlockSizeInBytes) { + return fail(new RangeError('Page blob size cannot be larger than ' + writeBlockSizeInBytes + ' bytes.')); + } + } + + callback(); + return true; +}; + +/** +* Validates a blob type. +* +* @param {string} type The type name. +*/ +exports.blobTypeIsValid = function (type, callback) { + var getEnumValues = function (obj) { + var values = []; + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + values.push(obj[prop]); + } + } + return values; + }; + + return this.isValidEnumValue(type, getEnumValues(blobConstants.BlobTypes), callback); +}; + +/** +* Validates share ACL type. +* +* @param {string} type The type name. +*/ +exports.shareACLIsValid = function (type, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (type != FileUtilities.SharePublicAccessType.OFF) { + fail(new ArgumentError('type', 'The access type is not supported.')); + } + + callback(); + return true; +}; + +/** +* Validates share quota value. +* +* @param {int} type The quota value. +*/ +exports.shareQuotaIsValid = function (quota, callback) { + var fail; + + initCallback(callback, function (f, cb) { + fail = f; + callback = cb; + }); + + if (quota && quota <= 0) { + fail(new RangeError('The share quota value, in GB, must be greater than 0.')); + } + + callback(); + return true; +}; + +// common functions for validating arguments + +function throwMissingArgument(name, func) { + throw new ArgumentNullError(name, 'Required argument ' + name + ' for function ' + func + ' is not defined'); +} + +function ArgumentValidator(functionName) { + this.func = functionName; +} + +_.extend(ArgumentValidator.prototype, { + string: function (val, name) { + this.exists(val, name); + if (typeof val !== 'string') { + throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be a non-empty string'); + } + }, + + stringAllowEmpty: function (val, name) { + if (typeof val !== 'string') { + throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be a string'); + } + }, + + object: function (val, name) { + this.exists(val, name); + if (typeof val !== 'object') { + throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be an object'); + } + }, + + exists: function (val, name) { + if (!val) { + throwMissingArgument(name, this.func); + } + }, + + function: function (val, name) { + this.exists(val, name); + if (typeof val !== 'function') { + throw new TypeError('Parameter ' + name + ' for function ' + this.func + ' should be a function'); + } + }, + + value: function (val, name) { + if (!val && val !== 0) { + throwMissingArgument(name, this.func); + } + }, + + nonEmptyArray: function (val, name) { + if (!val || val.length === 0) { + throw new TypeError('Required array argument ' + name + ' for function ' + this.func + ' is either not defined or empty'); + } + }, + + callback: function (val) { + this.exists(val, 'callback'); + this.function(val, 'callback'); + }, + + test: function (predicate, message) { + if (!predicate()) { + throw new Error(message + ' in function ' + this.func); + } + }, + + tableNameIsValid: exports.tableNameIsValid, + browserFileIsValid: exports.browserFileIsValid, + containerNameIsValid: exports.containerNameIsValid, + shareNameIsValid: exports.shareNameIsValid, + blobNameIsValid: exports.blobNameIsValid, + blobTierNameIsValid: exports.blobTierNameIsValid, + pageRangesAreValid: exports.pageRangesAreValid, + queueNameIsValid: exports.queueNameIsValid, + blobTypeIsValid: exports.blobTypeIsValid, + shareACLIsValid: exports.shareACLIsValid, + shareQuotaIsValid: exports.shareQuotaIsValid, + isValidEnumValue: exports.isValidEnumValue +}); + +function validateArgs(functionName, validationRules) { + var validator = new ArgumentValidator(functionName); + validationRules(validator); +} + +exports.ArgumentValidator = ArgumentValidator; +exports.validateArgs = validateArgs; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/blob/blobservice.browser.js b/node_modules/azure-storage/lib/services/blob/blobservice.browser.js new file mode 100644 index 000000000..d81f7cec7 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/blobservice.browser.js @@ -0,0 +1,319 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var BlobService = require('./blobservice.core'); +var azureCommon = require('./../../common/common.browser'); +var extend = require('extend'); +var mime = require('browserify-mime'); + +var Constants = azureCommon.Constants; +var azureutil = azureCommon.util; +var BlobConstants = Constants.BlobConstants; +var BrowserFileReadStream = azureCommon.BrowserFileReadStream; +var SpeedSummary = azureCommon.SpeedSummary; +var validate = azureCommon.validate; + +/** +* Creates a new block blob. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* (Only available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {File} browserFile The File object to be uploaded created by HTML File API. +* @param {object} [options] The request options. +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createBlockBlobFromBrowserFile = function (container, blob, browserFile, optionsOrCallback, callback) { + return this._createBlobFromBrowserFile(container, blob, BlobConstants.BlobTypes.BLOCK, browserFile, optionsOrCallback, callback); +}; + +/** +* Uploads a page blob from an HTML file. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* (Only available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {File} browserFile The File object to be uploaded created by HTML File API. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The upload tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createPageBlobFromBrowserFile = function (container, blob, browserFile, optionsOrCallback, callback) { + return this._createBlobFromBrowserFile(container, blob, BlobConstants.BlobTypes.PAGE, browserFile, optionsOrCallback, callback); +}; + +/** +* Creates a new append blob from an HTML File object. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* If you want to append data to an already existing blob, please look at appendFromBrowserFile. +* (Only available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {File} browserFile The File object to be uploaded created by HTML File API. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 ahash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createAppendBlobFromBrowserFile = function (container, blob, browserFile, optionsOrCallback, callback) { + return this._createBlobFromBrowserFile(container, blob, BlobConstants.BlobTypes.APPEND, browserFile, optionsOrCallback, callback); +}; + +/** +* Appends to an append blob from an HTML File object. Assumes the blob already exists on the service. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* (Only available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {File} browserFile The File object to be uploaded created by HTML File API. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.appendFromBrowserFile = function (container, blob, browserFile, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('appendFromBrowserFile', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.browserFileIsValid(browserFile); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + + var stream = new BrowserFileReadStream(browserFile); + var streamCallback = function (appendError, blob, response) { + if (azureutil.objectIsFunction(stream.destroy)) { + stream.destroy(); + } + callback(appendError, blob, response); + }; + this._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, browserFile.size, options, streamCallback); + + return options.speedSummary; +}; + +// Private methods + +/** +* Creates a new blob (Block/Page/Append). If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* (Only available in the JavaScript Client Library for Browsers) +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param {File} browserFile The File object to be uploaded created by HTML File API. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The MD5 hash of the blob content. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback The callback function. +* +* @return {SpeedSummary} +* +*/ +BlobService.prototype._createBlobFromBrowserFile = function (container, blob, blobType, browserFile, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_createBlobFromBrowserFile', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.blobTypeIsValid(blobType); + v.browserFileIsValid(browserFile); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + + var self = this; + var creationCallback = function (createError, createBlob, createResponse) { + if (createError) { + callback(createError, createBlob, createResponse); + } else { + // Automatically detect the mime type + if(azureutil.tryGetValueChain(options, ['contentSettings','contentType'], undefined) === undefined) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings','contentType'], mime.lookup(browserFile.name)); + } + + var stream = new BrowserFileReadStream(browserFile); + var streamCallback = function (createError, createBlob, createResponse) { + if (azureutil.objectIsFunction(stream.destroy)) { + stream.destroy(); + } + callback(createError, createBlob, createResponse); + }; + self._uploadBlobFromStream(true, container, blob, blobType, stream, browserFile.size, options, streamCallback); + } + }; + + this._createBlob(container, blob, blobType, browserFile.size, options, creationCallback); + + return options.speedSummary; +}; + +module.exports = BlobService; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/blob/blobservice.core.js b/node_modules/azure-storage/lib/services/blob/blobservice.core.js new file mode 100644 index 000000000..ceacb50b1 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/blobservice.core.js @@ -0,0 +1,5733 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var qs = require('querystring'); +var url = require('url'); +var util = require('util'); +var _ = require('underscore'); +var extend = require('extend'); + +var azureCommon = require('./../../common/common.core'); +var BlockRangeStream = require('./internal/blockrangestream'); +var Md5Wrapper = require('./../../common/md5-wrapper'); +var PageRangeStream = require('./internal/pagerangestream'); +var RangeStream = require('./../../common/streams/rangestream'); +var azureutil = azureCommon.util; +var SR = azureCommon.SR; +var validate = azureCommon.validate; +var StorageServiceClient = azureCommon.StorageServiceClient; +var WebResource = azureCommon.WebResource; + +// Constants +var Constants = azureCommon.Constants; +var BlobConstants = Constants.BlobConstants; +var HeaderConstants = Constants.HeaderConstants; +var QueryStringConstants = Constants.QueryStringConstants; +var RequestLocationMode = Constants.RequestLocationMode; + +// Streams +var BatchOperation = azureCommon.BatchOperation; +var SpeedSummary = azureCommon.SpeedSummary; +var ChunkAllocator = azureCommon.ChunkAllocator; +var ChunkStream = azureCommon.ChunkStream; +var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream; + +// Models requires +var AclResult = azureCommon.AclResult; +var ServiceStatsParser = azureCommon.ServiceStatsParser; +var BlockListResult = require('./models/blocklistresult'); +var BlobResult = require('./models/blobresult'); +var ContainerResult = require('./models/containerresult'); +var LeaseResult = require('./models/leaseresult'); + +var BlobUtilities = require('./blobutilities'); + +// Errors requires +var errors = require('../../common/errors/errors'); +var ArgumentError = errors.ArgumentError; +var ArgumentNullError = errors.ArgumentNullError; +var StorageError = errors.StorageError; + +/** +* Creates a new BlobService object. +* If no connection string or storageaccount and storageaccesskey are provided, +* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. +* @class +* The BlobService class is used to perform operations on the Microsoft Azure Blob Service. +* The Blob Service provides storage for binary large objects, and provides +* functions for working with data stored in blobs as either streams or pages of data. +* +* For more information on the Blob Service, as well as task focused information on using it in a Node.js application, see +* [How to Use the Blob Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/). +* The following defaults can be set on the blob service. +* singleBlobPutThresholdInBytes The default maximum size, in bytes, of a blob before it must be separated into blocks. +* defaultEnableReuseSocket The default boolean value to enable socket reuse when uploading local files or streams. +* If the Node.js version is lower than 0.10.x, socket reuse will always be turned off. +* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Blob service. +* defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Blob service. +* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Blob service. +* defaultLocationMode The default location mode for requests made via the Blob service. +* parallelOperationThreadCount The number of parallel operations that may be performed when uploading a blob that is greater than +* the value specified by the singleBlobPutThresholdInBytes property in size. +* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Blob service; true to use the +* Nagle algorithm; otherwise, false. The default value is false. +* @constructor +* @extends {StorageServiceClient} +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {string} [endpointSuffix] The endpoint suffix. +*/ +function BlobService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) { + var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix); + + BlobService['super_'].call(this, + storageServiceSettings._name, + storageServiceSettings._key, + storageServiceSettings._blobEndpoint, + storageServiceSettings._usePathStyleUri, + storageServiceSettings._sasToken); + + this.defaultEnableReuseSocket = Constants.DEFAULT_ENABLE_REUSE_SOCKET; + this.singleBlobPutThresholdInBytes = BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES; + this.parallelOperationThreadCount = Constants.DEFAULT_PARALLEL_OPERATION_THREAD_COUNT; +} + +util.inherits(BlobService, StorageServiceClient); + +// Non-class methods + +/** +* Create resource name +* @ignore +* +* @param {string} containerName Container name +* @param {string} blobName Blob name +* @return {string} The encoded resource name. +*/ +function createResourceName(containerName, blobName, forSAS) { + // Resource name + if (blobName && !forSAS) { + blobName = encodeURIComponent(blobName); + blobName = blobName.replace(/%2F/g, '/'); + blobName = blobName.replace(/%5C/g, '/'); + blobName = blobName.replace(/\+/g, '%20'); + } + + // return URI encoded resource name + if (blobName) { + return containerName + '/' + blobName; + } + else { + return containerName; + } +} + +// Blob service methods + +/** +* Gets the service stats for a storage account’s Blob service. +* +* @this {BlobService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceStats}` will contain the stats and +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getServiceStats = function (optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + validate.validateArgs('getServiceStats', function (v) { + v.callback(callback); + }); + + var webResource = WebResource.get() + .withQueryOption(QueryStringConstants.COMP, 'stats') + .withQueryOption(QueryStringConstants.RESTYPE, 'service'); + + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.serviceStatsResult = null; + if (!responseObject.error) { + responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats); + } + + // function to be called after all filters + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response); + }; + + // call the first filter + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets the properties of a storage account’s Blob service, including Azure Storage Analytics. +* +* @this {BlobService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceProperties}` will contain the properties +* and `response` will contain information related to this operation. +*/ +BlobService.prototype.getServiceProperties = function (optionsOrCallback, callback) { + return this.getAccountServiceProperties(optionsOrCallback, callback); +}; + +/** +* Sets the properties of a storage account's Blob service, including Azure Storage Analytics. +* You can also use this operation to set the default request version for all incoming requests that do not have a version specified. +* When you set blob service properties (such as enabling soft delete), it may take up to 30 seconds to take effect. +* +* @this {BlobService} +* @param {object} serviceProperties The service properties. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise, `response` +* will contain information related to this operation. +*/ +BlobService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) { + return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback); +}; + +/** +* Sets the tier of a blockblob under a blob storage account, or the tier of a pageblob under a premium storage account. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} blobTier Please see BlobUtilities.BlobTier.StandardBlobTier or BlobUtilities.BlobTier.PremiumPageBlobTier for possible values. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise, `response` +* will contain information related to this operation. +*/ +BlobService.prototype.setBlobTier = function (container, blob, blobTier, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setBlobTier', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.string(blobTier, 'blobTier'); + v.containerNameIsValid(container); + v.blobNameIsValid(container, blob); + v.blobTierNameIsValid(blobTier); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'tier') + .withHeader(HeaderConstants.ACCESS_TIER, blobTier); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Lists a segment containing a collection of container items under the specified account. +* +* @this {BlobService} +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage. +* @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata') +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[containers]{@link ContainerResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listContainersSegmented = function (currentToken, optionsOrCallback, callback) { + this.listContainersSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of container items whose names begin with the specified prefix under the specified account. +* +* @this {BlobService} +* @param {string} prefix The prefix of the container name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage. +* @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata') +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[containers]{@link ContainerResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listContainersSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listContainers', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get() + .withQueryOption(QueryStringConstants.COMP, 'list') + .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults) + .withQueryOption(QueryStringConstants.INCLUDE, options.include); + + if (!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker); + } + + webResource.withQueryOption(QueryStringConstants.PREFIX, prefix); + + options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken); + + var processResponseCallback = function (responseObject, next) { + responseObject.listContainersResult = null; + + if (!responseObject.error) { + responseObject.listContainersResult = { + entries: null, + continuationToken: null + }; + responseObject.listContainersResult.entries = []; + + var containers = []; + + if (responseObject.response.body.EnumerationResults.Containers && responseObject.response.body.EnumerationResults.Containers.Container) { + containers = responseObject.response.body.EnumerationResults.Containers.Container; + if (!_.isArray(containers)) { + containers = [containers]; + } + } + + containers.forEach(function (currentContainer) { + var containerResult = ContainerResult.parse(currentContainer); + responseObject.listContainersResult.entries.push(containerResult); + }); + + if (responseObject.response.body.EnumerationResults.NextMarker) { + responseObject.listContainersResult.continuationToken = { + nextMarker: null, + targetLocation: null + }; + + responseObject.listContainersResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker; + responseObject.listContainersResult.continuationToken.targetLocation = responseObject.targetLocation; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.listContainersResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +// Container methods + +/** +* Checks whether or not a container exists on the service. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerResult}` will contain +* the container information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.doesContainerExist = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('doesContainerExist', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + this._doesContainerExist(container, false, options, callback); +}; + +/** +* Creates a new container under the specified account. +* If a container with the same name already exists, the operation fails. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerResult}` will contain +* the container information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createContainer = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createContainer', function (v) { + v.string(container, 'container'); + v.test(function () { return container !== '$logs'; }, + 'Container name format is incorrect'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container'); + + webResource.addOptionalMetadataHeaders(options.metadata); + webResource.withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel); + + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.containerResult = new ContainerResult(container); + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + + if (options.metadata) { + responseObject.containerResult.metadata = options.metadata; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Creates a new container under the specified account if the container does not exists. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerResult}` will contain +* the container information including `created` boolean member. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error) { +* if(!error) { +* // Container created or exists, and is public +* } +* }); +*/ +BlobService.prototype.createContainerIfNotExists = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createContainerIfNotExists', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var self = this; + self._doesContainerExist(container, true, options, function (error, result, response) { + var exists = result.exists; + result.created = false; + delete result.exists; + + if (error) { + callback(error, result, response); + } else if (exists) { + response.isSuccessful = true; + callback(error, result, response); + } else { + self.createContainer(container, options, function (createError, containerResult, createResponse) { + if (!createError) { + containerResult.created = true; + } + else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS) { + // If it was created before, there was no actual error. + createError = null; + createResponse.isSuccessful = true; + } + + callback(createError, containerResult, createResponse); + }); + } + }); +}; + +/** +* Retrieves a container and its properties from a specified account. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {string} [options.leaseId] The container lease identifier. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerResult}` will contain +* information for the container. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getContainerProperties = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getContainerProperties', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.containerResult = new ContainerResult(container); + responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Returns all user-defined metadata for the container. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The container lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerResult}` will contain +* information for the container. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getContainerMetadata = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getContainerMetadata', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withQueryOption(QueryStringConstants.COMP, 'metadata') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.containerResult = new ContainerResult(container); + responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets the container's metadata. +* +* Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container. +* It's not possible to modify an individual name/value pair. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} metadata The metadata key/value pairs. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The container lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.setContainerMetadata = function (container, metadata, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setContainerMetadata', function (v) { + v.string(container, 'container'); + v.object(metadata, 'metadata'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withQueryOption(QueryStringConstants.COMP, 'metadata') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + webResource.addOptionalMetadataHeaders(metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.containerResult = new ContainerResult(container); + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets the container's ACL. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The container lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerAclResult}` will contain +* information for the container. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getContainerAcl = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getContainerAcl', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withQueryOption(QueryStringConstants.COMP, 'acl') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.containerResult = new ContainerResult(container); + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + responseObject.containerResult.signedIdentifiers = AclResult.parse(responseObject.response.body); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Updates the container's ACL. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {Object.} signedIdentifiers The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access. +* @param {string} [options.leaseId] The container lease identifier. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ContainerAclResult}` will contain +* information for the container. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.setContainerAcl = function (container, signedIdentifiers, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setContainerAcl', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var policies = null; + if (signedIdentifiers) { + if (_.isArray(signedIdentifiers)) { + throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS); + } + policies = AclResult.serialize(signedIdentifiers); + } + + var webResource = WebResource.put(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withQueryOption(QueryStringConstants.COMP, 'acl') + .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0) + .withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel) + .withHeader(HeaderConstants.LEASE_ID, options.leaseId) + .withBody(policies); + + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.containerResult = new ContainerResult(container, options.publicAccessLevel); + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + if (signedIdentifiers) { + responseObject.containerResult.signedIdentifiers = signedIdentifiers; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Marks the specified container for deletion. +* The container and any blobs contained within it are later deleted during garbage collection. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {string} [options.leaseId] The container lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.deleteContainer = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteContainer', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.del(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified container for deletion if it exists. +* The container and any blobs contained within it are later deleted during garbage collection. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {string} [options.leaseId] The container lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will +* be true if the container exists and was deleted, or false if the container +* did not exist. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.deleteContainerIfExists = function (container, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteContainerIfExists', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var self = this; + self._doesContainerExist(container, true, options, function (error, result, response) { + if (error) { + callback(error, result.exists, response); + } else if (!result.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteContainer(container, options, function (deleteError, deleteResponse) { + var deleted; + if (!deleteError) { + deleted = true; + } else if (deleteError && deleteError.statuscode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.BlobErrorCodeStrings.CONTAINER_NOT_FOUND) { + // If it was deleted already, there was no actual error. + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +/** +* Lists a segment containing a collection of blob directory items in the container. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {int} [options.maxResults] Specifies the maximum number of directories to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[directories]{@link DirectoryResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listBlobDirectoriesSegmented = function (container, currentToken, optionsOrCallback, callback) { + this.listBlobDirectoriesSegmentedWithPrefix(container, null /* prefix */, currentToken, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of blob directory items in the container. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} prefix The prefix of the blob directory. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {int} [options.maxResults] Specifies the maximum number of directories to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[directories]{@link BlobResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listBlobDirectoriesSegmentedWithPrefix = function (container, prefix, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + userOptions.delimiter = '/'; + + this._listBlobsOrDircotriesSegmentedWithPrefix(container, prefix, currentToken, BlobConstants.ListBlobTypes.Directory, userOptions, callback); +}; + +/** +* Lists a segment containing a collection of blob items in the container. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {string} [options.delimiter] Delimiter, i.e. '/', for specifying folder hierarchy. +* @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy', 'deleted'). +* Please find these values in BlobUtilities.BlobListingDetails. Multiple values can be added separated with a comma (,). +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[blobs]{@link BlobResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listBlobsSegmented = function (container, currentToken, optionsOrCallback, callback) { + this.listBlobsSegmentedWithPrefix(container, null /* prefix */, currentToken, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} prefix The prefix of the blob name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {string} [options.delimiter] Delimiter, i.e. '/', for specifying folder hierarchy. +* @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy', 'deleted'). +* Please find these values in BlobUtilities.BlobListingDetails. Multiple values can be added separated with a comma (,). +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the entries of `[blobs]{@link BlobResult}` and the continuation token for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listBlobsSegmentedWithPrefix = function (container, prefix, currentToken, optionsOrCallback, callback) { + this._listBlobsOrDircotriesSegmentedWithPrefix(container, prefix, currentToken, BlobConstants.ListBlobTypes.Blob, optionsOrCallback, callback); +}; + +// Lease methods + +/** +* Acquires a new lease. If container and blob are specified, acquires a blob lease. Otherwise, if only container is specified and blob is null, acquires a container lease. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.leaseDuration] The lease duration in seconds. A non-infinite lease can be between 15 and 60 seconds. Default is never to expire. +* @param {string} [options.proposedLeaseId] The proposed lease identifier. Must be a GUID. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link LeaseResult}` will contain +* the lease information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.acquireLease = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('acquireLease', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + if (!options.leaseDuration) { + options.leaseDuration = -1; + } + + this._leaseImpl(container, blob, null /* leaseId */, BlobConstants.LeaseOperation.ACQUIRE, options, callback); +}; + +/** +* Renews an existing lease. If container and blob are specified, renews the blob lease. Otherwise, if only container is specified and blob is null, renews the container lease. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} leaseId The lease identifier. Must be a GUID. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link LeaseResult}` will contain +* the lease information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.renewLease = function (container, blob, leaseId, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('renewLease', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.RENEW, options, callback); +}; + +/** +* Changes the lease ID of an active lease. If container and blob are specified, changes the blob lease. Otherwise, if only container is specified and blob is null, changes the +* container lease. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} leaseId The current lease identifier. +* @param {string} proposedLeaseId The proposed lease identifier. Must be a GUID. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link LeaseResult}` will contain the lease information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.changeLease = function (container, blob, leaseId, proposedLeaseId, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('changeLease', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + options.proposedLeaseId = proposedLeaseId; + this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.CHANGE, options, callback); +}; + +/** +* Releases the lease. If container and blob are specified, releases the blob lease. Otherwise, if only container is specified and blob is null, releases the container lease. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} leaseId The lease identifier. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link LeaseResult}` will contain +* the lease information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.releaseLease = function (container, blob, leaseId, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('releaseLease', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + this._leaseImpl(container, blob, leaseId, BlobConstants.LeaseOperation.RELEASE, options, callback); +}; + +/** +* Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. If container and blob are specified, breaks the blob lease. +* Otherwise, if only container is specified and blob is null, breaks the container lease. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {int} [options.leaseBreakPeriod] The lease break period, between 0 and 60 seconds. If unspecified, a fixed-duration lease breaks after +* the remaining lease period elapses, and an infinite lease breaks immediately. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link LeaseResult}` will contain +* the lease information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.breakLease = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('breakLease', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + this._leaseImpl(container, blob, null /*leaseId*/, BlobConstants.LeaseOperation.BREAK, options, callback); +}; + +// Blob methods + +/** +* Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. +* It does not return or modify the content of the blob. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* information about the blob. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getBlobProperties = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getBlobProperties', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.head(resourceName); + + if (options.snapshotId) { + webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + } + + BlobResult.setHeadersFromBlob(webResource, options); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Returns all user-defined metadata for the specified blob or snapshot. +* It does not modify or return the content of the blob. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* information about the blob. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getBlobMetadata = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getBlobMetadata', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.head(resourceName); + + webResource.withQueryOption(QueryStringConstants.COMP, 'metadata'); + webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + + BlobResult.setHeadersFromBlob(webResource, options); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets user-defined properties for the specified blob or snapshot. +* It does not modify or return the content of the blob. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [properties] The blob properties to set. +* @param {string} [properties.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [properties.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [properties.contentLanguage] The natural languages used by this resource. +* @param {string} [properties.cacheControl] The blob's cache control. +* @param {string} [properties.contentDisposition] The blob's content disposition. +* @param {string} [properties.contentMD5] The blob's MD5 hash. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* information about the blob. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.setBlobProperties = function (container, blob, properties, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setBlobProperties', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, { contentSettings: properties }, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'properties'); + + BlobResult.setPropertiesFromBlob(webResource, options); + + this._setBlobPropertiesHelper({ + webResource: webResource, + options: options, + container: container, + blob: blob, + callback: callback + }); +}; + +/** +* Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs +* It does not modify or return the content of the blob. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} metadata The metadata key/value pairs. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* information on the blob. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.setBlobMetadata = function (container, blob, metadata, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setBlobMetadata', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.object(metadata, 'metadata'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'metadata'); + + webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + + options.metadata = metadata; + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + + +/** +* Provides a stream to read from a blob. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link BlobResult}` will contain the blob information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* var writable = fs.createWriteStream(destinationFileNameTarget); +* blobService.createReadStream(containerName, blobName).pipe(writable); +*/ +BlobService.prototype.createReadStream = function (container, blob, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + validate.validateArgs('createReadStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + }); + + var readStream = new ChunkStream(); + this.getBlobToStream(container, blob, readStream, options, function (error, responseBlob, response) { + if (error) { + readStream.emit('error', error); + } + + if (callback) { + callback(error, responseBlob, response); + } + }); + + return readStream; +}; + +/** +* Downloads a blob into a stream. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {Stream} writeStream The write stream. +* @param {object} [options] The request options. +* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download. +* Set the option to true for small blobs. +* Parallel download and speed summary won't work with this option on. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link BlobResult}` will contain the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +* +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* blobService.getBlobToStream('taskcontainer', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverBlob) { +* if(!error) { +* // Blob available in serverBlob.blob variable +* } +* }); +*/ +BlobService.prototype.getBlobToStream = function (container, blob, writeStream, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + userOptions.speedSummary = userOptions.speedSummary || new SpeedSummary(blob); + + validate.validateArgs('getBlobToStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.object(writeStream, 'writeStream'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var propertiesRequestOptions = { + timeoutIntervalInMs: options.timeoutIntervalInMs, + clientRequestTimeoutInMs: options.clientRequestTimeoutInMs, + snapshotId: options.snapshotId, + accessConditions: options.accessConditions + }; + + if (options.skipSizeCheck) { + this._getBlobToStream(container, blob, writeStream, options, callback); + } else { + var self = this; + this.getBlobProperties(container, blob, propertiesRequestOptions, function (error, properties) { + if (error) { + callback(error); + } else { + var size; + if (options.rangeStart) { + var endOffset = properties.contentLength - 1; + var end = options.rangeEnd ? Math.min(options.rangeEnd, endOffset) : endOffset; + size = end - options.rangeStart + 1; + } else { + size = properties.contentLength; + } + options.speedSummary.totalSize = size; + + if (size > self.singleBlobPutThresholdInBytes) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(properties, ['contentSettings', 'contentMD5'], null)); + self._getBlobToRangeStream(container, blob, properties.blobType, writeStream, options, callback); + } else { + self._getBlobToStream(container, blob, writeStream, options, callback); + } + } + }); + } + + return options.speedSummary; +}; + +/** +* Downloads a blob into a text string. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {BlobService~blobToText} callback `error` will contain information +* if an error occurs; otherwise `text` will contain the blob contents, +* and `[blockBlob]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getBlobToText = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getBlobToText', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.get(resourceName) + .withRawResponse(); + + webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + + BlobResult.setHeadersFromBlob(webResource, options); + this._setRangeContentMD5Header(webResource, options); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.text = null; + responseObject.blobResult = null; + + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + responseObject.text = responseObject.response.body; + + self._validateLengthAndMD5(options, responseObject); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.text, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. +* If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, +* or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error +* and nothing will be deleted. +* If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; `response` will contain information related to this operation. +*/ +BlobService.prototype.deleteBlob = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.del(resourceName) + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + if (!azureutil.objectIsNull(options.snapshotId) && !azureutil.objectIsNull(options.deleteSnapshots)) { + throw new ArgumentError('options', SR.INVALID_DELETE_SNAPSHOT_OPTION); + } + + webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + webResource.withHeader(HeaderConstants.DELETE_SNAPSHOT, options.deleteSnapshots); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* The undelete Blob operation restores the contents and metadata of soft deleted blob or snapshot. +* Attempting to undelete a blob or snapshot that is not soft deleted will succeed without any changes. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; `response` will contain information related to this operation. +*/ +BlobService.prototype.undeleteBlob = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'undelete'); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks whether or not a blob exists on the service. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information including the `exists` boolean member. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.doesBlobExist = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('doesBlobExist', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + this._doesBlobExist(container, blob, false, options, callback); +}; + +/** +* Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted during garbage collection. +* If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, +* or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error +* and nothing will be deleted. +* If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will +* be true if the blob was deleted, or false if the blob +* does not exist. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.deleteBlobIfExists = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteBlobIfExists', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var self = this; + self._doesBlobExist(container, blob, true, options, function (error, existsResult, response) { + if (error) { + callback(error, existsResult.exists, response); + } else if (!existsResult.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteBlob(container, blob, options, function (deleteError, deleteResponse) { + var deleted; + if (!deleteError) { + deleted = true; + } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.BlobErrorCodeStrings.BLOB_NOT_FOUND) { + // If it was deleted already, there was no actual error. + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +/** +* Creates a read-only snapshot of a blob. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {string} [options.leaseId] The lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the ID of the snapshot. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createBlobSnapshot = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createBlobSnapshot', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'snapshot'); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.snapshotId = null; + if (!responseObject.error) { + responseObject.snapshotId = responseObject.response.headers[HeaderConstants.SNAPSHOT]; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.snapshotId, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. +* +* @this {BlobService} +* @param {string} sourceUri The source blob URI. +* @param {string} targetContainer The target container name. +* @param {string} targetBlob The target blob name. +* @param {object} [options] The request options. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {boolean} [options.isIncrementalCopy] If it's incremental copy or not. Refer to https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/incremental-copy-blob +* @param {string} [options.snapshotId] The source blob snapshot identifier. +* @param {object} [options.metadata] The target blob metadata key/value pairs. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.sourceLeaseId] The source blob lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {AccessConditions} [options.sourceAccessConditions] The source access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.startCopyBlob = function (sourceUri, targetContainer, targetBlob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('startCopyBlob', function (v) { + v.string(sourceUri, 'sourceUri'); + v.string(targetContainer, 'targetContainer'); + v.string(targetBlob, 'targetBlob'); + v.containerNameIsValid(targetContainer); + v.callback(callback); + }); + + var targetResourceName = createResourceName(targetContainer, targetBlob); + + var options = extend(true, {}, userOptions); + + if (options.snapshotId) { + var uri = url.parse(sourceUri, true); + if (uri.query['snapshot']) { + throw new ArgumentError('options.snapshotId', 'Duplicate snapshot supplied in both the source uri and option.'); + } + + uri.search = undefined; + uri.query['snapshot'] = options.snapshotId; + + sourceUri = url.format(uri); + } + + var webResource = WebResource.put(targetResourceName) + .withHeader(HeaderConstants.COPY_SOURCE, sourceUri); + + if (options.isIncrementalCopy) { + webResource.withQueryOption(QueryStringConstants.COMP, 'incrementalcopy'); + } + + webResource.withHeader(HeaderConstants.ACCESS_TIER, options.blobTier); + webResource.withHeader(HeaderConstants.LEASE_ID, options.leaseId); + webResource.withHeader(HeaderConstants.SOURCE_LEASE_ID, options.sourceLeaseId); + webResource.addOptionalMetadataHeaders(options.metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(targetContainer, targetBlob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + + if (options.metadata) { + responseObject.blobResult.metadata = options.metadata; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Abort a blob copy operation. +* +* @this {BlobService} +* @param {string} container The destination container name. +* @param {string} blob The destination blob name. +* @param {string} copyId The copy operation identifier. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information if an error occurs; +* `response` will contain information related to this operation. +*/ +BlobService.prototype.abortCopyBlob = function (container, blob, copyId, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('abortCopyBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var resourceName = createResourceName(container, blob); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COPY_ID, copyId) + .withQueryOption(QueryStringConstants.COMP, 'copy') + .withHeader(HeaderConstants.COPY_ACTION, 'abort'); + + webResource.withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Retrieves a shared access signature token. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} [blob] The blob name. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {string} [sharedAccessPolicy.Id] The signed identifier. +* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired (The UTC value will be used). +* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} [sharedAccessPolicy.AccessPolicy.Protocols] The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* @param {object} [headers] The optional header values to set for a blob returned wth this SAS. +* @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used. +* @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used. +* @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used. +* @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used. +* @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used. +* @return {string} The shared access signature query string. Note this string does not contain the leading "?". +*/ +BlobService.prototype.generateSharedAccessSignature = function (container, blob, sharedAccessPolicy, headers) { + // check if the BlobService is able to generate a shared access signature + if (!this.storageCredentials) { + throw new ArgumentNullError('storageCredentials'); + } + + if (!this.storageCredentials.generateSignedQueryString) { + throw new ArgumentError('storageCredentials', SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY); + } + + // Validate container name. Blob name is optional. + validate.validateArgs('generateSharedAccessSignature', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.object(sharedAccessPolicy, 'sharedAccessPolicy'); + }); + + var resourceType = BlobConstants.ResourceTypes.CONTAINER; + if (blob) { + validate.validateArgs('generateSharedAccessSignature', function (v) { + v.string(blob, 'blob'); + }); + resourceType = BlobConstants.ResourceTypes.BLOB; + } + + if (sharedAccessPolicy.AccessPolicy) { + if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Start)) { + if (!_.isDate(sharedAccessPolicy.AccessPolicy.Start)) { + sharedAccessPolicy.AccessPolicy.Start = new Date(sharedAccessPolicy.AccessPolicy.Start); + } + + sharedAccessPolicy.AccessPolicy.Start = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Start); + } + + if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Expiry)) { + if (!_.isDate(sharedAccessPolicy.AccessPolicy.Expiry)) { + sharedAccessPolicy.AccessPolicy.Expiry = new Date(sharedAccessPolicy.AccessPolicy.Expiry); + } + + sharedAccessPolicy.AccessPolicy.Expiry = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Expiry); + } + } + + var resourceName = createResourceName(container, blob, true); + return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Blob, resourceName, sharedAccessPolicy, null, { headers: headers, resourceType: resourceType }); +}; + +/** +* Retrieves a blob or container URL. +* +* @param {string} container The container name. +* @param {string} [blob] The blob name. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint. +* @param {boolean} [snapshotId] The snapshot identifier. +* @return {string} The formatted URL string. +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* var sharedAccessPolicy = { +* AccessPolicy: { +* Permissions: azure.BlobUtilities.SharedAccessPermissions.READ, +* Start: startDate, +* Expiry: expiryDate +* }, +* }; +* +* var sasToken = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy); +* var sasUrl = blobService.getUrl(containerName, blobName, sasToken); +*/ +BlobService.prototype.getUrl = function (container, blob, sasToken, primary, snapshotId) { + validate.validateArgs('getUrl', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + }); + + var host; + if (!azureutil.objectIsNull(primary) && primary === false) { + host = this.host.secondaryHost; + } else { + host = this.host.primaryHost; + } + + host = azureutil.trimPortFromUri(host); + if (host && host.lastIndexOf('/') !== (host.length - 1)) { + host = host + '/'; + } + + var query = qs.parse(sasToken); + if (snapshotId) { + query[QueryStringConstants.SNAPSHOT] = snapshotId; + } + + var fullPath = url.format({ pathname: this._getPath(createResourceName(container, blob)), query: query }); + return url.resolve(host, fullPath); +}; + +// Page blob methods + +/** +* Creates a page blob of the specified length. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {int} length The length of the page blob in bytes. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The MD5 hash of the blob content. +* @param {string} [options.sequenceNumber] The blob's sequence number. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createPageBlob = function (container, blob, length, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createPageBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.value(length, 'length'); + v.callback(callback); + }); + + if (length && length % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_BLOB_LENGTH); + } + + var options = extend(true, {}, userOptions); + + var resourceName = createResourceName(container, blob); + + var webResource = WebResource.put(resourceName) + .withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.PAGE) + .withHeader(HeaderConstants.BLOB_CONTENT_LENGTH, length) + .withHeader(HeaderConstants.CONTENT_LENGTH, 0) + .withHeader(HeaderConstants.ACCESS_TIER, options.blobTier) + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Uploads a page blob from a stream. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createPageBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) { + return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.PAGE, stream, streamLength, optionsOrCallback, callback); +}; + +/** +* Provides a stream to write to a page blob. Assumes that the blob exists. +* If it does not, please create the blob using createPageBlob before calling this method or use createWriteStreamNewPageBlob. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs and true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* blobService.createPageBlob(containerName, blobName, 1024, function (err) { +* // Pipe file to a blob +* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToExistingPageBlob(containerName, blobName)); +* }); +*/ +BlobService.prototype.createWriteStreamToExistingPageBlob = function (container, blob, optionsOrCallback, callback) { + return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.PAGE, 0, false, optionsOrCallback, callback); +}; + +/** +* Provides a stream to write to a page blob. Creates the blob before writing data. If the blob already exists on the service, it will be overwritten. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} length The blob length. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs and true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* blobService.createPageBlob(containerName, blobName, 1024, function (err) { +* // Pipe file to a blob +* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToNewPageBlob(containerName, blobName)); +* }); +*/ +BlobService.prototype.createWriteStreamToNewPageBlob = function (container, blob, length, optionsOrCallback, callback) { + return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.PAGE, length, true, optionsOrCallback, callback); +}; + +/** +* Updates a page blob from a stream. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {Stream} readStream The read stream. +* @param {int} rangeStart The range start. +* @param {int} rangeEnd The range end. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.transactionalContentMD5] An optional hash value used to ensure transactional integrity for the page. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the page information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createPagesFromStream = function (container, blob, readStream, rangeStart, rangeEnd, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createPagesFromStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + if ((rangeEnd - rangeStart) + 1 > BlobConstants.MAX_UPDATE_PAGE_SIZE) { + throw new RangeError(SR.INVALID_PAGE_RANGE_FOR_UPDATE); + } + + var self = this; + if (azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) { + azureutil.calculateMD5(readStream, BlobConstants.MAX_UPDATE_PAGE_SIZE, options, function (internalBuff, contentMD5) { + options.transactionalContentMD5 = contentMD5; + self._createPages(container, blob, internalBuff, null /* stream */, rangeStart, rangeEnd, options, callback); + }); + } else { + self._createPages(container, blob, null /* text */, readStream, rangeStart, rangeEnd, options, callback); + } +}; + +/** +* Lists page ranges. Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {int} [options.rangeStart] The range start. +* @param {int} [options.rangeEnd] The range end. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the page ranges information, see `[Range]{@link Range}` for detailed information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listPageRanges = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listPageRanges', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var resourceName = createResourceName(container, blob); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'pagelist') + .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + + if (options.rangeStart && options.rangeStart % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_START_OFFSET); + } + + if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_END_OFFSET); + } + + BlobResult.setHeadersFromBlob(webResource, options); + + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.pageRanges = null; + if (!responseObject.error) { + responseObject.pageRanges = []; + + var pageRanges = []; + if (responseObject.response.body.PageList.PageRange) { + pageRanges = responseObject.response.body.PageList.PageRange; + + if (!_.isArray(pageRanges)) { + pageRanges = [pageRanges]; + } + } + + pageRanges.forEach(function (pageRange) { + var range = { + start: parseInt(pageRange.Start, 10), + end: parseInt(pageRange.End, 10) + }; + + responseObject.pageRanges.push(range); + }); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.pageRanges, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets page ranges that have been updated or cleared since the snapshot specified by `previousSnapshotTime` was taken. Gets all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} previousSnapshotTime The previous snapshot time for comparison. Must be prior to `options.snapshotId` if it's provided. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {int} [options.rangeStart] The range start. +* @param {int} [options.rangeEnd] The range end. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the page ranges diff information, see `[RangeDiff]{@link RangeDiff}` for detailed information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.getPageRangesDiff = function (container, blob, previousSnapshotTime, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getPageRangesDiff', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var resourceName = createResourceName(container, blob); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'pagelist') + .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId) + .withQueryOption(QueryStringConstants.PREV_SNAPSHOT, previousSnapshotTime); + + if (options.rangeStart && options.rangeStart % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_START_OFFSET); + } + + if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_END_OFFSET); + } + + if (options.rangeEnd && (options.rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_END_OFFSET); + } + + BlobResult.setHeadersFromBlob(webResource, options); + + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.pageRangesDiff = null; + if (!responseObject.error) { + responseObject.pageRangesDiff = []; + + if (responseObject.response.body.PageList.PageRange) { + var updatedPageRanges = responseObject.response.body.PageList.PageRange; + + if (!_.isArray(updatedPageRanges)) { + updatedPageRanges = [updatedPageRanges]; + } + + updatedPageRanges.forEach(function (pageRange) { + var range = { + start: parseInt(pageRange.Start, 10), + end: parseInt(pageRange.End, 10), + isCleared: false + }; + + responseObject.pageRangesDiff.push(range); + }); + } + + if (responseObject.response.body.PageList.ClearRange) { + var clearedPageRanges = responseObject.response.body.PageList.ClearRange; + + if (!_.isArray(clearedPageRanges)) { + clearedPageRanges = [clearedPageRanges]; + } + + clearedPageRanges.forEach(function (pageRange) { + var range = { + start: parseInt(pageRange.Start, 10), + end: parseInt(pageRange.End, 10), + isCleared: true + }; + + responseObject.pageRangesDiff.push(range); + }); + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.pageRangesDiff, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Clears a range of pages. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {int} rangeStart The range start. +* @param {int} rangeEnd The range end. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.clearPageRange = function (container, blob, rangeStart, rangeEnd, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('clearPageRange', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var request = this._updatePageBlobPagesImpl(container, blob, rangeStart, rangeEnd, BlobConstants.PageWriteOptions.CLEAR, options); + + var self = this; + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + self.performRequest(request, null, options, processResponseCallback); +}; + +/** +* Resizes a page blob. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {String} size The size of the page blob, in bytes. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The blob lease identifier. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the page information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.resizePageBlob = function (container, blob, size, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('resizePageBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'properties') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + if (size && size % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_BLOB_LENGTH); + } + + webResource.withHeader(HeaderConstants.BLOB_CONTENT_LENGTH, size); + + this._setBlobPropertiesHelper({ + webResource: webResource, + options: options, + container: container, + blob: blob, + callback: callback + }); + +}; + +/** +* Sets the page blob's sequence number. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {SequenceNumberAction} sequenceNumberAction A value indicating the operation to perform on the sequence number. +* The allowed values are defined in azure.BlobUtilities.SequenceNumberAction. +* @param {string} sequenceNumber The sequence number. The value of the sequence number must be between 0 and 2^63 - 1. +* Set this parameter to null if this operation is an increment action. +* @param {object} [options] The request options. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the page information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.setPageBlobSequenceNumber = function (container, blob, sequenceNumberAction, sequenceNumber, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setPageBlobSequenceNumber', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + if (sequenceNumberAction === BlobUtilities.SequenceNumberAction.INCREMENT) { + if (!azureutil.objectIsNull(sequenceNumber)) { + throw new ArgumentError('sequenceNumber', SR.BLOB_INVALID_SEQUENCE_NUMBER); + } + } else { + if (azureutil.objectIsNull(sequenceNumber)) { + throw new ArgumentNullError('sequenceNumber', util.format(SR.ARGUMENT_NULL_OR_EMPTY, 'sequenceNumber')); + } + } + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'properties') + .withHeader(HeaderConstants.SEQUENCE_NUMBER_ACTION, sequenceNumberAction); + + if (sequenceNumberAction !== BlobUtilities.SequenceNumberAction.INCREMENT) { + webResource.withHeader(HeaderConstants.SEQUENCE_NUMBER, sequenceNumber); + } + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +// Block blob methods + +/** +* Uploads a block blob from a stream. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createBlockBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) { + return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.BLOCK, stream, streamLength, optionsOrCallback, callback); +}; + +/** +* Uploads a block blob from a text string. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|object} text The blob text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createBlockBlobFromText = function (container, blob, text, optionsOrCallback, callback) { + return this._createBlobFromText(container, blob, BlobConstants.BlobTypes.BLOCK, text, optionsOrCallback, callback); +}; + +/** +* Provides a stream to write to a block blob. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs and true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToBlockBlob(containerName, blobName, { blockIdPrefix: 'block' })); +*/ +BlobService.prototype.createWriteStreamToBlockBlob = function (container, blob, optionsOrCallback, callback) { + return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.BLOCK, 0, false, optionsOrCallback, callback); +}; + +/** +* Creates a new block to be committed as part of a blob. +* +* @this {BlobService} +* @param {string} blockId The block identifier. +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {Stream} readStream The read stream. +* @param {int} streamLength The stream length. +* @param {object} [options] The request options. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createBlockFromStream = function (blockId, container, blob, readStream, streamLength, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createBlockFromStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.exists(readStream, 'readStream'); + v.value(streamLength, 'streamLength'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + if (streamLength > BlobConstants.MAX_BLOCK_BLOB_BLOCK_SIZE) { + throw new RangeError(SR.INVALID_STREAM_LENGTH); + } else { + this._createBlock(blockId, container, blob, null, readStream, streamLength, options, callback); + } +}; + +/** +* Creates a new block to be committed as part of a blob. +* +* @this {BlobService} +* @param {string} blockId The block identifier. +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|buffer} content The block content. +* @param {object} [options] The request options. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createBlockFromText = function (blockId, container, blob, content, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createBlockFromText', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content)); + + if (contentLength > BlobConstants.MAX_BLOCK_BLOB_BLOCK_SIZE) { + throw new RangeError(SR.INVALID_TEXT_LENGTH); + } else { + this._createBlock(blockId, container, blob, content, null, contentLength, options, callback); + } +}; + +/** +* Creates a new block to be committed as part of a block blob. +* @ignore +* +* @this {BlobService} +* @param {string} blockId The block identifier. +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|buffer} content The block content. +* @param (Stream) stream The stream to the data to store. +* @param {int} length The length of the stream or text to upload. +* @param {object} [options] The request options. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype._createBlock = function (blockId, container, blob, content, stream, length, options, callback) { + var resourceName = createResourceName(container, blob); + + var self = this; + var startCreateBlock = function () { + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'block') + .withQueryOption(QueryStringConstants.BLOCK_ID, new Buffer(blockId).toString('base64')) + .withHeader(HeaderConstants.CONTENT_LENGTH, length); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + if (!azureutil.objectIsNull(content)) { + self.performRequest(webResource, content, options, processResponseCallback); + } else { + self.performRequestOutputStream(webResource, stream, options, processResponseCallback); + } + }; + + if (azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) { + if (!azureutil.objectIsNull(content)) { + options.transactionalContentMD5 = azureutil.getContentMd5(content); + startCreateBlock(); + } else { + azureutil.calculateMD5(stream, length, options, function (internalBuff, contentMD5) { + options.transactionalContentMD5 = contentMD5; + content = internalBuff; + length = internalBuff.length; + startCreateBlock(); + }); + } + } else { + startCreateBlock(); + } +}; + +/** +* Writes a blob by specifying the list of block IDs that make up the blob. +* In order to be written as part of a blob, a block must have been successfully written to the server in a prior +* createBlock operation. +* Note: If no valid list is specified in the blockList parameter, blob would be updated with empty content, +* i.e. existing blocks in the blob will be removed, this behavior is kept for backward compatibility consideration. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} blockList The wrapper for block ID list contains block IDs that make up the blob. +* Three kinds of list are provided, please choose one to use according to requirement. +* For more background knowledge, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-list +* @param {string[]} [blockList.LatestBlocks] The list contains block IDs that make up the blob sequentially. +* All the block IDs in this list will be specified within Latest element. +* Choose this list to contain block IDs indicates that the Blob service should first search +* the uncommitted block list, and then the committed block list for the named block. +* @param {string[]} [blockList.CommittedBlocks] The list contains block IDs that make up the blob sequentially. +* All the block IDs in this list will be specified within Committed element. +* Choose this list to contain block IDs indicates that the Blob service should only search +* the committed block list for the named block. +* @param {string[]} [blockList.UncommittedBlocks] The list contains block IDs that make up the blob sequentially. +* All the block IDs in this list will be specified within Uncommitted element. +* Choose this list to contain block IDs indicates that the Blob service should only search +* the uncommitted block list for the named block. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* blobService.createBlockFromText("sampleBlockName", containerName, blobName, "sampleBlockContent", function(error) { +* assert.equal(error, null); +* // In this example, LatestBlocks is used, we hope the Blob service first search +* // the uncommitted block list, and then the committed block list for the named block "sampleBlockName", +* // and thus make sure the block is with latest content. +* blobService.commitBlocks(containerName, blobName, { LatestBlocks: ["sampleBlockName"] }, function(error) { +* assert.equal(error, null); +* }); +* }); +* + */ +BlobService.prototype.commitBlocks = function (container, blob, blockList, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('commitBlocks', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.object(blockList, 'blockList'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var blockListXml = BlockListResult.serialize(blockList); + + var resourceName = createResourceName(container, blob); + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'blocklist') + .withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(blockListXml)) + .withBody(blockListXml); + + BlobResult.setPropertiesFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.list = null; + if (!responseObject.error) { + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + responseObject.blobResult.list = blockList; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Retrieves the list of blocks that have been uploaded as part of a block blob. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlockListFilter} blocklisttype The type of block list to retrieve. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The source blob snapshot identifier. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the blocklist information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.listBlocks = function (container, blob, blocklisttype, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listBlocks', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var resourceName = createResourceName(container, blob); + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'blocklist') + .withQueryOption(QueryStringConstants.BLOCK_LIST_TYPE, blocklisttype) + .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.blockListResult = null; + if (!responseObject.error) { + responseObject.blockListResult = BlockListResult.parse(responseObject.response.body.BlockList); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blockListResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Generate a random block id prefix +*/ +BlobService.prototype.generateBlockIdPrefix = function () { + var prefix = Math.floor(Math.random() * 0x100000000).toString(16); + return azureutil.zeroPaddingString(prefix, 8); +}; + +/** +* Get a block id according to prefix and block number +*/ +BlobService.prototype.getBlockId = function (prefix, number) { + return prefix + '-' + azureutil.zeroPaddingString(number, 6); +}; + +// Append blob methods + +/** +* Creates an empty append blob. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createOrReplaceAppendBlob = function (container, blob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createOrReplaceAppendBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var resourceName = createResourceName(container, blob); + + var webResource = WebResource.put(resourceName) + .withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.APPEND) + .withHeader(HeaderConstants.LEASE_ID, options.leaseId) + .withHeader(HeaderConstants.CONTENT_LENGTH, 0); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Uploads an append blob from a stream. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* If you want to append data to an already existing blob, please look at appendFromStream. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createAppendBlobFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) { + return this._createBlobFromStream(container, blob, BlobConstants.BlobTypes.APPEND, stream, streamLength, optionsOrCallback, callback); +}; + +/** +* Uploads an append blob from a text string. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* If you want to append data to an already existing blob, please look at appendFromText. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|object} text The blob text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.createAppendBlobFromText = function (container, blob, text, optionsOrCallback, callback) { + return this._createBlobFromText(container, blob, BlobConstants.BlobTypes.APPEND, text, optionsOrCallback, callback); +}; + +/** +* Provides a stream to write to a new append blob. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs and true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback The callback function. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName)); +*/ +BlobService.prototype.createWriteStreamToNewAppendBlob = function (container, blob, optionsOrCallback, callback) { + return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.APPEND, 0, true, optionsOrCallback, callback); +}; + +/** +* Provides a stream to write to an existing append blob. Assumes that the blob exists. +* If it does not, please create the blob using createAppendBlob before calling this method or use createWriteStreamToNewAppendBlob. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs and true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback The callback function. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName)); +*/ +BlobService.prototype.createWriteStreamToExistingAppendBlob = function (container, blob, optionsOrCallback, callback) { + return this._createWriteStreamToBlob(container, blob, BlobConstants.BlobTypes.APPEND, 0, false, optionsOrCallback, callback); +}; + +/** +* Appends to an append blob from a stream. Assumes the blob already exists on the service. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.appendFromStream = function (container, blob, stream, streamLength, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + validate.validateArgs('appendFromStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.exists(stream, 'stream'); + v.value(streamLength, 'streamLength'); + v.callback(callback); + }); + + return this._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, streamLength, options, callback); +}; + +/** +* Appends to an append blob from a text string. Assumes the blob already exists on the service. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|object} text The blob text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.appendFromText = function (container, blob, text, optionsOrCallback, callback) { + return this._uploadBlobFromText(false, container, blob, BlobConstants.BlobTypes.APPEND, text, optionsOrCallback, callback); +}; + + +/** +* Creates a new block from a read stream to be appended to an append blob. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {Stream} readStream The read stream. +* @param {int} streamLength The stream length. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to. +* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype.appendBlockFromStream = function (container, blob, readStream, streamLength, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('appendBlockFromStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.exists(readStream, 'readStream'); + v.value(streamLength, 'streamLength'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + if (streamLength > BlobConstants.MAX_APPEND_BLOB_BLOCK_SIZE) { + throw new RangeError(SR.INVALID_STREAM_LENGTH); + } else { + this._appendBlock(container, blob, null, readStream, streamLength, options, callback); + } +}; + +/** +* Creates a new block from a text to be appended to an append blob. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|object} content The block text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to. +* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype.appendBlockFromText = function (container, blob, content, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('appendBlockFromText', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var contentLength = (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content)); + if (contentLength > BlobConstants.MAX_APPEND_BLOB_BLOCK_SIZE) { + throw new RangeError(SR.INVALID_TEXT_LENGTH); + } else { + this._appendBlock(container, blob, content, null, contentLength, options, callback); + } +}; + +// Private methods + +/** +* Creates a new blob from a stream. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The upload tracker objects. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback The callback function. +* @return {SpeedSummary} +*/ +BlobService.prototype._createBlobFromStream = function (container, blob, blobType, stream, streamLength, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_createBlobFromStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.blobTypeIsValid(blobType); + v.exists(stream, 'stream'); + v.value(streamLength, 'streamLength'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var self = this; + var creationCallback = function (createError, createBlob, createResponse) { + if (createError) { + callback(createError, createBlob, createResponse); + } else { + self._uploadBlobFromStream(true, container, blob, blobType, stream, streamLength, options, callback); + } + }; + + this._createBlob(container, blob, blobType, streamLength, options, creationCallback); + + return options.speedSummary; +}; + +/** +* Uploads a block blob or an append blob from a text string. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param {string|buffer} content The blob text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* information about the blob. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._createBlobFromText = function (container, blob, blobType, content, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_createBlobFromText', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.blobTypeIsValid(blobType); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var self = this; + var creationCallback = function (createError, createBlob, createResponse) { + if (createError) { + callback(createError, createBlob, createResponse); + } else { + self._uploadBlobFromText(true, container, blob, blobType, content, options, callback); + } + }; + + var contentLength = azureutil.objectIsNull(content) ? 0 : ((Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content))); + this._createBlob(container, blob, blobType, contentLength, options, creationCallback); + + return options.speedSummary; +}; + +/** +* Provides a stream to write to a block blob or an append blob. +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param {int} length The blob length. +* @param {bool} createNewBlob Specifies whether create a new blob. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {string} [options.blockSize] The size of each block. Maximum is 100MB. (For block blob only) +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs and true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback The callback function. +* @return {Stream} +*/ +BlobService.prototype._createWriteStreamToBlob = function (container, blob, blobType, length, createNewBlob, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_createWriteStreamToBlob', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.blobTypeIsValid(blobType); + }); + + var options = extend(true, {}, userOptions); + + var sizeLimitation; + if (blobType === BlobConstants.BlobTypes.BLOCK) { + // default to true, unless explicitly set to false + options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true; + sizeLimitation = options.blockSize || BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + } else if (blobType == BlobConstants.BlobTypes.PAGE) { + sizeLimitation = BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES; + } else if (blobType == BlobConstants.BlobTypes.APPEND) { + sizeLimitation = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + } + + var stream = new ChunkStream({ calcContentMd5: options.storeBlobContentMD5 }); + stream._highWaterMark = sizeLimitation; + + stream.pause(); //Immediately pause the stream in order to wait for the destination to getting ready + + var self = this; + var createCallback = function (createError, createBlob, createResponse) { + if (createError) { + if (callback) { + callback(createError, createBlob, createResponse); + } + } else { + self._uploadBlobFromStream(createNewBlob, container, blob, blobType, stream, null, options, function (error, blob, response) { + if (error) { + stream.emit('error', error); + } + + if (callback) { + callback(error, blob, response); + } + }); + } + }; + + if (createNewBlob === true) { + this._createBlob(container, blob, blobType, length, options, createCallback); + } else { + createCallback(); + } + + return stream; +}; + +/** +* Upload blob content from a stream. Assumes the blob already exists. +* +* @ignore +* +* @this {BlobService} +* @param {bool} isNewBlob Specifies whether the blob is newly created. +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The upload tracker objects. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback The callback function. +* @return {SpeedSummary} +*/ +BlobService.prototype._uploadBlobFromStream = function (isNewBlob, container, blob, blobType, stream, streamLength, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + + if (blobType === BlobConstants.BlobTypes.BLOCK) { + // default to true, unless explicitly set to false + options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true; + } + + stream.pause(); + + var self = this; + var startUpload = function () { + var putBlockBlobFromStream = function () { + if (streamLength > 0 && azureutil.objectIsNull(azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null)) && options.storeBlobContentMD5) { + azureutil.calculateMD5(stream, Math.min(self.singleBlobPutThresholdInBytes, streamLength), options, function (internalBuff, contentMD5) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], contentMD5); + self._putBlockBlob(container, blob, internalBuff, null, internalBuff.length, options, callback); + }); + stream.resume(); + } else { + // Stream will resume when it has a pipe destination or a 'data' listener + self._putBlockBlob(container, blob, null, stream, streamLength, options, callback); + } + }; + + if (streamLength === null || streamLength >= self.singleBlobPutThresholdInBytes || blobType !== BlobConstants.BlobTypes.BLOCK) { + var chunkStream = new ChunkStreamWithStream(stream, { calcContentMd5: options.storeBlobContentMD5 }); + self._uploadContentFromChunkStream(container, blob, blobType, chunkStream, streamLength, options, callback); + } else { + putBlockBlobFromStream(); + } + }; + + if (!isNewBlob) { + if (options.storeBlobContentMD5 && blobType !== BlobConstants.BlobTypes.BLOCK) { + throw new Error(SR.MD5_NOT_POSSIBLE); + } + + if (blobType === BlobConstants.BlobTypes.APPEND || options.accessConditions) { + // Do a getBlobProperties right at the beginning for existing blobs and use the user passed in access conditions. + // So any pre-condition failure on the first block (in a strictly single writer scenario) is caught. + // This call also helps us get the append position to append to if the user hasn’t specified an access condition. + this.getBlobProperties(container, blob, options, function (error, properties, response) { + if (error && !(options.accessConditions && options.accessConditions.EtagNonMatch === '*' && response.statusCode === 400)) { + callback(error); + } else { + if (blobType === BlobConstants.BlobTypes.APPEND) { + options.appendPosition = properties.contentLength; + } + + startUpload(); + } + }); + } else { + startUpload(); + } + } else { + startUpload(); + } + + return options.speedSummary; +}; + +/** +* Upload blob content from a text. Assumes the blob already exists. +* +* @ignore +* +* @this {BlobService} +* @param {bool} isNewBlob Specifies whether the blob is newly created. +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param (string) content The blob text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The upload tracker objects. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback The callback function. +* @return {SpeedSummary} +*/ +BlobService.prototype._uploadBlobFromText = function (isNewBlob, container, blob, blobType, content, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + options[HeaderConstants.CONTENT_TYPE] = (options.contentSettings && options.contentSettings.contentType) || 'text/plain;charset="utf-8"'; + + var self = this; + var startUpload = function () { + var operationFunc; + var length = azureutil.objectIsNull(content) ? 0 : (Buffer.isBuffer(content) ? content.length : Buffer.byteLength(content)); + + if (blobType === BlobConstants.BlobTypes.BLOCK) { + // default to true, unless explicitly set to false + options.storeBlobContentMD5 = options.storeBlobContentMD5 === false ? false : true; + operationFunc = self._putBlockBlob; + + if (length > BlobConstants.MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES) { + throw new RangeError(SR.INVALID_BLOB_LENGTH); + } + } else if (blobType === BlobConstants.BlobTypes.APPEND) { + operationFunc = self._appendBlock; + + if (length > BlobConstants.MAX_APPEND_BLOB_BLOCK_SIZE) { + throw new RangeError(SR.INVALID_TEXT_LENGTH); + } + } + + var finalCallback = function (error, blobResult, response) { + if (blobType !== BlobConstants.BlobTypes.BLOCK) { + self.setBlobProperties(container, blob, options.contentSettings, options, function (error, blob, response) { + blob = extend(false, blob, blobResult); + callback(error, blob, response); + }); + } else { + callback(error, blobResult, response); + } + }; + + operationFunc.call(self, container, blob, content, null, length, options, finalCallback); + }; + + if (!isNewBlob) { + if (options.storeBlobContentMD5 && blobType !== BlobConstants.BlobTypes.BLOCK) { + throw new Error(SR.MD5_NOT_POSSIBLE); + } + + if (blobType === BlobConstants.BlobTypes.APPEND || options.accessConditions) { + // Do a getBlobProperties right at the beginning for existing blobs and use the user passed in access conditions. + // So any pre-condition failure on the first block (in a strictly single writer scenario) is caught. + // This call also helps us get the append position to append to if the user hasn’t specified an access condition. + this.getBlobProperties(container, blob, options, function (error, properties) { + if (error) { + callback(error); + } else { + if (blobType === BlobConstants.BlobTypes.APPEND) { + options.appendPosition = properties.contentLength; + } + + startUpload(); + } + }); + } + } else { + if (!azureutil.objectIsNull(content) && azureutil.objectIsNull(azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null)) && options.storeBlobContentMD5) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.getContentMd5(content)); + } + startUpload(); + } +}; + +/** +* Uploads a block blob from a stream. +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} text The blob text. +* @param (Stream) stream Stream to the data to store. +* @param {int} length The length of the stream or text to upload. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* information about the blob. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._putBlockBlob = function (container, blob, text, stream, length, options, callback) { + if (!options.speedSummary) { + options.speedSummary = new SpeedSummary(blob); + } + + var speedSummary = options.speedSummary; + speedSummary.totalSize = length; + + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream') + .withHeader(HeaderConstants.BLOB_TYPE, BlobConstants.BlobTypes.BLOCK) + .withHeader(HeaderConstants.CONTENT_LENGTH, length); + + if (!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) { + options.transactionalContentMD5 = azureutil.getContentMd5(text); + } + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + if (options.metadata) { + responseObject.blobResult.metadata = options.metadata; + } + } + + var finalCallback = function (returnObject) { + if (!returnObject || !returnObject.error) { + speedSummary.increment(length); + } + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + if (!azureutil.objectIsNull(text)) { + this.performRequest(webResource, text, options, processResponseCallback); + } else { + this.performRequestOutputStream(webResource, stream, options, processResponseCallback); + } + + return options.speedSummary; +}; + +/** +* Appends a new block to an append blob. +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string|buffer} content The block content. +* @param (Stream) stream The stream to the data to store. +* @param {int} length The length of the stream or content to upload. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to. +* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] The blob’s MD5 hash. This hash is used to verify the integrity of the blob during transport. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +BlobService.prototype._appendBlock = function (container, blob, content, stream, length, options, callback) { + var speedSummary = options.speedSummary || new SpeedSummary(blob); + speedSummary.totalSize = length; + + var self = this; + var startAppendBlock = function () { + var resourceName = createResourceName(container, blob); + + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'appendblock') + .withHeader(HeaderConstants.CONTENT_LENGTH, length) + .withHeader(HeaderConstants.BLOB_CONDITION_MAX_SIZE, options.maxBlobSize) + .withHeader(HeaderConstants.BLOB_CONDITION_APPEND_POSITION, options.appendPosition); + + BlobResult.setHeadersFromBlob(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + if (!returnObject || !returnObject.error) { + speedSummary.increment(length); + } + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + if (!azureutil.objectIsNull(content)) { + self.performRequest(webResource, content, options, processResponseCallback); + } else { + self.performRequestOutputStream(webResource, stream, options, processResponseCallback); + } + }; + + if (azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) { + if (!azureutil.objectIsNull(content)) { + options.transactionalContentMD5 = azureutil.getContentMd5(content); + startAppendBlock(); + } else { + azureutil.calculateMD5(stream, length, options, function (internalBuff, contentMD5) { + options.transactionalContentMD5 = contentMD5; + content = internalBuff; + length = internalBuff.length; + startAppendBlock(); + }); + } + } else { + startAppendBlock(); + } + + return options.speedSummary; +}; + +/** +* Creates and dispatches lease requests. +* @ignore +* +* @this {BlobService} +* @param {object} webResource The web resource. +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} leaseId The lease identifier. Required to renew, change or release the lease. +* @param {string} leaseAction The lease action (BlobConstants.LeaseOperation.*). Required. +* @param {object} userOptions The request options. +* @param {int} [userOptions.leaseBreakPeriod] The lease break period. +* @param {string} [userOptions.leaseDuration] The lease duration. Default is never to expire. +* @param {string} [userOptions.proposedLeaseId] The proposed lease identifier. This is required for the CHANGE lease action. +* @param {LocationMode} [userOptions.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {int} [userOptions.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [userOptions.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, lease, response)} callback `error` will contain information +* if an error occurs; otherwise `lease` will contain +* the lease information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._leaseImpl = function (container, blob, leaseId, leaseAction, options, callback) { + var webResource; + if (!azureutil.objectIsNull(blob)) { + validate.validateArgs('_leaseImpl', function (v) { + v.string(blob, 'blob'); + }); + var resourceName = createResourceName(container, blob); + webResource = WebResource.put(resourceName); + } else { + webResource = WebResource.put(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container'); + } + + webResource.withQueryOption(QueryStringConstants.COMP, 'lease') + .withHeader(HeaderConstants.LEASE_ID, leaseId) + .withHeader(HeaderConstants.LEASE_ACTION, leaseAction.toLowerCase()) + .withHeader(HeaderConstants.LEASE_BREAK_PERIOD, options.leaseBreakPeriod) + .withHeader(HeaderConstants.PROPOSED_LEASE_ID, options.proposedLeaseId) + .withHeader(HeaderConstants.LEASE_DURATION, options.leaseDuration); + + var processResponseCallback = function (responseObject, next) { + responseObject.leaseResult = null; + if (!responseObject.error) { + responseObject.leaseResult = new LeaseResult(container, blob); + responseObject.leaseResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.leaseResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Updates a page blob from text. +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} text The text string. +* @param {Stream} readStream The read stream. +* @param {int} rangeStart The range start. +* @param {int} rangeEnd The range end. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The target blob lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the page content. This hash is used to verify the integrity of the page during transport. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, pageBlob, response)} callback `error` will contain information +* if an error occurs; otherwise `pageBlob` will contain +* the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._createPages = function (container, blob, text, readStream, rangeStart, rangeEnd, options, callback) { + var request = this._updatePageBlobPagesImpl(container, blob, rangeStart, rangeEnd, BlobConstants.PageWriteOptions.UPDATE, options); + + // At this point, we have already validated that the range is less than 4MB. Therefore, we just need to calculate the contentMD5 if required. + // Even when this is called from the createPagesFromStream method, it is pre-buffered and called with text. + if (!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5) { + request.withHeader(HeaderConstants.CONTENT_MD5, azureutil.getContentMd5(text)); + } + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + if (!azureutil.objectIsNull(text)) { + this.performRequest(request, text, options, processResponseCallback); + } else { + this.performRequestOutputStream(request, readStream, options, processResponseCallback); + } +}; + +/** +* @ignore +*/ +BlobService.prototype._updatePageBlobPagesImpl = function (container, blob, rangeStart, rangeEnd, writeMethod, options) { + if (rangeStart && rangeStart % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_START_OFFSET); + } + + if (rangeEnd && (rangeEnd + 1) % BlobConstants.PAGE_SIZE !== 0) { + throw new RangeError(SR.INVALID_PAGE_END_OFFSET); + } + + // this is necessary if this is called from _uploadContentFromChunkStream->_createPages + if (!options) { + options = {}; + } + + options.rangeStart = rangeStart; + options.rangeEnd = rangeEnd; + + options.contentLength = writeMethod === BlobConstants.PageWriteOptions.UPDATE ? (rangeEnd - rangeStart) + 1 : 0; + + var resourceName = createResourceName(container, blob); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'page') + .withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream') + .withHeader(HeaderConstants.PAGE_WRITE, writeMethod); + + BlobResult.setHeadersFromBlob(webResource, options); + + return webResource; +}; + +/** +* Uploads blob content from a stream. +* For block blob, it creates a new block to be committed. +* For page blob, it writes a range of pages. +* For append blob, it appends a new block. +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} blobType The blob type. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object|function} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to. +* @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {function(error, null)} callback The callback function. +* @return {SpeedSummary} +*/ + +BlobService.prototype._uploadContentFromChunkStream = function (container, blob, blobType, chunkStream, streamLength, options, callback) { + this.logger.debug(util.format('_uploadContentFromChunkStream for blob %s', blob)); + + var apiName; + var isBlockBlobUpload; + var isPageBlobUpload; + var isAppendBlobUpload; + var sizeLimitation; + var originalContentMD5 = azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null); + var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount; + + if (blobType == BlobConstants.BlobTypes.BLOCK) { + apiName = 'createBlockFromText'; + isBlockBlobUpload = true; + + // BlockBlob can only have 50000 blocks in maximum + var minBlockSize = Math.ceil(streamLength / 50000); + if (options.blockSize) { + if (options.blockSize < minBlockSize) { + // options.blockSize is less than the minBlockSize, error callback + var error = new ArgumentError('options.blockSize', util.format('The minimum blockSize is %s and the provided blockSize %s is too small.', minBlockSize, options.blockSize)); + callback(error); + return; + } else { + sizeLimitation = options.blockSize; + } + } else { + // 4MB minimum for auto-calculated block size + sizeLimitation = Math.max(minBlockSize, BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES); + } + } else if (blobType == BlobConstants.BlobTypes.PAGE) { + apiName = '_createPages'; + isPageBlobUpload = true; + sizeLimitation = BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES; + } else if (blobType == BlobConstants.BlobTypes.APPEND) { + apiName = 'appendBlockFromText'; + isAppendBlobUpload = true; + parallelOperationThreadCount = 1; + sizeLimitation = BlobConstants.DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES; + } else { + var error = new ArgumentError('blobType', util.format('Unknown blob type %s', blobType)); + callback(error); + return; + } + + chunkStream._highWaterMark = sizeLimitation; + + this._setOperationExpiryTime(options); + + // initialize the speed summary + var speedSummary = options.speedSummary || new SpeedSummary(blob); + speedSummary.totalSize = streamLength; + + // initialize chunk allocator + var allocator = new ChunkAllocator(sizeLimitation, parallelOperationThreadCount, { logger: this.logger }); + chunkStream.setMemoryAllocator(allocator); + chunkStream.setOutputLength(streamLength); + + // if this is a FileReadStream, set the allocator on that stream + if (chunkStream._stream && chunkStream._stream.setMemoryAllocator) { + var fileReadStreamAllocator = new ChunkAllocator(chunkStream._stream._highWaterMark, parallelOperationThreadCount, { logger: this.logger }); + chunkStream._stream.setMemoryAllocator(fileReadStreamAllocator); + } + + // initialize batch operations + var batchOperations = new BatchOperation(apiName, { + callInOrder: isAppendBlobUpload, + callbackInOrder: isAppendBlobUpload, + logger: this.logger, + enableReuseSocket: this.defaultEnableReuseSocket, + operationMemoryUsage: sizeLimitation + }); + batchOperations.setConcurrency(parallelOperationThreadCount); + + // initialize options + var rangeOptions = { + leaseId: options.leaseId, + timeoutIntervalInMs: options.timeoutIntervalInMs, + clientRequestTimeoutInMs: options.clientRequestTimeoutInMs, + operationExpiryTime: options.operationExpiryTime, + maxBlobSize: options.maxBlobSize, + appendPosition: options.appendPosition || 0, + initialAppendPosition: options.appendPosition || 0, + absorbConditionalErrorsOnRetry: options.absorbConditionalErrorsOnRetry + }; + + // initialize block blob variables + var blockIdPrefix = options.blockIdPrefix || this.generateBlockIdPrefix(); + var blockCount = 0; + var blockIds = []; + var blobResult = {}; + + var self = this; + chunkStream.on('data', function (data, range) { + var operation = null; + var full = false; + var autoIncrement = speedSummary.getAutoIncrementFunction(data.length); + + if (data.length > sizeLimitation) { + throw new RangeError(util.format(SR.EXCEEDED_SIZE_LIMITATION, sizeLimitation, data.length)); + } + + if (options.useTransactionalMD5) { + //calculate content md5 for the current uploading block data + var contentMD5 = azureutil.getContentMd5(data); + rangeOptions.transactionalContentMD5 = contentMD5; + } + + var checkLengthLimit = function () { + if (!streamLength) return true; + if (range.start >= streamLength) { + self.logger.debug(util.format('Stop uploading data from %s bytes to %s bytes to blob %s because of limit %s', range.start, range.end, blob, streamLength)); + chunkStream.stop(); + return false; + } else if (range.end >= streamLength) { + self.logger.debug(util.format('Clip uploading data from %s bytes to %s bytes to blob %s because of limit %s', range.start, range.end, blob, streamLength)); + range.end = streamLength - 1; + data = data.slice(0, streamLength - range.start); + if (options.useTransactionalMD5) { + rangeOptions.transactionalContentMD5 = azureutil.getContentMd5(data); + } + } + return true; + }; + + var uploadBlockBlobChunk = function () { + if (!checkLengthLimit()) return; + var blockId = self.getBlockId(blockIdPrefix, blockCount); + blockIds.push(blockId); + + operation = new BatchOperation.RestOperation(self, apiName, blockId, container, blob, data, rangeOptions, function (error) { + if (!error) { + autoIncrement(); + } else { + self.logger.debug(util.format('Stop uploading data as error happens. Error: %s', util.inspect(error))); + chunkStream.stop(); + } + allocator.releaseBuffer(data); + data = null; + }); + + blockCount++; + }; + + var uploadPageBlobChunk = function () { + if (!checkLengthLimit()) return; + + if (azureutil.isBufferAllZero(data)) { + self.logger.debug(util.format('Skip upload data from %s bytes to %s bytes to blob %s', range.start, range.end, blob)); + speedSummary.increment(data.length); + } else { + self.logger.debug(util.format('Upload data from %s bytes to %s bytes to blob %s', range.start, range.end, blob)); + operation = new BatchOperation.RestOperation(self, apiName, container, blob, data, null, range.start, range.end, rangeOptions, function (error) { + if (!error) { + autoIncrement(); + } else { + self.logger.debug(util.format('Stop uploading data as error happens. Error: %s', util.inspect(error))); + chunkStream.stop(); + } + allocator.releaseBuffer(data); + data = null; + }); + } + }; + + var uploadAppendBlobChunk = function () { + if (!checkLengthLimit()) return; + + rangeOptions.appendPosition = Number(rangeOptions.initialAppendPosition) + Number(range.start); + + // We cannot differentiate between max size condition failing only in the retry versus failing in the first attempt and retry. + // So we will eliminate the latter and handle the former in the append operation callback. + if (options.maxBlobSize && rangeOptions.appendPosition + data.length > options.maxBlobSize) { + throw new Error(SR.MAX_BLOB_SIZE_CONDITION_NOT_MEET); + } + + operation = new BatchOperation.RestOperation(self, apiName, container, blob, data, rangeOptions, function (error, currentBlob) { + if (!error) { + autoIncrement(); + } else { + self.logger.debug(util.format('Stop uploading data as error happens. Error: %s', util.inspect(error))); + chunkStream.stop(); + } + blobResult = currentBlob; + allocator.releaseBuffer(data); + data = null; + }); + }; + + if (isBlockBlobUpload) { + uploadBlockBlobChunk(); + } else if (isAppendBlobUpload) { + uploadAppendBlobChunk(); + } else if (isPageBlobUpload) { + uploadPageBlobChunk(); + } + + if (operation) { + full = batchOperations.addOperation(operation); + operation = null; + + if (full) { + self.logger.debug('File stream paused'); + chunkStream.pause(); + } + } + }); + + chunkStream.on('end', function () { + self.logger.debug(util.format('File read stream ended for blob %s', blob)); + batchOperations.enableComplete(); + }); + + batchOperations.on('drain', function () { + self.logger.debug('file stream resume'); + chunkStream.resume(); + }); + + batchOperations.on('end', function (error) { + self.logger.debug('batch operations commited'); + + speedSummary = null; + if (error) { + callback(error); + return; + } + + if (originalContentMD5) { + options.contentSettings.contentMD5 = originalContentMD5; + } else if (options.storeBlobContentMD5) { + var contentMD5 = chunkStream.getContentMd5('base64'); + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], contentMD5); + } + + if (isBlockBlobUpload) { + //commit block list + var blockList = { 'UncommittedBlocks': blockIds }; + self.commitBlocks(container, blob, blockList, options, function (error, blockList, response) { + self.logger.debug(util.format('Blob %s committed', blob)); + + if (error) { + chunkStream.finish(); + + callback(error); + } else { + blobResult['commmittedBlocks'] = blockIds; + + chunkStream.finish(); + callback(error, blobResult, response); + } + }); + } else { + // upload page blob or append blob completely + var blobProperties = options.contentSettings; + self.setBlobProperties(container, blob, blobProperties, function (error, blob, response) { + chunkStream.finish(); + blob = extend(false, blob, blobResult); + callback(error, blob, response); + }); + } + }); + + return speedSummary; +}; + +/** +* Checks whether or not a container exists on the service. +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {string} [options.leaseId] The lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the container information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._doesContainerExist = function (container, primaryOnly, options, callback) { + var webResource = WebResource.head(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + if (primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + } + + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = new ContainerResult(container); + if (!responseObject.error) { + responseObject.containerResult.exists = true; + responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers); + + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.containerResult.exists = false; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.containerResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks whether or not a blob exists on the service. +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the blob information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._doesBlobExist = function (container, blob, primaryOnly, options, callback) { + var resourceName = createResourceName(container, blob); + var webResource = WebResource.head(resourceName) + .withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId) + .withHeader(HeaderConstants.LEASE_ID, options.leaseId); + + if (primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + } + + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = new BlobResult(container, blob); + if (!responseObject.error) { + responseObject.blobResult.exists = true; + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.blobResult.exists = false; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* @ignore +*/ +BlobService.prototype._setBlobPropertiesHelper = function (settings) { + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(settings.container, settings.blob); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + settings.callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(settings.webResource, null, settings.options, processResponseCallback); +}; + +/** +* @ignore +*/ +BlobService.prototype._validateLengthAndMD5 = function (options, responseObject) { + var storedMD5 = responseObject.response.headers[Constants.HeaderConstants.CONTENT_MD5]; + var contentLength; + + if (!azureutil.objectIsNull(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH])) { + contentLength = parseInt(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH], 10); + } + + // If the user has not specified this option, the default value should be false. + if (azureutil.objectIsNull(options.disableContentMD5Validation)) { + options.disableContentMD5Validation = false; + } + + // None of the below cases should be retried. So set the error in every case so the retry policy filter handle knows that it shouldn't be retried. + if (options.disableContentMD5Validation === false && options.useTransactionalMD5 === true && azureutil.objectIsNull(storedMD5)) { + responseObject.error = new StorageError(SR.MD5_NOT_PRESENT_ERROR); + responseObject.retryable = false; + } + + // Validate length and if required, MD5. + // If getBlobToText called this method, then the responseObject.length and responseObject.contentMD5 are not set. Calculate them first using responseObject.response.body and then validate. + if (azureutil.objectIsNull(responseObject.length)) { + if (typeof responseObject.response.body == 'string') { + responseObject.length = Buffer.byteLength(responseObject.response.body); + } else if (Buffer.isBuffer(responseObject.response.body)) { + responseObject.length = responseObject.response.body.length; + } + } + + if (!azureutil.objectIsNull(contentLength) && responseObject.length !== contentLength) { + responseObject.error = new Error(SR.CONTENT_LENGTH_MISMATCH); + responseObject.retryable = false; + } + + if (options.disableContentMD5Validation === false && azureutil.objectIsNull(responseObject.contentMD5)) { + responseObject.contentMD5 = azureutil.getContentMd5(responseObject.response.body); + } + + if (options.disableContentMD5Validation === false && !azureutil.objectIsNull(storedMD5) && storedMD5 !== responseObject.contentMD5) { + responseObject.error = new Error(util.format(SR.HASH_MISMATCH, storedMD5, responseObject.contentMD5)); + responseObject.retryable = false; + } +}; + +/** +* @ignore +*/ +BlobService.prototype._setRangeContentMD5Header = function (webResource, options) { + if (!azureutil.objectIsNull(options.rangeStart) && options.useTransactionalMD5) { + if (azureutil.objectIsNull(options.rangeEnd)) { + throw new ArgumentNullError('options.rangeEndHeader', util.format(SR.ARGUMENT_NULL_OR_EMPTY, options.rangeEndHeader)); + } + + var size = parseInt(options.rangeEnd, 10) - parseInt(options.rangeStart, 10) + 1; + if (size > BlobConstants.MAX_RANGE_GET_SIZE_WITH_MD5) { + throw new ArgumentError('options', SR.INVALID_RANGE_FOR_MD5); + } else { + webResource.withHeader(HeaderConstants.RANGE_GET_CONTENT_MD5, 'true'); + } + } +}; + +/** +* Downloads a blockblob, pageblob or appendblob into a range stream. +* @ignore +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} blobType The type of blob to download: block blob, page blob or append blob. +* @param {Stream} writeStream The write stream. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype._getBlobToRangeStream = function (container, blob, blobType, writeStream, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + validate.validateArgs('_getBlobToRangeStream', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.blobNameIsValid(container, blob); + v.blobTypeIsValid(blobType); + v.callback(callback); + }); + + var rangeStream = null; + var isPageBlobDownload = true; + + if (blobType == BlobConstants.BlobTypes.PAGE) { + rangeStream = new PageRangeStream(this, container, blob, options); + } else if (blobType == BlobConstants.BlobTypes.APPEND) { + rangeStream = new RangeStream(this, container, blob, options); + isPageBlobDownload = false; + } else if (blobType == BlobConstants.BlobTypes.BLOCK) { + rangeStream = new BlockRangeStream(this, container, blob, options); + isPageBlobDownload = false; + } + + if (!options.speedSummary) { + options.speedSummary = new SpeedSummary(blob); + } + + var speedSummary = options.speedSummary; + var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount; + var batchOperations = new BatchOperation('getBlobInRanges', { callbackInOrder: true, logger: this.logger, enableReuseSocket: this.defaultEnableReuseSocket }); + batchOperations.setConcurrency(parallelOperationThreadCount); + + var self = this; + var checkMD5sum = !options.disableContentMD5Validation; + var md5Hash = null; + if (checkMD5sum) { + md5Hash = new Md5Wrapper().createMd5Hash(); + } + + var savedBlobResult = null; + var savedBlobResponse = null; + + rangeStream.on('range', function (range) { + if (!speedSummary.totalSize) { + speedSummary.totalSize = rangeStream.rangeSize; + } + + var requestOptions = { + rangeStart: range.start, + rangeEnd: range.end, + responseEncoding: null //Use Buffer to store the response data + }; + + var rangeSize = range.size; + requestOptions.timeoutIntervalInMs = options.timeoutIntervalInMs; + requestOptions.clientRequestTimeoutInMs = options.clientRequestTimeoutInMs; + requestOptions.useTransactionalMD5 = options.useTransactionalMD5; + requestOptions.snapshotId = options.snapshotId; + + if (range.dataSize === 0) { + if (isPageBlobDownload) { + var autoIncrement = speedSummary.getAutoIncrementFunction(rangeSize); + //No operation to do and only wait for write zero to file in callback + var writeZeroOperation = new BatchOperation.CommonOperation(BatchOperation.noOperation, function (error) { + if (error) return; + var bufferAvailable = azureutil.writeZerosToStream(writeStream, rangeSize, md5Hash, autoIncrement); + //There is no need to pause the rangestream since we can perform http request and write disk at the same time + self.logger.debug(util.format('Write %s bytes Zero from %s to %s', rangeSize, range.start, range.end)); + if (!bufferAvailable) { + self.logger.debug('Write stream is full and pause batch operation'); + batchOperations.pause(); + } + }); + batchOperations.addOperation(writeZeroOperation); + } else { + self.logger.debug(util.format('Can not read %s bytes to %s bytes of blob %s', range.start, range.end, blob)); + } + return; + } + + if (range.start > range.end) { + return; + } + + var operation = new BatchOperation.RestOperation(self, 'getBlobToText', container, blob, requestOptions, function (error, content, blobResult, response) { + if (!error) { + if (rangeSize !== content.length) { + self.logger.warn(util.format('Request %s bytes, but server returns %s bytes', rangeSize, content.length)); + } + //Save one of the succeeded callback parameters and use them at the final callback + if (!savedBlobResult) { + savedBlobResult = blobResult; + } + if (!savedBlobResponse) { + savedBlobResponse = response; + } + var autoIncrement = speedSummary.getAutoIncrementFunction(content.length); + var bufferAvailable = writeStream.write(content, autoIncrement); + if (!bufferAvailable) { + self.logger.debug('Write stream is full and pause batch operation'); + batchOperations.pause(); + } + if (md5Hash) { + md5Hash.update(content); + } + content = null; + } else { + self.logger.debug(util.format('Stop downloading data as error happens. Error: %s', util.inspect(error))); + rangeStream.stop(); + } + }); + + var full = batchOperations.addOperation(operation); + if (full) { + self.logger.debug('Pause range stream'); + rangeStream.pause(); + } + }); + + rangeStream.on('end', function () { + self.logger.debug('Range stream has ended.'); + batchOperations.enableComplete(); + }); + + batchOperations.on('drain', function () { + self.logger.debug('Resume range stream'); + rangeStream.resume(); + }); + + writeStream.on('drain', function () { + self.logger.debug('Resume batch operations'); + batchOperations.resume(); + }); + + batchOperations.on('end', function (error) { + self.logger.debug('Download completed!'); + if (error) { + callback(error); + return; + } else { + writeStream.end(function () { + self.logger.debug('Write stream has ended'); + if (!savedBlobResult) { + savedBlobResult = {}; + } + + azureutil.setObjectInnerPropertyValue(savedBlobResult, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null)); + savedBlobResult.clientSideContentMD5 = null; + if (md5Hash) { + savedBlobResult.clientSideContentMD5 = md5Hash.digest('base64'); + } + callback(error, savedBlobResult, savedBlobResponse); + }); + } + }); + + var listOptions = { + timeoutIntervalInMs: options.timeoutIntervalInMs, + clientRequestTimeoutInMs: options.clientRequestTimeoutInMs, + snapshotId: options.snapshotId, + leaseId: options.leaseId, + blockListFilter: BlobUtilities.BlockListFilter.COMMITTED + }; + + rangeStream.list(listOptions, function (error) { + callback(error); + }); + + return speedSummary; +}; + +/** +* Downloads a blockblob or pageblob into a stream. +* @ignore +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {Stream} writeStream The write stream. +* @param {object} [options] The request options. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the blob information. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._getBlobToStream = function (container, blob, writeStream, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + var resourceName = createResourceName(container, blob); + var webResource = WebResource.get(resourceName).withRawResponse(); + + var options = extend(true, {}, userOptions); + webResource.withQueryOption(QueryStringConstants.SNAPSHOT, options.snapshotId); + + BlobResult.setHeadersFromBlob(webResource, options); + + this._setRangeContentMD5Header(webResource, options); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.blobResult = null; + + if (!responseObject.error) { + responseObject.blobResult = new BlobResult(container, blob); + responseObject.blobResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.blobResult.getPropertiesFromHeaders(responseObject.response.headers); + + self._validateLengthAndMD5(options, responseObject); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.blobResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequestInputStream(webResource, null, writeStream, options, processResponseCallback); +}; + +/** +* Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container. +* @ignore +* @this {BlobService} +* @param {string} container The container name. +* @param {string} prefix The prefix of the blob name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {ListBlobTypes} listBlobType Specifies the item type of the results. +* @param {object} [options] The request options. +* @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy', 'deleted'). +* Please find these values in BlobUtilities.BlobListingDetails. Multiple values can be added separated with a comma (,). +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the entries of blobs and the continuation token for the next listing operation. +* `response` will contain information related to this operation. +*/ +BlobService.prototype._listBlobsOrDircotriesSegmentedWithPrefix = function (container, prefix, currentToken, listBlobType, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listBlobsSegmented', function (v) { + v.string(container, 'container'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(container) + .withQueryOption(QueryStringConstants.RESTYPE, 'container') + .withQueryOption(QueryStringConstants.COMP, 'list') + .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults) + .withQueryOptions(options, + QueryStringConstants.DELIMITER, + QueryStringConstants.INCLUDE); + + if (!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker); + } + + webResource.withQueryOption(QueryStringConstants.PREFIX, prefix); + + options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken); + + var processResponseCallback = function (responseObject, next) { + responseObject.listBlobsResult = null; + if (!responseObject.error) { + responseObject.listBlobsResult = { + entries: null, + continuationToken: null + }; + + responseObject.listBlobsResult.entries = []; + var results = []; + + if (listBlobType == BlobConstants.ListBlobTypes.Directory && responseObject.response.body.EnumerationResults.Blobs.BlobPrefix) { + results = responseObject.response.body.EnumerationResults.Blobs.BlobPrefix; + if (!_.isArray(results)) { + results = [results]; + } + } else if (listBlobType == BlobConstants.ListBlobTypes.Blob && responseObject.response.body.EnumerationResults.Blobs.Blob) { + results = responseObject.response.body.EnumerationResults.Blobs.Blob; + if (!_.isArray(results)) { + results = [results]; + } + } + + results.forEach(function (currentBlob) { + var blobResult = BlobResult.parse(currentBlob); + responseObject.listBlobsResult.entries.push(blobResult); + }); + + if (responseObject.response.body.EnumerationResults.NextMarker) { + responseObject.listBlobsResult.continuationToken = { + nextMarker: null, + targetLocation: null + }; + + responseObject.listBlobsResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker; + responseObject.listBlobsResult.continuationToken.targetLocation = responseObject.targetLocation; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.listBlobsResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Create a new blob. +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param {int} size The blob size. +* @param {object} [options] The request options. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {errorOrResult} callback The callback which operates on the specific blob. +*/ +BlobService.prototype._createBlob = function (container, blob, blobType, size, options, creationCallback) { + if (blobType == BlobConstants.BlobTypes.APPEND) { + this.createOrReplaceAppendBlob(container, blob, options, function (createError, createResponse) { + creationCallback(createError, null, createResponse); + }); + } else if (blobType == BlobConstants.BlobTypes.PAGE) { + this.createPageBlob(container, blob, size, options, function (createError) { + creationCallback(createError); + }); + } else if (blobType == BlobConstants.BlobTypes.BLOCK) { + creationCallback(); + } +}; + +/** +* The callback for {BlobService~getBlobToText}. +* @typedef {function} BlobService~blobToText +* @param {object} error If an error occurs, the error information. +* @param {string} text The text returned from the blob. +* @param {object} blockBlob Information about the blob. +* @param {object} response Information related to this operation. +*/ + +BlobService.SpeedSummary = SpeedSummary; + +module.exports = BlobService; diff --git a/node_modules/azure-storage/lib/services/blob/blobservice.node.js b/node_modules/azure-storage/lib/services/blob/blobservice.node.js new file mode 100644 index 000000000..0e4622586 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/blobservice.node.js @@ -0,0 +1,461 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../common/common.node'); +var BlobService = require('./blobservice.core'); +var extend = require('extend'); +var fs = require('fs'); +var mime = require('browserify-mime'); + +var azureutil = azureCommon.util; +var Constants = azureCommon.Constants; +var FileReadStream = azureCommon.FileReadStream; +var SpeedSummary = azureCommon.SpeedSummary; +var validate = azureCommon.validate; +var BlobConstants = Constants.BlobConstants; + +/** +* Downloads a blob into a file. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} localFileName The local path to the file to be downloaded. +* @param {object} [options] The request options. +* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download. +* Set the option to true for small blobs. +* Parallel download and speed summary won't work with this option on. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link BlobResult}` will contain the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +* +* @example +* var azure = require('azure-storage'); +* var blobService = azure.createBlobService(); +* blobService.getBlobToLocalFile('taskcontainer', 'task1', 'task1-download.txt', function(error, serverBlob) { +* if(!error) { +* // Blob available in serverBlob.blob variable +* } +*/ +BlobService.prototype.getBlobToLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + + validate.validateArgs('getBlobToLocalFile', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.string(localFileName, 'localFileName'); + v.containerNameIsValid(container); + v.callback(callback); + }); + + return this._getBlobToLocalFile(container, blob, localFileName, options, callback); +}; + +/** +* Uploads a page blob from file. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} localFileName The local path to the file to be uploaded. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The upload tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. +* The default value is false for page blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createPageBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) { + return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.PAGE, localFileName, optionsOrCallback, callback); +}; + +/** +* Creates a new block blob. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} localFileName The local path to the file to be uploaded. +* @param {object} [options] The request options. +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createBlockBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) { + return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.BLOCK, localFileName, optionsOrCallback, callback); +}; + +/** +* Creates a new append blob from a local file. If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* If you want to append data to an already existing blob, please look at appendFromLocalFile. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} localFileName The local path to the file to be uploaded. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 ahash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.createAppendBlobFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) { + return this._createBlobFromLocalFile(container, blob, BlobConstants.BlobTypes.APPEND, localFileName, optionsOrCallback, callback); +}; + +/** +* Appends to an append blob from a local file. Assumes the blob already exists on the service. +* This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. +* If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} localFileName The local path to the file to be uploaded. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. +* @param {string} [options.leaseId] The lease identifier. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link BlobResult}` will contain +* the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +BlobService.prototype.appendFromLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('appendFromLocalFile', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.string(localFileName, 'localFileName'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + + var self = this; + fs.stat(localFileName, function (error, stat) { + if (error) { + callback(error); + } else { + var stream = new FileReadStream(localFileName, { calcContentMd5: options.storeBlobContentMD5 }); + var streamCallback = function (appendError, blob, response) { + if (azureutil.objectIsFunction(stream.destroy)) { + stream.destroy(); + } + callback(appendError, blob, response); + }; + self._uploadBlobFromStream(false, container, blob, BlobConstants.BlobTypes.APPEND, stream, stat.size, options, streamCallback); + } + }); + + return options.speedSummary; +}; + +// Private methods + +/** +* Creates a new blob (Block/Page/Append). If the blob already exists on the service, it will be overwritten. +* To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. +* +* @ignore +* +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {BlobType} blobType The blob type. +* @param {string} localFileName The local path to the file to be uploaded. +* @param {object} [options] The request options. +* @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. (For append blob only) +* @param {int} [options.blockSize] The size of each block. Maximum is 100MB. +* @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. (For block blob only) +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. +* @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. +* @param {object} [options.contentSettings] The content settings of the blob. +* @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. +* @param {string} [options.contentSettings.contentMD5] The MD5 hash of the blob content. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback The callback function. +* +* @return {SpeedSummary} +* +*/ +BlobService.prototype._createBlobFromLocalFile = function (container, blob, blobType, localFileName, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_createBlobFromLocalFile', function (v) { + v.string(container, 'container'); + v.string(blob, 'blob'); + v.containerNameIsValid(container); + v.blobTypeIsValid(blobType); + v.string(localFileName, 'localFileName'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + + var self = this; + var size = 0; + + var creationCallback = function (createError, createBlob, createResponse) { + if (createError) { + callback(createError, createBlob, createResponse); + } else { + // Automatically detect the mime type + if(azureutil.tryGetValueChain(options, ['contentSettings','contentType'], undefined) === undefined) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings','contentType'], mime.lookup(localFileName)); + } + + var stream = new FileReadStream(localFileName, { calcContentMd5: options.storeBlobContentMD5 }); + var streamCallback = function (createError, createBlob, createResponse) { + if (azureutil.objectIsFunction(stream.destroy)) { + stream.destroy(); + } + callback(createError, createBlob, createResponse); + }; + self._uploadBlobFromStream(true, container, blob, blobType, stream, size, options, streamCallback); + } + }; + + // Check the file size to determine the upload method: single request or chunks + fs.stat(localFileName, function (error, stat) { + if (error) { + callback(error); + } else { + size = stat.size; + self._createBlob(container, blob, blobType, size, options, creationCallback); + } + }); + + return options.speedSummary; +}; + +/** +* Downloads a blob into a file. +* @ignore +* @this {BlobService} +* @param {string} container The container name. +* @param {string} blob The blob name. +* @param {string} localFileName The local path to the file to be downloaded. +* @param {object} [options] The request options. +* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download. +* Set the option to true for small blobs. +* Parallel download and speed summary won't work with this option on. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.snapshotId] The snapshot identifier. +* @param {string} [options.leaseId] The lease identifier. +* @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the blob information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +* +*/ +BlobService.prototype._getBlobToLocalFile = function (container, blob, localFileName, optionsOrCallback, callback) { + var options; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; }); + options.speedSummary = options.speedSummary || new SpeedSummary(blob); + + var writeStream = fs.createWriteStream(localFileName, { 'highWaterMark': BlobConstants.MAX_QUEUED_WRITE_DISK_BUFFER_SIZE }); + writeStream.on('error', function (error) { + callback(error); + }); + + this.getBlobToStream(container, blob, writeStream, options, function (error, responseBlob, response) { + if (error) { + writeStream.end(function () { + // If the download failed from the beginning, remove the file. + if (fs.existsSync(localFileName) && writeStream.bytesWritten === 0) { + fs.unlinkSync(localFileName); + } + callback(error, responseBlob, response); + }); + } else { + callback(error, responseBlob, response); + } + }); + + return options.speedSummary; +}; + +module.exports = BlobService; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/blob/blobutilities.js b/node_modules/azure-storage/lib/services/blob/blobutilities.js new file mode 100644 index 000000000..d03758f70 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/blobutilities.js @@ -0,0 +1,136 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'BlobUtilities'. +exports = module.exports; + +/** +* Defines constants, enums, and utility functions for use with the Blob service. +* @namespace BlobUtilities +*/ +var BlobUtilities = { + /** + * Permission types + * + * @const + * @enum {string} + */ + SharedAccessPermissions: { + READ: 'r', + ADD: 'a', + CREATE: 'c', + WRITE: 'w', + DELETE: 'd', + LIST: 'l' + }, + + /** + * Blob listing details. + * + * @const + * @enum {string} + */ + BlobListingDetails: { + SNAPSHOTS: 'snapshots', + METADATA: 'metadata', + UNCOMMITTED_BLOBS: 'uncommittedblobs', + COPY: 'copy', + DELETED: 'deleted' + }, + + /** + * Deletion options for blob snapshots + * + * @const + * @enum {string} + */ + SnapshotDeleteOptions: { + SNAPSHOTS_ONLY: 'only', + BLOB_AND_SNAPSHOTS: 'include' + }, + + /** + * Type of block list to retrieve + * + * @const + * @enum {string} + */ + BlockListFilter: { + ALL: 'all', + COMMITTED: 'committed', + UNCOMMITTED: 'uncommitted' + }, + + /** + * Blobs and container public access types. + * + * @const + * @enum {string} + */ + BlobContainerPublicAccessType: { + OFF: null, + CONTAINER: 'container', + BLOB: 'blob' + }, + + /** + * Describes actions that can be performed on a page blob sequence number. + * @const + * @enum {string} + */ + SequenceNumberAction: { + MAX: 'max', + UPDATE: 'update', + INCREMENT: 'increment' + }, + + /** + * Candidate values for blob tiers. + * + * @property {object} PremiumPageBlobTier Candidate values for premium pageblob tiers. + * @property {string} PremiumPageBlobTier.P4 + * @property {string} PremiumPageBlobTier.P6 + * @property {string} PremiumPageBlobTier.P10 + * @property {string} PremiumPageBlobTier.P20 + * @property {string} PremiumPageBlobTier.P30 + * @property {string} PremiumPageBlobTier.P40 + * @property {string} PremiumPageBlobTier.P50 + * @property {string} PremiumPageBlobTier.P60 + * @property {object} StandardBlobTier Candidate values for standard blobs tiers. + * @property {string} StandardBlobTier.HOT + * @property {string} StandardBlobTier.COOL + * @property {string} StandardBlobTier.ARCHIVE + */ + BlobTier: { + PremiumPageBlobTier: { + P4: 'P4', + P6: 'P6', + P10: 'P10', + P20: 'P20', + P30: 'P30', + P40: 'P40', + P50: 'P50', + P60: 'P60' + }, + StandardBlobTier: { + HOT: 'Hot', + COOL: 'Cool', + ARCHIVE: 'Archive' + } + } +}; + +module.exports = BlobUtilities; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js b/node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js new file mode 100644 index 000000000..7881f7075 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js @@ -0,0 +1,203 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var Constants = require('./../../../common/util/constants'); +var EventEmitter = require('events').EventEmitter; +var BlobUtilities = require('./../blobutilities'); + +/** +* BlockBlob block range stream +*/ +function BlockRangeStream(blobServiceClient, container, blob, options) { + this.blobServiceClient = blobServiceClient; + this.container = container; + this.blob = blob; + this._emitter = new EventEmitter(); + this._paused = false; + this._emittedAll = false; + this._emittedRangeType = null; + this._emittedRangeIndex = null; + this._offset = 0; + this._rangelist = []; + this._isEmitting = false; + if (options.rangeStart) { + this._startOffset = options.rangeStart; + } else { + this._startOffset = 0; + } + if (options.rangeEnd) { + this._endOffset = options.rangeEnd; + } else { + this._endOffset = Number.MAX_VALUE; + } +} + +/** +* Add event listener +*/ +BlockRangeStream.prototype.on = function (event, listener) { + this._emitter.on(event, listener); +}; + +/** +* Get block list +*/ +BlockRangeStream.prototype.list = function (options, callback) { + if (!options) { + options = {}; + } + + if (!options.blockListFilter) { + options.blockListFilter = BlobUtilities.BlockListFilter.ALL; + } + + var self = this; + this.blobServiceClient.listBlocks(this.container, this.blob, options.blockListFilter, options, function (error, blocklist, response) { + if (error) { + callback(error); + } else { + var totalSize = parseInt(response.headers[Constants.HeaderConstants.BLOB_CONTENT_LENGTH], 10); + if (!blocklist.CommittedBlocks) { + //Convert single block blob to block blob range + var name = 'NODESDK_BLOCKBLOB_RANGESTREAM'; + blocklist.CommittedBlocks = [{ Name : name, Size : totalSize }]; + } + + self._rangelist = blocklist; + self._emitBlockList(); + self = blocklist = null; + } + }); +}; + +/** +* Emit block ranges +*/ +BlockRangeStream.prototype._emitBlockList = function () { + if (this._paused || this._emittedAll || this._isEmitting) return; + + var self = this; + this._getTypeList(function () { + self._rangelist = null; + self._emittedAll = true; + self._emitter.emit('end'); + }); +}; + +/** +* Get the block type list +*/ +BlockRangeStream.prototype._getTypeList = function (callback) { + this._isEmitting = true; + try { + var typeStart = false; + if (this._rangelist) { + for (var blockType in this._rangelist) { + if (this._rangelist.hasOwnProperty(blockType)) { + if (this._emittedRangeType === null || typeStart || this._emittedRangeType == blockType) { + this._emittedRangeType = blockType; + typeStart = true; + } else if (this._emittedRangeType !== blockType) { + continue; + } + + if (this._paused) { + return; + } + + this._emitBlockRange (blockType, callback); + } + } + } + } finally { + this._isEmitting = false; + } +}; + +/** +* Get the block list +*/ +BlockRangeStream.prototype._emitBlockRange = function (blockType, callback) { + var blockList = this._rangelist[blockType]; + var indexStart = false; + for (var blockIndex = 0; blockIndex < blockList.length; blockIndex++) { + if (this._emittedRangeIndex === null || indexStart || this._emittedRangeIndex === blockIndex) { + this._emittedRangeIndex = blockIndex; + indexStart = true; + } else if (this._emittedRangeIndex !== blockIndex) { + continue; + } + + if (this._paused) { + return; + } + + var range = blockList[blockIndex]; + // follow the same naming convention of page ranges and json + range.name = range.Name; + range.type = blockType; + range.start = this._offset; + this._offset += parseInt(range.Size, 10); + range.end = this._offset - 1; + delete range.Name; + delete range.Size; + + if (range.start > this._endOffset) { + break; + } else if (range.end < this._startOffset) { + continue; + } else { + range.start = Math.max(range.start, this._startOffset); + range.end = Math.min(range.end, this._endOffset); + range.size = range.end - range.start + 1; + range.dataSize = range.size; + this._emitter.emit('range', range); + } + } + + // remove the used range and avoid memory leak + this._rangelist[blockType] = null; + + callback(); +}; + +/** +* Pause the stream +*/ +BlockRangeStream.prototype.pause = function () { + this._paused = true; +}; + +/** +* Resume the stream +*/ +BlockRangeStream.prototype.resume = function () { + this._paused = false; + if (!this._isEmitting) { + this._emitBlockList(); + } +}; + +/** +* Stop the stream +*/ +BlockRangeStream.prototype.stop = function () { + this.pause(); + this._emittedAll = true; + this._emitter.emit('end'); +}; + +module.exports = BlockRangeStream; diff --git a/node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js b/node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js new file mode 100644 index 000000000..d97e562ff --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js @@ -0,0 +1,43 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var util = require('util'); +var RangeStream = require('./../../../common/streams/rangestream'); +var Constants = require('./../../../common/util/constants'); + +/** +* PageBlob page range stream +*/ +function PageRangeStream(blobServiceClient, container, blob, options) { + PageRangeStream['super_'].call(this, blobServiceClient, container, blob, options); + + if (options.minRangeSize) { + this._minRangeSize = options.minRangeSize; + } else { + this._minRangeSize = Constants.BlobConstants.MIN_WRITE_PAGE_SIZE_IN_BYTES; + } + if (options.maxRangeSize) { + this._maxRangeSize = options.maxRangeSize; + } else { + this._maxRangeSize = Constants.BlobConstants.DEFAULT_WRITE_PAGE_SIZE_IN_BYTES; + } + this._lengthHeader = Constants.HeaderConstants.BLOB_CONTENT_LENGTH; + this._listFunc = blobServiceClient.listPageRanges; +} + +util.inherits(PageRangeStream, RangeStream); + +module.exports = PageRangeStream; diff --git a/node_modules/azure-storage/lib/services/blob/models/blobresult.js b/node_modules/azure-storage/lib/services/blob/models/blobresult.js new file mode 100644 index 000000000..2b32b1d35 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/models/blobresult.js @@ -0,0 +1,304 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); + +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var Constants = azureCommon.Constants; +var HeaderConstants = Constants.HeaderConstants; + +/** +* Creates a new BlobResult object. +* @class +* The BlobResult class is used to store the blob information. +* + * @property {string} container The container name. + * @property {string} name The blob name. + * @property {object} metadata The metadata key/value pair. + * @property {string} etag The etag. + * @property {string} lastModified The date/time that the blob was last modified. + * @property {string} contentLength The size of the blob in bytes. + * @property {string} blobType The blob type. + * @property {boolean} isIncrementalCopy If the blob is incremental copy blob. + * @property {string} requestId The request id. + * @property {string} sequenceNumber The current sequence number for a page blob. + * @property {string} contentRange The content range. + * @property {string} committedBlockCount The committed block count. + * @property {string} serverEncrypted If the blob data and application metadata are completely encrypted using the specified algorithm. true/false. + * @property {object} contentSettings The content settings. + * @property {string} contentSettings.contentType The content type. + * @property {string} contentSettings.contentEncoding The content encoding. + * @property {string} contentSettings.contentLanguage The content language. + * @property {string} contentSettings.cacheControl The cache control. + * @property {string} contentSettings.contentDisposition The content disposition. + * @property {string} contentSettings.contentMD5 The content MD5 hash. + * @property {object} lease The lease information. + * @property {string} lease.id The lease id. + * @property {string} lease.status The lease status. + * @property {string} lease.state The lease state. + * @property {string} lease.duration The lease duration. + * @property {object} copy The copy information. + * @property {string} copy.id The copy id. + * @property {string} copy.status The copy status. + * @property {string} copy.completionTime The copy completion time. + * @property {string} copy.statusDescription The copy status description. + * @property {string} copy.destinationSnapshot The snapshot time of the last successful incremental copy snapshot for this blob. + * @property {string} copy.progress The copy progress. + * @property {string} copy.source The copy source. + * +* @constructor +* @param {string} [container] The container name. +* @param {string} [name] The blob name. +*/ +function BlobResult(container, name) { + if (container) { + this.container = container; + } + + if (name) { + this.name = name; + } +} + +BlobResult.parse = function (blobXml) { + var blobResult = new BlobResult(); + + for (var propertyName in blobXml) { + if (blobXml.hasOwnProperty(propertyName)) { + if (propertyName === 'Properties') { + // Lift out the properties onto the main object to keep consistent across all APIs like: getBlobProperties + azureutil.setPropertyValueFromXML(blobResult, blobXml[propertyName], true); + } else if (propertyName === 'Metadata') { + var resultPropertyName = azureutil.normalizePropertyNameFromXML(propertyName); + blobResult[resultPropertyName] = {}; + azureutil.setPropertyValueFromXML(blobResult[resultPropertyName], blobXml[propertyName], false); + } else { + blobResult[propertyName.toLowerCase()] = blobXml[propertyName]; + } + } + } + + if (blobResult.isIncrementalCopy !== undefined) { + blobResult.isIncrementalCopy = (blobResult.isIncrementalCopy === 'true'); + } + + // convert accessTierInferred to boolean type + if (blobResult.accessTierInferred !== undefined) { + blobResult.accessTierInferred = (blobResult.accessTierInferred === 'true'); + } + + if (blobResult.deleted !== undefined) { + blobResult.deleted = (blobResult.deleted == 'true'); + } + + if (blobResult.remainingRetentionDays !== undefined) { + blobResult.remainingRetentionDays = parseInt(blobResult.remainingRetentionDays); + } + + return blobResult; +}; + +var headersForProperties = { + 'lastModified': 'LAST_MODIFIED', + 'etag': 'ETAG', + 'sequenceNumber': 'SEQUENCE_NUMBER', + 'blobType': 'BLOB_TYPE', + 'contentLength': 'CONTENT_LENGTH', + 'blobContentLength': 'BLOB_CONTENT_LENGTH', + 'contentRange': 'CONTENT_RANGE', + 'committedBlockCount': 'BLOB_COMMITTED_BLOCK_COUNT', + 'serverEncrypted': 'SERVER_ENCRYPTED', + 'requestId': 'REQUEST_ID', + + 'range': 'RANGE', + 'blobRange': 'STORAGE_RANGE', + 'getContentMd5': 'RANGE_GET_CONTENT_MD5', + 'acceptRanges': 'ACCEPT_RANGES', + 'appendOffset': 'BLOB_APPEND_OFFSET', + + 'accessTier': 'ACCESS_TIER', + 'accessTierChangeTime': 'ACCESS_TIER_CHANGE_TIME', + 'accessTierInferred': 'ACCESS_TIER_INFERRED', + 'archiveStatus': 'ARCHIVE_STATUS', + + 'isIncrementalCopy': 'INCREMENTAL_COPY', + + // ContentSettings + 'contentSettings.contentType': 'CONTENT_TYPE', + 'contentSettings.contentEncoding': 'CONTENT_ENCODING', + 'contentSettings.contentLanguage': 'CONTENT_LANGUAGE', + 'contentSettings.cacheControl': 'CACHE_CONTROL', + 'contentSettings.contentDisposition': 'CONTENT_DISPOSITION', + 'contentSettings.contentMD5': 'CONTENT_MD5', + + // Lease + 'lease.id': 'LEASE_ID', + 'lease.status': 'LEASE_STATUS', + 'lease.duration': 'LEASE_DURATION', + 'lease.state': 'LEASE_STATE', + + // Copy + 'copy.id': 'COPY_ID', + 'copy.status': 'COPY_STATUS', + 'copy.source': 'COPY_SOURCE', + 'copy.progress': 'COPY_PROGRESS', + 'copy.completionTime': 'COPY_COMPLETION_TIME', + 'copy.statusDescription': 'COPY_STATUS_DESCRIPTION', + 'copy.destinationSnapshot': 'COPY_DESTINATION_SNAPSHOT' +}; + +BlobResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + var setBlobPropertyFromHeaders = function (blobProperty, headerProperty) { + if (!azureutil.tryGetValueChain(self, blobProperty.split('.'), null) && headers[headerProperty.toLowerCase()]) { + azureutil.setObjectInnerPropertyValue(self, blobProperty.split('.'), headers[headerProperty.toLowerCase()]); + + if (blobProperty === 'copy.progress') { + var info = azureutil.parseCopyProgress(self.copy.progress); + self.copy.bytesCopied = parseInt(info.bytesCopied); + self.copy.totalBytes = parseInt(info.totalBytes); + } + } + }; + + // For range get, 'x-ms-blob-content-md5' indicate the overall MD5 of the blob. Try to set the contentMD5 using this header if it presents + setBlobPropertyFromHeaders('contentSettings.contentMD5', HeaderConstants.BLOB_CONTENT_MD5); + + _.chain(headersForProperties).pairs().each(function (pair) { + var property = pair[0]; + var header = HeaderConstants[pair[1]]; + setBlobPropertyFromHeaders(property, header); + }); + + // convert isIncrementalCopy to boolean type + if (self.isIncrementalCopy !== undefined) { + self.isIncrementalCopy = (self.isIncrementalCopy === 'true'); + } + + // convert accessTierInferred to boolean type + if (self.accessTierInferred !== undefined) { + self.accessTierInferred = (self.accessTierInferred == 'true'); + } +}; + +/** +* This method sets the HTTP headers and is used by all methods except setBlobProperties and commitBlocks. Those 2 methods will set the x-ms-* headers using setPropertiesFromBlob. +* @ignore +*/ +BlobResult.setHeadersFromBlob = function (webResource, blob) { + var setHeaderPropertyFromBlob = function (headerProperty, blobProperty) { + var blobPropertyValue = azureutil.tryGetValueChain(blob, blobProperty.split('.'), null); + if (blobPropertyValue) { + webResource.withHeader(headerProperty, blobPropertyValue); + } + }; + + if (blob) { + // Content-Type + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_TYPE, 'contentSettings.contentType'); + + // Content-Encoding + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_ENCODING, 'contentSettings.contentEncoding'); + + // Content-Language + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_LANGUAGE, 'contentSettings.contentLanguage'); + + // Content-Disposition + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_DISPOSITION, 'contentSettings.contentDisposition'); + + // Cache-Control + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CACHE_CONTROL, 'contentSettings.cacheControl'); + + // Blob's Content-MD5 + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_MD5, 'contentSettings.contentMD5'); + + // Content-Length + setHeaderPropertyFromBlob(HeaderConstants.CONTENT_LENGTH, 'contentLength'); + + // transactional Content-MD5 + setHeaderPropertyFromBlob(HeaderConstants.CONTENT_MD5, 'transactionalContentMD5'); + + // Range + if (!azureutil.objectIsNull(blob.rangeStart)) { + var range = 'bytes=' + blob.rangeStart + '-'; + + if (!azureutil.objectIsNull(blob.rangeEnd)) { + range += blob.rangeEnd; + } + + webResource.withHeader(HeaderConstants.RANGE, range); + } + + // Blob Type + setHeaderPropertyFromBlob(HeaderConstants.BLOB_TYPE, 'blobType'); + + // Lease id + setHeaderPropertyFromBlob(HeaderConstants.LEASE_ID, 'leaseId'); + + // Sequence number + setHeaderPropertyFromBlob(HeaderConstants.SEQUENCE_NUMBER, 'sequenceNumber'); + setHeaderPropertyFromBlob(HeaderConstants.SEQUENCE_NUMBER_ACTION, 'sequenceNumberAction'); + + if (blob.metadata) { + webResource.addOptionalMetadataHeaders(blob.metadata); + } + } +}; + +/** +* This method sets the x-ms-* headers and is used by setBlobProperties and commitBlocks. All other methods will set the regular HTTP headers using setHeadersFromBlob. +* @ignore +*/ +BlobResult.setPropertiesFromBlob = function (webResource, blob) { + var setHeaderPropertyFromBlob = function (headerProperty, blobProperty) { + var propertyValue = azureutil.tryGetValueChain(blob, blobProperty.split('.'), null); + if (propertyValue) { + webResource.withHeader(headerProperty, propertyValue); + } + }; + + if (blob) { + // Content-Type + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_TYPE, 'contentSettings.contentType'); + + // Content-Encoding + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_ENCODING, 'contentSettings.contentEncoding'); + + // Content-Language + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_LANGUAGE, 'contentSettings.contentLanguage'); + + // Content-Disposition + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_DISPOSITION, 'contentSettings.contentDisposition'); + + // Cache-Control + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CACHE_CONTROL, 'contentSettings.cacheControl'); + + // Content-MD5 + setHeaderPropertyFromBlob(HeaderConstants.BLOB_CONTENT_MD5, 'contentSettings.contentMD5'); + + // Lease id + setHeaderPropertyFromBlob(HeaderConstants.LEASE_ID, 'leaseId'); + + if (blob.metadata) { + webResource.addOptionalMetadataHeaders(blob.metadata); + } + } +}; + +module.exports = BlobResult; diff --git a/node_modules/azure-storage/lib/services/blob/models/blocklistresult.js b/node_modules/azure-storage/lib/services/blob/models/blocklistresult.js new file mode 100644 index 000000000..54f7b822b --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/models/blocklistresult.js @@ -0,0 +1,85 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); + +var azureCommon = require('./../../../common/common.core'); +var xmlbuilder = azureCommon.xmlbuilder; +var Constants = azureCommon.Constants; + +/** +* Builds an XML representation for a block list. +* +* @param {array} The block list. +* @return {string} The XML block list. +*/ +exports.serialize = function (blockListJs) { + var blockListDoc = xmlbuilder.create(); + blockListDoc = blockListDoc.begin(Constants.BlobConstants.BLOCK_LIST_ELEMENT, { version: '1.0', encoding: 'utf-8' }); + + if (_.isArray(blockListJs.LatestBlocks)) { + blockListJs.LatestBlocks.forEach(function (block) { + blockListDoc = blockListDoc.ele(Constants.BlobConstants.LATEST_ELEMENT) + .txt(new Buffer(block).toString('base64')) + .up(); + }); + } + + if (_.isArray(blockListJs.CommittedBlocks)) { + blockListJs.CommittedBlocks.forEach(function (block) { + blockListDoc = blockListDoc.ele(Constants.BlobConstants.COMMITTED_ELEMENT) + .txt(new Buffer(block).toString('base64')) + .up(); + }); + } + + if (_.isArray(blockListJs.UncommittedBlocks)) { + blockListJs.UncommittedBlocks.forEach(function (block) { + blockListDoc = blockListDoc.ele(Constants.BlobConstants.UNCOMMITTED_ELEMENT) + .txt(new Buffer(block).toString('base64')) + .up(); + }); + } + + return blockListDoc.doc().toString(); +}; + +exports.parse = function (blockListXml) { + var blockListResult = {}; + + if (blockListXml.CommittedBlocks && blockListXml.CommittedBlocks.Block) { + blockListResult.CommittedBlocks = blockListXml.CommittedBlocks.Block; + if (!_.isArray(blockListResult.CommittedBlocks)) { + blockListResult.CommittedBlocks = [blockListResult.CommittedBlocks]; + } + blockListResult.CommittedBlocks.forEach(function(block) { + block.Name = new Buffer(block.Name, 'base64').toString(); + }); + } + + if (blockListXml.UncommittedBlocks && blockListXml.UncommittedBlocks.Block) { + blockListResult.UncommittedBlocks = blockListXml.UncommittedBlocks.Block; + if (!_.isArray(blockListResult.UncommittedBlocks)) { + blockListResult.UncommittedBlocks = [blockListResult.UncommittedBlocks]; + } + blockListResult.UncommittedBlocks.forEach(function(block) { + block.Name = new Buffer(block.Name, 'base64').toString(); + }); + } + + return blockListResult; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/blob/models/containerresult.js b/node_modules/azure-storage/lib/services/blob/models/containerresult.js new file mode 100644 index 000000000..6139de460 --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/models/containerresult.js @@ -0,0 +1,116 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var Constants = azureCommon.Constants; + +var HeaderConstants = Constants.HeaderConstants; +var BlobUtilities = require('../blobutilities'); + +/** +* Creates a new ContainerResult object. +* @class +* The ContainerResult class is used to store the container information. +* + * @property {string} name The container name. + * @property {string} publicAccessLevel The public access level. + * @property {object} metadata The metadata key/value pair. + * @property {string} etag The etag. + * @property {string} lastModified The date/time that the container was last modified. + * @property {string} requestId The request id. + * @property {object} lease The lease information. + * @property {string} lease.status The lease status. + * @property {string} lease.state The lease state. + * @property {string} lease.duration The lease duration. + * +* @constructor +* @param {string} [container] The container name. +* @param {string} [publicAccessLevel] The public access level. +*/ +function ContainerResult(name, publicAccessLevel) { + if (name) { + this.name = name; + } + + if (publicAccessLevel) { + this.publicAccessLevel = publicAccessLevel; + } +} + +ContainerResult.parse = function (containerXml) { + var containerResult = new ContainerResult(); + + for (var propertyName in containerXml) { + if (containerXml.hasOwnProperty(propertyName)) { + if (propertyName === 'Properties') { + // Lift out the properties onto the main object to keep consistent across all APIs like: getContainerProperties + azureutil.setPropertyValueFromXML(containerResult, containerXml[propertyName], true); + } else if (propertyName === 'Metadata') { + var resultPropertyName = azureutil.normalizePropertyNameFromXML(propertyName); + containerResult[resultPropertyName] = {}; + azureutil.setPropertyValueFromXML(containerResult[resultPropertyName], containerXml[propertyName], false); + } else { + containerResult[propertyName.toLowerCase()] = containerXml[propertyName]; + } + } + } + + if (!containerResult.publicAccessLevel) { + containerResult.publicAccessLevel = BlobUtilities.BlobContainerPublicAccessType.OFF; + } + + return containerResult; +}; + +ContainerResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + var setContainerPropertyFromHeaders = function (containerProperty, headerProperty) { + if (!azureutil.tryGetValueChain(self, containerProperty.split('.'), null) && headers[headerProperty.toLowerCase()]) { + azureutil.setObjectInnerPropertyValue(self, containerProperty.split('.'), headers[headerProperty.toLowerCase()]); + } + }; + + setContainerPropertyFromHeaders('etag', HeaderConstants.ETAG); + setContainerPropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED); + setContainerPropertyFromHeaders('lease.status', HeaderConstants.LEASE_STATUS); + setContainerPropertyFromHeaders('lease.state', HeaderConstants.LEASE_STATE); + setContainerPropertyFromHeaders('lease.duration', HeaderConstants.LEASE_DURATION); + setContainerPropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID); + + if (!self.publicAccessLevel) { + self.publicAccessLevel = BlobUtilities.BlobContainerPublicAccessType.OFF; + if (headers[HeaderConstants.BLOB_PUBLIC_ACCESS]) { + self.publicAccessLevel = headers[HeaderConstants.BLOB_PUBLIC_ACCESS]; + } + } + + if (self.publicAccessLevel === 'true') { + // The container was marked for full public read access using a version prior to 2009-09-19. + self.publicAccessLevel = BlobUtilities.BlobContainerPublicAccessType.CONTAINER; + } +}; + +/** +* The container ACL settings. +* @typedef {object} ContainerAclResult +* @extends {ContainerResult} +* @property {Object.} signedIdentifiers The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +*/ + +module.exports = ContainerResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/blob/models/leaseresult.js b/node_modules/azure-storage/lib/services/blob/models/leaseresult.js new file mode 100644 index 000000000..8163b372e --- /dev/null +++ b/node_modules/azure-storage/lib/services/blob/models/leaseresult.js @@ -0,0 +1,73 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var Constants = require('./../../../common/common.core').Constants; +var HeaderConstants = Constants.HeaderConstants; + + +/** +* Creates a new LeaseResult object. +* @class +* The LeaseResult class is used to store the lease information. +* + * @property {string} container The container name. + * @property {string} blob The blob name. + * @property {string} id The lease id. + * @property {string} time Approximate time remaining in the lease period, in seconds. + * @property {string} etag The etag. + * @property {string} lastModified The date/time that the lease was last modified. + * +* @constructor +* @param {string} [container] The container name. +* @param {string} [blob] The blob name. +* @param {string} [id] The lease id. +* @param {string} [time] Approximate time remaining in the lease period, in seconds. +*/ +function LeaseResult(container, blob, id, time) { + if (container) { + this.container = container; + } + + if (blob) { + this.blob = blob; + } + + if (id) { + this.id = id; + } + + if (time) { + this.time = time; + } +} + +LeaseResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + if (!self['id'] && headers[HeaderConstants.LEASE_ID]) { + self['id'] = headers[HeaderConstants.LEASE_ID]; + } + + if (!self['time'] && headers[HeaderConstants.LEASE_TIME]) { + self['time'] = parseInt(headers[HeaderConstants.LEASE_TIME], 10); + } + + self['etag'] = headers[HeaderConstants.ETAG]; + self['lastModified'] = headers[HeaderConstants.LAST_MODIFIED.toLowerCase()]; +}; + +module.exports = LeaseResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/file/fileservice.browser.js b/node_modules/azure-storage/lib/services/file/fileservice.browser.js new file mode 100644 index 000000000..79bbed217 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/fileservice.browser.js @@ -0,0 +1,95 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var FileService = require('./fileservice.core'); +var azureCommon = require('./../../common/common.browser'); +var extend = require('extend'); + +var azureutil = azureCommon.util; +var BrowserFileReadStream = azureCommon.BrowserFileReadStream; +var SpeedSummary = azureCommon.SpeedSummary; +var validate = azureCommon.validate; +var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream; + +/** +* Uploads a file to storage from an HTML File object. If the file already exists on the service, it will be overwritten. +* (Only available in the JavaScript Client Library for Browsers) +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {File} browserFile The File object to be uploaded created by HTML File API. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* The default value is false for files. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +FileService.prototype.createFileFromBrowserFile = function (share, directory, file, browserFile, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createFileFromBrowserFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.browserFileIsValid(browserFile); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(file); + + var self = this; + this.createFile(share, directory, file, browserFile.size, options, function (error) { + if (error) { + callback(error); + } else { + var stream = new BrowserFileReadStream(browserFile); + var chunkStream = new ChunkStreamWithStream(stream, { calcContentMd5: options.storeFileContentMD5 }); + self._createFileFromChunkStream(share, directory, file, chunkStream, browserFile.size, options, callback); + } + }); + + return options.speedSummary; +}; + +module.exports = FileService; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/file/fileservice.core.js b/node_modules/azure-storage/lib/services/file/fileservice.core.js new file mode 100644 index 000000000..25283e7e1 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/fileservice.core.js @@ -0,0 +1,3937 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var qs = require('querystring'); +var url = require('url'); +var util = require('util'); +var _ = require('underscore'); +var extend = require('extend'); +var path = require('path'); + +var azureCommon = require('./../../common/common.core'); +var Md5Wrapper = require('./../../common/md5-wrapper'); +var azureutil = azureCommon.util; +var SR = azureCommon.SR; +var validate = azureCommon.validate; +var SpeedSummary = azureCommon.SpeedSummary; +var StorageServiceClient = azureCommon.StorageServiceClient; +var WebResource = azureCommon.WebResource; + +// Constants +var Constants = azureCommon.Constants; +var FileConstants = Constants.FileConstants; +var HeaderConstants = Constants.HeaderConstants; +var HttpConstants = Constants.HttpConstants; +var QueryStringConstants = Constants.QueryStringConstants; + +// Streams +var BatchOperation = azureCommon.BatchOperation; +var SpeedSummary = azureCommon.SpeedSummary; +var ChunkAllocator = azureCommon.ChunkAllocator; +var ChunkStream = azureCommon.ChunkStream; +var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream; +var FileRangeStream = require('./internal/filerangestream'); + +// Models requires +var ShareResult = require('./models/shareresult'); +var DirectoryResult = require('./models/directoryresult'); +var FileResult = require('./models/fileresult'); +var AclResult = azureCommon.AclResult; + +// Errors requires +var errors = require('../../common/errors/errors'); +var ArgumentNullError = errors.ArgumentNullError; +var ArgumentError = errors.ArgumentError; + +/** +* Creates a new FileService object. +* If no connection string or storageaccount and storageaccesskey are provided, +* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. +* @class +* The FileService class is used to perform operations on the Microsoft Azure File Service. +* The File Service provides storage for binary large objects, and provides functions for working with data stored in files. +* +* For more information on the File Service, as well as task focused information on using it in a Node.js application, see +* [How to Use the File Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-file-storage/). +* The following defaults can be set on the file service. +* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the file service. +* defaultEnableReuseSocket The default boolean value to enable socket reuse when uploading local files or streams. +* If the Node.js version is lower than 0.10.x, socket reuse will always be turned off. +* defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the file service. +* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the file service. +* defaultLocationMode The default location mode for requests made via the file service. +* parallelOperationThreadCount The number of parallel operations that may be performed when uploading a file. +* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the file service; true to use the +* Nagle algorithm; otherwise, false. The default value is false. +* @constructor +* @extends {StorageServiceClient} +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {string} [endpointSuffix] The endpoint suffix. +*/ +function FileService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) { + var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix); + + FileService['super_'].call(this, + storageServiceSettings._name, + storageServiceSettings._key, + storageServiceSettings._fileEndpoint, + storageServiceSettings._usePathStyleUri, + storageServiceSettings._sasToken); + + this.defaultEnableReuseSocket = Constants.DEFAULT_ENABLE_REUSE_SOCKET; + this.singleFileThresholdInBytes = FileConstants.DEFAULT_SINGLE_FILE_GET_THRESHOLD_IN_BYTES; + this.parallelOperationThreadCount = Constants.DEFAULT_PARALLEL_OPERATION_THREAD_COUNT; +} + +util.inherits(FileService, StorageServiceClient); + +// Utility methods + +/** +* Create resource name +* @ignore +* +* @param {string} share Share name +* @param {string} [directory] Directory name +* @param {string} [file] File name +* @return {string} The encoded resource name. +*/ +function createResourceName(share, directory, file, forSAS) { + var encode = function(name) { + if (name && !forSAS) { + name = encodeURIComponent(name); + name = name.replace(/%2F/g, '/'); + name = name.replace(/%5C/g, '/'); + name = name.replace(/\+/g, '%20'); + } + return name; + }; + + var name = share; + + if (directory) { + // if directory does not start with '/', add it + if (directory[0] !== '/') { + name += ('/'); + } + + name += encode(directory); + } + + if (file) { + // if the current path does not end with '/', add it + if (name[name.length - 1] !== '/') { + name += ('/'); + } + + name += encode(file); + } + + return path.normalize(name).replace(/\\/g, '/'); +} + +// File service methods + +/** +* Gets the properties of a storage account's File service, including Azure Storage Analytics. +* +* @this {FileService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceProperties}` will contain the properties +* and `response` will contain information related to this operation. +*/ +FileService.prototype.getServiceProperties = function (optionsOrCallback, callback) { + return this.getAccountServiceProperties(optionsOrCallback, callback); +}; + +/** +* Sets the properties of a storage account's File service, including Azure Storage Analytics. +* You can also use this operation to set the default request version for all incoming requests that do not have a version specified. +* +* @this {FileService} +* @param {object} serviceProperties The service properties. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise, `response` +* will contain information related to this operation. +*/ +FileService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) { + return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback); +}; + +// Share methods + +/** +* Lists a segment containing a collection of share items under the specified account. +* +* @this {FileService} +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.maxResults] Specifies the maximum number of shares to return per call to Azure storage. +* @param {string} [options.include] Include this parameter to specify that the share's metadata be returned as part of the response body. (allowed values: '', 'metadata', 'snapshots' or any combination of them) +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[shares]{@link ShareResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +FileService.prototype.listSharesSegmented = function (currentToken, optionsOrCallback, callback) { + this.listSharesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of share items whose names begin with the specified prefix under the specified account. +* +* @this {FileService} +* @param {string} prefix The prefix of the share name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {string} [options.prefix] Filters the results to return only shares whose name begins with the specified prefix. +* @param {int} [options.maxResults] Specifies the maximum number of shares to return per call to Azure storage. +* @param {string} [options.include] Include this parameter to specify that the share's metadata be returned as part of the response body. (allowed values: '', 'metadata', 'snapshots' or any combination of them) +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[shares]{@link ShareResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +FileService.prototype.listSharesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listShares', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get() + .withQueryOption(QueryStringConstants.COMP, 'list') + .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults) + .withQueryOption(QueryStringConstants.INCLUDE, options.include); + + if (!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker); + } + + webResource.withQueryOption(QueryStringConstants.PREFIX, prefix); + + //options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken); + + var processResponseCallback = function (responseObject, next) { + responseObject.listSharesResult = null; + + if (!responseObject.error) { + responseObject.listSharesResult = { + entries: null, + continuationToken: null + }; + responseObject.listSharesResult.entries = []; + + var shares = []; + + if (responseObject.response.body.EnumerationResults.Shares && responseObject.response.body.EnumerationResults.Shares.Share) { + shares = responseObject.response.body.EnumerationResults.Shares.Share; + if (!_.isArray(shares)) { + shares = [shares]; + } + } + + shares.forEach(function (currentShare) { + var shareResult = ShareResult.parse(currentShare); + responseObject.listSharesResult.entries.push(shareResult); + }); + + if (responseObject.response.body.EnumerationResults.NextMarker) { + responseObject.listSharesResult.continuationToken = { + nextMarker: null, + targetLocation: null + }; + + responseObject.listSharesResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker; + responseObject.listSharesResult.continuationToken.targetLocation = responseObject.targetLocation; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.listSharesResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks whether or not a share exists on the service. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareResult}` will contain +* the share information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +FileService.prototype.doesShareExist = function (share, optionsOrCallback, callback) { + this._doesShareExist(share, false, optionsOrCallback, callback); +}; + +/** +* Creates a new share under the specified account. +* If a share with the same name already exists, the operation fails. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {int} [options.quota] Specifies the maximum size of the share, in gigabytes. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareResult}` will contain +* the share information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.createShare = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createShare', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.shareQuotaIsValid(userOptions.quota); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withHeader(HeaderConstants.SHARE_QUOTA, options.quota); + + webResource.addOptionalMetadataHeaders(options.metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + + if (options.metadata) { + responseObject.shareResult.metadata = options.metadata; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Creates a share snapshot. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the ID of the snapshot. +* `response` will contain information related to this operation. +*/ +FileService.prototype.createShareSnapshot = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createShareSnapshot', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, QueryStringConstants.SNAPSHOT); + webResource.addOptionalMetadataHeaders(options.metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.snapshotId = null; + if (!responseObject.error) { + responseObject.snapshotId = responseObject.response.headers[HeaderConstants.SNAPSHOT]; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.snapshotId, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Creates a new share under the specified account if the share does not exists. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareResult}` will contain +* the share information including `created` boolean member. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var FileService = azure.createFileService(); +* FileService.createShareIfNotExists('taskshare', function(error) { +* if(!error) { +* // Share created or already existed +* } +* }); +*/ +FileService.prototype.createShareIfNotExists = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createShareIfNotExists', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + delete options.shareSnapshotId; + + var self = this; + self._doesShareExist(share, true, options, function(error, result, response) { + var exists = result.exists; + result.created = false; + delete result.exists; + + if(error){ + callback(error, result, response); + } else if (exists) { + response.isSuccessful = true; + callback(error, result, response); + } else { + self.createShare(share, options, function (createError, responseShare, createResponse) { + if(!createError){ + responseShare.created = true; + } + else if (createError && createError.statusCode === HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.FileErrorCodeStrings.SHARE_ALREADY_EXISTS) { + // If it was created before, there was no actual error. + createError = null; + createResponse.isSuccessful = true; + } + + callback(createError, responseShare, createResponse); + }); + } + }); +}; + +/** +* Retrieves a share and its properties from a specified account. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. + + +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareResult}` will contain +* information for the share. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getShareProperties = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getShareProperties', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + //options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets the properties for the specified share. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [properties] The share properties to set. +* @param {string|int} [properties.quota] Specifies the maximum size of the share, in gigabytes. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[share]{@link ShareResult}` will contain +* information about the share. +* `response` will contain information related to this operation. +*/ +FileService.prototype.setShareProperties = function (share, properties, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setShareProperties', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.shareQuotaIsValid(userOptions.quota); + v.callback(callback); + }); + + var options = extend(true, properties, userOptions); + var resourceName = createResourceName(share); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, 'properties') + .withHeader(HeaderConstants.SHARE_QUOTA, options.quota); + + FileResult.setProperties(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets the share statistics for a share. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `[result]{@link ServiceStats}` will contain the stats and +* `response` will contain information related to this operation. +*/ +FileService.prototype.getShareStats = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getShareStats', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, 'stats'); + + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = ShareResult.parse(responseObject.response.body, share); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + // function to be called after all filters + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + // call the first filter + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + + +/** +* Returns all user-defined metadata for the share. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareResult}` will contain +* information for the share. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getShareMetadata = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getShareMetadata', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, 'metadata') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets the share's metadata. +* +* Calling the Set Share Metadata operation overwrites all existing metadata that is associated with the share. +* It's not possible to modify an individual name/value pair. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} metadata The metadata key/value pairs. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +FileService.prototype.setShareMetadata = function (share, metadata, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setShareMetadata', function (v) { + v.string(share, 'share'); + v.object(metadata, 'metadata'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, 'metadata'); + + webResource.addOptionalMetadataHeaders(metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets the share's ACL. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareAclResult}` will contain +* information for the share. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getShareAcl = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getShareAcl', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, 'acl'); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + responseObject.shareResult.signedIdentifiers = AclResult.parse(responseObject.response.body); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Updates the share's ACL. +* +* @this {FileService} +* @param {string} share The share name. +* @param {Object.} signedIdentifiers The share ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link ShareAclResult}` will contain +* information for the share. +* `response` will contain information related to this operation. +*/ +FileService.prototype.setShareAcl = function (share, signedIdentifiers, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setShareAcl', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var policies = null; + if (signedIdentifiers) { + if(_.isArray(signedIdentifiers)) { + throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS); + } + policies = AclResult.serialize(signedIdentifiers); + } + + var webResource = WebResource.put(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.COMP, 'acl') + .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0) + .withBody(policies); + + var processResponseCallback = function (responseObject, next) { + responseObject.shareResult = null; + if (!responseObject.error) { + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + if (signedIdentifiers) { + responseObject.shareResult.signedIdentifiers = signedIdentifiers; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Marks the specified share for deletion. +* The share and any files contained within it are later deleted during garbage collection. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.FileUtilities.ShareSnapshotDeleteOptions.*. +* @param {string} [options.shareSnapshotId] The share snapshot identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +FileService.prototype.deleteShare = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteShare', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + if (!azureutil.objectIsNull(options.shareSnapshotId) && !azureutil.objectIsNull(options.deleteSnapshots)) { + throw new ArgumentError('options', SR.INVALID_DELETE_SNAPSHOT_OPTION); + } + + var webResource = WebResource.del(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId) + .withHeader(HeaderConstants.DELETE_SNAPSHOT, options.deleteSnapshots); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified share for deletion if it exists. +* The share and any files contained within it are later deleted during garbage collection. +* +* @this {FileService} +* @param {string} share The share name. +* @param {object} [options] The request options. +* @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.FileUtilities.ShareSnapshotDeleteOptions.*. +* @param {string} [options.shareSnapshotId] The share snapshot identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will +* be true if the share exists and was deleted, or false if the share +* did not exist. +* `response` will contain information related to this operation. +*/ +FileService.prototype.deleteShareIfExists = function (share, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteShareIfExists', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var self = this; + self._doesShareExist(share, true, options, function (error, result, response) { + if(error){ + callback(error, result.exists, response); + } else if (!result.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteShare(share, options, function (deleteError, deleteResponse) { + var deleted; + if (!deleteError){ + deleted = true; + } else if (deleteError && deleteError.statuscode === HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.FileErrorCodeStrings.SHARE_NOT_FOUND) { + // If it was deleted already, there was no actual error. + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +// Directory methods + +/** +* Checks whether or not a directory exists on the service. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The share snapshot identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain +* the directory information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +FileService.prototype.doesDirectoryExist = function (share, directory, optionsOrCallback, callback) { + this._doesDirectoryExist(share, directory, false, optionsOrCallback, callback); +}; + +/** +* Creates a new directory under the specified account. +* If a directory with the same name already exists, the operation fails. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain +* the directory information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.createDirectory = function (share, directory, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createDirectory', function (v) { + v.string(share, 'share'); + v.string(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(createResourceName(share, directory)) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory'); + + webResource.addOptionalMetadataHeaders(options.metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.directoryResult = null; + if (!responseObject.error) { + responseObject.directoryResult = new DirectoryResult(directory); + responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.directoryResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Creates a new directory under the specified account if the directory does not exists. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain +* the directory information including `created` boolean member. +* already exists. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var FileService = azure.createFileService(); +* FileService.createDirectoryIfNotExists('taskshare', taskdirectory', function(error) { +* if(!error) { +* // Directory created or already existed +* } +* }); +*/ +FileService.prototype.createDirectoryIfNotExists = function (share, directory, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createDirectoryIfNotExists', function (v) { + v.string(share, 'share'); + v.string(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + delete options.shareSnapshotId; + + var self = this; + self._doesDirectoryExist(share, directory, true, options, function(error, result, response) { + var exists = result.exists; + result.created = false; + delete result.exists; + + if(error){ + callback(error, result, response); + } else if (exists) { + response.isSuccessful = true; + callback(error, result, response); + } else { + self.createDirectory(share, directory, options, function (createError, responseDirectory, createResponse) { + if(!createError){ + responseDirectory.created = true; + } + else if (createError && createError.statusCode === HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.StorageErrorCodeStrings.RESOURCE_ALREADY_EXISTS) { + // If it was created before, there was no actual error. + createError = null; + createResponse.isSuccessful = true; + } + + callback(createError, responseDirectory, createResponse); + }); + } + }); +}; + +/** +* Retrieves a directory and its properties from a specified account. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain +* information for the directory. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getDirectoryProperties = function (share, directory, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getDirectoryProperties', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(createResourceName(share, directory)) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.directoryResult = null; + if (!responseObject.error) { + responseObject.directoryResult = new DirectoryResult(directory); + responseObject.directoryResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.directoryResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified directory for deletion. The directory must be empty before it can be deleted. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +FileService.prototype.deleteDirectory = function (share, directory, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteDirectory', function (v) { + v.string(share, 'share'); + v.string(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.del(createResourceName(share, directory)) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory'); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified directory for deletion if it exists. The directory must be empty before it can be deleted. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will +* be true if the directory exists and was deleted, or false if the directory +* did not exist. +* `response` will contain information related to this operation. +*/ +FileService.prototype.deleteDirectoryIfExists = function (share, directory, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteDirectoryIfExists', function (v) { + v.string(share, 'share'); + v.string(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + delete options.shareSnapshotId; + + var self = this; + self._doesDirectoryExist(share, directory, true, options, function(error, result, response) { + if(error){ + callback(error, result.exists, response); + } else if (!result.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteDirectory(share, directory, options, function (deleteError, deleteResponse) { + var deleted; + if (!deleteError){ + deleted = true; + } else if (deleteError && deleteError.statuscode === HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND) { + // If it was deleted already, there was no actual error. + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +/** +* Lists a segment containing a collection of file items in the directory. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {int} [options.maxResults] Specifies the maximum number of files to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* entries.files which contains a list of `[files]{@link FileResult}`, entries.directories which contains a list of `[directories]{@link DirectoryResult}` and the continuationToken for the next listing operation. +* `response` will contain information related to this operation. +*/ +FileService.prototype.listFilesAndDirectoriesSegmented = function (share, directory, currentToken, optionsOrCallback, callback) { + this.listFilesAndDirectoriesSegmentedWithPrefix(share, directory, null /*prefix*/, currentToken, optionsOrCallback, callback); +}; + + +/** +* Lists a segment containing a collection of file items in the directory. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} prefix The prefix of the directory/files name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {int} [options.maxResults] Specifies the maximum number of files to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* entries.files which contains a list of `[files]{@link FileResult}`, entries.directories which contains a list of `[directories]{@link DirectoryResult}` and the continuationToken for the next listing operation. +* `response` will contain information related to this operation. +*/ +FileService.prototype.listFilesAndDirectoriesSegmentedWithPrefix = function (share, directory, prefix, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listFilesSegmented', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(createResourceName(share, directory)) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory') + .withQueryOption(QueryStringConstants.COMP, 'list') + .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults) + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + if (!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker); + } + + webResource.withQueryOption(QueryStringConstants.PREFIX, prefix); + + var processResponseCallback = function (responseObject, next) { + responseObject.listResult = null; + if (!responseObject.error) { + responseObject.listResult = { + entries: null, + continuationToken: null + }; + + responseObject.listResult.entries = {}; + responseObject.listResult.entries.files = []; + responseObject.listResult.entries.directories = []; + var files = []; + var directories = []; + + // parse files + if (responseObject.response.body.EnumerationResults.Entries.File) { + files = responseObject.response.body.EnumerationResults.Entries.File; + if (!_.isArray(files)) { + files = [ files ]; + } + } + + files.forEach(function (currentFile) { + var fileResult = FileResult.parse(currentFile); + responseObject.listResult.entries.files.push(fileResult); + }); + + // parse directories + if (responseObject.response.body.EnumerationResults.Entries.Directory) { + directories = responseObject.response.body.EnumerationResults.Entries.Directory; + if (!_.isArray(directories)) { + directories = [ directories ]; + } + } + + directories.forEach(function (currentDirectory) { + var directoryResult = DirectoryResult.parse(currentDirectory); + responseObject.listResult.entries.directories.push(directoryResult); + }); + + // parse continuation token + if(responseObject.response.body.EnumerationResults.NextMarker) { + responseObject.listResult.continuationToken = { + nextMarker: null, + targetLocation: null + }; + + responseObject.listResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker; + responseObject.listResult.continuationToken.targetLocation = responseObject.targetLocation; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.listResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Returns all user-defined metadata for the specified directory. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain +* information about the directory. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getDirectoryMetadata = function (share, directory, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getDirectoryMetadata', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory); + var webResource = WebResource.head(resourceName) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory') + .withQueryOption(QueryStringConstants.COMP, 'metadata') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.directoryResult = null; + if (!responseObject.error) { + responseObject.directoryResult = new DirectoryResult(directory); + responseObject.directoryResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.directoryResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets user-defined metadata for the specified directory as one or more name-value pairs +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {object} metadata The metadata key/value pairs. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link DirectoryResult}` will contain +* information on the directory. +* `response` will contain information related to this operation. +*/ +FileService.prototype.setDirectoryMetadata = function (share, directory, metadata, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setDirectoryMetadata', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.shareNameIsValid(share); + v.object(metadata, 'metadata'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory') + .withQueryOption(QueryStringConstants.COMP, 'metadata'); + + webResource.addOptionalMetadataHeaders(metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.directoryResult = null; + if (!responseObject.error) { + responseObject.directoryResult = new DirectoryResult(directory); + responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.directoryResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +// File methods + +/** +* Retrieves a shared access signature token. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} [directory] The directory name. Use '' to refer to the base directory. +* @param {string} [file] The file name. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {string} [sharedAccessPolicy.Id] The signed identifier. +* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired (The UTC value will be used). +* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} [sharedAccessPolicy.AccessPolicy.Protocols] The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* @param {object} [headers] The optional header values to set for a file returned wth this SAS. +* @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used. +* @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used. +* @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used. +* @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used. +* @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used. +* @return {string} The shared access signature query string. Note this string does not contain the leading "?". +*/ +FileService.prototype.generateSharedAccessSignature = function (share, directory, file, sharedAccessPolicy, headers) { + // check if the FileService is able to generate a shared access signature + if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) { + throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY); + } + + // Validate share name. File name is optional. + validate.validateArgs('generateSharedAccessSignature', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.object(sharedAccessPolicy, 'sharedAccessPolicy'); + }); + + var resourceType = FileConstants.ResourceTypes.SHARE; + if (file) { + validate.validateArgs('generateSharedAccessSignature', function (v) { + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + }); + resourceType = FileConstants.ResourceTypes.FILE; + } else { + directory = ''; // If file is not set, directory is not a part of the string to sign. + } + + if (sharedAccessPolicy.AccessPolicy) { + if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Start)) { + if (!_.isDate(sharedAccessPolicy.AccessPolicy.Start)) { + sharedAccessPolicy.AccessPolicy.Start = new Date(sharedAccessPolicy.AccessPolicy.Start); + } + + sharedAccessPolicy.AccessPolicy.Start = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Start); + } + + if (!azureutil.objectIsNull(sharedAccessPolicy.AccessPolicy.Expiry)) { + if (!_.isDate(sharedAccessPolicy.AccessPolicy.Expiry)) { + sharedAccessPolicy.AccessPolicy.Expiry = new Date(sharedAccessPolicy.AccessPolicy.Expiry); + } + + sharedAccessPolicy.AccessPolicy.Expiry = azureutil.truncatedISO8061Date(sharedAccessPolicy.AccessPolicy.Expiry); + } + } + + var resourceName = createResourceName(share, directory, file, true); + return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.File, resourceName, sharedAccessPolicy, null, { headers: headers, resourceType: resourceType }); +}; + +/** +* Retrieves a file or directory URL. +* +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} [file] The file name. File names may not start or end with the delimiter '/'. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint. +* @param {boolean} [shareSnapshotId] The snapshot identifier of the share. +* @return {string} The formatted URL string. +* @example +* var azure = require('azure-storage'); +* var fileService = azure.createFileService(); +* var sharedAccessPolicy = { +* AccessPolicy: { +* Permissions: azure.FileUtilities.SharedAccessPermissions.READ, +* Start: startDate, +* Expiry: expiryDate +* }, +* }; +* +* var sasToken = fileService.generateSharedAccessSignature(shareName, directoryName, fileName, sharedAccessPolicy); +* var url = fileService.getUrl(shareName, directoryName, fileName, sasToken, true); +*/ +FileService.prototype.getUrl = function (share, directory, file, sasToken, primary, shareSnapshotId) { + validate.validateArgs('getUrl', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.shareNameIsValid(share); + }); + + var host; + if(!azureutil.objectIsNull(primary) && primary === false) { + host = this.host.secondaryHost; + } else { + host = this.host.primaryHost; + } + host = azureutil.trimPortFromUri(host); + if(host && host.lastIndexOf('/') !== (host.length - 1)){ + host = host + '/'; + } + + var name = createResourceName(share, directory, file); + var query = qs.parse(sasToken); + if(shareSnapshotId) { + query[QueryStringConstants.SHARE_SNAPSHOT] = shareSnapshotId; + } + return url.resolve(host, url.format({pathname: this._getPath(name), query: query})); +}; + +/** +* Returns all user-defined metadata, standard HTTP properties, and system properties for the file. +* It does not return or modify the content of the file. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* information about the file. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getFileProperties = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getFileProperties', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.head(resourceName) + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Returns all user-defined metadata for the specified file. +* It does not modify or return the content of the file. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* information about the file. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getFileMetadata = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getFileMetadata', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.head(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'metadata') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets user-defined properties for the specified file. +* It does not modify or return the content of the file. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [properties] The file properties to set. +* @param {string} [properties.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [properties.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [properties.contentLanguage] The natural languages used by this resource. +* @param {string} [properties.cacheControl] The file's cache control. +* @param {string} [properties.contentDisposition] The file's content disposition. +* @param {string} [properties.contentLength] Resizes a file to the specified size. If the specified byte value is less than the current size of the file, +* then all ranges above the specified byte value are cleared. +* @param {string} [properties.contentMD5] The file's MD5 hash. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* information about the file. +* `response` will contain information related to this operation. +*/ +FileService.prototype.setFileProperties = function (share, directory, file, properties, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setFileProperties', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {contentSettings: properties, contentLength: properties.contentLength }, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'properties'); + + FileResult.setProperties(webResource, options); + + var processResponseCallback = function(responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function(returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets user-defined metadata for the specified file as one or more name-value pairs +* It does not modify or return the content of the file. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} metadata The metadata key/value pairs. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* information on the file. +* `response` will contain information related to this operation. +*/ +FileService.prototype.setFileMetadata = function (share, directory, file, metadata, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setFileMetadata', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.object(metadata, 'metadata'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'metadata'); + + webResource.addOptionalMetadataHeaders(metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Resizes a file. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {String} size The size of the file, in bytes. +* @param {object} [options] The request options. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* information about the file. +* `response` will contain information related to this operation. +*/ +FileService.prototype.resizeFile = function (share, directory, file, size, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('resizeFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.value(size); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'properties'); + + webResource.withHeader(HeaderConstants.FILE_CONTENT_LENGTH, size); + + var processResponseCallback = function(responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function(returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks whether or not a file exists on the service. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* the file information including the `exists` boolean member. +* `response` will contain information related to this operation. +*/ +FileService.prototype.doesFileExist = function (share, directory, file, optionsOrCallback, callback) { + this._doesFileExist(share, directory, file, false, optionsOrCallback, callback); +}; + +/** +* Creates a file of the specified length. If the file already exists on the service, it will be overwritten. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {int} length The length of the file in bytes. +* @param {object} [options] The request options. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* the file information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.createFile = function (share, directory, file, length, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + validate.validateArgs('createFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.value(length); + v.callback(callback); + }); + + var resourceName = createResourceName(share, directory, file); + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(resourceName) + .withHeader(HeaderConstants.TYPE, 'file') + .withHeader(HeaderConstants.FILE_CONTENT_LENGTH, length); + + FileResult.setProperties(webResource, options); + + var processResponseCallback = function(responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function(returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified file for deletion. The file is later deleted during garbage collection. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; `response` will contain information related to this operation. +*/ +FileService.prototype.deleteFile = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.del(resourceName); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Marks the specified file for deletion if it exists. The file is later deleted during garbage collection. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will +* be true if the file was deleted, or false if the file +* does not exist. +* `response` will contain information related to this operation. +*/ +FileService.prototype.deleteFileIfExists = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteFileIfExists', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + delete options.shareSnapshotId; + + var self = this; + self._doesFileExist(share, directory, file, true, options, function(error, result, response) { + if(error){ + callback(error, result.exists, response); + } else if (!result.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteFile(share, directory, file, options, function (deleteError, deleteResponse) { + var deleted; + if (!deleteError){ + deleted = true; + } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.FileErrorCodeStrings.FILE_NOT_FOUND) { + // If it was deleted already, there was no actual error. + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +/** +* Downloads a file into a text string. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {int} [options.rangeStart] The range start. +* @param {int} [options.rangeEnd] The range end. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {FileService~FileToText} callback `error` will contain information +* if an error occurs; otherwise `text` will contain the file contents, +* and `[file]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.getFileToText = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getFileToText', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId) + .withRawResponse(); + + FileResult.setHeaders(webResource, options); + this._setRangeContentMD5Header(webResource, options); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.text = null; + responseObject.fileResult = null; + + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true); + responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.text = responseObject.response.body; + + self._validateLengthAndMD5(options, responseObject); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.text, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Provides a stream to read from a file. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var fileService = azure.createFileService(); +* var writable = fs.createWriteStream(destinationFileNameTarget); +* fileService.createReadStream(shareName, directoryName, fileName).pipe(writable); +*/ +FileService.prototype.createReadStream = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createReadStream', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + }); + + var options = extend(true, {}, userOptions); + + var readStream = new ChunkStream(options); + this.getFileToStream(share, directory, file, readStream, options, function (error, fileResponse, response) { + if(error) { + readStream.emit('error', error); + } + + if(callback) { + callback(error, fileResponse, response); + } + }); + + return readStream; +}; + +/** +* Downloads a file into a stream. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {Stream} writeStream The write stream. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download. +* Set the option to true for small files. +* Parallel download and speed summary won't work with this option on. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +* +* +* @example +* var azure = require('azure-storage'); +* var FileService = azure.createFileService(); +* FileService.getFileToStream('taskshare', taskdirectory', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverFile) { +* if(!error) { +* // file available in serverFile.file variable +* } +* }); +*/ +FileService.prototype.getFileToStream = function (share, directory, file, writeStream, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + userOptions.speedSummary = userOptions.speedSummary || new SpeedSummary(file); + + validate.validateArgs('getFileToStream', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.object(writeStream, 'writeStream'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var propertiesRequestOptions = { + timeoutIntervalInMs : options.timeoutIntervalInMs, + clientRequestTimeoutInMs : options.clientRequestTimeoutInMs, + accessConditions : options.accessConditions, + shareSnapshotId : options.shareSnapshotId + }; + + if (options.skipSizeCheck) { + this._getFileToStream(share, directory, file, writeStream, options, callback); + } else { + var self = this; + this.getFileProperties(share, directory, file, propertiesRequestOptions, function (error, properties) { + if (error) { + callback(error); + } else { + var size; + if (options.rangeStart) { + var endOffset = properties.contentLength - 1; + var end = options.rangeEnd ? Math.min(options.rangeEnd, endOffset) : endOffset; + size = end - options.rangeStart + 1; + } else { + size = properties.contentLength; + } + options.speedSummary.totalSize = size; + + if (size > self.singleFileThresholdInBytes) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(properties, ['contentSettings', 'contentMD5'], null)); + self._getFileToRangeStream(share, directory, file, writeStream, options, callback); + } else { + self._getFileToStream(share, directory, file, writeStream, options, callback); + } + } + }); + } + + return options.speedSummary; +}; + +/** +* Lists file ranges. Lists all of the ranges by default, or only the ranges over a specific range of bytes if rangeStart and rangeEnd are specified. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {int} [options.rangeStart] The range start. +* @param {int} [options.rangeEnd] The range end. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* the range information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.listRanges = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listRanges', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var resourceName = createResourceName(share, directory, file); + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'rangelist') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + FileResult.setHeaders(webResource, options); + + var processResponseCallback = function (responseObject, next) { + responseObject.ranges = null; + if (!responseObject.error) { + responseObject.ranges = []; + + var ranges = []; + if (responseObject.response.body.Ranges.Range) { + ranges = responseObject.response.body.Ranges.Range; + + if (!_.isArray(ranges)) { + ranges = [ ranges ]; + } + } + + ranges.forEach(function (fileRange) { + var range = { + start: parseInt(fileRange.Start, 10), + end: parseInt(fileRange.End, 10) + }; + + responseObject.ranges.push(range); + }); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.ranges, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Clears a range. Clears all of the ranges by default, or only the ranges over a specific range of bytes if rangeStart and rangeEnd are specified. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {int} rangeStart The range start. +* @param {int} rangeEnd The range end. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* the directory information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.clearRange = function (share, directory, file, rangeStart, rangeEnd, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('clearRange', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.value(rangeStart); + v.value(rangeEnd); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var request = this._updateFilesImpl(share, directory, file, rangeStart, rangeEnd, FileConstants.RangeWriteOptions.CLEAR, options); + + var processResponseCallback = function(responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function(returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(request, null, options, processResponseCallback); +}; + +/** +* Updates a range from a stream. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {Stream} readStream The read stream. +* @param {int} rangeStart The range start. +* @param {int} rangeEnd The range end. +* @param {object} [options] The request options. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {string} [options.transactionalContentMD5] An optional hash value used to ensure transactional integrity for the page. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link FileResult}` will contain +* the file information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.createRangesFromStream = function (share, directory, file, readStream, rangeStart, rangeEnd, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createRangesFromStream', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.object(readStream, 'readStream'); + v.shareNameIsValid(share); + v.value(rangeStart); + v.value(rangeEnd); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var requiresContentMD5 = azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5 === true; + + var length = (rangeEnd - rangeStart) + 1; + if(length > FileConstants.MAX_UPDATE_FILE_SIZE) { + throw new Error(SR.INVALID_FILE_RANGE_FOR_UPDATE); + } + + var self = this; + if (requiresContentMD5) { + azureutil.calculateMD5(readStream, length, options, function(internalBuff, contentMD5) { + options.transactionalContentMD5 = contentMD5; + self._createRanges(share, directory, file, internalBuff, null /* stream */, rangeStart, rangeEnd, options, callback); + }); + } else { + self._createRanges(share, directory, file, null /* text */, readStream, rangeStart, rangeEnd, options, callback); + } +}; + +/** +* Uploads a file from a text string. If the file already exists on the service, it will be overwritten. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {string|object} text The file text, as a string or in a Buffer. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The upload tracker objects; +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* The default value is false for files. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {FileService~FileToText} callback `error` will contain information +* if an error occurs; otherwise `text` will contain the file contents, +* and `[file]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @example +* var azure = require('azure-storage'); +* var fileService = azure.createFileService(); +* +* var text = 'Hello World!'; +* +* fileService.createFileFromText('taskshare', 'taskdirectory', 'taskfile', text, function(error, result, response) { +* if (!error) { +* // file created +* } +* }); +*/ +FileService.prototype.createFileFromText = function (share, directory, file, text, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createFileFromText', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.exists(text, 'text'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var length = Buffer.isBuffer(text) ? text.length : Buffer.byteLength(text); + if (length > FileConstants.MAX_UPDATE_FILE_SIZE) { + throw new Error(SR.INVALID_FILE_LENGTH); + } + + if(options.storeFileContentMD5 && azureutil.objectIsNull(azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null))) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], azureutil.getContentMd5(text)); + } + + var self = this; + this.createFile(share, directory, file, length, options, function(error) { + if(error) { + callback(error); + } + else { + self._createRanges(share, directory, file, text, null, 0, length - 1, options, callback); + } + }); +}; + +/** +* Uploads a file from a stream. If the file already exists on the service, it will be overwritten. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* The default value is false for files. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +* @example +* var stream = require('stream'); +* var azure = require('azure-storage'); +* var fileService = azure.createFileService(); +* +* var fileStream = new stream.Readable(); +* fileStream.push(myFileBuffer); +* fileStream.push(null); +* +* fileService.createFileFromStream('taskshare', 'taskdirectory', 'taskfile', fileStream, myFileBuffer.length, function(error, result, response) { +* if (!error) { +* // file uploaded +* } +* }); +*/ +FileService.prototype.createFileFromStream = function(share, directory, file, stream, streamLength, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createFileFromStream', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.object(stream, 'stream'); + v.value(streamLength, 'streamLength'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(file); + + stream.pause(); // Immediately pause the stream in order to compatible with Node v0.8 + + var self = this; + this.createFile(share, directory, file, streamLength, options, function(error) { + if(error) { + callback(error); + } else { + var chunkStream = new ChunkStreamWithStream(stream, {calcContentMd5: options.storeFileContentMD5}); + self._createFileFromChunkStream(share, directory, file, chunkStream, streamLength, options, callback); + } + }); + + return options.speedSummary; +}; + +/** +* Provides a stream to write to a file. Assumes that the file exists. +* If it does not, please create the file using createFile before calling this method or use createWriteStreamNewFile. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* The default value is false for files. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var FileService = azure.createFileService(); +* FileService.createFile(shareName, directoryName, fileName, 1024, function (err) { +* // Pipe file to a file +* var stream = fs.createReadStream(fileNameTarget).pipe(FileService.createWriteStreamToExistingFile(shareName, directoryName, fileName)); +* }); +*/ +FileService.prototype.createWriteStreamToExistingFile = function (share, directory, file, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createWriteStreamToExistingFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + }); + + var options = extend(true, {}, userOptions); + + var stream = new ChunkStream({calcContentMd5: options.storeFileContentMD5}); + this._createFileFromChunkStream(share, directory, file, stream, null, options, function (error, file, response) { + if(error) { + stream.emit('error', error); + } + + if (callback) { + callback(error, file, response); + } + }); + + return stream; +}; + +/** +* Provides a stream to write to a file. Creates the file before writing data. +* Please note the `Stream` returned by this API should be used with piping. +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {string} length The file length. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* The default value is false for files. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {Stream} +* @example +* var azure = require('azure-storage'); +* var FileService = azure.createFileService(); +* var stream = fs.createReadStream(fileNameTarget).pipe(FileService.createWriteStreamToNewFile(shareName, directoryName, fileName)); +*/ +FileService.prototype.createWriteStreamToNewFile = function (share, directory, file, length, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createWriteStreamToNewFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.value(length, 'length'); + v.shareNameIsValid(share); + }); + + var options = extend(true, {}, userOptions); + + var stream = new ChunkStream({calcContentMd5: options.storeFileContentMD5}); + stream.pause(); + + var self = this; + this.createFile(share, directory, file, length, options, function(error) { + if(error) { + stream.emit('error', error); + callback(error); + } + else { + stream.resume(); + self._createFileFromChunkStream(share, directory, file, stream, null, options, function (error, file, response) { + if(error) { + stream.emit('error', error); + } + + if (callback) { + callback(error, file, response); + } + }); + } + }); + + return stream; +}; + +/** +* Starts to copy a file to a destination within the storage account. +* +* @this {FileService} +* @param {string} sourceUri The source file or blob URI. +* @param {string} targetShare The target share name. +* @param {string} targetDirectory The target directory name. +* @param {string} targetFile The target file name. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The target file metadata key/value pairs. +* @param {AccessConditions} [options.accessConditions] The access conditions. +* @param {AccessConditions} [options.sourceAccessConditions] The source access conditions. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.startCopyFile = function (sourceUri, targetShare, targetDirectory, targetFile, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('startCopyFile', function (v) { + v.string(targetShare, 'targetShare'); + v.stringAllowEmpty(targetDirectory, 'targetDirectory'); + v.string(targetFile, 'targetFile'); + v.shareNameIsValid(targetShare); + v.callback(callback); + }); + + var targetResourceName = createResourceName(targetShare, targetDirectory, targetFile); + + var options = extend(true, {}, userOptions); + + var webResource = WebResource.put(targetResourceName) + .withHeader(HeaderConstants.COPY_SOURCE, sourceUri) + .addOptionalMetadataHeaders(options.metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(targetShare, targetDirectory, targetFile); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true); + + if (options.metadata) { + responseObject.fileResult.metadata = options.metadata; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Abort a file copy operation. +* +* @this {FileService} +* @param {string} share The destination share name. +* @param {string} directory The destination directory name. +* @param {string} file The destination file name. +* @param {string} copyId The copy operation identifier. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +*/ +FileService.prototype.abortCopyFile = function (share, directory, file, copyId, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('abortCopyFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var resourceName = createResourceName(share, directory, file); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COPY_ID, copyId) + .withQueryOption(QueryStringConstants.COMP, 'copy') + .withHeader(HeaderConstants.COPY_ACTION, 'abort'); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +// Internal Methods + +/** +* Updates a file from text. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {string} text The text string. +* @param {Stream} readStream The read stream. +* @param {int} rangeStart The range start. +* @param {int} rangeEnd The range end. +* @param {object} [options] The request options. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {bool} [options.transactionalContentMD5] An MD5 hash of the content. This hash is used to verify the integrity of the data during transport. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, file, response)} callback `error` will contain information +* if an error occurs; otherwise `file` will contain +* the file information. +* `response` will contain information related to this operation. +*/ +FileService.prototype._createRanges = function (share, directory, file, text, readStream, rangeStart, rangeEnd, options, callback) { +var request = this._updateFilesImpl(share, directory, file, rangeStart, rangeEnd, FileConstants.RangeWriteOptions.UPDATE, options); + + // At this point, we have already validated that the range is less than 4MB. Therefore, we just need to calculate the contentMD5 if required. + if(!azureutil.objectIsNull(text) && azureutil.objectIsNull(options.transactionalContentMD5) && options.useTransactionalMD5 === true) { + request.withHeader(HeaderConstants.CONTENT_MD5, azureutil.getContentMd5(text)); + } + + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = null; + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + if(!azureutil.objectIsNull(text)) { + this.performRequest(request, text, options, processResponseCallback); + } else { + this.performRequestOutputStream(request, readStream, options, processResponseCallback); + } +}; + +/** +* Uploads a file from a stream. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param (Stream) stream Stream to the data to store. +* @param {int} streamLength The length of the stream to upload. +* @param {object|function} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The MD5 hash of the file content. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {function(error, null)} callback The callback function. +* @return {SpeedSummary} +*/ +FileService.prototype._createFileFromChunkStream = function(share, directory, file, chunkStream, streamLength, options, callback) { + this.logger.debug(util.format('_createFileFromChunkStream for file %s', file)); + + var apiName = '_createRanges'; + var sizeLimitation = FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES; + var originalContentMD5 = azureutil.tryGetValueChain(options, ['contentSettings', 'contentMD5'], null); + + this._setOperationExpiryTime(options); + + // initialize the speed summary + var speedSummary = options.speedSummary || new SpeedSummary(); + speedSummary.totalSize = streamLength; + + var parallelOperationThreadCount = options.parallelOperationThreadCount || this.parallelOperationThreadCount; + + // initialize chunk allocator + var allocator = new ChunkAllocator(sizeLimitation, parallelOperationThreadCount, { logger: this.logger }); + + // if this is a FileReadStream, set the allocator on that stream + if (chunkStream._stream && chunkStream._stream.setMemoryAllocator) { + chunkStream._stream.setMemoryAllocator(allocator); + } + + // initialize batch operations + var batchOperations = new BatchOperation(apiName, { logger : this.logger, enableReuseSocket : this.defaultEnableReuseSocket}); + batchOperations.setConcurrency(parallelOperationThreadCount); + + // initialize options + var rangeOptions = { + timeoutIntervalInMs: options.timeoutIntervalInMs, + clientRequestTimeoutInMs: options.clientRequestTimeoutInMs, + operationExpiryTime: options.operationExpiryTime + }; + + var self = this; + chunkStream.on('data', function (data, range) { + var operation = null; + var full = false; + var autoIncrement = speedSummary.getAutoIncrementFunction(data.length); + + if(data.length > sizeLimitation) { + throw new Error(util.format(SR.EXCEEDED_SIZE_LIMITATION, sizeLimitation, data.length)); + } + + if (options.useTransactionalMD5) { + //calculate content md5 for the current uploading block data + var contentMD5 = azureutil.getContentMd5(data); + rangeOptions.transactionalContentMD5 = contentMD5; + } + + if (azureutil.isBufferAllZero(data)) { + self.logger.debug(util.format('Skip upload data from %s bytes to %s bytes to file %s', range.start, range.end, file)); + speedSummary.increment(data.length); + } else { + operation = new BatchOperation.RestOperation(self, apiName, share, directory, file, data, null, range.start, range.end, rangeOptions, function (error) { + if(!error) { + autoIncrement(); + } else { + self.logger.debug(util.format('Stop downloading data as error happens. Error: %s', util.inspect(error))); + chunkStream.stop(); + } + + allocator.releaseBuffer(data); + data = null; + }); + } + + if (operation) { + full = batchOperations.addOperation(operation); + operation = null; + + if(full) { + self.logger.debug('file stream paused'); + chunkStream.pause(); + } + } + }); + + chunkStream.on('end', function () { + self.logger.debug(util.format('File read stream ended for file %s', file)); + batchOperations.enableComplete(); + }); + + batchOperations.on('drain', function () { + self.logger.debug('File stream resume'); + chunkStream.resume(); + }); + + batchOperations.on('end', function (error) { + self.logger.debug('batch operations commited'); + + if (error) { + callback(error); + return; + } + + if (originalContentMD5) { + options.contentSettings.contentMD5 = originalContentMD5; + } else if (options.storeFileContentMD5) { + azureutil.setObjectInnerPropertyValue(options, ['contentSettings', 'contentMD5'], chunkStream.getContentMd5('base64')); + } + + // upload file completely + var fileProperties = extend(false, options.contentSettings, { contentLength: options.streamLength }); + self.setFileProperties(share, directory, file, fileProperties, function (error, file, response) { + chunkStream.finish(); + callback(error, file, response); + }); + }); + + return speedSummary; +}; + +/** +* Downloads a file into a stream. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {Stream} writeStream The write stream. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the file information. +* `response` will contain information related to this operation. +* +* @return {SpeedSummary} +*/ +FileService.prototype._getFileToStream = function (share, directory, file, writeStream, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_getFileToStream', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.object(writeStream, 'writeStream'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.get(resourceName) + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId) + .withRawResponse(); + + FileResult.setHeaders(webResource, options); + this._setRangeContentMD5Header(webResource, options); + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = null; + + if (!responseObject.error) { + responseObject.fileResult = new FileResult(share, directory, file); + responseObject.fileResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers, true); + + self._validateLengthAndMD5(options, responseObject); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequestInputStream(webResource, null, writeStream, options, processResponseCallback); +}; + +/** +* Downloads a file into a range stream. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {Stream} writeStream The write stream. +* @param {object} [options] The request options. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the file information. +* `response` will contain information related to this operation. +* +* @return {SpeedSummary} +*/ +FileService.prototype._getFileToRangeStream = function (share, directory, file, writeStream, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_getFileToRangeStream', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.object(writeStream, 'writeStream'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var speedSummary = userOptions.speedSummary || new SpeedSummary(file); + var parallelOperationThreadCount = userOptions.parallelOperationThreadCount || this.parallelOperationThreadCount; + var batchOperations = new BatchOperation('getfile', { callbackInOrder: true, logger : this.logger, enableReuseSocket : this.defaultEnableReuseSocket }); + batchOperations.setConcurrency(parallelOperationThreadCount); + + var rangeStream = new FileRangeStream(this, share, directory, file, userOptions); + + var self = this; + var checkMD5sum = !userOptions.disableContentMD5Validation; + var md5Hash = null; + if (checkMD5sum) { + md5Hash = new Md5Wrapper().createMd5Hash(); + } + + var savedFileResult = null; + var savedFileResponse = null; + + rangeStream.on('range', function (range) { + if (!speedSummary.totalSize) { + speedSummary.totalSize = rangeStream.rangeSize; + } + + var requestOptions = { + rangeStart : range.start, + rangeEnd : range.end, + responseEncoding : null //Use Buffer to store the response data + }; + + var rangeSize = range.size; + requestOptions.shareSnapshotId = userOptions.shareSnapshotId; + requestOptions.timeoutIntervalInMs = userOptions.timeoutIntervalInMs; + requestOptions.clientRequestTimeoutInMs = userOptions.clientRequestTimeoutInMs; + requestOptions.useTransactionalMD5 = userOptions.useTransactionalMD5; + + if (range.dataSize === 0) { + var autoIncrement = speedSummary.getAutoIncrementFunction(rangeSize); + //No operation to do and only wait for write zero to file in callback + var writeZeroOperation = new BatchOperation.CommonOperation(BatchOperation.noOperation, function (error) { + if (error) return; + var bufferAvailable = azureutil.writeZerosToStream(writeStream, rangeSize, md5Hash, autoIncrement); + //There is no need to pause the rangestream since we can perform http request and write disk at the same time + self.logger.debug(util.format('Write %s bytes Zero from %s to %s', rangeSize, range.start, range.end)); + if (!bufferAvailable) { + self.logger.debug('Write stream is full and pause batch operation'); + batchOperations.pause(); + } + }); + batchOperations.addOperation(writeZeroOperation); + return; + } + + if (range.start > range.end) { + return; + } + + var operation = new BatchOperation.RestOperation(self, 'getFileToText', share, directory, file, requestOptions, function (error, content, fileResult, response) { + if (!error) { + if (rangeSize !== content.length) { + self.logger.warn(util.format('Request %s bytes, but server returns %s bytes', rangeSize, content.length)); + } + //Save one of the succeeded callback parameters and use them at the final callback + if (!savedFileResult) { + savedFileResult = fileResult; + } + if (!savedFileResponse) { + savedFileResponse = response; + } + var autoIncrement = speedSummary.getAutoIncrementFunction(content.length); + var bufferAvailable = writeStream.write(content, autoIncrement); + if (!bufferAvailable) { + self.logger.debug('Write stream is full and pause batch operation'); + batchOperations.pause(); + } + if (md5Hash) { + md5Hash.update(content); + } + content = null; + } else { + self.logger.debug(util.format('Stop downloading data as error happens. Error: %s', util.inspect(error))); + rangeStream.stop(); + } + }); + + var full = batchOperations.addOperation(operation); + if (full) { + self.logger.debug('Pause range stream'); + rangeStream.pause(); + } + }); + + rangeStream.on('end', function () { + self.logger.debug('Range stream has ended.'); + batchOperations.enableComplete(); + }); + + batchOperations.on('drain', function () { + self.logger.debug('Resume range stream'); + rangeStream.resume(); + }); + + writeStream.on('drain', function () { + self.logger.debug('Resume batch operations'); + batchOperations.resume(); + }); + + batchOperations.on('end', function (error) { + self.logger.debug('Download completed!'); + if (error) { + callback(error); + } else { + writeStream.end(function () { + self.logger.debug('Write stream has ended'); + if (!savedFileResult) { + savedFileResult = {}; + } + azureutil.setObjectInnerPropertyValue(savedFileResult, ['contentSettings', 'contentMD5'], azureutil.tryGetValueChain(userOptions, ['contentSettings', 'contentMD5'], null)); + savedFileResult.clientSideContentMD5 = null; + if (md5Hash) { + savedFileResult.clientSideContentMD5 = md5Hash.digest('base64'); + } + callback(error, savedFileResult, savedFileResponse); + }); + } + }); + + var listOptions = { + timeoutIntervalInMs : userOptions.timeoutIntervalInMs, + clientRequestTimeoutInMs : userOptions.clientRequestTimeoutInMs, + }; + + rangeStream.list(listOptions); + return speedSummary; +}; + +/** +* @ignore +*/ +FileService.prototype._setRangeContentMD5Header = function (webResource, options) { + if(!azureutil.objectIsNull(options.rangeStart) && options.useTransactionalMD5) { + if(azureutil.objectIsNull(options.rangeEnd)) { + throw new ArgumentNullError(util.format(SR.ARGUMENT_NULL_OR_EMPTY, options.rangeEndHeader)); + } + + var size = parseInt(options.rangeEnd, 10) - parseInt(options.rangeStart, 10) + 1; + if (size > FileConstants.MAX_RANGE_GET_SIZE_WITH_MD5) { + throw new Error(SR.INVALID_RANGE_FOR_MD5); + } else { + webResource.withHeader(HeaderConstants.RANGE_GET_CONTENT_MD5, 'true'); + } + } +}; + +/** +* @ignore +*/ +FileService.prototype._updateFilesImpl = function (share, directory, file, rangeStart, rangeEnd, writeMethod, options) { + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.put(resourceName) + .withQueryOption(QueryStringConstants.COMP, 'range') + .withHeader(HeaderConstants.CONTENT_TYPE, 'application/octet-stream') + .withHeader(HeaderConstants.FILE_WRITE, writeMethod); + + options.rangeStart = rangeStart; + options.rangeEnd = rangeEnd; + + FileResult.setHeaders(webResource, options); + + if(writeMethod === FileConstants.RangeWriteOptions.UPDATE) { + var size = (rangeEnd - rangeStart) + 1; + webResource.withHeader(HeaderConstants.CONTENT_LENGTH, size); + } else { + webResource.withHeader(HeaderConstants.CONTENT_LENGTH, 0); + } + + return webResource; +}; + +/** +* @ignore +*/ +FileService.prototype._validateLengthAndMD5 = function (options, responseObject) { + var storedMD5 = responseObject.response.headers[Constants.HeaderConstants.CONTENT_MD5]; + var contentLength; + + if (!azureutil.objectIsNull(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH])) { + contentLength = parseInt(responseObject.response.headers[Constants.HeaderConstants.CONTENT_LENGTH], 10); + } + + // If the user has not specified this option, the default value should be false. + if(azureutil.objectIsNull(options.disableContentMD5Validation)) { + options.disableContentMD5Validation = false; + } + + // None of the below cases should be retried. So set the error in every case so the retry policy filter handle knows that it shouldn't be retried. + if (options.disableContentMD5Validation === false && options.useTransactionalMD5 === true && azureutil.objectIsNull(storedMD5)) { + responseObject.error = new Error(SR.MD5_NOT_PRESENT_ERROR); + responseObject.retryable = false; + } + + // Validate length and if required, MD5. + // If getFileToText called this method, then the responseObject.length and responseObject.contentMD5 are not set. Calculate them first using responseObject.response.body and then validate. + if(azureutil.objectIsNull(responseObject.length)) { + if (typeof responseObject.response.body == 'string') { + responseObject.length = Buffer.byteLength(responseObject.response.body); + } else if (Buffer.isBuffer(responseObject.response.body)) { + responseObject.length = responseObject.response.body.length; + } + } + + if(!azureutil.objectIsNull(contentLength) && responseObject.length !== contentLength) { + responseObject.error = new Error(SR.CONTENT_LENGTH_MISMATCH); + responseObject.retryable = false; + } + + if(options.disableContentMD5Validation === false && azureutil.objectIsNull(responseObject.contentMD5)) { + responseObject.contentMD5 = azureutil.getContentMd5(responseObject.response.body); + } + + if (options.disableContentMD5Validation === false && !azureutil.objectIsNull(storedMD5) && storedMD5 !== responseObject.contentMD5) { + responseObject.error = new Error(util.format(SR.HASH_MISMATCH, storedMD5, responseObject.contentMD5)); + responseObject.retryable = false; + } +}; + +/** +* Checks whether or not a file exists on the service. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the file information including the `exists` boolean member. +* `response` will contain information related to this operation. +*/ +FileService.prototype._doesFileExist = function (share, directory, file, primaryOnly, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('FileExists', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var resourceName = createResourceName(share, directory, file); + var webResource = WebResource.head(resourceName) + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + /*if(primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + }*/ + + var processResponseCallback = function (responseObject, next) { + responseObject.fileResult = new FileResult(share, directory, file); + if (!responseObject.error) { + responseObject.fileResult.exists = true; + responseObject.fileResult.getPropertiesFromHeaders(responseObject.response.headers); + + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.fileResult.exists = false; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.fileResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks whether or not a directory exists on the service. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The share snapshot identifier. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the directory information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +FileService.prototype._doesDirectoryExist = function (share, directory, primaryOnly, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('directoryExists', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(createResourceName(share, directory)) + .withQueryOption(QueryStringConstants.RESTYPE, 'directory') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + /*if(primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + }*/ + + var self = this; + var processResponseCallback = function(responseObject, next){ + responseObject.directoryResult = new DirectoryResult(directory); + responseObject.directoryResult.exists = false; + + if (!responseObject.error) { + responseObject.directoryResult.exists = true; + responseObject.directoryResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.directoryResult.getPropertiesFromHeaders(responseObject.response.headers); + + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.directoryResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks whether or not a share exists on the service. +* @ignore +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} [options.shareSnapshotId] The share snapshot identifier. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* the share information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +FileService.prototype._doesShareExist = function (share, primaryOnly, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('shareExists', function (v) { + v.string(share, 'share'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(share) + .withQueryOption(QueryStringConstants.RESTYPE, 'share') + .withQueryOption(QueryStringConstants.SHARE_SNAPSHOT, options.shareSnapshotId); + + /*if(primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + }*/ + + var processResponseCallback = function(responseObject, next){ + responseObject.shareResult = new ShareResult(share); + responseObject.shareResult.exists = false; + + if (!responseObject.error) { + responseObject.shareResult.exists = true; + responseObject.shareResult.getPropertiesFromHeaders(responseObject.response.headers); + + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.shareResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* The callback for {FileService~getFileToText}. +* @typedef {function} FileService~FileToText +* @param {object} error If an error occurs, the error information. +* @param {string} text The text returned from the file. +* @param {object} file Information about the file. +* @param {object} response Information related to this operation. +*/ + +FileService.SpeedSummary = SpeedSummary; + +module.exports = FileService; diff --git a/node_modules/azure-storage/lib/services/file/fileservice.node.js b/node_modules/azure-storage/lib/services/file/fileservice.node.js new file mode 100644 index 000000000..32bee8d83 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/fileservice.node.js @@ -0,0 +1,182 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../common/common.node'); +var extend = require('extend'); +var fs = require('fs'); +var FileService = require('./fileservice.core'); + +var azureutil = azureCommon.util; +var FileReadStream = azureCommon.FileReadStream; +var SpeedSummary = azureCommon.SpeedSummary; +var validate = azureCommon.validate; + +/** +* Downloads an Azure file into a file. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param {string} localFileName The local path to the file to be downloaded. +* @param {object} [options] The request options. +* @param {string} [options.shareSnapshotId] The snapshot identifier of the share. +* @param {boolean} [options.skipSizeCheck] Skip the size check to perform direct download. +* Set the option to true for small files. +* Parallel download and speed summary won't work with this option on. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects. +* @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. +* @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. +* @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. +* @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. +* @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +* +* @example +* var azure = require('azure-storage'); +* var FileService = azure.createFileService(); +* FileService.getFileToLocalFile('taskshare', taskdirectory', 'task1', 'task1-download.txt', function(error, serverFile) { +* if(!error) { +* // file available in serverFile.file variable +* } +*/ +FileService.prototype.getFileToLocalFile = function (share, directory, file, localFileName, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + userOptions.speedSummary = userOptions.speedSummary || new SpeedSummary(file); + + validate.validateArgs('getFileToLocalFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.string(localFileName, 'localFileName'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var writeStream = fs.createWriteStream(localFileName); + writeStream.on('error', function (error) { + callback(error); + }); + + this.getFileToStream(share, directory, file, writeStream, options, function (error, responseFile, response) { + if (error) { + writeStream.end(function () { + // If the download failed from the beginning, remove the file. + if (fs.existsSync(localFileName) && writeStream.bytesWritten === 0) { + fs.unlinkSync(localFileName); + } + callback(error, responseFile, response); + }); + } else { + callback(error, responseFile, response); + } + }); + + return options.speedSummary; +}; + + +/** +* Uploads a file to storage from a local file. If the file already exists on the service, it will be overwritten. +* (Not available in the JavaScript Client Library for Browsers) +* +* @this {FileService} +* @param {string} share The share name. +* @param {string} directory The directory name. Use '' to refer to the base directory. +* @param {string} file The file name. File names may not start or end with the delimiter '/'. +* @param (string) localFileName The local path to the file to be uploaded. +* @param {object} [options] The request options. +* @param {SpeedSummary} [options.speedSummary] The download tracker objects; +* @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. +* The default value is false for files. +* @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. +* @param {object} [options.contentSettings] The file's content settings. +* @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. +* @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. +* @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. +* @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. +* @param {string} [options.contentSettings.contentDisposition] The file's content disposition. +* @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link FileResult}` will contain the file information. +* `response` will contain information related to this operation. +* @return {SpeedSummary} +*/ +FileService.prototype.createFileFromLocalFile = function (share, directory, file, localFileName, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createFileFromLocalFile', function (v) { + v.string(share, 'share'); + v.stringAllowEmpty(directory, 'directory'); + v.string(file, 'file'); + v.string(localFileName, 'localFileName'); + v.shareNameIsValid(share); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.speedSummary = options.speedSummary || new SpeedSummary(file); + + var self = this; + fs.stat(localFileName, function(error, stat) { + if (error) { + callback(error); + } else { + self.createFile(share, directory, file, stat.size, options, function(error) { + if(error) { + callback(error); + } else { + var stream = new FileReadStream(localFileName, {calcContentMd5: options.storeFileContentMD5}); + self._createFileFromChunkStream(share, directory, file, stream, stat.size, options, callback); + } + }); + } + }); + + return options.speedSummary; +}; + +module.exports = FileService; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/file/fileutilities.js b/node_modules/azure-storage/lib/services/file/fileutilities.js new file mode 100644 index 000000000..c227b893e --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/fileutilities.js @@ -0,0 +1,72 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'FileUtilities'. +exports = module.exports; + +/** +* Defines constants, enums, and utility functions for use with the File service. +* @namespace FileUtilities +*/ +var FileUtilities = { + /** + * Permission types + * + * @const + * @enum {string} + */ + SharedAccessPermissions: { + READ: 'r', + CREATE: 'c', + WRITE: 'w', + DELETE: 'd', + LIST: 'l' + }, + + /** + * Listing details. + * + * @const + * @enum {string} + */ + ListingDetails: { + METADATA: 'metadata' + }, + + /** + * File and share public access types. + * + * @const + * @enum {string} + */ + SharePublicAccessType: { + OFF: null, + SHARE: 'share', + FILE: 'file' + }, + + /** + * Deletion options for share snapshots + * + * @const + * @enum {string} + */ + ShareSnapshotDeleteOptions: { + SHARE_AND_SNAPSHOTS: 'include' + }, +}; + +module.exports = FileUtilities; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/file/internal/filerangestream.js b/node_modules/azure-storage/lib/services/file/internal/filerangestream.js new file mode 100644 index 000000000..e7e9327d8 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/internal/filerangestream.js @@ -0,0 +1,46 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var util = require('util'); +var RangeStream = require('./../../../common/streams/rangestream'); +var Constants = require('./../../../common/util/constants'); + +/** +* File range stream +*/ +function FileRangeStream(fileServiceClient, share, directory, file, options) { + FileRangeStream['super_'].call(this, fileServiceClient, null, null, options); + + this._lengthHeader = Constants.HeaderConstants.FILE_CONTENT_LENGTH; + if (options.minRangeSize) { + this._minRangeSize = options.minRangeSize; + } else { + this._minRangeSize = Constants.FileConstants.MIN_WRITE_FILE_SIZE_IN_BYTES; + } + if (options.maxRangeSize) { + this._maxRangeSize = options.maxRangeSize; + } else { + this._maxRangeSize = Constants.FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES; + } + this._listFunc = fileServiceClient.listRanges; + this._resourcePath.push(share); + this._resourcePath.push(directory); + this._resourcePath.push(file); +} + +util.inherits(FileRangeStream, RangeStream); + +module.exports = FileRangeStream; diff --git a/node_modules/azure-storage/lib/services/file/models/directoryresult.js b/node_modules/azure-storage/lib/services/file/models/directoryresult.js new file mode 100644 index 000000000..f39d32e86 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/models/directoryresult.js @@ -0,0 +1,58 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var HeaderConstants = require('./../../../common/common.core').Constants.HeaderConstants; + +/** +* Creates a new DirectoryResult object. +* @class +* The DirectoryResult class is used to store the directory information. +* + * @property {string} name The container name. + * @property {object} metadata The metadata key/value pair. + * @property {string} etag The etag. + * @property {string} lastModified The date/time that the directory was last modified. + * @property {string} requestId The request id. + * @property {string} serverEncrypted If the directory metadata is completely encrypted using the specified algorithm. true/false. + * +* @constructor +* @param {string} [name] The directory name. +*/ +function DirectoryResult(name) { + this.name = name; +} + +DirectoryResult.parse = function (dirXml) { + return new DirectoryResult(dirXml.Name); +}; + +DirectoryResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + var setDirectoryPropertyFromHeaders = function (directoryProperty, headerProperty) { + if (!self[directoryProperty] && headers[headerProperty.toLowerCase()]) { + self[directoryProperty] = headers[headerProperty.toLowerCase()]; + } + }; + + setDirectoryPropertyFromHeaders('etag', HeaderConstants.ETAG); + setDirectoryPropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED); + setDirectoryPropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID); + setDirectoryPropertyFromHeaders('serverEncrypted', HeaderConstants.SERVER_ENCRYPTED); +}; + +module.exports = DirectoryResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/file/models/fileresult.js b/node_modules/azure-storage/lib/services/file/models/fileresult.js new file mode 100644 index 000000000..818cdbf37 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/models/fileresult.js @@ -0,0 +1,207 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); + +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var Constants = azureCommon.Constants; +var HeaderConstants = Constants.HeaderConstants; + +/** +* Creates a new FileResult object. +* @class +* The FileResult class is used to store the file information. +* + * @property {string} share The share name. + * @property {string} directory The directory name. + * @property {string} name The file name. + * @property {object} metadata The metadata key/value pair. + * @property {string} etag The etag. + * @property {string} lastModified The date/time that the file was last modified. + * @property {string} requestId The request id. + * @property {string} acceptRanges The accept ranges. + * @property {string} serverEncrypted If the file data and application metadata are completely encrypted using the specified algorithm. true/false. + * @property {string} contentRange The content range + * @property {string} contentLength The size of the file in bytes. + * @property {object} contentSettings The content settings. + * @property {string} contentSettings.contentType The content type. + * @property {string} contentSettings.contentEncoding The content encoding. + * @property {string} contentSettings.contentLanguage The content language. + * @property {string} contentSettings.cacheControl The cache control. + * @property {string} contentSettings.contentDisposition The content disposition. + * @property {string} contentSettings.contentMD5 The content MD5 hash. + * @property {object} copy The copy information. + * @property {string} copy.id The copy id. + * @property {string} copy.status The copy status. + * @property {string} copy.completionTime The copy completion time. + * @property {string} copy.statusDescription The copy status description. + * @property {string} copy.progress The copy progress. + * @property {string} copy.source The copy source. + * +* @constructor +* @param {string} [share] The share name. +* @param {string} [directory] The directory name. +* @param {string} [name] The file name. +*/ +function FileResult(share, directory, name) { + this.share = share; + this.directory = directory; + this.name = name; +} + +FileResult.parse = function (entryXml) { + var listResult = new FileResult(); + for (var propertyName in entryXml) { + if (propertyName === 'Properties') { + // Lift out the properties onto the main object to keep consistent across all APIs like: getFileProperties + azureutil.setPropertyValueFromXML(listResult, entryXml[propertyName], true); + } else { + listResult[propertyName.toLowerCase()] = entryXml[propertyName]; + } + } + + return listResult; +}; + +var responseHeaders = { + 'acceptRanges': 'ACCEPT_RANGES', + 'contentLength': 'CONTENT_LENGTH', + 'contentRange': 'CONTENT_RANGE', + + 'contentSettings.contentType': 'CONTENT_TYPE', + 'contentSettings.contentEncoding': 'CONTENT_ENCODING', + 'contentSettings.contentLanguage': 'CONTENT_LANGUAGE', + 'contentSettings.cacheControl': 'CACHE_CONTROL', + 'contentSettings.contentDisposition': 'CONTENT_DISPOSITION', + 'contentSettings.contentMD5': 'CONTENT_MD5', + 'contentSettings.fileContentMD5': 'FILE_CONTENT_MD5', + + 'copy.id': 'COPY_ID', + 'copy.status': 'COPY_STATUS', + 'copy.source': 'COPY_SOURCE', + 'copy.progress': 'COPY_PROGRESS', + 'copy.completionTime': 'COPY_COMPLETION_TIME', + 'copy.statusDescription': 'COPY_STATUS_DESCRIPTION' +}; + +FileResult.prototype.getPropertiesFromHeaders = function (headers, content) { + var self = this; + + var setFilePropertyFromHeaders = function (fileProperty, headerProperty) { + if (!azureutil.tryGetValueChain(self, fileProperty.split('.'), null) && headers[headerProperty.toLowerCase()]) { + azureutil.setObjectInnerPropertyValue(self, fileProperty.split('.'), headers[headerProperty.toLowerCase()]); + + if (fileProperty === 'copy.progress') { + var info = azureutil.parseCopyProgress(self.copy.progress); + self.copy.bytesCopied = parseInt(info.bytesCopied); + self.copy.totalBytes = parseInt(info.totalBytes); + } + } + }; + + // For range get, 'x-ms-content-md5' indicate the overall MD5 of the file. Try to set the contentMD5 using this header if it presents + setFilePropertyFromHeaders('contentSettings.contentMD5', HeaderConstants.FILE_CONTENT_MD5); + + setFilePropertyFromHeaders('etag', HeaderConstants.ETAG); + setFilePropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED); + setFilePropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID); + setFilePropertyFromHeaders('serverEncrypted', HeaderConstants.SERVER_ENCRYPTED); + + if (content) { + _.chain(responseHeaders).pairs().each(function (pair) { + var property = pair[0]; + var header = HeaderConstants[pair[1]]; + setFilePropertyFromHeaders(property, header); + }); + + } +}; + +/** +* This method sets the HTTP headers and is used by all methods except setFileProperties and createFile. +* Those methods will set the x-ms-* headers using setProperties. +*/ +FileResult.setHeaders = function (webResource, options) { + var setHeaderProperty = function (headerProperty, fileProperty) { + var propertyValue = azureutil.tryGetValueChain(options, fileProperty.split('.'), null); + if (propertyValue) { + webResource.withHeader(headerProperty, propertyValue); + } + }; + + if (options) { + // Content-MD5 + setHeaderProperty(HeaderConstants.CONTENT_MD5, 'transactionalContentMD5'); + + // Content-Length + setHeaderProperty(HeaderConstants.CONTENT_LENGTH, 'contentLength'); + + // Range + if (!azureutil.objectIsNull(options.rangeStart)) { + var range = 'bytes=' + options.rangeStart + '-'; + + if (!azureutil.objectIsNull(options.rangeEnd)) { + range += options.rangeEnd; + } + + webResource.withHeader(HeaderConstants.STORAGE_RANGE, range); + } + } +}; + +/** +* This method sets the x-ms-* headers and is used by setFileProperties and createFile. +* All other methods will set the regular HTTP headers using setHeaders. +*/ +FileResult.setProperties = function (webResource, options) { + var setHeaderProperty = function (headerProperty, fileProperty) { + var propertyValue = azureutil.tryGetValueChain(options, fileProperty.split('.'), null); + if (propertyValue) { + webResource.withHeader(headerProperty, propertyValue); + } + }; + + if (options) { + // Content-Length + setHeaderProperty(HeaderConstants.FILE_CONTENT_LENGTH, 'contentLength'); + + // Content-Type + setHeaderProperty(HeaderConstants.FILE_CONTENT_TYPE, 'contentSettings.contentType'); + + // Content-Encoding + setHeaderProperty(HeaderConstants.FILE_CONTENT_ENCODING, 'contentSettings.contentEncoding'); + + // Content-Language + setHeaderProperty(HeaderConstants.FILE_CONTENT_LANGUAGE, 'contentSettings.contentLanguage'); + + // Content-Disposition + setHeaderProperty(HeaderConstants.FILE_CONTENT_DISPOSITION, 'contentSettings.contentDisposition'); + + // Cache-Control + setHeaderProperty(HeaderConstants.FILE_CACHE_CONTROL, 'contentSettings.cacheControl'); + + // Content-MD5 + setHeaderProperty(HeaderConstants.FILE_CONTENT_MD5, 'contentSettings.contentMD5'); + + if (options.metadata) { + webResource.addOptionalMetadataHeaders(options.metadata); + } + } +}; + +module.exports = FileResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/file/models/shareresult.js b/node_modules/azure-storage/lib/services/file/models/shareresult.js new file mode 100644 index 000000000..398ad8187 --- /dev/null +++ b/node_modules/azure-storage/lib/services/file/models/shareresult.js @@ -0,0 +1,84 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var Constants = azureCommon.Constants; +var HeaderConstants = Constants.HeaderConstants; + +/** +* Creates a new ShareResult object. +* @class +* The ShareResult class is used to store the share information. +* + * @property {string} name The share name. + * @property {object} metadata The metadata key/value pair. + * @property {string} etag The etag. + * @property {string} lastModified The date/time that the share was last modified. + * @property {string} requestId The request id. + * @property {string} quota The share quota. + * +* @constructor +* @param {string} [name] The share name. +*/ +function ShareResult(name) { + this.name = name; +} + +ShareResult.parse = function (shareXml, name) { + var shareResult = new ShareResult(name); + for (var propertyName in shareXml) { + if (shareXml.hasOwnProperty(propertyName)) { + if (propertyName === 'Properties') { + // Lift out the properties onto the main object to keep consistent across all APIs like: getShareProperties + azureutil.setPropertyValueFromXML(shareResult, shareXml[propertyName], true); + } else if (propertyName === 'Metadata' || propertyName === 'ShareStats') { + var resultPropertyName = azureutil.normalizePropertyNameFromXML(propertyName); + shareResult[resultPropertyName] = {}; + azureutil.setPropertyValueFromXML(shareResult[resultPropertyName], shareXml[propertyName], propertyName === 'ShareStats'); + } else { + shareResult[propertyName.toLowerCase()] = shareXml[propertyName]; + } + } + } + + return shareResult; +}; + +ShareResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + var setSharePropertyFromHeaders = function (shareProperty, headerProperty) { + if (!self[shareProperty] && headers[headerProperty.toLowerCase()]) { + self[shareProperty] = headers[headerProperty.toLowerCase()]; + } + }; + + setSharePropertyFromHeaders('etag', HeaderConstants.ETAG); + setSharePropertyFromHeaders('lastModified', HeaderConstants.LAST_MODIFIED); + setSharePropertyFromHeaders('requestId', HeaderConstants.REQUEST_ID); + setSharePropertyFromHeaders('quota', HeaderConstants.SHARE_QUOTA); +}; + +/** +* The share ACL settings. +* @typedef {object} ShareAclResult +* @extends {ShareAclResult} +* @property {Object.} signedIdentifiers The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +*/ + +module.exports = ShareResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js b/node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js new file mode 100644 index 000000000..0586a85ce --- /dev/null +++ b/node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js @@ -0,0 +1,131 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var xmlbuilder = azureCommon.xmlbuilder; +var Constants = azureCommon.Constants; + +var HeaderConstants = Constants.HeaderConstants; + +/** +* Creates a new QueueMessageResult object. +* @class +* The QueueMessageResult class is used to store the queue message information. +* +* @property {string} queue The queue name. +* @property {string} messageId The message id. +* @property {string} popReceipt The pop receipt. +* @property {string} messageText The message text. +* @property {string} timeNextVisible The time next visible. +* @property {string} insertionTime The insertion time. +* @property {string} expirationTime The expiration time. +* @property {number} dequeueCount The dequeue count. + * +* @constructor +* @param {string} [queue] The queue name. +* @param {string} [messageId] The message id. +* @param {string} [popReceipt] The pop receipt. +*/ +function QueueMessageResult(queue, messageId, popReceipt) { + if (queue) { + this.queue = queue; + } + + if (messageId) { + this.messageId = messageId; + } + + if (popReceipt) { + this.popReceipt = popReceipt; + } +} + +/** +* Builds an XML representation for a queue message +* +* @param {string} messageJs The queue message. +* @param {QueueMessageEncoder} The message encoder. +* @return {string} The XML queue message. +*/ +QueueMessageResult.serialize = function (messageJs, encoder) { + var doc = xmlbuilder.create(); + doc = doc.begin(Constants.QueueConstants.QUEUE_MESSAGE_ELEMENT, { version: '1.0', encoding: 'utf-8' }); + + if (messageJs) { + var message; + if (encoder !== null && encoder !== undefined) { + message = encoder.encode(messageJs); + } else { + message = messageJs; + } + + doc.ele(Constants.QueueConstants.MESSAGE_TEXT_ELEMENT) + .txt(message) + .up(); + } else { + doc.ele(Constants.QueueConstants.MESSAGE_TEXT_ELEMENT).up(); + } + + return doc.doc().toString(); +}; + + +/** +* Pase the XML representation of a queue message to a QueueMessageResult object. +* +* @param {Object} messageXml The XML representation of the queue message. +* @param {QueueMessageEncoder} The message encoder. +* @return {QueueMessageResult} The QueueMessageResult object. +*/ +QueueMessageResult.parse = function (messageXml, encoder) { + var queueMessageResult = new QueueMessageResult(); + for (var property in messageXml) { + if (property === Constants.QueueConstants.MESSAGE_TEXT_ELEMENT) { + if (encoder !== null && encoder !== undefined) { + queueMessageResult.messageText = encoder.decode(messageXml[property]); + } else { + queueMessageResult.messageText = messageXml[property]; + } + } else { + var resultPropertyName = azureutil.normalizePropertyNameFromXML(property); + queueMessageResult[resultPropertyName] = messageXml[property]; + } + } + + // Convert dequeueCount to number + if (queueMessageResult.dequeueCount) { + queueMessageResult.dequeueCount = parseInt(queueMessageResult.dequeueCount); + } + + return queueMessageResult; +}; + +QueueMessageResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + var setmessagePropertyFromHeaders = function (messageProperty, headerProperty) { + if (!self[messageProperty] && headers[headerProperty.toLowerCase()]) { + self[messageProperty] = headers[headerProperty.toLowerCase()]; + } + }; + + setmessagePropertyFromHeaders('popReceipt', HeaderConstants.POP_RECEIPT); + setmessagePropertyFromHeaders('timeNextVisible', HeaderConstants.TIME_NEXT_VISIBLE); +}; + +module.exports = QueueMessageResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/queue/models/queueresult.js b/node_modules/azure-storage/lib/services/queue/models/queueresult.js new file mode 100644 index 000000000..0b91ee99b --- /dev/null +++ b/node_modules/azure-storage/lib/services/queue/models/queueresult.js @@ -0,0 +1,72 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var Constants = require('./../../../common/common.core').Constants; +var HeaderConstants = Constants.HeaderConstants; + +/** +* Creates a new QueueResult object. +* @class +* The QueueResult class is used to store the queue information. +* +* @property {string} name The queue name. +* @property {object} metadata The metadata key/value pair. +* @property {number} approximateMessageCount The approximate number of messages in the queue. This number is not lower than the actual number of messages in the queue, but could be higher. +* @property {Object.} signedIdentifiers The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. + * +* @constructor +* @param {string} [name] The queue name. +* @param {string} [metadata] The metadata key/value pair. +*/ +function QueueResult(name, metadata) { + if (name) { + this.name = name; + } + + if (metadata) { + this.metadata = metadata; + } +} + +QueueResult.parse = function (messageXml) { + var queueResult = new QueueResult(); + for (var property in messageXml) { + if (messageXml.hasOwnProperty(property)) { + queueResult[property.toLowerCase()] = messageXml[property]; + } + } + + return queueResult; +}; + +QueueResult.prototype.getPropertiesFromHeaders = function (headers) { + var self = this; + + var setPropertyFromHeaders = function (queueProperty, headerProperty, typeConverterFunc) { + if (!self[queueProperty] && headers[headerProperty.toLowerCase()]) { + if(typeConverterFunc) { + self[queueProperty] = typeConverterFunc(headers[headerProperty.toLowerCase()]); + } else{ + self[queueProperty] = headers[headerProperty.toLowerCase()]; + } + } + }; + + setPropertyFromHeaders('approximateMessageCount', HeaderConstants.APPROXIMATE_MESSAGES_COUNT, parseInt); +}; + +module.exports = QueueResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/queue/queuemessageencoder.js b/node_modules/azure-storage/lib/services/queue/queuemessageencoder.js new file mode 100644 index 000000000..c99bd2af4 --- /dev/null +++ b/node_modules/azure-storage/lib/services/queue/queuemessageencoder.js @@ -0,0 +1,182 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. + +var util = require('util'); + +/** + * The interface for classes that represent a encoder which can be used to specify how the queue service encodes and decodes queue messages. + * + * To specify how the queue service encodes and decodes queue messages, set `queueService.messageEncoder` to object of built-in encoder types + * `[TextBase64QueueMessageEncoder]{@link TextBase64QueueMessageEncoder}`, `[BinaryBase64QueueMessageEncoder]{@link BinaryBase64QueueMessageEncoder}`, `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`, + * or custom implementation of the QueueMessageEncoder. + * + * @class + */ +function QueueMessageEncoder() { +} + +/** + * Function to encode queue messages. + * + * @param {object} [input] The target to be encoded. + * @return {string} + */ +QueueMessageEncoder.prototype.encode = function(input){ + return input; +}; + +/** + * Function to decode queue messages + * + * @param {string} [textToBeDecoded] The base64 string to be decoded. + * @returns {any} + */ +QueueMessageEncoder.prototype.decode = function(textToBeDecoded){ + return textToBeDecoded; +}; + + +/** + * Create a new TextBase64QueueMessageEncoder object + * @class + * + * Encode from utf-8 string to base64 string + * Decode from base64 string to utf-8 string. + * + * @constructor + * @extends {QueueMessageEncoder} + */ +function TextBase64QueueMessageEncoder(){ +} +util.inherits(TextBase64QueueMessageEncoder, QueueMessageEncoder); + +/** + * Encode from utf-8 string to base64 string + * @this TextBase64QueueMessageEncoder + * + * @param {string} [input] The target to be encoded. + * + * @return {string} + */ +TextBase64QueueMessageEncoder.prototype.encode = function(input){ + return new Buffer(input, 'utf8').toString('base64'); +}; + +/** + * Decode from base64 string to utf-8 string. + * @this TextBase64QueueMessageEncoder + * + * @param {string} [textToBeDecoded] The base64 string to be decoded. + * + * @return {string} + */ +TextBase64QueueMessageEncoder.prototype.decode = function(textToDecode){ + return new Buffer(textToDecode, 'base64').toString('utf8'); +}; + + +/** + * Create a new BinaryBase64QueueMessageEncoder object + * @class + * + * Encode from binary buffer to base64 string + * Decode from base64 string to binary buffer. + * + * @constructor + * @extends {QueueMessageEncoder} + */ +function BinaryBase64QueueMessageEncoder(){ +} +util.inherits(BinaryBase64QueueMessageEncoder, QueueMessageEncoder); + +/** + * Encode from binary buffer string to base64 string + * @this BinaryBase64QueueMessageEncoder + * + * @param {Buffer} [input] The target to be encoded. + * + * @return {string} + */ +BinaryBase64QueueMessageEncoder.prototype.encode = function(input){ + return input.toString('base64'); +}; + + +/** + * Decode from base64 string to binary buffer. + * @this BinaryBase64QueueMessageEncoder + * + * @param {string} [textToBeDecoded] The base64 string to be decoded. + * + * @return {Buffer} + */ +BinaryBase64QueueMessageEncoder.prototype.decode = function(textToDecode){ + return new Buffer(textToDecode, 'base64'); +}; + + +/** + * Create a new TextXmlQueueMessageEncoder object + * @class + * + * Encode utf-8 string by escaping the xml markup characters. + * Decode from utf-8 string by unescaping the xml markup characters. + * + * @constructor + * @extends {QueueMessageEncoder} + */ +function TextXmlQueueMessageEncoder(){ +} +util.inherits(TextXmlQueueMessageEncoder, QueueMessageEncoder); + +/** + * Encode utf-8 string by escaping the xml markup characters. + * @this TextXmlQueueMessageEncoder + * + * @param {string} [input] The target to be encoded. + * + * @return {string} + */ +TextXmlQueueMessageEncoder.prototype.encode = function(input){ + return input.replace(/&/gm, '&') + .replace(//gm, '>') + .replace(/"/gm, '"') + .replace(/'/gm, '''); +}; + +/** + * Decode from utf-8 string by unescaping the xml markup characters. + * @this TextXmlQueueMessageEncoder + * + * @param {string} [textToBeDecoded] The base64 string to be decoded. + * + * @return {string} + */ +TextXmlQueueMessageEncoder.prototype.decode = function(textToDecode){ + return textToDecode.replace(/&/gm, '&') + .replace(/</gm, '<') + .replace(/>/gm, '>') + .replace(/"/gm, '"') + .replace(/'/gm, '\''); +}; + +module.exports = QueueMessageEncoder; +module.exports.TextBase64QueueMessageEncoder = TextBase64QueueMessageEncoder; +module.exports.BinaryBase64QueueMessageEncoder = BinaryBase64QueueMessageEncoder; +module.exports.TextXmlQueueMessageEncoder = TextXmlQueueMessageEncoder; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/queue/queueservice.js b/node_modules/azure-storage/lib/services/queue/queueservice.js new file mode 100644 index 000000000..b92ab451f --- /dev/null +++ b/node_modules/azure-storage/lib/services/queue/queueservice.js @@ -0,0 +1,1468 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var util = require('util'); +var _ = require('underscore'); +var extend = require('extend'); + +var azureCommon = require('./../../common/common.core'); +var azureutil = azureCommon.util; +var SR = azureCommon.SR; +var validate = azureCommon.validate; + +var StorageServiceClient = azureCommon.StorageServiceClient; +var WebResource = azureCommon.WebResource; +var Constants = azureCommon.Constants; +var QueryStringConstants = Constants.QueryStringConstants; +var HeaderConstants = Constants.HeaderConstants; +var RequestLocationMode = Constants.RequestLocationMode; + +// Models requires +var QueueResult = require('./models/queueresult'); +var AclResult = azureCommon.AclResult; +var QueueMessageResult = require('./models/queuemessageresult'); +var QueueMessageEncoder = require('./queuemessageencoder'); +var ServiceStatsParser = azureCommon.ServiceStatsParser; + +/** +* Creates a new QueueService object. +* If no connection string or storageaccount and storageaccesskey are provided, +* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. +* @class +* The QueueService class is used to perform operations on the Microsoft Azure Queue Service. +* +* For more information on using the Queue Service, as well as task focused information on using it from a Node.js application, see +* [How to Use the Queue Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-queues/). +* The following defaults can be set on the Queue service. +* messageEncoder The message encoder to specify how QueueService encodes and decodes the queue message. Default is `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`. +* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Queue service. +* defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Queue service. +* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Queue service. +* defaultLocationMode The default location mode for requests made via the Queue service. +* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Queue service; true to use the +* Nagle algorithm; otherwise, false. The default value is false. +* @constructor +* @augments {StorageServiceClient} +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {string} [endpointSuffix] The endpoint suffix. +*/ +function QueueService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) { + var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix); + + QueueService['super_'].call(this, + storageServiceSettings._name, + storageServiceSettings._key, + storageServiceSettings._queueEndpoint, + storageServiceSettings._usePathStyleUri, + storageServiceSettings._sasToken); + + if (this.anonymous) { + throw new Error(SR.ANONYMOUS_ACCESS_BLOBSERVICE_ONLY); + } + + /** + * @property {boolean} QueueService#messageEncoder + * @defaultvalue {QueueMessageEncoder} `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`. + * The message encoder to specify how QueueService encodes and decodes the queue message. Default is `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`. + */ + this.messageEncoder = new QueueMessageEncoder.TextXmlQueueMessageEncoder(); +} + +util.inherits(QueueService, StorageServiceClient); + +/** +* Gets the service stats for a storage account’s Queue service. +* +* @this {QueueService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise, `[result]{@link ServiceStats}` +* will contain the stats and `response` +* will contain information related to this operation. +*/ +QueueService.prototype.getServiceStats = function (optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getServiceStats', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get() + .withQueryOption(QueryStringConstants.COMP, 'stats') + .withQueryOption(QueryStringConstants.RESTYPE, 'service'); + + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.serviceStatsResult = null; + if (!responseObject.error) { + responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats); + } + + // function to be called after all filters + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response); + }; + + // call the first filter + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics. +* +* @this {QueueService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise, `[result]{@link ServiceProperties}` +* will contain the properties and `response` +* will contain information related to this operation. +*/ +QueueService.prototype.getServiceProperties = function (optionsOrCallback, callback) { + return this.getAccountServiceProperties(optionsOrCallback, callback); +}; + +/** +* Sets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics. +* You can also use this operation to set the default request version for all incoming requests that do not have a version specified. +* +* @this {QueueService} +* @param {object} serviceProperties The service properties. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise, `response` +* will contain information related to this operation. +*/ +QueueService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) { + return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of queue items whose names begin with the specified prefix under the given account. +* +* @this {QueueService} +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {int} [options.maxResults] Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {string} [options.include] Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata') +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[queues]{@link QueueResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.listQueuesSegmented = function (currentToken, optionsOrCallback, callback) { + this.listQueuesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of queue items under the given account. +* +* @this {QueueService} +* @param {string} prefix The prefix of the queue name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.* @param {string} [options.prefix] Filters the results to return only queues whose name begins with the specified prefix. +* @param {object} [options] The request options. +* @param {string} [options.marker] String value that identifies the portion of the list to be returned with the next list operation. +* @param {int} [options.maxResults] Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000) +* @param {string} [options.include] Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata') +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of `[queues]{@link QueueResult}` and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.listQueuesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listQueuesSegmentedWithPrefix', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(); + webResource.withQueryOption(QueryStringConstants.COMP, 'list') + .withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults) + .withQueryOption(QueryStringConstants.INCLUDE, options.include) + .withQueryOption(QueryStringConstants.PREFIX, prefix); + + if(!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker); + } + + options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken); + + var processResponseCallback = function (responseObject, next) { + responseObject.listQueuesResult = null; + + if (!responseObject.error) { + responseObject.listQueuesResult = { + entries: null, + continuationToken: null + }; + responseObject.listQueuesResult.entries = []; + var queues = []; + + if (responseObject.response.body.EnumerationResults.Queues && responseObject.response.body.EnumerationResults.Queues.Queue) { + queues = responseObject.response.body.EnumerationResults.Queues.Queue; + + if (!_.isArray(queues)) { + queues = [ queues ]; + } + + queues.forEach(function (currentQueue) { + var queueResult = QueueResult.parse(currentQueue); + responseObject.listQueuesResult.entries.push(queueResult); + }); + + if(responseObject.response.body.EnumerationResults.NextMarker) { + responseObject.listQueuesResult.continuationToken = { + nextMarker: null, + targetLocation: null + }; + + responseObject.listQueuesResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker; + responseObject.listQueuesResult.continuationToken.targetLocation = responseObject.targetLocation; + } + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.listQueuesResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Checks to see if a queue exists. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise, `[result]{@link QueueResult}` will contain +* the queue information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.doesQueueExist = function (queue, optionsOrCallback, callback) { + this._doesQueueExist(queue, false, optionsOrCallback, callback); +}; + +/** +* Creates a new queue under the given account. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueResult}` will contain +* the queue information. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.createQueue = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createQueue', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(queue); + if (options) { + webResource.addOptionalMetadataHeaders(options.metadata); + } + + var processResponseCallback = function (responseObject, next) { + responseObject.queueResult = null; + if (!responseObject.error) { + responseObject.queueResult = new QueueResult(queue); + if (options && options.metadata) { + responseObject.queueResult.metadata = options.metadata; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Creates a new queue under the given account if it doesn't exist. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {object} [options.metadata] The metadata key/value pairs. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueResult}` will contain +* the queue information including `created` boolean member and +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var queueService = azure.createQueueService(); +* queueService.createQueueIfNotExists('taskqueue', function(error) { +* if(!error) { +* // Queue created or exists +* } +* }); +*/ +QueueService.prototype.createQueueIfNotExists = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createQueueIfNotExists', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var self = this; + self._doesQueueExist(queue, true, options, function(error, result, response) { + var exists = result.exists; + result.created = false; + delete result.exists; + + if (error) { + callback(error, result, response); + } else if (exists) { + response.isSuccessful = true; + callback(error, result, response); + } else { + self.createQueue(queue, options, function(createError, responseQueue, createResponse) { + if (!createError) { + responseQueue.created = true; + } + else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.QueueErrorCodeStrings.QUEUE_ALREADY_EXISTS) { + createError = null; + responseQueue.created = false; + createResponse.isSuccessful = true; + } + + callback(createError, responseQueue, createResponse); + }); + } + }); +}; + +/** +* Permanently deletes the specified queue. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information if an error occurs; +* `response` will contain information related to this operation. +*/ +QueueService.prototype.deleteQueue = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteQueue', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.del(queue); + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Permanently deletes the specified queue if it exists. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* 'true' if the queue was deleted and 'false' if the queue did not exist. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.deleteQueueIfExists = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteQueueIfExists', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var self = this; + self._doesQueueExist(queue, true, options, function existsCallback(error, existsResult, response) { + if (error) { + callback(error, existsResult.exists, response); + } else if (!existsResult.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteQueue(queue, options, function(deleteError, deleteResponse) { + var deleted; + if (!deleteError) { + deleted = true; + } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.QueueErrorCodeStrings.QUEUE_NOT_FOUND) { + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +/** +* Returns queue properties, including user-defined metadata. +* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueResult}` will contain +* the queue information. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.getQueueMetadata = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getQueueMetadata', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(queue) + .withQueryOption(QueryStringConstants.COMP, 'metadata'); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var self = this; + var processResponseCallback = function (responseObject, next) { + responseObject.queueResult = null; + if (!responseObject.error) { + responseObject.queueResult = new QueueResult(queue); + responseObject.queueResult.metadata = self.parseMetadataHeaders(responseObject.response.headers); + responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} metadata The metadata key/value pairs. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueResult}` will contain +* the queue information. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.setQueueMetadata = function (queue, metadata, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setQueueMetadata', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.put(queue) + .withQueryOption(QueryStringConstants.COMP, 'metadata') + .addOptionalMetadataHeaders(metadata); + + var processResponseCallback = function (responseObject, next) { + responseObject.queueResult = null; + if (!responseObject.error) { + responseObject.queueResult = new QueueResult(queue, metadata); + responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Adds a new message to the back of the message queue. +* The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size for previous versions. +* Unencoded messages must be in a format that can be included in an XML request with UTF-8 encoding. +* Queue messages are encoded using the `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`. See queueService.messageEncoder to set encoder defaults. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {string|Buffer} messageText The message text. +* @param {object} [options] The request options. +* @param {int} [options.messageTimeToLive] The time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter is omitted, the default time-to-live is 7 days +* @param {int} [options.visibilityTimeout] Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain +* the message. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var queueService = azure.createQueueService(); +* queueService.createMessage('taskqueue', 'Hello world!', function(error) { +* if(!error) { +* // Message inserted +* } +* }); +*/ +QueueService.prototype.createMessage = function (queue, messageText, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createMessage', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var xmlMessageDescriptor = QueueMessageResult.serialize(messageText, this.messageEncoder); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.post(queue + '/messages') + .withHeader(HeaderConstants.CONTENT_TYPE, 'application/atom+xml;charset="utf-8"') + .withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(xmlMessageDescriptor, 'utf8')) + .withQueryOption(QueryStringConstants.MESSAGE_TTL, options.messageTimeToLive) + .withQueryOption(QueryStringConstants.VISIBILITY_TIMEOUT, options.visibilityTimeout) + .withBody(xmlMessageDescriptor); + + var messageEncoder = this.messageEncoder; + + var processResponseCallback = function (responseObject, next) { + responseObject.queueMessageResults = []; + + if (responseObject.response && responseObject.response.body && responseObject.response.body.QueueMessagesList && responseObject.response.body.QueueMessagesList.QueueMessage) { + var messages = responseObject.response.body.QueueMessagesList.QueueMessage; + + if (!_.isArray(messages)) { + messages = [ messages ]; + } + + messages.forEach(function (message) { + var queueMessageResult = QueueMessageResult.parse(message, messageEncoder); + responseObject.queueMessageResults.push(queueMessageResult); + }); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, responseObject.queueMessageResults[0], returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Retrieve messages from the queue and makes them invisible to other consumers. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {int} [options.numOfMessages] A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation. +* @param {int} [options.visibilityTimeout] Required if not peek only. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* a list of `[messages]{@link QueueMessageResult}`. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var queueService = azure.createQueueService(); +* var queueName = 'taskqueue'; +* queueService.getMessages(queueName, function(error, serverMessages) { +* if(!error) { +* // Process the message in less than 30 seconds, the message +* // text is available in serverMessages[0].messagetext +* queueService.deleteMessage(queueName, serverMessages[0].messageId, serverMessages[0].popReceipt, function(error) { +* if(!error){ +* // Message deleted +* } +* }); +* } +* }); +*/ +QueueService.prototype.getMessages = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getMessages', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + delete options.peekOnly; + + this._getOrPeekMessages(queue, options, callback); +}; + +/** +* Retrieves a message from the queue and makes it invisible to other consumers. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {int} [options.visibilityTimeout] Required if not peek only. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain +* the message. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var queueService = azure.createQueueService(); +* var queueName = 'taskqueue'; +* queueService.getMessage(queueName, function(error, serverMessage) { +* if(!error) { +* // Process the message in less than 30 seconds, the message +* // text is available in serverMessage.messagetext +* queueService.deleteMessage(queueName, serverMessage.messageId, serverMessage.popReceipt, function(error) { +* if(!error){ +* // Message deleted +* } +* }); +* } +* }); +*/ +QueueService.prototype.getMessage = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getMessage', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.numOfMessages = 1; + + var finalCallback = function(error, messages, response){ + var message; + if(messages && messages.length > 0){ + message = messages[0]; + } + + callback(error, message, response); + }; + + this.getMessages(queue, options, finalCallback); +}; + +/** +* Retrieves messages from the front of the queue, without changing the messages visibility. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {int} [options.numOfMessages] A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `result` will contain +* `[messages]{@link QueueMessageResult}`. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.peekMessages = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('peekMessages', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.peekOnly = true; + delete options.visibilityTimeout; + + this._getOrPeekMessages(queue, options, callback); +}; + +/** +* Retrieves a message from the front of the queue, without changing the message visibility. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain +* the message. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.peekMessage = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('peekMessage', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.numOfMessages = 1; + + var finalCallback = function(error, messages, response){ + var message; + if(messages && messages.length > 0){ + message = messages[0]; + } + + callback(error, message, response); + }; + + this.peekMessages(queue, options, finalCallback); +}; + +/** +* Deletes a specified message from the queue. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {string} messageId The message identifier of the message to delete. +* @param {string} popReceipt A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information if an error occurs; +* `response` will contain information related to this operation. +*/ +QueueService.prototype.deleteMessage = function (queue, messageId, popReceipt, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteMessage', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + if (azureutil.objectIsNull(popReceipt)) { + throw new Error(SR.INVALID_POP_RECEIPT); + } + + if (azureutil.objectIsNull(messageId)) { + throw new Error(SR.INVALID_MESSAGE_ID); + } + + var options = extend(true, {}, userOptions); + var webResource = WebResource.del(queue + '/messages/' + messageId) + .withQueryOption(QueryStringConstants.POP_RECEIPT, popReceipt, null, true); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Clears all messages from the queue. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information +* if an error occurs; otherwise +* `response` will contain information related to this operation. +*/ +QueueService.prototype.clearMessages = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('clearMessages', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.del(queue + '/messages'); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Updates the visibility timeout of a message. You can also use this operation to update the contents of a message. +* A message must be in a format that can be included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in size. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {string} messageId The message identifier of the message to update. +* @param {string} popReceipt A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation +* @param {int} visibilityTimeout Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. +* @param {object} [options] The request options. +* @param {object} [options.messageText] The new message text. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain +* the message result information. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.updateMessage = function (queue, messageId, popReceipt, visibilityTimeout, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('updateMessage', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + if (azureutil.objectIsNull(popReceipt)) { + throw new Error(SR.INVALID_POP_RECEIPT); + } + + if (azureutil.objectIsNull(messageId)) { + throw new Error(SR.INVALID_MESSAGE_ID); + } + + var options = extend(true, {}, userOptions); + var content = null; + if (options.messageText) { + content = QueueMessageResult.serialize(options.messageText, this.messageEncoder); + } + + var contentLength = content ? Buffer.byteLength(content, 'utf8') : 0; + + var webResource = WebResource.put(queue + '/messages/' + messageId) + .withHeader(HeaderConstants.CONTENT_TYPE, 'application/atom+xml;charset="utf-8"') + .withHeader(HeaderConstants.CONTENT_LENGTH, contentLength) + .withQueryOption(QueryStringConstants.POP_RECEIPT, popReceipt, null, true) + .withQueryOption(QueryStringConstants.VISIBILITY_TIMEOUT, visibilityTimeout) + .withBody(content); + + var processResponseCallback = function (responseObject, next) { + responseObject.queueMessageResult = null; + if (!responseObject.error) { + responseObject.queueMessageResult = new QueueMessageResult(queue, messageId); + responseObject.queueMessageResult.getPropertiesFromHeaders(responseObject.response.headers); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueMessageResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Gets the queue's ACL. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueResult}` will contain +* information for the queue. +* `response` will contain information related to this operation. +*/ +QueueService.prototype.getQueueAcl = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getQueueAcl', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.get(queue) + .withQueryOption(QueryStringConstants.COMP, 'acl'); + + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var processResponseCallback = function (responseObject, next) { + responseObject.queueResult = null; + if (!responseObject.error) { + responseObject.queueResult = new QueueResult(queue); + responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers); + responseObject.queueResult.signedIdentifiers = AclResult.parse(responseObject.response.body); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Updates the queue's ACL. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @property {Object.} signedIdentifiers The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information +* if an error occurs; otherwise `[result]{@link QueueResult}` will contain +* information for the queue. +* `response` will contain information related to this operation. +* @example +* var azure = require('azure-storage'); +* var SharedAccessPermissions = azure.QueueUtilities.SharedAccessPermissions; +* var queueService = azure.createQueueService(); +* var sharedAccessPolicies = [ +* {AccessPolicy: { +* Permissions: PROCESS, +* Start: startDate, +* Expiry: expiryDate +* }, +* Id: processOnly, +* }, +* {AccessPolicy: { +* Permissions: SharedAccessPermissions.PROCESS + SharedAccessPermissions.DELETE, +* Start: startDate, +* Expiry: expiryDate +* }, +* Id: processAndDelete, +* }]; +* +* queueService.setQueueAcl(queueName, sharedAccessPolicies, function(error, queueResult, response) { +* // do whatever +* }); +*/ +QueueService.prototype.setQueueAcl = function (queue, signedIdentifiers, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setQueueAcl', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var policies = null; + if (signedIdentifiers) { + if(_.isArray(signedIdentifiers)) { + throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS); + } + policies = AclResult.serialize(signedIdentifiers); + } + + var webResource = WebResource.put(queue) + .withQueryOption(QueryStringConstants.COMP, 'acl') + .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0) + .withBody(policies); + + var processResponseCallback = function (responseObject, next) { + responseObject.containerResult = null; + if (!responseObject.error) { + responseObject.queueResult = new QueueResult(queue); + responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers); + if (signedIdentifiers) { + responseObject.queueResult.signedIdentifiers = signedIdentifiers; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Retrieves a shared access signature token. +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {string} [sharedAccessPolicy.Id] The signed identifier. +* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired (The UTC value will be used). +* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} sharedAccessPolicy.AccessPolicy.Protocols The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* @return {string} The shared access signature query string. Note this string does not contain the leading "?". +*/ +QueueService.prototype.generateSharedAccessSignature = function (queue, sharedAccessPolicy) { + // check if the QueueService is able to generate a shared access signature + if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) { + throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY); + } + + validate.validateArgs('generateSharedAccessSignature', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.object(sharedAccessPolicy, 'sharedAccessPolicy'); + }); + + return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Queue, queue, sharedAccessPolicy, null); +}; + +/** +* Checks to see if a queue exists. +* @ignore +* +* @this {QueueService} +* @param {string} queue The queue name. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information +* if an error occurs; otherwise, `result` will contain +* the queue information including `exists` boolean member +* and `response` will contain information related to this operation. +* +*/ +QueueService.prototype._doesQueueExist = function (queue, primaryOnly, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('doesQueueExist', function(v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + var webResource = WebResource.head(queue) + .withQueryOption(QueryStringConstants.COMP, 'metadata'); + + if(primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + } + + var processResponseCallback = function(responseObject, next) { + responseObject.queueResult = new QueueResult(queue); + responseObject.queueResult.exists = false; + + if (!responseObject.error) { + responseObject.queueResult.exists = true; + responseObject.queueResult.getPropertiesFromHeaders(responseObject.response.headers); + + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.queueResult.exists = false; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** + * @ignore + */ +QueueService.prototype._getOrPeekMessages = function (queue, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('_getOrPeekMessages', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + if (!options.numOfMessages) { + options.numOfMessages = 1; + } + + var webResource = WebResource.get(queue + '/messages') + .withQueryOption(QueryStringConstants.NUM_OF_MESSAGES, options.numOfMessages) + .withQueryOption(QueryStringConstants.VISIBILITY_TIMEOUT, options.visibilityTimeout) + .withQueryOption(QueryStringConstants.PEEK_ONLY, options.peekOnly); + + if (options.peekOnly) { + // For peek message, it's a read-only action and can be performed against secondary endpoint. + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + } + + + var messageEncoder = this.messageEncoder; + var processResponseCallback = function (responseObject, next) { + responseObject.queueMessageResults = null; + + if (!responseObject.error) { + responseObject.queueMessageResults = []; + + if (responseObject.response.body.QueueMessagesList && responseObject.response.body.QueueMessagesList.QueueMessage) { + var messages = responseObject.response.body.QueueMessagesList.QueueMessage; + + if (!_.isArray(messages)) { + messages = [ messages ]; + } + + messages.forEach(function (message) { + var queueMessageResult = QueueMessageResult.parse(message, messageEncoder); + responseObject.queueMessageResults.push(queueMessageResult); + }); + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queueMessageResults, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Retrieves a queue URL. +* +* @param {string} queue The queue name. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint. +* @return {string} The formatted URL string. +* @example +* var azure = require('azure-storage'); +* var queueService = azure.createQueueService(); +* var sharedAccessPolicy = { +* AccessPolicy: { +* Permissions: azure.QueueUtilities.SharedAccessPermissions.READ, +* Start: startDate, +* Expiry: expiryDate +* }, +* }; +* +* var sasToken = queueService.generateSharedAccessSignature(queue, sharedAccessPolicy); +* var sasUrl = queueService.getUrl(queue, sasToken); +*/ +QueueService.prototype.getUrl = function (queue, sasToken, primary) { + validate.validateArgs('getUrl', function (v) { + v.string(queue, 'queue'); + v.queueNameIsValid(queue); + }); + + return this._getUrl(queue, sasToken, primary); +}; + +module.exports = QueueService; diff --git a/node_modules/azure-storage/lib/services/queue/queueutilities.js b/node_modules/azure-storage/lib/services/queue/queueutilities.js new file mode 100644 index 000000000..6786fd043 --- /dev/null +++ b/node_modules/azure-storage/lib/services/queue/queueutilities.js @@ -0,0 +1,39 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'QueueUtilities'. +exports = module.exports; + +/** +* Defines enums for use with the Queue service. +* @namespace QueueUtilities +*/ +var QueueUtilities = { + /** + * Permission types. + * + * @const + * @enum {string} + */ + SharedAccessPermissions: { + READ: 'r', + ADD: 'a', + UPDATE: 'u', + PROCESS: 'p' + } +}; + +module.exports = QueueUtilities; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/internal/edmhandler.js b/node_modules/azure-storage/lib/services/table/internal/edmhandler.js new file mode 100644 index 000000000..47edd4da0 --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/internal/edmhandler.js @@ -0,0 +1,197 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var _ = require('underscore'); +var util = require('util'); +var guid = require('uuid'); + +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var SR = azureCommon.SR; + +var TableUtilities = require('../tableutilities'); +var EdmType = TableUtilities.EdmType; + +/** +* Get the Edm type of an object. +* +* @param {object} value A typed instance. +* @return {string} The Edm type. +*/ +exports.propertyType = function (value, guessNumberType) { + if (_.isNumber(value)) { + if (guessNumberType) { + if (azureutil.objectIsInt(value)) { + return 'Edm.Int32'; + } else { + return 'Edm.Double'; + } + } else { + return null; + } + } else if (_.isBoolean(value)) { + return 'Edm.Boolean'; + } else if (_.isDate(value)) { + return 'Edm.DateTime'; + } else { + return 'Edm.String'; + } +}; + +/** +* Convert a JSON value from over the wire into the correct EDM type. +* +* Note that Int64, is remaining a string. Converting it to a Number would lose precision. +* Int32, Boolean, and Double should already be the correct non-string types +* +* @param {string} type The type of the value as it appears in the type attribute. +* @param value The value in JSON format. +* @return {object} The unserialized value. +*/ +exports.deserializeValueFromJson = function (type, value) { + if (type) { + switch (type) { + case EdmType.BINARY: + return new Buffer(value, 'base64'); + case EdmType.DATETIME: + return new Date(value); + case EdmType.GUID: + return value; + case EdmType.DOUBLE: + // Account for Infinity and NaN: + if (typeof value !== 'number') { + return parseFloat(value); + } + return value; + case EdmType.INT32: + case EdmType.INT64: + case EdmType.STRING: + case EdmType.BOOLEAN: + return value; + default: + throw new Error(util.format(SR.TYPE_NOT_SUPPORTED, type)); + } + } else { + return value; + } +}; + +/** +* Convert a raw EdmType value into the JSON value expected to be sent over the wire. +* +* TODO: validate correct input types? +* Expects Edm.Int64 and Edm.String to be string, Edm.Double and Edm.Int32 to be Number, +* Edm.Guid to be an array or buffer compatible with Node.uuid, Edm.Binary to be a Node Buffer, Edm.DateTime to be a Date, +* and Edm.Boolean to be a boolean. +* +* @param {string} type The type of the value as it will appear in the type attribute. +* @param {string} value The value +* @return {object} The serialized value. +*/ +exports.serializeValue = function (type, value) { + switch (type) { + case EdmType.BINARY: + if (Buffer.isBuffer(value)) { + return value.toString('base64'); + } + return value; + case EdmType.DATETIME: + if (_.isDate(value)) { + return value.toISOString(); + } + return value; + case EdmType.GUID: + if (Buffer.isBuffer(value) || _.isArray(value)) { + return guid.unparse(value); + } + return value; + case EdmType.INT64: + case EdmType.DOUBLE: + return value.toString(); + case EdmType.INT32: + if (value === Number.POSITIVE_INFINITY) { + return 'Infinity'; + } + if (value === Number.NEGATIVE_INFINITY) { + return '-Infinity'; + } + if (azureutil.objectIsNaN(value)) { + return 'NaN'; + } + return value; + case EdmType.STRING: + case EdmType.BOOLEAN: + return value; + default: + throw new Error(SR.TYPE_NOT_SUPPORTED + type); + } +}; + +/* +* Determines if a type annotation is required for the input type when sending JSON data to the service. +*/ +exports.isTypeRequired = function(type, value) { + switch (type) { + case EdmType.BINARY: + case EdmType.INT64: + case EdmType.DATETIME: + case EdmType.GUID: + case EdmType.DOUBLE: + return true; + case EdmType.INT32: + if (typeof value !== 'number' || value === Number.POSITIVE_INFINITY || value === Number.NEGATIVE_INFINITY || (azureutil.objectIsNaN(value))) { + return true; + } + return false; + case EdmType.STRING: + case EdmType.BOOLEAN: + return false; + default: + throw new Error(util.format(SR.TYPE_NOT_SUPPORTED, type)); + } +}; + +/** +* Serializes value into proper value to be used in odata query value. +* +* @param {object} value The value to be serialized. +* @return {string} The serialized value. +*/ +exports.serializeQueryValue = function (value, type) { + var edmType = type || exports.propertyType(value, true); + switch (edmType) { + case EdmType.INT32: + return value.toString(); + case EdmType.BOOLEAN: + return value ? 'true' : 'false'; + case EdmType.DOUBLE: + return value.toString(); + case EdmType.INT64: + return value.toString() + 'L'; + case EdmType.DATETIME: + if(_.isDate(value)) { + var dateTimeString = value.toISOString(); + return 'datetime\'' + dateTimeString + '\''; + } + throw new Error(util.format(SR.INVALID_EDM_TYPE, value, type)); + case EdmType.GUID: + return 'guid\'' + value.toString() + '\''; + case EdmType.BINARY: + return 'X\'' + value.toString('hex') + '\''; + default: + return '\'' + value.toString().replace(/'/g, '\'\'') + '\''; + } +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/internal/odatahandler.js b/node_modules/azure-storage/lib/services/table/internal/odatahandler.js new file mode 100644 index 000000000..344b639fb --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/internal/odatahandler.js @@ -0,0 +1,217 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var util = require('util'); + +var azureCommon = require('./../../../common/common.core'); +var azureutil = azureCommon.util; +var SR = azureCommon.SR; +var Constants = azureCommon.Constants; +var edmHandler = require('./edmhandler'); + +var prefixLength = Constants.TableConstants.ODATA_PREFIX.length; +var suffixLength = Constants.TableConstants.ODATA_TYPE_SUFFIX.length; + +exports = module.exports; + +/* Serialize an entity to an Odata (Json based) payload +* Input must be in the following format: +* { stringValue: { '$': 'Edm.String', '_': 'my string' }, myInt: { '$': 'Edm.Int32', '_': 3 } } +*/ +exports.serializeJson = function (entity) { + function normalizeEntityProperty(property) { + if(azureutil.objectIsNull(property)) { + return { _: property }; + } + + if (typeof property === 'object' && property.hasOwnProperty(Constants.TableConstants.ODATA_VALUE_MARKER)) { + return property; + } + + var result = { _: property }; + result[Constants.TableConstants.ODATA_TYPE_MARKER] = edmHandler.propertyType(property, true); + + return result; + } + + var result = {}; + for (var propName in entity) { + // ignore if .metadata or null or undefined + if (propName !== Constants.TableConstants.ODATA_METADATA_MARKER) { + var property = normalizeEntityProperty(entity[propName]); + if (!azureutil.objectIsNull(property[Constants.TableConstants.ODATA_VALUE_MARKER])) { + var value = property[Constants.TableConstants.ODATA_VALUE_MARKER]; + var type = property[Constants.TableConstants.ODATA_TYPE_MARKER]; + + if (type === undefined) { + type = edmHandler.propertyType(value, true); + } + + result[propName] = edmHandler.serializeValue(type, value); + if (edmHandler.isTypeRequired(type, value)) { + result[propName + Constants.TableConstants.ODATA_TYPE_SUFFIX] = type; + } + } + } + } + + var replacer = function(key, value) { + if (value === Number.POSITIVE_INFINITY) { + return 'Infinity'; + } + if (value === Number.NEGATIVE_INFINITY) { + return '-Infinity'; + } + if (azureutil.objectIsNaN(value)) { + return 'NaN'; + } + return value; + }; + + return JSON.stringify(result, replacer); +}; + +/* +Input: The body of the HTTP response from the server from a table list as JSON (responseObject.response.body). + +Return: +This will return an array in the following format: + +[ + tableName1, + tableName2 +] + +For example, + +[ + myTable1, + myTable2 +] + +*/ +exports.parseJsonTables = function (response) { + var result = []; + + if (response.value) { + for (var i = 0; i < response.value.length; i++) { + var entity = response.value[i].TableName; + result.push(entity); + } + } + + return result; +}; + +/* +Input: The body of the HTTP response from the server from a table query as JSON (responseObject.response.body). + +Return: +This will return an array in the following format: + +[ + {{ '$': edmHandler1, '_': value1}, { '$': edmHandler2, '_': value2}, { '$': edmHandler3, '_': value3}}, + {{ '$': edmHandler4, '_': value4}, { '$': edmHandler5, '_': value5}, { '$': edmHandler6, '_': value6}} +] + +For example, + +[ + {{ '$': Edm.Int32, '_': 42}, { '$': Edm.String, '_': 'sample string'}, { '$': Edm.Boolean, '_': false}}, + {{ '$': Edm.Int64, '_': 42}, { '$': Edm.String, '_': 'sample string 2'}, { '$': Edm.Boolean, '_': true}} +] + +*/ +exports.parseJsonEntities = function (response, autoResolveProperties, propertyResolver, entityResolver) { + if (!response.value) { + return [exports.parseJsonSingleEntity(response, autoResolveProperties, propertyResolver, entityResolver)]; + } else { + var result = []; + + for (var i = 0; i < response.value.length; i++) { + var rawEntity = response.value[i]; + var entity = exports.parseJsonSingleEntity(rawEntity, autoResolveProperties, propertyResolver, entityResolver); + result.push(entity); + } + + return result; + } +}; + +exports.parseJsonSingleEntity = function(rawEntity, autoResolveProperties, propertyResolver, entityResolver) { + var rawEntityProperties = {}; + var entityPropertyTypes = {PartitionKey: 'Edm.String', RowKey: 'Edm.String', Timestamp: 'Edm.DateTime'}; + var odataMetadata = {}; + + // parse properties + for (var entityPropertyName in rawEntity) { + if (azureutil.stringStartsWith(entityPropertyName, Constants.TableConstants.ODATA_PREFIX)) { + odataMetadata[entityPropertyName.slice(prefixLength)] = rawEntity[entityPropertyName]; + } else if (azureutil.stringEndsWith(entityPropertyName, Constants.TableConstants.ODATA_TYPE_SUFFIX)) { + entityPropertyTypes[entityPropertyName.slice(0, entityPropertyName.length - suffixLength)] = rawEntity[entityPropertyName]; + } else { + rawEntityProperties[entityPropertyName] = rawEntity[entityPropertyName]; + } + } + + // make sure etag is set + if (!odataMetadata.etag && rawEntityProperties.Timestamp) { + var timestampString = new Buffer(rawEntityProperties.Timestamp).toString(); + odataMetadata.etag = 'W/"datetime\'' + timestampString + '\'"'; + } + + var entity = {}; + for (var entityPropertyName in rawEntityProperties) { + if (rawEntityProperties.hasOwnProperty(entityPropertyName)) { + // set the type, if given in the response + var entityPropertyType = entityPropertyTypes[entityPropertyName]; + entity[entityPropertyName] = {}; + + // use the given property resolver if present, otherwise infer type if undefined + if (propertyResolver) { + // partition key, row key, name, value, type if present + entityPropertyType = propertyResolver(rawEntityProperties.PartitionKey, rawEntityProperties.RowKey, entityPropertyName, rawEntityProperties[entityPropertyName], entityPropertyType); + } + if (!entityPropertyType && autoResolveProperties) { + entityPropertyType = edmHandler.propertyType(rawEntityProperties[entityPropertyName], false); + } + + if (entityPropertyType) { + entity[entityPropertyName][Constants.TableConstants.ODATA_TYPE_MARKER] = entityPropertyType; + } + + try { + entity[entityPropertyName][Constants.TableConstants.ODATA_VALUE_MARKER] = edmHandler.deserializeValueFromJson(entityPropertyType, rawEntityProperties[entityPropertyName]); + } catch (err) { + if (propertyResolver) { + // if a property resolver was used and the type is invalid, throw an appropriate error + throw new Error(util.format(SR.INVALID_PROPERTY_RESOLVER, entityPropertyName, entityPropertyType, rawEntityProperties[entityPropertyName])); + } else { + throw err; + } + } + } + } + + entity[Constants.TableConstants.ODATA_METADATA_MARKER] = odataMetadata; + + if (entityResolver) { + entity = entityResolver(entity); + } + + return entity; +}; diff --git a/node_modules/azure-storage/lib/services/table/internal/requesthandler.js b/node_modules/azure-storage/lib/services/table/internal/requesthandler.js new file mode 100644 index 000000000..6bbac20ea --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/internal/requesthandler.js @@ -0,0 +1,135 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +var util = require('util'); +var azureCommon = require('./../../../common/common.core'); +var WebResource = azureCommon.WebResource; +var SR = azureCommon.SR; +var Constants = azureCommon.Constants; +var HeaderConstants = Constants.HeaderConstants; +var TableConstants = Constants.TableConstants; +var entityResult = require('../models/entityresult'); + +exports = module.exports; + +/** +* Retrieves the entity path from the table name and an entity descriptor. +* @ignore +* +* @param {string} table The table name. +* @param {object} entity The entity descriptor. +* @return {string} The entity path. +*/ +function getEntityPath (tableName, partitionKey, rowKey) { + var path = '/' + tableName; + + if (typeof (partitionKey) === 'string' && typeof (rowKey) === 'string') { + // Escape single quotes according to OData Protocol Specification: "single quotes within string literals are represented as two consecutive single quotes". + partitionKey = partitionKey.replace(/'/g, '\'\''); + rowKey = rowKey.replace(/'/g, '\'\''); + path = path + '(PartitionKey=\'' + encodeURIComponent(partitionKey.toString('utf8')) + '\',RowKey=\'' + encodeURIComponent(rowKey.toString('utf8')) + '\')'; + } else { + throw new Error(SR.INCORRECT_ENTITY_KEYS); + } + + return path; +} + +/** +* Constructs the web resource for a table operation. +* +* @param {string} operation The operation to perform. +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The create options or callback function. +* @param {boolean} [options.checkEtag] Boolean value indicating weather the etag should be matched or not. +* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @return {webResource} +*/ +exports.constructEntityWebResource = function (operation, table, entityDescriptor, options) { + var webResource = null; + if (operation === TableConstants.Operations.INSERT) { + webResource = WebResource.post(table) + .withHeader(HeaderConstants.PREFER, options.echoContent ? HeaderConstants.PREFER_CONTENT : HeaderConstants.PREFER_NO_CONTENT); + } else { + var partitionKey; + var rowKey; + + if (typeof (entityDescriptor.PartitionKey) === 'string') { + partitionKey = entityDescriptor.PartitionKey; + } else { + partitionKey = entityDescriptor.PartitionKey[TableConstants.ODATA_VALUE_MARKER]; + } + + if (typeof (entityDescriptor.RowKey) === 'string') { + rowKey = entityDescriptor.RowKey; + } else { + rowKey = entityDescriptor.RowKey[TableConstants.ODATA_VALUE_MARKER]; + } + + var path = getEntityPath(table, partitionKey, rowKey); + + if (operation === TableConstants.Operations.DELETE) { + webResource = WebResource.del(path); + } else if (operation === TableConstants.Operations.MERGE || operation === TableConstants.Operations.INSERT_OR_MERGE) { + webResource = WebResource.merge(path); + } else if (operation === TableConstants.Operations.REPLACE || operation === TableConstants.Operations.INSERT_OR_REPLACE) { + webResource = WebResource.put(path); + } else if (operation === TableConstants.Operations.RETRIEVE) { + webResource = WebResource.get(path); + } else { + throw new Error(util.format(SR.INVALID_TABLE_OPERATION, operation)); + } + } + + if (operation === TableConstants.Operations.DELETE || operation === TableConstants.Operations.REPLACE || operation === TableConstants.Operations.MERGE) { + webResource.withHeader(HeaderConstants.IF_MATCH, entityResult.getEtag(entityDescriptor) || '*'); + } + + var entitySerializedDescriptor; + if (!(operation === TableConstants.Operations.DELETE || operation === TableConstants.Operations.RETRIEVE)) { + entitySerializedDescriptor = entityResult.serialize(entityDescriptor); + } + + exports.setTableRequestHeadersAndBody(webResource, entitySerializedDescriptor, options.payloadFormat); + + return webResource; +}; + +/** +* Sets the table request headers. +* +* @param {string} webResource The webResource to add headers to. +* @param {object} [body] The body of the request. +*/ +exports.setTableRequestHeadersAndBody = function (webResource, body, acceptType) { + if (body) { + webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body, 'utf8')) + .withBody(body) + .withHeader(HeaderConstants.CONTENT_TYPE, HeaderConstants.JSON_CONTENT_TYPE_VALUE); + } + + webResource.withHeader(HeaderConstants.ACCEPT, acceptType) + .withHeader(HeaderConstants.MAX_DATA_SERVICE_VERSION, TableConstants.DEFAULT_DATA_SERVICE_VERSION); +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js b/node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js new file mode 100644 index 000000000..42cccdbbd --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js @@ -0,0 +1,92 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var util = require('util'); +var azureCommon = require('./../../../common/common.core'); +var SharedKey = azureCommon.SharedKey; +var azureutil = azureCommon.util; +var Constants = azureCommon.Constants; +var HeaderConstants = Constants.HeaderConstants; +var QueryStringConstants = Constants.QueryStringConstants; + +/** +* Creates a new SharedKeyTable object. +* +* @constructor +* @param {string} storageAccount The storage account. +* @param {string} storageAccessKey The storage account's access key. +* @param {bool} usePathStyleUri Boolean value indicating if the path, or the hostname, should include the storage account. +*/ +function SharedKeyTable(storageAccount, storageAccessKey, usePathStyleUri) { + SharedKeyTable['super_'].call(this, + storageAccount, + storageAccessKey, + usePathStyleUri); +} + +util.inherits(SharedKeyTable, SharedKey); + +/** +* Signs a request with the Authentication header. +* +* @param {WebResource} The webresource to be signed. +* @param {function(error)} callback The callback function. +*/ +SharedKeyTable.prototype.signRequest = function (webResource, callback) { + var getvalueToAppend = function (value) { + if (azureutil.objectIsNull(value)) { + return '\n'; + } else { + return value + '\n'; + } + }; + + var stringToSign = + webResource.method + '\n' + + getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_MD5]) + + getvalueToAppend(webResource.headers[HeaderConstants.CONTENT_TYPE]) + + getvalueToAppend(webResource.headers[HeaderConstants.MS_DATE]) + + this._getCanonicalizedResource(webResource); + + var signature = this.signer.sign(stringToSign); + + webResource.withHeader(HeaderConstants.AUTHORIZATION, 'SharedKey ' + this.storageAccount + ':' + signature); + callback(null); +}; + +/* +* Retrieves the webresource's canonicalized resource string. +* @param {WebResource} webResource The webresource to get the canonicalized resource string from. +* @return {string} The canonicalized resource string. +*/ +SharedKeyTable.prototype._getCanonicalizedResource = function (webResource) { + var path = '/'; + if (webResource.path) { + path = webResource.path; + } + + var canonicalizedResource = '/' + this.storageAccount + path; + + var queryStringValues = webResource.queryString; + if (queryStringValues[QueryStringConstants.COMP]) { + canonicalizedResource += '?comp=' + queryStringValues[QueryStringConstants.COMP]; + } + + return canonicalizedResource; +}; + +module.exports = SharedKeyTable; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/models/batchresult.js b/node_modules/azure-storage/lib/services/table/models/batchresult.js new file mode 100644 index 000000000..4e39ad950 --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/models/batchresult.js @@ -0,0 +1,232 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../../common/common.core'); +var Md5Wrapper = require('./../../../common/md5-wrapper'); +var StorageServiceClient = azureCommon.StorageServiceClient; +var WebResource = azureCommon.WebResource; +var Constants = azureCommon.Constants; +var HeaderConstants = Constants.HeaderConstants; +var TableConstants = Constants.TableConstants; + +var RequestHandler = require('../internal/requesthandler'); +var entityResult = require('./entityresult'); + +/** +* Creates a new BatchResult. +* +* @param {TableService} tableService The table service. +* @param {string} table The table name. +* @param {array} operations The array of batch operations. +* @constructor +* @ignore +*/ +function BatchResult(tableService, table, operations) { + this.tableService = tableService; + this.table = table; + this.operations = operations; + this.batchBoundary = 'batch_' + BatchResult._getBoundary(); + this.changesetBoundary = 'changeset_' + BatchResult._getBoundary(); +} + +/** +* Gets a boundary string. +* +* @return {string} The boundary string. +* @ignore +*/ +BatchResult._getBoundary = function () { + return (new Md5Wrapper().createMd5Hash()).update('' + (new Date()).getTime()).digest('hex'); +}; + +/** +* Constructs the batch web request. +* +* @return {WebResource} The batch WebResource. +* @ignore +*/ +BatchResult.prototype.constructWebResource = function () { + var webResource = WebResource.post('$batch') + .withRawResponse(true); + + webResource.withHeader(HeaderConstants.CONTENT_TYPE, 'multipart/mixed; charset="utf-8"; boundary=' + this.batchBoundary); + webResource.withHeader(HeaderConstants.DATA_SERVICE_VERSION, '3.0;'); + webResource.withHeader(HeaderConstants.MAX_DATA_SERVICE_VERSION, '3.0;NetFx'); + + return webResource; +}; + +/** +* Serializes the batch web body. +* +* @return {string} The serialized batch content. +* @ignore +*/ +BatchResult.prototype.serialize = function () { + var body = '--' + this.batchBoundary + '\n'; + + if (this.operations.length === 1 && this.operations[0].type === TableConstants.Operations.RETRIEVE) { + body += HeaderConstants.CONTENT_TYPE + ': application/http\n'; + body += HeaderConstants.CONTENT_TRANSFER_ENCODING + ': binary\n\n'; + body += this._serializeOperation(this.operations[0]); + } else { + body += HeaderConstants.CONTENT_TYPE + ': multipart/mixed;charset="utf-8";boundary=' + this.changesetBoundary + '\n\n'; + + for (var i = 0; i < this.operations.length; i++) { + body += '--' + this.changesetBoundary + '\n'; + body += HeaderConstants.CONTENT_TYPE + ': application/http\n'; + body += HeaderConstants.CONTENT_TRANSFER_ENCODING + ': binary\n\n'; + body += this._serializeOperation(this.operations[i], i) + '\n'; + } + body += '--' + this.changesetBoundary + '--\n'; + } + body += '--' + this.batchBoundary + '--'; + + return body; +}; + +/** +* Serializes a request within the batch. +* +* @param {object} The operation to serialize. +* @param {number} The index of the operation in the operations arrray. +* @return {string} The serialized operation content. +* @ignore +*/ +BatchResult.prototype._serializeOperation = function (operation, count) { + operation.options.payloadFormat = operation.options.payloadFormat || this.tableService.defaultPayloadFormat; + var webResource = RequestHandler.constructEntityWebResource(operation.type, this.table, operation.entity, operation.options); + + if (count) { + webResource.headers[HeaderConstants.CONTENT_ID] = count; + } + + if (webResource.headers[HeaderConstants.CONTENT_TYPE]) { + webResource.headers[HeaderConstants.CONTENT_TYPE] += 'type=entry'; + } + + this.tableService._setRequestUrl(webResource); + + var content = webResource.method + ' ' + webResource.uri + ' HTTP/1.1\n'; + + Object.keys(webResource.headers).forEach(function (header) { + content += header + ': ' + webResource.headers[header] + '\n'; + }); + + content += '\n'; + content += webResource.body || ''; + + return content; +}; + +/** +* Parses a batch response. +* +* @param {object} responseObject The response object for the batch request. +* @return {array} An array with the processed / parsed responses. +*/ +BatchResult.prototype.parse = function (responseObject) { + var responses = null; + if (responseObject && responseObject.response && responseObject.response.body && + typeof responseObject.response.body === 'string') { + responses = []; + var rawResponses = responseObject.response.body.split(TableConstants.CHANGESET_DELIMITER); + + if(rawResponses.length === 1) { + rawResponses = responseObject.response.body.split(TableConstants.BATCH_DELIMITER); + } + + var self = this; + rawResponses.forEach(function (rawResponse) { + // Find HTTP/1.1 CODE line + var httpLocation = rawResponse.indexOf('HTTP/1.1'); + if (httpLocation !== -1) { + rawResponse = rawResponse.substring(httpLocation); + + // valid response + var response = self._parseOperation(rawResponse); + responses.push(response); + } + }); + } + + return responses; +}; + +/** +* Parses a partial response. +* +* @param {string} rawResponse The raw, unparsed, http response from the server for the batch response. +* @return {object} A response object. +*/ +BatchResult.prototype._parseOperation = function (rawResponse) { + var responseObject = { + error: null, + response: { } + }; + + // Split into multiple lines and process them + var responseLines = rawResponse.split('\r\n'); + + if (responseLines.length > 0) { + // Retrieve response code + var headers = responseLines.shift().split(' '); + if (headers.length >= 2) { + responseObject.response.statusCode = parseInt(headers[1]); + responseObject.response.isSuccessful = WebResource.validResponse(responseObject.response.statusCode); + } + + // Populate headers + responseObject.response.headers = { }; + responseObject.response.body = ''; + + var isBody = false; + responseLines.forEach(function (line) { + if (line === '' && !isBody) { + isBody = true; + } else if (isBody) { + responseObject.response.body += line; + } else { + var headerSplit = line.indexOf(':'); + if (headerSplit !== -1) { + responseObject.response.headers[line.substring(0, headerSplit).trim().toLowerCase()] = line.substring(headerSplit + 1).trim(); + } + } + }); + + StorageServiceClient._parseResponse(responseObject.response, this.tableService.xml2jsSettings); + if (!responseObject.response.isSuccessful) { + responseObject.error = StorageServiceClient._normalizeError(responseObject.response.body, responseObject.response); + } + + if (!responseObject.error) { + var index = responseObject.response.headers[HeaderConstants.CONTENT_ID] || 0; + var propertyResolver; + var entityResolver; + if (index && this.operations[index]) { + var options = this.operations[index].options; + propertyResolver = options.propertyResolver; + entityResolver = options.entityResolver; + } + responseObject.entity = entityResult.parseEntity(responseObject.response, propertyResolver, entityResolver); + } + } + + return responseObject; +}; + +module.exports = BatchResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/models/entityresult.js b/node_modules/azure-storage/lib/services/table/models/entityresult.js new file mode 100644 index 000000000..ac96ce741 --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/models/entityresult.js @@ -0,0 +1,62 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var azureCommon = require('./../../../common/common.core'); +var Constants = azureCommon.Constants; +var TableConstants = Constants.TableConstants; +var HeaderConstants = Constants.HeaderConstants; +var odataHandler = require('../internal/odatahandler'); + +exports = module.exports; + +exports.serialize = function (entity) { + return odataHandler.serializeJson(entity); +}; + +exports.parseQuery = function (response, autoResolveProperties, propertyResolver, entityResolver) { + var result = {}; + if (response.body) { + result = odataHandler.parseJsonEntities(response.body, autoResolveProperties, propertyResolver, entityResolver); + } + + return result; +}; + +exports.parseEntity = function (response, autoResolveProperties, propertyResolver, entityResolver) { + var result = {}; + if (response.body) { + result = odataHandler.parseJsonSingleEntity(response.body, autoResolveProperties, propertyResolver, entityResolver); + } + + if (response.headers && response.headers[HeaderConstants.ETAG.toLowerCase()]) { + if (!result[TableConstants.ODATA_METADATA_MARKER]) { + result[TableConstants.ODATA_METADATA_MARKER] = {}; + } + + result[TableConstants.ODATA_METADATA_MARKER].etag = response.headers[HeaderConstants.ETAG.toLowerCase()]; + } + + return result; +}; + +exports.getEtag = function (entity) { + var etag; + if (entity && entity[TableConstants.ODATA_METADATA_MARKER]) { + etag = entity[TableConstants.ODATA_METADATA_MARKER].etag; + } + return etag; +}; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/models/tableresult.js b/node_modules/azure-storage/lib/services/table/models/tableresult.js new file mode 100644 index 000000000..c6228287b --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/models/tableresult.js @@ -0,0 +1,37 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var odataHandler = require('../internal/odatahandler'); + +function TableResult(name) { + this.name = name; +} + +TableResult.serialize = function (tableName) { + return JSON.stringify({ TableName: tableName }); +}; + +TableResult.parse = function (response) { + var result = null; + if (response.body) { + result = odataHandler.parseJsonTables(response.body); + } + + return result; +}; + +exports = module.exports = TableResult; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/tablebatch.js b/node_modules/azure-storage/lib/services/table/tablebatch.js new file mode 100644 index 000000000..98bb3aecb --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/tablebatch.js @@ -0,0 +1,209 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var extend = require('extend'); + +var azureCommon = require('./../../common/common.core'); +var SR = azureCommon.SR; +var validate = azureCommon.validate; +var Constants = azureCommon.Constants; +var TableConstants = Constants.TableConstants; + +/** +* Creates a new TableBatch. +* +* @constructor +*/ +function TableBatch() { + this.operations = []; + this.pk = null; + this.retrieve = false; +} + +/** +* Removes all of the operations from the batch. +*/ +TableBatch.prototype.clear = function () { + this.operations = []; +}; + +/** +* Returns a boolean value indicating weather there are operations in the batch. +* +* @return {Boolean} True if there are operations queued up; false otherwise. +*/ +TableBatch.prototype.hasOperations = function () { + return this.operations.length > 0; +}; + +/** +* Returns the number of operations in the batch. +* +* @return {number} The number of operations in the batch. +*/ +TableBatch.prototype.size = function () { + return this.operations.length; +}; + +/** +* Adds a retrieve operation to the batch. Note that this must be the only operation in the batch. +* +* @param {string} partitionKey The partition key. +* @param {string} rowKey The row key. +* @param {object} [options] The request options. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, +* and the property Edm type if given by the service, returns the Edm type of the property. +* @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object. +*/ +TableBatch.prototype.retrieveEntity = function (partitionKey, rowKey, options) { + var entity = { PartitionKey: {_: partitionKey, $: 'Edm.String'}, + RowKey: {_: rowKey, $: 'Edm.String'}, + }; + this.addOperation(TableConstants.Operations.RETRIEVE, entity, options); +}; + +/** +* Adds an insert operation to the batch. +* +* @param {object} entity The entity. +* @param {object} [options] The request options. +* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Inserts only, default to false. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name, +* property value, and the property Edm type if given by the service, returns the Edm type of the property. +* @param {Function(entity)} [options.entityResolver] The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns +* a modified object. +*/ +TableBatch.prototype.insertEntity = function (entity, options) { + this.addOperation(TableConstants.Operations.INSERT, entity, options); +}; + +/** +* Adds a delete operation to the batch. +* +* @param {object} entity The entity. +*/ +TableBatch.prototype.deleteEntity = function (entity) { + this.addOperation(TableConstants.Operations.DELETE, entity); +}; + +/** +* Adds a merge operation to the batch. +* +* @param {object} entity The entity. +*/ +TableBatch.prototype.mergeEntity = function (entity) { + this.addOperation(TableConstants.Operations.MERGE, entity); +}; + +/** +* Adds an replace operation to the batch. +* +* @param {object} entity The entity. +*/ +TableBatch.prototype.replaceEntity = function (entity) { + this.addOperation(TableConstants.Operations.REPLACE, entity); +}; + +/** +* Adds an insert or replace operation to the batch. +* +* @param {object} entity The entity. +*/ +TableBatch.prototype.insertOrReplaceEntity = function (entity) { + this.addOperation(TableConstants.Operations.INSERT_OR_REPLACE, entity); +}; + +/** +* Adds an insert or merge operation to the batch. +* +* @param {object} entity The entity. +*/ +TableBatch.prototype.insertOrMergeEntity = function (entity) { + this.addOperation(TableConstants.Operations.INSERT_OR_MERGE, entity); +}; + +/** +* Adds an operation to the batch after performing checks. +* +* @param {string} operationType The type of operation to perform. See Constants.TableConstants.Operations +* @param {object} entity The entity. +* @param {object} [options] The request options. +*/ +TableBatch.prototype.addOperation = function (operationType, entity, options) { + validate.validateArgs('addOperation', function (v) { + v.object(entity, 'entity'); + v.object(entity.PartitionKey, 'entity.PartitionKey'); + v.object(entity.RowKey, 'entity.RowKey'); + v.stringAllowEmpty(entity.PartitionKey._, 'entity.PartitionKey._'); + v.stringAllowEmpty(entity.RowKey._, 'entity.RowKey._'); + }); + + if(this.operations.length >= 100) { + throw new Error(SR.BATCH_TOO_LARGE); + } + + if (operationType === TableConstants.Operations.RETRIEVE) { + if(this.hasOperations()) { + throw new Error(SR.BATCH_ONE_RETRIEVE); + } else { + this.retrieve = true; + } + } else if (this.retrieve) { + throw new Error(SR.BATCH_ONE_RETRIEVE); + } + + if (!this.hasOperations()) { + this.pk = entity.PartitionKey._; + } else if (entity.PartitionKey._ !== this.pk) { + throw new Error(SR.BATCH_ONE_PARTITION_KEY); + } + + var copiedOptions = extend(true, {}, options); + this.operations.push({type: operationType, entity: entity, options: copiedOptions}); +}; + +/** +* Gets an operation from the batch. Returns null if the index does not exist. +* +* @param {number} index The index in the operations array at which to remove an element. +* @return {object} The removed operation. +*/ +TableBatch.prototype.getOperation = function (index) { + return this.operations[index]; +}; + +/** +* Removes an operation from the batch. Returns null if the index does not exist. +* +* @param {number} index The index in the operations array at which to remove an element. +* @return {object} The removed operation. +*/ +TableBatch.prototype.removeOperation = function (index) { + var operation = this.operations.splice(index, 1)[0]; + + // if the array is empty, unlock the partition key + if (!this.hasOperations()) { + this.pk = null; + this.retrieve = false; + } + + return operation; +}; + +module.exports = TableBatch; diff --git a/node_modules/azure-storage/lib/services/table/tablequery.js b/node_modules/azure-storage/lib/services/table/tablequery.js new file mode 100644 index 000000000..9e225eee4 --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/tablequery.js @@ -0,0 +1,419 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var _ = require('underscore'); +var util = require('util'); + +var azureCommon = require('./../../common/common.core'); +var azureutil = azureCommon.util; +var SR = azureCommon.SR; +var QueryStringConstants = azureCommon.Constants.QueryStringConstants; + +var edmHandler = require('./internal/edmhandler'); +var TableUtilities = require('./tableutilities'); +var QueryComparisons = TableUtilities.QueryComparisons; +var TableOperators = TableUtilities.TableOperators; +var EdmType = TableUtilities.EdmType; + +/** + * Creates a new TableQuery object. + * + * @constructor + */ +function TableQuery() { + this._fields = []; + this._where = []; + this._top = null; +} + +/** +* Specifies the select clause. If no arguments are given, all fields will be selected. +* +* @param {array} fields The fields to be selected. +* @return {TableQuery} A table query object with the select clause. +* @example +* var tableQuery = new TableQuery().select('field1', 'field2'); +*/ +TableQuery.prototype.select = function () { + var self = this; + if (arguments) { + _.each(arguments, function (argument) { + self._fields.push(argument); + }); + } + + return this; +}; + +/** + * Specifies the top clause. + * + * @param {int} top The number of items to fetch. + * @return {TableQuery} A table query object with the top clause. + * @example + * var tableQuery = new TableQuery().top(10); + * + * // tasktable should already exist and have entities + * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) { + * if(!error) { + * var entities = result.entities; // there will be 10 or less entities + * // do stuff with the returned entities if there are any + * // if result.continuationToken exists, to get the next 10 (or less) entities + * // call queryEntities as above, but with the returned token instead of null + * } + * }); + */ +TableQuery.prototype.top = function (top) { + this._top = top; + return this; +}; + +/** + * Specifies the where clause. + * + * Valid type specifier strings include: ?string?, ?bool?, ?int32?, ?double?, ?date?, ?guid?, ?int64?, ?binary? + * A type must be specified for guid, int64, and binaries or the filter produced will be incorrect. + * + * @param {string} condition The condition string. + * @param {string|array} value Value(s) to insert in question mark (?) parameters. + * @return {TableQuery} A table query object with the where clause. + * @example + * var tableQuery = new TableQuery().where(TableQuery.guidFilter('GuidField', QueryComparisons.EQUAL, guidVal)); + * OR + * var tableQuery = new TableQuery().where('Name == ? or Name <= ?', name1, name2); + * OR + * var tableQuery = new TableQuery().where('Name == ?string? && Value == ?int64?', name1, int64Val); + * + * // tasktable should already exist and have entities + * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result, response) { + * if(!error) { + * var entities = result.entities; + * // do stuff with the returned entities if there are any + * } + * }); + */ +TableQuery.prototype.where = function (condition) { + this._where.push(TableQuery._encodeConditionString(condition, arguments)); + return this; +}; + +/** + * Generates a property filter condition string for an 'int' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|int} value An 'int' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.int32Filter('IntField', QueryComparisons.EQUAL, 5); + */ +TableQuery.int32Filter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.INT32); +}; + +/** + * Generates a property filter condition string for a 'int64' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|int64} value An 'int64' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.int64Filter('Int64Field', QueryComparisons.EQUAL, 123); + */ +TableQuery.int64Filter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.INT64); +}; + +/** + * Generates a property filter condition string for a 'double' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|double}value A 'double' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.doubleFilter('DoubleField', QueryComparisons.EQUAL, 123.45); + */ +TableQuery.doubleFilter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.DOUBLE); +}; + +/** + * Generates a property filter condition string for a 'boolean' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|boolean} value A 'boolean' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.booleanFilter('BooleanField', QueryComparisons.EQUAL, false); + */ +TableQuery.booleanFilter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.BOOLEAN); +}; + +/** + * Generates a property filter condition string for a 'datetime' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|date} value A 'datetime' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.dateFilter('DateTimeField', QueryComparisons.EQUAL, new Date(Date.UTC(2001, 1, 3, 4, 5, 6))); + */ +TableQuery.dateFilter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.DATETIME); +}; + +/** + * Generates a property filter condition string for a 'guid' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|guid} value A 'guid' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.guidFilter('GuidField', QueryComparisons.EQUAL, guid.v1()); + */ +TableQuery.guidFilter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.GUID); +}; + +/** + * Generates a property filter condition string for a 'binary' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|buffer}value A 'buffer' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.binaryFilter('BinaryField', QueryComparisons.EQUAL, new Buffer('hello')); + */ +TableQuery.binaryFilter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.BINARY); +}; + +/** + * Generates a property filter condition string. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string} value A 'string' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.stringFilter('StringField', QueryComparisons.EQUAL, 'name'); + */ +TableQuery.stringFilter = function (propertyName, operation, value) { + return TableQuery._concatFilterString(propertyName, operation, value, EdmType.STRING); +}; + +/** + * Creates a filter condition using the specified logical operator on two filter conditions. + * + * @param {string} filterA A string containing the first formatted filter condition. + * @param {string} operatorString A string containing the operator to use (AND, OR). + * @param {string} filterB A string containing the second formatted filter condition. + * @return {string} A string containing the combined filter expression. + * @example + * var filter1 = TableQuery.stringFilter('Name', QueryComparisons.EQUAL, 'Person'); + * var filter2 = TableQuery.booleanFilter('Visible', QueryComparisons.EQUAL, true); + * var combinedFilter = TableQuery.combineFilters(filter1, TableUtilities.TableOperators.AND, filter2); + */ +TableQuery.combineFilters = function (filterA, operatorString, filterB) { + return filterA + ' ' + operatorString + ' ' + filterB; +}; + +/** + * Specifies an AND where condition. + * + * @param {string} condition The condition string. + * @param {array} arguments Any number of arguments to be replaced in the condition by the question mark (?). + * @return {TableQuery} A table query object with the and clause. + * @example + * var tableQuery = new TableQuery() + * .where('Name == ? or Name <= ?', 'Person1', 'Person2'); + * .and('Age >= ?', 18); + */ +TableQuery.prototype.and = function (condition) { + if (this._where.length === 0) { + throw new Error(util.format(SR.QUERY_OPERATOR_REQUIRES_WHERE, 'AND')); + } + + this._where.push(' and ' + TableQuery._encodeConditionString(condition, arguments)); + return this; +}; + +/** + * Specifies an OR where condition. + * + * @param {string} condition The condition. + * @param {array} arguments Any number of arguments to be replaced in the condition by the question mark (?). + * @return {TableQuery} A table query object with the or clause. + * @example + * var tableQuery = new TableQuery() + * .where('Name == ? or Name <= ?', 'Person1', 'Person2'); + * .or('Age >= ?', 18); + */ +TableQuery.prototype.or = function (condition) { + if (this._where.length === 0) { + throw new Error(util.format(SR.QUERY_OPERATOR_REQUIRES_WHERE, 'OR')); + } + + this._where.push(' or ' + TableQuery._encodeConditionString(condition, arguments)); + return this; +}; + +/** + * Returns the query string object for the query. + * + * @return {object} JSON object representing the query string arguments for the query. + */ +TableQuery.prototype.toQueryObject = function () { + var query = {}; + if (this._fields.length > 0) { + query[QueryStringConstants.SELECT] = this._fields.join(','); + } + + if (this._where.length > 0) { + query[QueryStringConstants.FILTER] = this._where.join(''); + } + + if (this._top) { + query[QueryStringConstants.TOP] = this._top; + } + + return query; +}; + +// Functions + +/** +* Concat the filter string parameters. +* +* @param {string} propertyName A string containing the name of the property to compare. +* @param {string} operation A string containing the comparison operator to use. +* See Constants.TableConstants.QueryComparisons for a list of allowed operations. +* @param {object} value The value to compare with the property. +* @param {string} type A string EdmType of the property to compare. +* @return {string} A string containing the formatted filter condition. +* @ignore +*/ +TableQuery._concatFilterString = function (propertyName, operation, value, type) { + if (azureutil.objectIsNull(propertyName)) { + throw new Error(util.format(SR.ARGUMENT_NULL_OR_UNDEFINED, 'propertyName')); + } + + if (azureutil.objectIsNull(operation)) { + throw new Error(util.format(SR.ARGUMENT_NULL_OR_UNDEFINED, 'operation')); + } + + if (azureutil.objectIsNull(value)) { + throw new Error(util.format(SR.ARGUMENT_NULL_OR_UNDEFINED, 'value')); + } + + var serializedValue = edmHandler.serializeQueryValue(value, type); + return propertyName + ' ' + operation + ' ' + serializedValue; +}; + +/** + * Encodes a condition string. + * + * @param {string} condition The condition. + * @param {array} arguments Any number of arguments to be replaced in the condition by the question mark (?). + * @return {TableQuery} A table query object with the or clause + * @ignore + */ +TableQuery._encodeConditionString = function (condition, args) { + var encodedCondition = TableQuery._replaceOperators(condition); + if (args.length > 1) { + var sections = encodedCondition.split(/(\?string\?|\?int32\?|\?int64\?|\?bool\?|\?double\?|\?date\?|\?binary\?|\?guid\?|\?)/); + var count = 1; + for (var i = 0; i < sections.length && count < args.length; i++) { + if (sections[i].indexOf('?') === 0) { + var type = TableQuery._getEdmType(sections[i]); + sections[i] = edmHandler.serializeQueryValue(args[count], type); + count++; + } + } + encodedCondition = sections.join(''); + } + + return encodedCondition; +}; + +/** + * Converts the query string type to an Edm type. + * + * @param {string} type The type included in the query string. + * @return {string} The EdmType. + * @ignore + */ +TableQuery._getEdmType = function (type) { + switch (type) { + case '?binary?': + return EdmType.BINARY; + case '?int64?': + return EdmType.INT64; + case '?date?': + return EdmType.DATETIME; + case '?guid?': + return EdmType.GUID; + case '?int32?': + return EdmType.INT32; + case '?double?': + return EdmType.DOUBLE; + case '?bool?': + return EdmType.BOOLEAN; + case '?string?': + return EdmType.STRING; + default: + return undefined; + } +}; + +/** + * Replace operators. + * @ignore + * @param {string} whereClause The text where to replace the operators. + * @return {string} The string with the replaced operators. + * @ignore + */ +TableQuery._replaceOperators = function (whereClause) { + var encodedWhereClause = whereClause.replace(/ == /g, ' ' + QueryComparisons.EQUAL + ' '); + encodedWhereClause = encodedWhereClause.replace(/ != /g, ' ' + QueryComparisons.NOT_EQUAL + ' '); + encodedWhereClause = encodedWhereClause.replace(/ >= /g, ' ' + QueryComparisons.GREATER_THAN_OR_EQUAL + ' '); + encodedWhereClause = encodedWhereClause.replace(/ > /g, ' ' + QueryComparisons.GREATER_THAN + ' '); + encodedWhereClause = encodedWhereClause.replace(/ <= /g, ' ' + QueryComparisons.LESS_THAN_OR_EQUAL + ' '); + encodedWhereClause = encodedWhereClause.replace(/ < /g, ' ' + QueryComparisons.LESS_THAN + ' '); + encodedWhereClause = encodedWhereClause.replace(/ \&\& /g, ' ' + TableOperators.AND + ' '); + encodedWhereClause = encodedWhereClause.replace(/ \|\| /g, ' ' + TableOperators.OR + ' '); + encodedWhereClause = encodedWhereClause.replace(/!/g, TableOperators.NOT); + + return encodedWhereClause; +}; + +module.exports = TableQuery; diff --git a/node_modules/azure-storage/lib/services/table/tableservice.js b/node_modules/azure-storage/lib/services/table/tableservice.js new file mode 100644 index 000000000..6ddf5505d --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/tableservice.js @@ -0,0 +1,1391 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Module dependencies. +var util = require('util'); +var extend = require('extend'); +var _ = require('underscore'); + +var azureCommon = require('./../../common/common.core'); +var azureutil = azureCommon.util; +var validate = azureCommon.validate; +var SR = azureCommon.SR; +var StorageServiceClient = azureCommon.StorageServiceClient; +var SharedKeyTable = require('./internal/sharedkeytable'); +var RequestHandler = require('./internal/requesthandler'); +var TableQuery = require('./tablequery'); +var WebResource = azureCommon.WebResource; +var Constants = azureCommon.Constants; +var QueryStringConstants = Constants.QueryStringConstants; +var HeaderConstants = Constants.HeaderConstants; +var TableConstants = Constants.TableConstants; +var RequestLocationMode = Constants.RequestLocationMode; + +// Models requires +var TableResult = require('./models/tableresult'); +var entityResult = require('./models/entityresult'); +var BatchResult = require('./models/batchresult'); +var ServiceStatsParser = azureCommon.ServiceStatsParser; +var AclResult = azureCommon.AclResult; +var TableUtilities = require('./tableutilities'); + +/** +* Creates a new TableService object. +* If no connection string or storageaccount and storageaccesskey are provided, +* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. +* @class +* The TableService object allows you to peform management operations with the Microsoft Azure Table Service. +* The Table Service stores data in rows of key-value pairs. A table is composed of multiple rows, and each row +* contains key-value pairs. There is no schema, so each row in a table may store a different set of keys. +* +* For more information on the Table Service, as well as task focused information on using it from a Node.js application, see +* [How to Use the Table Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-table-storage/). +* The following defaults can be set on the Table service. +* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Table service. +* defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Table service. +* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Table service. +* defaultLocationMode The default location mode for requests made via the Table service. +* defaultPayloadFormat The default payload format for requests made via the Table service. +* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Table service.; true to use the +* Nagle algorithm; otherwise, false. The default value is false. +* @constructor +* @extends {StorageServiceClient} +* +* @param {string} [storageAccountOrConnectionString] The storage account or the connection string. +* @param {string} [storageAccessKey] The storage access key. +* @param {string|object} [host] The host address. To define primary only, pass a string. +* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {string} [endpointSuffix] The endpoint suffix. +*/ +function TableService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) { + var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix); + + TableService['super_'].call(this, + storageServiceSettings._name, + storageServiceSettings._key, + storageServiceSettings._tableEndpoint, + storageServiceSettings._usePathStyleUri, + storageServiceSettings._sasToken); + + if (this.anonymous) { + throw new Error(SR.ANONYMOUS_ACCESS_BLOBSERVICE_ONLY); + } + + if(this.storageAccount && this.storageAccessKey) { + this.storageCredentials = new SharedKeyTable(this.storageAccount, this.storageAccessKey, this.usePathStyleUri); + } + + this.defaultPayloadFormat = TableUtilities.PayloadFormat.MINIMAL_METADATA; +} + +util.inherits(TableService, StorageServiceClient); + +// Table service methods + +/** +* Gets the service stats for a storage account’s Table service. +* +* @this {TableService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link ServiceStats}` will contain the stats. +* `response` will contain information related to this operation. +*/ +TableService.prototype.getServiceStats = function (optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getServiceStats', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var webResource = WebResource.get() + .withQueryOption(QueryStringConstants.COMP, 'stats') + .withQueryOption(QueryStringConstants.RESTYPE, 'service'); + + var processResponseCallback = function (responseObject, next) { + responseObject.serviceStatsResult = null; + if (!responseObject.error) { + responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats); + } + + // function to be called after all filters + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response); + }; + + // call the first filter + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Gets the properties of a storage account’s Table service, including Azure Storage Analytics. +* +* @this {TableService} +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `[result]{@link ServiceProperties}` will contain the properties. +* `response` will contain information related to this operation. +*/ +TableService.prototype.getServiceProperties = function (optionsOrCallback, callback) { + return this.getAccountServiceProperties(optionsOrCallback, callback); +}; + +/** +* Sets the properties of a storage account’s Table service, including Azure Storage Analytics. +* You can also use this operation to set the default request version for all incoming requests that do not have a version specified. +* +* @this {TableService} +* @param {object} serviceProperties The service properties. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information if an error occurs; +* `response` will contain information related to this operation. +*/ +TableService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) { + return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of table items under the specified account. +* +* @this {TableService} +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The create options or callback function. +* @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of tables and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +TableService.prototype.listTablesSegmented = function (currentToken, optionsOrCallback, callback) { + this.listTablesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback); +}; + +/** +* Lists a segment containing a collection of table items under the specified account. +* +* @this {TableService} +* @param {string} prefix The prefix of the table name. +* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The create options or callback function. +* @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain `entries` and `continuationToken`. +* `entries` gives a list of tables and the `continuationToken` is used for the next listing operation. +* `response` will contain information related to this operation. +*/ +TableService.prototype.listTablesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('listTables', function (v) { + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat; + + var webResource = WebResource.get(TableConstants.TABLE_SERVICE_TABLE_NAME); + RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat); + + if(!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(TableConstants.NEXT_TABLE_NAME, currentToken.nextTableName); + } + + if(!azureutil.objectIsNull(prefix)) { + var query = new TableQuery() + .where(TableConstants.TABLE_NAME + ' >= ?', prefix) + .and(TableConstants.TABLE_NAME + ' < ?', prefix + '{'); + + webResource.withQueryOption(QueryStringConstants.FILTER, query.toQueryObject().$filter); + } + + if(!azureutil.objectIsNull(options.maxResults)) { + var query = new TableQuery().top(options.maxResults); + webResource.withQueryOption(QueryStringConstants.TOP, query.toQueryObject().$top); + } + + options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken); + + var processResponseCallback = function (responseObject, next) { + responseObject.listTablesResult = null; + + if (!responseObject.error) { + responseObject.listTablesResult = { + entries: null, + continuationToken: null + }; + responseObject.listTablesResult.entries = TableResult.parse(responseObject.response); + + if (responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME] && + !azureutil.objectIsEmpty(responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME])) { + responseObject.listTablesResult.continuationToken = { + nextTableName: null, + targetLocation: null + }; + + responseObject.listTablesResult.continuationToken.nextTableName = responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME]; + responseObject.listTablesResult.continuationToken.targetLocation = responseObject.targetLocation; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.listTablesResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +// Table Methods + +/** +* Gets the table's ACL. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the ACL information for the table. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +* `response` will contain information related to this operation. +*/ +TableService.prototype.getTableAcl = function (table, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('getTableAcl', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY; + + var webResource = WebResource.get(table) + .withQueryOption(QueryStringConstants.COMP, 'acl'); + + var processResponseCallback = function (responseObject, next) { + responseObject.tableResult = null; + if (!responseObject.error) { + responseObject.tableResult = new TableResult(table); + responseObject.tableResult.signedIdentifiers = AclResult.parse(responseObject.response.body); + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.tableResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Updates the table's ACL. +* +* @this {TableService} +* @param {string} table The table name. +* @param {Object.} signedIdentifiers The table ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain information for the table. +* `response` will contain information related to this operation. +*/ +TableService.prototype.setTableAcl = function (table, signedIdentifiers, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('setTableAcl', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var policies = null; + if (signedIdentifiers) { + if(_.isArray(signedIdentifiers)) { + throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS); + } + policies = AclResult.serialize(signedIdentifiers); + } + + var webResource = WebResource.put(table) + .withQueryOption(QueryStringConstants.COMP, 'acl') + .withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0) + .withBody(policies); + + var processResponseCallback = function (responseObject, next) { + responseObject.tableResult = null; + if (!responseObject.error) { + + // SetTableAcl doesn't actually return anything in the response + responseObject.tableResult = new TableResult(table); + if (signedIdentifiers) { + responseObject.tableResult.signedIdentifiers = signedIdentifiers; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.tableResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Retrieves a shared access signature token. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} sharedAccessPolicy The shared access policy. +* @param {string} [sharedAccessPolicy.Id] The signed identifier. +* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). +* @param {date|string} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired (The UTC value will be used). +* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. +* @param {string} [sharedAccessPolicy.AccessPolicy.Protocols] The protocols permitted for a request made with the account SAS. +* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http. +* @param {string} [sharedAccessPolicy.AccessPolicy.StartPk] The starting Partition Key for which the SAS will be valid. +* @param {string} [sharedAccessPolicy.AccessPolicy.EndPk] The ending Partition Key for which the SAS will be valid. +* @param {string} [sharedAccessPolicy.AccessPolicy.StartRk] The starting Row Key for which the SAS will be valid. +* @param {string} [sharedAccessPolicy.AccessPolicy.EndRk] The ending Row Key for which the SAS will be valid. +* @return {object} An object with the shared access signature. +*/ +TableService.prototype.generateSharedAccessSignature = function (table, sharedAccessPolicy) { + // check if the TableService is able to generate a shared access signature + if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) { + throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY); + } + + validate.validateArgs('generateSharedAccessSignature', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.object(sharedAccessPolicy, 'sharedAccessPolicy'); + }); + + var lowerCasedTableName = table.toLowerCase(); + return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Table, lowerCasedTableName, sharedAccessPolicy, null, { tableName: lowerCasedTableName }); +}; + +/** +* Checks whether or not a table exists on the service. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the table information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +TableService.prototype.doesTableExist = function (table, optionsOrCallback, callback) { + this._doesTableExist(table, false, optionsOrCallback, callback); +}; + +/** +* Creates a new table within a storage account. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the new table information. +* `response` will contain information related to this operation. +*/ +TableService.prototype.createTable = function (table, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createTable', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var tableDescriptor = TableResult.serialize(table); + + var webResource = WebResource.post('Tables') + .withHeader(HeaderConstants.PREFER, HeaderConstants.PREFER_NO_CONTENT); + + RequestHandler.setTableRequestHeadersAndBody(webResource, tableDescriptor, this.defaultPayloadFormat); + + var processResponseCallback = function (responseObject, next) { + responseObject.tableResponse = {}; + responseObject.tableResponse.isSuccessful = responseObject.error ? false : true; + responseObject.tableResponse.statusCode = responseObject.response.statusCode; + if (!responseObject.error) { + responseObject.tableResponse.TableName = table; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.tableResponse, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Creates a new table within a storage account if it does not exists. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* `result` will contain the table information including `created` boolean member +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var tableService = azure.createTableService(); +* tableService.createTableIfNotExists('tasktable', function(error) { +* if(!error) { +* // Table created or exists +* } +* }); +*/ +TableService.prototype.createTableIfNotExists = function (table, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('createTableIfNotExists', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var self = this; + self._doesTableExist(table, true, options, function(error, result, response) { + var exists = result.exists; + result.created = false; + delete result.exists; + + if (error) { + callback(error, result, response); + } else if (exists) { + response.isSuccessful = true; + callback(error, result, response); + } else { + self.createTable(table, options, function(createError, createResult, response) { + if (!createError) { + createResult.created = true; + } + else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.TableErrorCodeStrings.TABLE_ALREADY_EXISTS) { + createError = null; + createResult.created = false; + createResult.isSuccessful = true; + } + callback(createError, createResult, response); + }); + } + }); +}; + +/** +* Deletes a table from a storage account. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information if an error occurs; +* `response` will contain information related to this operation. +*/ +TableService.prototype.deleteTable = function (table, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteTable', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var webResource = WebResource.del('Tables(\'' + table + '\')'); + RequestHandler.setTableRequestHeadersAndBody(webResource, null, this.defaultPayloadFormat); + + var processResponseCallback = function (responseObject, next) { + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Deletes a table from a storage account, if it exists. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* `result` will be `true` if table was deleted, false otherwise +* `response` will contain information related to this operation. +*/ +TableService.prototype.deleteTableIfExists = function (table, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('deleteTableIfExists', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + var self = this; + self._doesTableExist(table, true, options, function(error, result, response) { + if (error) { + callback(error, result.exists, response); + } else if (!result.exists) { + response.isSuccessful = true; + callback(error, false, response); + } else { + self.deleteTable(table, options, function(deleteError, deleteResponse) { + var deleted; + if (!deleteError) { + deleted = true; + } else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND) { + deleted = false; + deleteError = null; + deleteResponse.isSuccessful = true; + } + + callback(deleteError, deleted, deleteResponse); + }); + } + }); +}; + +// Table Entity Methods + +/** +* Queries data in a table. To retrieve a single entity by partition key and row key, use retrieve entity. +* +* @this {TableService} +* @param {string} table The table name. +* @param {TableQuery} tableQuery The query to perform. Use null, undefined, or new TableQuery() to get all of the entities in the table. +* @param {object} currentToken A continuation token returned by a previous listing operation. +* Please use 'null' or 'undefined' if this is the first operation. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {bool} [options.autoResolveProperties] If true, guess at all property types. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(entity)} [options.entityResolver] The entity resolver. Given a single entity returned by the query, returns a modified object which is added to +* the entities array. +* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, +* and the property Edm type if given by the service, returns the Edm type of the property. +* @param {TableService~queryResponse} callback `error` will contain information if an error occurs; +* otherwise `entities` will contain the entities returned by the query. +* If more matching entities exist, and could not be returned, +* `queryResultContinuation` will contain a continuation token that can be used +* to retrieve the next set of results. +* `response` will contain information related to this operation. +* +* The logic for returning entity types can get complicated. Here is the algorithm used: +* ``` +* var propertyType; +* +* if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it +* propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService); +* } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur. +* propertyType = propertyTypeFromService; +* } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true +* if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does. +* propertyType = 'Edm.String'; +* } else if (javascript type is boolean) { +* propertyType = 'Edm.Boolean'; +* } +* } +* +* if (propertyType) { +* // Set the property type on the property. +* } else { +* // Property gets no EdmType. +* } +* ``` +* Notes: +* +* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime. +* * Explanation of autoResolveProperties: +* * String gets correctly resolved to 'Edm.String'. +* * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step). +* * Boolean gets correctly resolved to 'Edm.Boolean'. +* * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an +* inability to distinguish between the two in certain cases. +* +* @example +* var azure = require('azure-storage'); +* var tableService = azure.createTableService(); +* // tasktable should already exist and have entities +* +* // returns all entities in tasktable, and a continuation token for the next page of results if necessary +* tableService.queryEntities('tasktable', null, null \/*currentToken*\/, function(error, result) { +* if(!error) { +* var entities = result.entities; +* // do stuff with the returned entities if there are any +* } +* }); +* +* // returns field1 and field2 of the entities in tasktable, and a continuation token for the next page of results if necessary +* var tableQuery = new TableQuery().select('field1', 'field2'); +* tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) { +* if(!error) { +* var entities = result.entities; +* // do stuff with the returned entities if there are any +* } +* }); +*/ +TableService.prototype.queryEntities = function (table, tableQuery, currentToken, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('queryEntities', function (v) { + v.string(table, 'table'); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat; + + var webResource = WebResource.get(table); + RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat); + + if (tableQuery) { + var queryString = tableQuery.toQueryObject(); + Object.keys(queryString).forEach(function (queryStringName) { + webResource.withQueryOption(queryStringName, queryString[queryStringName]); + }); + } + + if(!azureutil.objectIsNull(currentToken)) { + webResource.withQueryOption(TableConstants.NEXT_PARTITION_KEY, currentToken.nextPartitionKey); + webResource.withQueryOption(TableConstants.NEXT_ROW_KEY, currentToken.nextRowKey); + } + + options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken); + + var processResponseCallback = function (responseObject, next) { + responseObject.queryEntitiesResult = null; + if (!responseObject.error) { + responseObject.queryEntitiesResult = { + entries: null, + continuationToken: null + }; + + // entries + responseObject.queryEntitiesResult.entries = entityResult.parseQuery(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver); + + // continuation token + var continuationToken = { + nextPartitionKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_PARTITION_KEY], + nextRowKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_ROW_KEY], + targetLocation: responseObject.targetLocation + }; + + if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(continuationToken.nextPartitionKey)) { + responseObject.queryEntitiesResult.continuationToken = continuationToken; + } + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.queryEntitiesResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Retrieves an entity from a table. +* +* @this {TableService} +* @param {string} table The table name. +* @param {string} partitionKey The partition key. +* @param {string} rowKey The row key. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {bool} [options.autoResolveProperties] If true, guess at all property types. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, +* and the property Edm type if given by the service, returns the Edm type of the property. +* @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will be the matching entity. +* `response` will contain information related to this operation. +* +* The logic for returning entity types can get complicated. Here is the algorithm used: +* ``` +* var propertyType; +* +* if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it +* propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService); +* } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur. +* propertyType = propertyTypeFromService; +* } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true +* if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does. +* propertyType = 'Edm.String'; +* } else if (javascript type is boolean) { +* propertyType = 'Edm.Boolean'; +* } +* } +* +* if (propertyType) { +* // Set the property type on the property. +* } else { +* // Property gets no EdmType. +* } +* ``` +* Notes: +* +* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime. +* * Explanation of autoResolveProperties: +* * String gets correctly resolved to 'Edm.String'. +* * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step). +* * Boolean gets correctly resolved to 'Edm.Boolean'. +* * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an +* inability to distinguish between the two in certain cases. +* +* @example +* var azure = require('azure-storage'); +* var tableService = azure.createTableService(); +* tableService.retrieveEntity('tasktable', 'tasksSeattle', '1', function(error, serverEntity) { +* if(!error) { +* // Entity available in serverEntity variable +* } +* }); +*/ +TableService.prototype.retrieveEntity = function (table, partitionKey, rowKey, optionsOrCallback, callback) { + var entityDescriptor = { PartitionKey: {_: partitionKey, $: 'Edm.String'}, + RowKey: {_: rowKey, $: 'Edm.String'}, + }; + + validate.validateArgs('retrieveEntity', function (v) { + v.stringAllowEmpty(partitionKey, 'partitionKey'); + v.stringAllowEmpty(rowKey, 'rowKey'); + }); + + this._performEntityOperation(TableConstants.Operations.RETRIEVE, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Inserts a new entity into a table. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The request options. +* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false. +* @param {string} [options.payloadFormat] The payload format to use in the response, if options.echoContent is true. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name, +* property value, and the property Edm type if given by the service, returns the Edm type of the property. +* @param {Function(entity)} [options.entityResolver] The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns +* a modified object. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the entity information. +* `response` will contain information related to this operation. +* +* @example +* var azure = require('azure-storage'); +* var tableService = azure.createTableService(); +* var task1 = { +* PartitionKey : {'_': 'tasksSeattle', '$':'Edm.String'}, +* RowKey: {'_': '1', '$':'Edm.String'}, +* Description: {'_': 'Take out the trash', '$':'Edm.String'}, +* DueDate: {'_': new Date(2011, 12, 14, 12), '$':'Edm.DateTime'} +* }; +* tableService.insertEntity('tasktable', task1, function(error) { +* if(!error) { +* // Entity inserted +* } +* }); +*/ +TableService.prototype.insertEntity = function (table, entityDescriptor, optionsOrCallback, callback) { + this._performEntityOperation(TableConstants.Operations.INSERT, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Inserts or updates a new entity into a table. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the entity information. +* `response` will contain information related to this operation. +*/ +TableService.prototype.insertOrReplaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) { + this._performEntityOperation(TableConstants.Operations.INSERT_OR_REPLACE, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Replaces an existing entity within a table. To replace conditionally based on etag, set entity['.metadata']['etag']. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the entity information. +* `response` will contain information related to this operation. +*/ +TableService.prototype.replaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) { + this._performEntityOperation(TableConstants.Operations.REPLACE, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Updates an existing entity within a table by merging new property values into the entity. To merge conditionally based on etag, set entity['.metadata']['etag']. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the entity information. +* response` will contain information related to this operation. +*/ +TableService.prototype.mergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) { + this._performEntityOperation(TableConstants.Operations.MERGE, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Inserts or updates an existing entity within a table by merging new property values into the entity. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain the entity information. +* `response` will contain information related to this operation. +*/ +TableService.prototype.insertOrMergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) { + this._performEntityOperation(TableConstants.Operations.INSERT_OR_MERGE, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Deletes an entity within a table. To delete conditionally based on etag, set entity['.metadata']['etag']. +* +* @this {TableService} +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResponse} callback `error` will contain information if an error occurs; +* `response` will contain information related to this operation. +*/ +TableService.prototype.deleteEntity = function (table, entityDescriptor, optionsOrCallback, callback) { + this._performEntityOperation(TableConstants.Operations.DELETE, table, entityDescriptor, optionsOrCallback, callback); +}; + +/** +* Executes the operations in the batch. +* +* @this {TableService} +* @param {string} table The table name. +* @param {TableBatch} batch The table batch to execute. +* @param {object} [options] The create options or callback function. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `result` will contain responses for each operation executed in the batch; +* `result.entity` will contain the entity information for each operation executed. +* `result.response` will contain the response for each operations executed. +* `response` will contain information related to this operation. +*/ +TableService.prototype.executeBatch = function (table, batch, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('executeBatch', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.object(batch, 'batch'); + v.callback(callback); + }); + + if(!batch.hasOperations()) { + throw new Error(SR.EMPTY_BATCH); + } + + var options = extend(true, {}, userOptions); + + var batchResult = new BatchResult(this, table, batch.operations); + var webResource = batchResult.constructWebResource(); + + var body = batchResult.serialize(); + webResource.withBody(body); + webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body, 'utf8')); + + var processResponseCallback = function (responseObject, next) { + var responseObjects = batchResult.parse(responseObject); + + var noError = true; + // if the batch was unsuccesful, there will be a single response indicating the error + if (responseObjects && responseObjects.length > 0) { + responseObjects.forEach(function(item){ + if(noError && !item.response.isSuccessful){ + responseObject = item; + noError = false; + } + }); + } + + if (noError) { + responseObject.operationResponses = responseObjects; + } + + var finalCallback = function (returnObject) { + // perform final callback + callback(returnObject.error, returnObject.operationResponses, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +// Private methods + +/** +* Checks whether or not a table exists on the service. +* @ignore +* +* @this {TableService} +* @param {string} table The table name. +* @param {string} primaryOnly If true, the request will be executed against the primary storage location. +* @param {object} [options] The request options. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {Function(error, result, response)} callback `error` will contain information if an error occurs; +* otherwise `result` will contain +* the table information including `exists` boolean member. +* `response` will contain information related to this operation. +*/ +TableService.prototype._doesTableExist = function (table, primaryOnly, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('doesTableExist', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + + if(primaryOnly === false) { + options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY; + } + + var webResource = WebResource.get('Tables(\'' + table + '\')'); + webResource.withHeader(HeaderConstants.ACCEPT, this.defaultPayloadFormat); + + var processResponseCallback = function (responseObject, next) { + responseObject.tableResult = {}; + responseObject.tableResult.isSuccessful = responseObject.error ? false : true; + responseObject.tableResult.statusCode = responseObject.response === null || responseObject.response === undefined ? undefined : responseObject.response.statusCode; + responseObject.tableResult.TableName = table; + + if(!responseObject.error){ + responseObject.tableResult.exists = true; + } else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) { + responseObject.error = null; + responseObject.tableResult.exists = false; + responseObject.response.isSuccessful = true; + } + + var finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.tableResult, returnObject.response); + }; + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, null, options, processResponseCallback); +}; + +/** +* Performs a table operation. +* +* @this {TableService} +* @param {string} operation The operation to perform. +* @param {string} table The table name. +* @param {object} entityDescriptor The entity descriptor. +* @param {object} [options] The create options or callback function. +* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false. +* @param {string} [options.payloadFormat] The payload format to use for the request. +* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. +* Please see StorageUtilities.LocationMode for the possible values. +* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. +* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. +* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. +* The maximum execution time interval begins at the time that the client begins building the request. The maximum +* execution time is checked intermittently while performing requests, and before executing retries. +* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. +* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. +* The default value is false. +* @param {errorOrResult} callback `error` will contain information if an error occurs; +* otherwise `entity` will contain the entity information. +* `response` will contain information related to this operation. +* @ignore +*/ +TableService.prototype._performEntityOperation = function (operation, table, entityDescriptor, optionsOrCallback, callback) { + var userOptions; + azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; }); + + validate.validateArgs('entityOperation', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + v.object(entityDescriptor, 'entityDescriptor'); + + if(typeof entityDescriptor.PartitionKey !== 'string') { + v.object(entityDescriptor.PartitionKey, 'entityDescriptor.PartitionKey'); + v.stringAllowEmpty(entityDescriptor.PartitionKey._, 'entityDescriptor.PartitionKey._'); + } + + if(typeof entityDescriptor.RowKey !== 'string') { + v.object(entityDescriptor.RowKey, 'entityDescriptor.RowKey'); + v.stringAllowEmpty(entityDescriptor.RowKey._, 'entityDescriptor.RowKey._'); + } + v.callback(callback); + }); + + var options = extend(true, {}, userOptions); + options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat; + + var webResource = RequestHandler.constructEntityWebResource(operation, table, entityDescriptor, options); + + var processResponseCallback = function (responseObject, next) { + var finalCallback; + if (operation === TableConstants.Operations.DELETE) { + finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.response); + }; + } else { + responseObject.entityResponse = null; + if (!responseObject.error) { + responseObject.entityResponse = entityResult.parseEntity(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver); + } + + finalCallback = function (returnObject) { + callback(returnObject.error, returnObject.entityResponse, returnObject.response); + }; + } + + next(responseObject, finalCallback); + }; + + this.performRequest(webResource, webResource.body, options, processResponseCallback); +}; + +/** +* Retrieves a table URL. +* +* @param {string} table The table name. +* @param {string} [sasToken] The Shared Access Signature token. +* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint. +* @return {string} The formatted URL string. +* @example +* var azure = require('azure-storage'); +* var tableService = azure.createTableService(); +* var sharedAccessPolicy = { +* AccessPolicy: { +* Permissions: azure.TableUtilities.SharedAccessPermissions.QUERY, +* Start: startDate, +* Expiry: expiryDate +* }, +* }; +* +* var sasToken = tableService.generateSharedAccessSignature(table, sharedAccessPolicy); +* var sasUrl = tableService.getUrl(table, sasToken); +*/ +TableService.prototype.getUrl = function (table, sasToken, primary) { + validate.validateArgs('getUrl', function (v) { + v.string(table, 'table'); + v.tableNameIsValid(table); + }); + + return this._getUrl(table, sasToken, primary); +}; + +/** +* Given the partition key, row key, property name, property value, +* and the property Edm type if given by the service, returns the Edm type of the property. +* @typedef {function} TableService~propertyResolver +* @param {object} pk The partition key. +* @param {object} rk The row key. +* @param {string} name The property name. +* @param {object} value The property value. +* @param {string} type The EDM type. +*/ + +/** +* Returns entities matched by a query. +* @callback TableService~queryResponse +* @param {object} error If an error occurs, the error information. +* @param {object} entities The entities returned by the query. +* @param {object} queryResultContinuation If more matching entities exist, and could not be returned, +* a continuation token that can be used to retrieve more results. +* @param {object} response Information related to this operation. +*/ + +module.exports = TableService; \ No newline at end of file diff --git a/node_modules/azure-storage/lib/services/table/tableutilities.js b/node_modules/azure-storage/lib/services/table/tableutilities.js new file mode 100644 index 000000000..c3f3d4e16 --- /dev/null +++ b/node_modules/azure-storage/lib/services/table/tableutilities.js @@ -0,0 +1,154 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// + +// Expose 'HeaderConstants'. +exports = module.exports; + +/** +* Defines constants, enums, and utility functions for use with the Table service. +* @namespace TableUtilities +*/ +var TableUtilities = { + /** + * Permission types. + * + * @const + * @enum {string} + */ + SharedAccessPermissions: { + QUERY: 'r', + ADD: 'a', + UPDATE: 'u', + DELETE: 'd' + }, + + /** + * Payload Format. + * + * @const + * @enum {string} + */ + PayloadFormat: { + FULL_METADATA: 'application/json;odata=fullmetadata', + MINIMAL_METADATA: 'application/json;odata=minimalmetadata', + NO_METADATA: 'application/json;odata=nometadata' + }, + + /** + * Defines the set of Boolean operators for constructing queries. + * + * @const + * @enum {string} + */ + TableOperators: { + AND: 'and', + NOT: 'not', + OR: 'or' + }, + + /** + * Filter property comparison operators. + * + * @const + * @enum {string} + */ + QueryComparisons: { + EQUAL: 'eq', + NOT_EQUAL: 'ne', + GREATER_THAN: 'gt', + GREATER_THAN_OR_EQUAL: 'ge', + LESS_THAN: 'lt', + LESS_THAN_OR_EQUAL: 'le' + }, + + /** + * Edm types. + * + * @const + * @enum {string} + */ + EdmType: { + STRING: 'Edm.String', + BINARY: 'Edm.Binary', + INT64: 'Edm.Int64', + INT32: 'Edm.Int32', + DOUBLE: 'Edm.Double', + DATETIME: 'Edm.DateTime', + GUID: 'Edm.Guid', + BOOLEAN: 'Edm.Boolean' + }, + + /** + * A helper to create table entities. + * + * @example + * var entGen = TableUtilities.entityGenerator; + * var entity = { PartitionKey: entGen.String('part2'), + * RowKey: entGen.String('row1'), + * boolValue: entGen.Boolean(true), + * intValue: entGen.Int32(42), + * dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))), + * }; + */ + entityGenerator: (function() + { + var EntityProperty = function (value, type) { + var entityProperty = { _:value}; + if (type) { + entityProperty['$'] = type; + } + return entityProperty; + }; + + return { + EntityProperty : EntityProperty, + + Int32 : function(value) { + return new EntityProperty(value, 'Edm.Int32'); + }, + + Int64 : function(value) { + return new EntityProperty(value, 'Edm.Int64'); + }, + + Binary : function(value) { + return new EntityProperty(value, 'Edm.Binary'); + }, + + Boolean : function(value) { + return new EntityProperty(value, 'Edm.Boolean'); + }, + + String : function(value) { + return new EntityProperty(value, 'Edm.String'); + }, + + Guid : function(value) { + return new EntityProperty(value, 'Edm.Guid'); + }, + + Double : function(value) { + return new EntityProperty(value, 'Edm.Double'); + }, + + DateTime : function(value) { + return new EntityProperty(value, 'Edm.DateTime'); + } + }; + })() +}; + +module.exports = TableUtilities; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/.bin/uuid b/node_modules/azure-storage/node_modules/.bin/uuid new file mode 100644 index 000000000..1315932ce --- /dev/null +++ b/node_modules/azure-storage/node_modules/.bin/uuid @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=`dirname "$0"` + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../uuid/bin/uuid" "$@" + ret=$? +else + node "$basedir/../uuid/bin/uuid" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/azure-storage/node_modules/.bin/uuid.cmd b/node_modules/azure-storage/node_modules/.bin/uuid.cmd new file mode 100644 index 000000000..da52d68ad --- /dev/null +++ b/node_modules/azure-storage/node_modules/.bin/uuid.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\uuid\bin\uuid" %* +) \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/request/CHANGELOG.md b/node_modules/azure-storage/node_modules/request/CHANGELOG.md new file mode 100644 index 000000000..af76719b4 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/CHANGELOG.md @@ -0,0 +1,674 @@ +## Change Log + +### v2.81.0 (2017/03/09) +- [#2584](https://github.com/request/request/pull/2584) Security issue: Upgrade qs to version 6.4.0 (@sergejmueller) +- [#2574](https://github.com/request/request/pull/2574) Migrating to safe-buffer for improved security. (@mikeal) +- [#2573](https://github.com/request/request/pull/2573) fixes #2572 (@ahmadnassri) + +### v2.80.0 (2017/03/04) +- [#2571](https://github.com/request/request/pull/2571) Correctly format the Host header for IPv6 addresses (@JamesMGreene) +- [#2558](https://github.com/request/request/pull/2558) Update README.md example snippet (@FredKSchott) +- [#2221](https://github.com/request/request/pull/2221) Adding a simple Response object reference in argument specification (@calamarico) +- [#2452](https://github.com/request/request/pull/2452) Adds .timings array with DNC, TCP, request and response times (@nicjansma) +- [#2553](https://github.com/request/request/pull/2553) add ISSUE_TEMPLATE, move PR template (@FredKSchott) +- [#2539](https://github.com/request/request/pull/2539) Create PULL_REQUEST_TEMPLATE.md (@FredKSchott) +- [#2524](https://github.com/request/request/pull/2524) Update caseless to version 0.12.0 🚀 (@greenkeeperio-bot) +- [#2460](https://github.com/request/request/pull/2460) Fix wrong MIME type in example (@OwnageIsMagic) +- [#2514](https://github.com/request/request/pull/2514) Change tags to keywords in package.json (@humphd) +- [#2492](https://github.com/request/request/pull/2492) More lenient gzip decompression (@addaleax) + +### v2.79.0 (2016/11/18) +- [#2368](https://github.com/request/request/pull/2368) Fix typeof check in test-pool.js (@forivall) +- [#2394](https://github.com/request/request/pull/2394) Use `files` in package.json (@SimenB) +- [#2463](https://github.com/request/request/pull/2463) AWS support for session tokens for temporary credentials (@simov) +- [#2467](https://github.com/request/request/pull/2467) Migrate to uuid (@simov, @antialias) +- [#2459](https://github.com/request/request/pull/2459) Update taper to version 0.5.0 🚀 (@greenkeeperio-bot) +- [#2448](https://github.com/request/request/pull/2448) Make other connect timeout test more reliable too (@mscdex) + +### v2.78.0 (2016/11/03) +- [#2447](https://github.com/request/request/pull/2447) Always set request timeout on keep-alive connections (@mscdex) + +### v2.77.0 (2016/11/03) +- [#2439](https://github.com/request/request/pull/2439) Fix socket 'connect' listener handling (@mscdex) +- [#2442](https://github.com/request/request/pull/2442) 👻😱 Node.js 0.10 is unmaintained 😱👻 (@greenkeeperio-bot) +- [#2435](https://github.com/request/request/pull/2435) Add followOriginalHttpMethod to redirect to original HTTP method (@kirrg001) +- [#2414](https://github.com/request/request/pull/2414) Improve test-timeout reliability (@mscdex) + +### v2.76.0 (2016/10/25) +- [#2424](https://github.com/request/request/pull/2424) Handle buffers directly instead of using "bl" (@zertosh) +- [#2415](https://github.com/request/request/pull/2415) Re-enable timeout tests on Travis + other fixes (@mscdex) +- [#2431](https://github.com/request/request/pull/2431) Improve timeouts accuracy and node v6.8.0+ compatibility (@mscdex, @greenkeeperio-bot) +- [#2428](https://github.com/request/request/pull/2428) Update qs to version 6.3.0 🚀 (@greenkeeperio-bot) +- [#2420](https://github.com/request/request/pull/2420) change .on to .once, remove possible memory leaks (@duereg) +- [#2426](https://github.com/request/request/pull/2426) Remove "isFunction" helper in favor of "typeof" check (@zertosh) +- [#2425](https://github.com/request/request/pull/2425) Simplify "defer" helper creation (@zertosh) +- [#2402](https://github.com/request/request/pull/2402) form-data@2.1.1 breaks build 🚨 (@greenkeeperio-bot) +- [#2393](https://github.com/request/request/pull/2393) Update form-data to version 2.1.0 🚀 (@greenkeeperio-bot) + +### v2.75.0 (2016/09/17) +- [#2381](https://github.com/request/request/pull/2381) Drop support for Node 0.10 (@simov) +- [#2377](https://github.com/request/request/pull/2377) Update form-data to version 2.0.0 🚀 (@greenkeeperio-bot) +- [#2353](https://github.com/request/request/pull/2353) Add greenkeeper ignored packages (@simov) +- [#2351](https://github.com/request/request/pull/2351) Update karma-tap to version 3.0.1 🚀 (@greenkeeperio-bot) +- [#2348](https://github.com/request/request/pull/2348) form-data@1.0.1 breaks build 🚨 (@greenkeeperio-bot) +- [#2349](https://github.com/request/request/pull/2349) Check error type instead of string (@scotttrinh) + +### v2.74.0 (2016/07/22) +- [#2295](https://github.com/request/request/pull/2295) Update tough-cookie to 2.3.0 (@stash-sfdc) +- [#2280](https://github.com/request/request/pull/2280) Update karma-tap to version 2.0.1 🚀 (@greenkeeperio-bot) + +### v2.73.0 (2016/07/09) +- [#2240](https://github.com/request/request/pull/2240) Remove connectionErrorHandler to fix #1903 (@zarenner) +- [#2251](https://github.com/request/request/pull/2251) tape@4.6.0 breaks build 🚨 (@greenkeeperio-bot) +- [#2225](https://github.com/request/request/pull/2225) Update docs (@ArtskydJ) +- [#2203](https://github.com/request/request/pull/2203) Update browserify to version 13.0.1 🚀 (@greenkeeperio-bot) +- [#2275](https://github.com/request/request/pull/2275) Update karma to version 1.1.1 🚀 (@greenkeeperio-bot) +- [#2204](https://github.com/request/request/pull/2204) Add codecov.yml and disable PR comments (@simov) +- [#2212](https://github.com/request/request/pull/2212) Fix link to http.IncomingMessage documentation (@nazieb) +- [#2208](https://github.com/request/request/pull/2208) Update to form-data RC4 and pass null values to it (@simov) +- [#2207](https://github.com/request/request/pull/2207) Move aws4 require statement to the top (@simov) +- [#2199](https://github.com/request/request/pull/2199) Update karma-coverage to version 1.0.0 🚀 (@greenkeeperio-bot) +- [#2206](https://github.com/request/request/pull/2206) Update qs to version 6.2.0 🚀 (@greenkeeperio-bot) +- [#2205](https://github.com/request/request/pull/2205) Use server-destory to close hanging sockets in tests (@simov) +- [#2200](https://github.com/request/request/pull/2200) Update karma-cli to version 1.0.0 🚀 (@greenkeeperio-bot) + +### v2.72.0 (2016/04/17) +- [#2176](https://github.com/request/request/pull/2176) Do not try to pipe Gzip responses with no body (@simov) +- [#2175](https://github.com/request/request/pull/2175) Add 'delete' alias for the 'del' API method (@simov, @MuhanZou) +- [#2172](https://github.com/request/request/pull/2172) Add support for deflate content encoding (@czardoz) +- [#2169](https://github.com/request/request/pull/2169) Add callback option (@simov) +- [#2165](https://github.com/request/request/pull/2165) Check for self.req existence inside the write method (@simov) +- [#2167](https://github.com/request/request/pull/2167) Fix TravisCI badge reference master branch (@a0viedo) + +### v2.71.0 (2016/04/12) +- [#2164](https://github.com/request/request/pull/2164) Catch errors from the underlying http module (@simov) + +### v2.70.0 (2016/04/05) +- [#2147](https://github.com/request/request/pull/2147) Update eslint to version 2.5.3 🚀 (@simov, @greenkeeperio-bot) +- [#2009](https://github.com/request/request/pull/2009) Support JSON stringify replacer argument. (@elyobo) +- [#2142](https://github.com/request/request/pull/2142) Update eslint to version 2.5.1 🚀 (@greenkeeperio-bot) +- [#2128](https://github.com/request/request/pull/2128) Update browserify-istanbul to version 2.0.0 🚀 (@greenkeeperio-bot) +- [#2115](https://github.com/request/request/pull/2115) Update eslint to version 2.3.0 🚀 (@simov, @greenkeeperio-bot) +- [#2089](https://github.com/request/request/pull/2089) Fix badges (@simov) +- [#2092](https://github.com/request/request/pull/2092) Update browserify-istanbul to version 1.0.0 🚀 (@greenkeeperio-bot) +- [#2079](https://github.com/request/request/pull/2079) Accept read stream as body option (@simov) +- [#2070](https://github.com/request/request/pull/2070) Update bl to version 1.1.2 🚀 (@greenkeeperio-bot) +- [#2063](https://github.com/request/request/pull/2063) Up bluebird and oauth-sign (@simov) +- [#2058](https://github.com/request/request/pull/2058) Karma fixes for latest versions (@eiriksm) +- [#2057](https://github.com/request/request/pull/2057) Update contributing guidelines (@simov) +- [#2054](https://github.com/request/request/pull/2054) Update qs to version 6.1.0 🚀 (@greenkeeperio-bot) + +### v2.69.0 (2016/01/27) +- [#2041](https://github.com/request/request/pull/2041) restore aws4 as regular dependency (@rmg) + +### v2.68.0 (2016/01/27) +- [#2036](https://github.com/request/request/pull/2036) Add AWS Signature Version 4 (@simov, @mirkods) +- [#2022](https://github.com/request/request/pull/2022) Convert numeric multipart bodies to string (@simov, @feross) +- [#2024](https://github.com/request/request/pull/2024) Update har-validator dependency for nsp advisory #76 (@TylerDixon) +- [#2016](https://github.com/request/request/pull/2016) Update qs to version 6.0.2 🚀 (@greenkeeperio-bot) +- [#2007](https://github.com/request/request/pull/2007) Use the `extend` module instead of util._extend (@simov) +- [#2003](https://github.com/request/request/pull/2003) Update browserify to version 13.0.0 🚀 (@greenkeeperio-bot) +- [#1989](https://github.com/request/request/pull/1989) Update buffer-equal to version 1.0.0 🚀 (@greenkeeperio-bot) +- [#1956](https://github.com/request/request/pull/1956) Check form-data content-length value before setting up the header (@jongyoonlee) +- [#1958](https://github.com/request/request/pull/1958) Use IncomingMessage.destroy method (@simov) +- [#1952](https://github.com/request/request/pull/1952) Adds example for Tor proxy (@prometheansacrifice) +- [#1943](https://github.com/request/request/pull/1943) Update eslint to version 1.10.3 🚀 (@simov, @greenkeeperio-bot) +- [#1924](https://github.com/request/request/pull/1924) Update eslint to version 1.10.1 🚀 (@greenkeeperio-bot) +- [#1915](https://github.com/request/request/pull/1915) Remove content-length and transfer-encoding headers from defaultProxyHeaderWhiteList (@yaxia) + +### v2.67.0 (2015/11/19) +- [#1913](https://github.com/request/request/pull/1913) Update http-signature to version 1.1.0 🚀 (@greenkeeperio-bot) + +### v2.66.0 (2015/11/18) +- [#1906](https://github.com/request/request/pull/1906) Update README URLs based on HTTP redirects (@ReadmeCritic) +- [#1905](https://github.com/request/request/pull/1905) Convert typed arrays into regular buffers (@simov) +- [#1902](https://github.com/request/request/pull/1902) node-uuid@1.4.7 breaks build 🚨 (@greenkeeperio-bot) +- [#1894](https://github.com/request/request/pull/1894) Fix tunneling after redirection from https (Original: #1881) (@simov, @falms) +- [#1893](https://github.com/request/request/pull/1893) Update eslint to version 1.9.0 🚀 (@greenkeeperio-bot) +- [#1852](https://github.com/request/request/pull/1852) Update eslint to version 1.7.3 🚀 (@simov, @greenkeeperio-bot, @paulomcnally, @michelsalib, @arbaaz, @nsklkn, @LoicMahieu, @JoshWillik, @jzaefferer, @ryanwholey, @djchie, @thisconnect, @mgenereu, @acroca, @Sebmaster, @KoltesDigital) +- [#1876](https://github.com/request/request/pull/1876) Implement loose matching for har mime types (@simov) +- [#1875](https://github.com/request/request/pull/1875) Update bluebird to version 3.0.2 🚀 (@simov, @greenkeeperio-bot) +- [#1871](https://github.com/request/request/pull/1871) Update browserify to version 12.0.1 🚀 (@greenkeeperio-bot) +- [#1866](https://github.com/request/request/pull/1866) Add missing quotes on x-token property in README (@miguelmota) +- [#1874](https://github.com/request/request/pull/1874) Fix typo in README.md (@gswalden) +- [#1860](https://github.com/request/request/pull/1860) Improve referer header tests and docs (@simov) +- [#1861](https://github.com/request/request/pull/1861) Remove redundant call to Stream constructor (@watson) +- [#1857](https://github.com/request/request/pull/1857) Fix Referer header to point to the original host name (@simov) +- [#1850](https://github.com/request/request/pull/1850) Update karma-coverage to version 0.5.3 🚀 (@greenkeeperio-bot) +- [#1847](https://github.com/request/request/pull/1847) Use node's latest version when building (@simov) +- [#1836](https://github.com/request/request/pull/1836) Tunnel: fix wrong property name (@KoltesDigital) +- [#1820](https://github.com/request/request/pull/1820) Set href as request.js uses it (@mgenereu) +- [#1840](https://github.com/request/request/pull/1840) Update http-signature to version 1.0.2 🚀 (@greenkeeperio-bot) +- [#1845](https://github.com/request/request/pull/1845) Update istanbul to version 0.4.0 🚀 (@greenkeeperio-bot) + +### v2.65.0 (2015/10/11) +- [#1833](https://github.com/request/request/pull/1833) Update aws-sign2 to version 0.6.0 🚀 (@greenkeeperio-bot) +- [#1811](https://github.com/request/request/pull/1811) Enable loose cookie parsing in tough-cookie (@Sebmaster) +- [#1830](https://github.com/request/request/pull/1830) Bring back tilde ranges for all dependencies (@simov) +- [#1821](https://github.com/request/request/pull/1821) Implement support for RFC 2617 MD5-sess algorithm. (@BigDSK) +- [#1828](https://github.com/request/request/pull/1828) Updated qs dependency to 5.2.0 (@acroca) +- [#1818](https://github.com/request/request/pull/1818) Extract `readResponseBody` method out of `onRequestResponse` (@pvoisin) +- [#1819](https://github.com/request/request/pull/1819) Run stringify once (@mgenereu) +- [#1814](https://github.com/request/request/pull/1814) Updated har-validator to version 2.0.2 (@greenkeeperio-bot) +- [#1807](https://github.com/request/request/pull/1807) Updated tough-cookie to version 2.1.0 (@greenkeeperio-bot) +- [#1800](https://github.com/request/request/pull/1800) Add caret ranges for devDependencies, except eslint (@simov) +- [#1799](https://github.com/request/request/pull/1799) Updated karma-browserify to version 4.4.0 (@greenkeeperio-bot) +- [#1797](https://github.com/request/request/pull/1797) Updated tape to version 4.2.0 (@greenkeeperio-bot) +- [#1788](https://github.com/request/request/pull/1788) Pinned all dependencies (@greenkeeperio-bot) + +### v2.64.0 (2015/09/25) +- [#1787](https://github.com/request/request/pull/1787) npm ignore examples, release.sh and disabled.appveyor.yml (@thisconnect) +- [#1775](https://github.com/request/request/pull/1775) Fix typo in README.md (@djchie) +- [#1776](https://github.com/request/request/pull/1776) Changed word 'conjuction' to read 'conjunction' in README.md (@ryanwholey) +- [#1785](https://github.com/request/request/pull/1785) Revert: Set default application/json content-type when using json option #1772 (@simov) + +### v2.63.0 (2015/09/21) +- [#1772](https://github.com/request/request/pull/1772) Set default application/json content-type when using json option (@jzaefferer) + +### v2.62.0 (2015/09/15) +- [#1768](https://github.com/request/request/pull/1768) Add node 4.0 to the list of build targets (@simov) +- [#1767](https://github.com/request/request/pull/1767) Query strings now cooperate with unix sockets (@JoshWillik) +- [#1750](https://github.com/request/request/pull/1750) Revert doc about installation of tough-cookie added in #884 (@LoicMahieu) +- [#1746](https://github.com/request/request/pull/1746) Missed comma in Readme (@nsklkn) +- [#1743](https://github.com/request/request/pull/1743) Fix options not being initialized in defaults method (@simov) + +### v2.61.0 (2015/08/19) +- [#1721](https://github.com/request/request/pull/1721) Minor fix in README.md (@arbaaz) +- [#1733](https://github.com/request/request/pull/1733) Avoid useless Buffer transformation (@michelsalib) +- [#1726](https://github.com/request/request/pull/1726) Update README.md (@paulomcnally) +- [#1715](https://github.com/request/request/pull/1715) Fix forever option in node > 0.10 #1709 (@calibr) +- [#1716](https://github.com/request/request/pull/1716) Do not create Buffer from Object in setContentLength(iojs v3.0 issue) (@calibr) +- [#1711](https://github.com/request/request/pull/1711) Add ability to detect connect timeouts (@kevinburke) +- [#1712](https://github.com/request/request/pull/1712) Set certificate expiration to August 2, 2018 (@kevinburke) +- [#1700](https://github.com/request/request/pull/1700) debug() when JSON.parse() on a response body fails (@phillipj) + +### v2.60.0 (2015/07/21) +- [#1687](https://github.com/request/request/pull/1687) Fix caseless bug - content-type not being set for multipart/form-data (@simov, @garymathews) + +### v2.59.0 (2015/07/20) +- [#1671](https://github.com/request/request/pull/1671) Add tests and docs for using the agent, agentClass, agentOptions and forever options. Forever option defaults to using http(s).Agent in node 0.12+ (@simov) +- [#1679](https://github.com/request/request/pull/1679) Fix - do not remove OAuth param when using OAuth realm (@simov, @jhalickman) +- [#1668](https://github.com/request/request/pull/1668) updated dependencies (@deamme) +- [#1656](https://github.com/request/request/pull/1656) Fix form method (@simov) +- [#1651](https://github.com/request/request/pull/1651) Preserve HEAD method when using followAllRedirects (@simov) +- [#1652](https://github.com/request/request/pull/1652) Update `encoding` option documentation in README.md (@daniel347x) +- [#1650](https://github.com/request/request/pull/1650) Allow content-type overriding when using the `form` option (@simov) +- [#1646](https://github.com/request/request/pull/1646) Clarify the nature of setting `ca` in `agentOptions` (@jeffcharles) + +### v2.58.0 (2015/06/16) +- [#1638](https://github.com/request/request/pull/1638) Use the `extend` module to deep extend in the defaults method (@simov) +- [#1631](https://github.com/request/request/pull/1631) Move tunnel logic into separate module (@simov) +- [#1634](https://github.com/request/request/pull/1634) Fix OAuth query transport_method (@simov) +- [#1603](https://github.com/request/request/pull/1603) Add codecov (@simov) + +### v2.57.0 (2015/05/31) +- [#1615](https://github.com/request/request/pull/1615) Replace '.client' with '.socket' as the former was deprecated in 2.2.0. (@ChALkeR) + +### v2.56.0 (2015/05/28) +- [#1610](https://github.com/request/request/pull/1610) Bump module dependencies (@simov) +- [#1600](https://github.com/request/request/pull/1600) Extract the querystring logic into separate module (@simov) +- [#1607](https://github.com/request/request/pull/1607) Re-generate certificates (@simov) +- [#1599](https://github.com/request/request/pull/1599) Move getProxyFromURI logic below the check for Invaild URI (#1595) (@simov) +- [#1598](https://github.com/request/request/pull/1598) Fix the way http verbs are defined in order to please intellisense IDEs (@simov, @flannelJesus) +- [#1591](https://github.com/request/request/pull/1591) A few minor fixes: (@simov) +- [#1584](https://github.com/request/request/pull/1584) Refactor test-default tests (according to comments in #1430) (@simov) +- [#1585](https://github.com/request/request/pull/1585) Fixing documentation regarding TLS options (#1583) (@mainakae) +- [#1574](https://github.com/request/request/pull/1574) Refresh the oauth_nonce on redirect (#1573) (@simov) +- [#1570](https://github.com/request/request/pull/1570) Discovered tests that weren't properly running (@seanstrom) +- [#1569](https://github.com/request/request/pull/1569) Fix pause before response arrives (@kevinoid) +- [#1558](https://github.com/request/request/pull/1558) Emit error instead of throw (@simov) +- [#1568](https://github.com/request/request/pull/1568) Fix stall when piping gzipped response (@kevinoid) +- [#1560](https://github.com/request/request/pull/1560) Update combined-stream (@apechimp) +- [#1543](https://github.com/request/request/pull/1543) Initial support for oauth_body_hash on json payloads (@simov, @aesopwolf) +- [#1541](https://github.com/request/request/pull/1541) Fix coveralls (@simov) +- [#1540](https://github.com/request/request/pull/1540) Fix recursive defaults for convenience methods (@simov) +- [#1536](https://github.com/request/request/pull/1536) More eslint style rules (@froatsnook) +- [#1533](https://github.com/request/request/pull/1533) Adding dependency status bar to README.md (@YasharF) +- [#1539](https://github.com/request/request/pull/1539) ensure the latest version of har-validator is included (@ahmadnassri) +- [#1516](https://github.com/request/request/pull/1516) forever+pool test (@devTristan) + +### v2.55.0 (2015/04/05) +- [#1520](https://github.com/request/request/pull/1520) Refactor defaults (@simov) +- [#1525](https://github.com/request/request/pull/1525) Delete request headers with undefined value. (@froatsnook) +- [#1521](https://github.com/request/request/pull/1521) Add promise tests (@simov) +- [#1518](https://github.com/request/request/pull/1518) Fix defaults (@simov) +- [#1515](https://github.com/request/request/pull/1515) Allow static invoking of convenience methods (@simov) +- [#1505](https://github.com/request/request/pull/1505) Fix multipart boundary extraction regexp (@simov) +- [#1510](https://github.com/request/request/pull/1510) Fix basic auth form data (@simov) + +### v2.54.0 (2015/03/24) +- [#1501](https://github.com/request/request/pull/1501) HTTP Archive 1.2 support (@ahmadnassri) +- [#1486](https://github.com/request/request/pull/1486) Add a test for the forever agent (@akshayp) +- [#1500](https://github.com/request/request/pull/1500) Adding handling for no auth method and null bearer (@philberg) +- [#1498](https://github.com/request/request/pull/1498) Add table of contents in readme (@simov) +- [#1477](https://github.com/request/request/pull/1477) Add support for qs options via qsOptions key (@simov) +- [#1496](https://github.com/request/request/pull/1496) Parameters encoded to base 64 should be decoded as UTF-8, not ASCII. (@albanm) +- [#1494](https://github.com/request/request/pull/1494) Update eslint (@froatsnook) +- [#1474](https://github.com/request/request/pull/1474) Require Colon in Basic Auth (@erykwalder) +- [#1481](https://github.com/request/request/pull/1481) Fix baseUrl and redirections. (@burningtree) +- [#1469](https://github.com/request/request/pull/1469) Feature/base url (@froatsnook) +- [#1459](https://github.com/request/request/pull/1459) Add option to time request/response cycle (including rollup of redirects) (@aaron-em) +- [#1468](https://github.com/request/request/pull/1468) Re-enable io.js/node 0.12 build (@simov, @mikeal, @BBB) +- [#1442](https://github.com/request/request/pull/1442) Fixed the issue with strictSSL tests on 0.12 & io.js by explicitly setting a cipher that matches the cert. (@BBB, @nickmccurdy, @demohi, @simov, @0x4139) +- [#1460](https://github.com/request/request/pull/1460) localAddress or proxy config is lost when redirecting (@simov, @0x4139) +- [#1453](https://github.com/request/request/pull/1453) Test on Node.js 0.12 and io.js with allowed failures (@nickmccurdy, @demohi) +- [#1426](https://github.com/request/request/pull/1426) Fixing tests to pass on io.js and node 0.12 (only test-https.js stiff failing) (@mikeal) +- [#1446](https://github.com/request/request/pull/1446) Missing HTTP referer header with redirects Fixes #1038 (@simov, @guimon) +- [#1428](https://github.com/request/request/pull/1428) Deprecate Node v0.8.x (@nylen) +- [#1436](https://github.com/request/request/pull/1436) Add ability to set a requester without setting default options (@tikotzky) +- [#1435](https://github.com/request/request/pull/1435) dry up verb methods (@sethpollack) +- [#1423](https://github.com/request/request/pull/1423) Allow fully qualified multipart content-type header (@simov) +- [#1430](https://github.com/request/request/pull/1430) Fix recursive requester (@tikotzky) +- [#1429](https://github.com/request/request/pull/1429) Throw error when making HEAD request with a body (@tikotzky) +- [#1419](https://github.com/request/request/pull/1419) Add note that the project is broken in 0.12.x (@nylen) +- [#1413](https://github.com/request/request/pull/1413) Fix basic auth (@simov) +- [#1397](https://github.com/request/request/pull/1397) Improve pipe-from-file tests (@nylen) + +### v2.53.0 (2015/02/02) +- [#1396](https://github.com/request/request/pull/1396) Do not rfc3986 escape JSON bodies (@nylen, @simov) +- [#1392](https://github.com/request/request/pull/1392) Improve `timeout` option description (@watson) + +### v2.52.0 (2015/02/02) +- [#1383](https://github.com/request/request/pull/1383) Add missing HTTPS options that were not being passed to tunnel (@brichard19) (@nylen) +- [#1388](https://github.com/request/request/pull/1388) Upgrade mime-types package version (@roderickhsiao) +- [#1389](https://github.com/request/request/pull/1389) Revise Setup Tunnel Function (@seanstrom) +- [#1374](https://github.com/request/request/pull/1374) Allow explicitly disabling tunneling for proxied https destinations (@nylen) +- [#1376](https://github.com/request/request/pull/1376) Use karma-browserify for tests. Add browser test coverage reporter. (@eiriksm) +- [#1366](https://github.com/request/request/pull/1366) Refactor OAuth into separate module (@simov) +- [#1373](https://github.com/request/request/pull/1373) Rewrite tunnel test to be pure Node.js (@nylen) +- [#1371](https://github.com/request/request/pull/1371) Upgrade test reporter (@nylen) +- [#1360](https://github.com/request/request/pull/1360) Refactor basic, bearer, digest auth logic into separate class (@simov) +- [#1354](https://github.com/request/request/pull/1354) Remove circular dependency from debugging code (@nylen) +- [#1351](https://github.com/request/request/pull/1351) Move digest auth into private prototype method (@simov) +- [#1352](https://github.com/request/request/pull/1352) Update hawk dependency to ~2.3.0 (@mridgway) +- [#1353](https://github.com/request/request/pull/1353) Correct travis-ci badge (@dogancelik) +- [#1349](https://github.com/request/request/pull/1349) Make sure we return on errored browser requests. (@eiriksm) +- [#1346](https://github.com/request/request/pull/1346) getProxyFromURI Extraction Refactor (@seanstrom) +- [#1337](https://github.com/request/request/pull/1337) Standardize test ports on 6767 (@nylen) +- [#1341](https://github.com/request/request/pull/1341) Emit FormData error events as Request error events (@nylen, @rwky) +- [#1343](https://github.com/request/request/pull/1343) Clean up readme badges, and add Travis and Coveralls badges (@nylen) +- [#1345](https://github.com/request/request/pull/1345) Update README.md (@Aaron-Hartwig) +- [#1338](https://github.com/request/request/pull/1338) Always wait for server.close() callback in tests (@nylen) +- [#1342](https://github.com/request/request/pull/1342) Add mock https server and redo start of browser tests for this purpose. (@eiriksm) +- [#1339](https://github.com/request/request/pull/1339) Improve auth docs (@nylen) +- [#1335](https://github.com/request/request/pull/1335) Add support for OAuth plaintext signature method (@simov) +- [#1332](https://github.com/request/request/pull/1332) Add clean script to remove test-browser.js after the tests run (@seanstrom) +- [#1327](https://github.com/request/request/pull/1327) Fix errors generating coverage reports. (@nylen) +- [#1330](https://github.com/request/request/pull/1330) Return empty buffer upon empty response body and encoding is set to null (@seanstrom) +- [#1326](https://github.com/request/request/pull/1326) Use faster container-based infrastructure on Travis (@nylen) +- [#1315](https://github.com/request/request/pull/1315) Implement rfc3986 option (@simov, @nylen, @apoco, @DullReferenceException, @mmalecki, @oliamb, @cliffcrosland, @LewisJEllis, @eiriksm, @poislagarde) +- [#1314](https://github.com/request/request/pull/1314) Detect urlencoded form data header via regex (@simov) +- [#1317](https://github.com/request/request/pull/1317) Improve OAuth1.0 server side flow example (@simov) + +### v2.51.0 (2014/12/10) +- [#1310](https://github.com/request/request/pull/1310) Revert changes introduced in https://github.com/request/request/pull/1282 (@simov) + +### v2.50.0 (2014/12/09) +- [#1308](https://github.com/request/request/pull/1308) Add browser test to keep track of browserify compability. (@eiriksm) +- [#1299](https://github.com/request/request/pull/1299) Add optional support for jsonReviver (@poislagarde) +- [#1277](https://github.com/request/request/pull/1277) Add Coveralls configuration (@simov) +- [#1307](https://github.com/request/request/pull/1307) Upgrade form-data, add back browserify compability. Fixes #455. (@eiriksm) +- [#1305](https://github.com/request/request/pull/1305) Fix typo in README.md (@LewisJEllis) +- [#1288](https://github.com/request/request/pull/1288) Update README.md to explain custom file use case (@cliffcrosland) + +### v2.49.0 (2014/11/28) +- [#1295](https://github.com/request/request/pull/1295) fix(proxy): no-proxy false positive (@oliamb) +- [#1292](https://github.com/request/request/pull/1292) Upgrade `caseless` to 0.8.1 (@mmalecki) +- [#1276](https://github.com/request/request/pull/1276) Set transfer encoding for multipart/related to chunked by default (@simov) +- [#1275](https://github.com/request/request/pull/1275) Fix multipart content-type headers detection (@simov) +- [#1269](https://github.com/request/request/pull/1269) adds streams example for review (@tbuchok) +- [#1238](https://github.com/request/request/pull/1238) Add examples README.md (@simov) + +### v2.48.0 (2014/11/12) +- [#1263](https://github.com/request/request/pull/1263) Fixed a syntax error / typo in README.md (@xna2) +- [#1253](https://github.com/request/request/pull/1253) Add multipart chunked flag (@simov, @nylen) +- [#1251](https://github.com/request/request/pull/1251) Clarify that defaults() does not modify global defaults (@nylen) +- [#1250](https://github.com/request/request/pull/1250) Improve documentation for pool and maxSockets options (@nylen) +- [#1237](https://github.com/request/request/pull/1237) Documenting error handling when using streams (@vmattos) +- [#1244](https://github.com/request/request/pull/1244) Finalize changelog command (@nylen) +- [#1241](https://github.com/request/request/pull/1241) Fix typo (@alexanderGugel) +- [#1223](https://github.com/request/request/pull/1223) Show latest version number instead of "upcoming" in changelog (@nylen) +- [#1236](https://github.com/request/request/pull/1236) Document how to use custom CA in README (#1229) (@hypesystem) +- [#1228](https://github.com/request/request/pull/1228) Support for oauth with RSA-SHA1 signing (@nylen) +- [#1216](https://github.com/request/request/pull/1216) Made json and multipart options coexist (@nylen, @simov) +- [#1225](https://github.com/request/request/pull/1225) Allow header white/exclusive lists in any case. (@RReverser) + +### v2.47.0 (2014/10/26) +- [#1222](https://github.com/request/request/pull/1222) Move from mikeal/request to request/request (@nylen) +- [#1220](https://github.com/request/request/pull/1220) update qs dependency to 2.3.1 (@FredKSchott) +- [#1212](https://github.com/request/request/pull/1212) Improve tests/test-timeout.js (@nylen) +- [#1219](https://github.com/request/request/pull/1219) remove old globalAgent workaround for node 0.4 (@request) +- [#1214](https://github.com/request/request/pull/1214) Remove cruft left over from optional dependencies (@nylen) +- [#1215](https://github.com/request/request/pull/1215) Add proxyHeaderExclusiveList option for proxy-only headers. (@RReverser) +- [#1211](https://github.com/request/request/pull/1211) Allow 'Host' header instead of 'host' and remember case across redirects (@nylen) +- [#1208](https://github.com/request/request/pull/1208) Improve release script (@nylen) +- [#1213](https://github.com/request/request/pull/1213) Support for custom cookie store (@nylen, @mitsuru) +- [#1197](https://github.com/request/request/pull/1197) Clean up some code around setting the agent (@FredKSchott) +- [#1209](https://github.com/request/request/pull/1209) Improve multipart form append test (@simov) +- [#1207](https://github.com/request/request/pull/1207) Update changelog (@nylen) +- [#1185](https://github.com/request/request/pull/1185) Stream multipart/related bodies (@simov) + +### v2.46.0 (2014/10/23) +- [#1198](https://github.com/request/request/pull/1198) doc for TLS/SSL protocol options (@shawnzhu) +- [#1200](https://github.com/request/request/pull/1200) Add a Gitter chat badge to README.md (@gitter-badger) +- [#1196](https://github.com/request/request/pull/1196) Upgrade taper test reporter to v0.3.0 (@nylen) +- [#1199](https://github.com/request/request/pull/1199) Fix lint error: undeclared var i (@nylen) +- [#1191](https://github.com/request/request/pull/1191) Move self.proxy decision logic out of init and into a helper (@FredKSchott) +- [#1190](https://github.com/request/request/pull/1190) Move _buildRequest() logic back into init (@FredKSchott) +- [#1186](https://github.com/request/request/pull/1186) Support Smarter Unix URL Scheme (@FredKSchott) +- [#1178](https://github.com/request/request/pull/1178) update form documentation for new usage (@FredKSchott) +- [#1180](https://github.com/request/request/pull/1180) Enable no-mixed-requires linting rule (@nylen) +- [#1184](https://github.com/request/request/pull/1184) Don't forward authorization header across redirects to different hosts (@nylen) +- [#1183](https://github.com/request/request/pull/1183) Correct README about pre and postamble CRLF using multipart and not mult... (@netpoetica) +- [#1179](https://github.com/request/request/pull/1179) Lint tests directory (@nylen) +- [#1169](https://github.com/request/request/pull/1169) add metadata for form-data file field (@dotcypress) +- [#1173](https://github.com/request/request/pull/1173) remove optional dependencies (@seanstrom) +- [#1165](https://github.com/request/request/pull/1165) Cleanup event listeners and remove function creation from init (@FredKSchott) +- [#1174](https://github.com/request/request/pull/1174) update the request.cookie docs to have a valid cookie example (@seanstrom) +- [#1168](https://github.com/request/request/pull/1168) create a detach helper and use detach helper in replace of nextTick (@seanstrom) +- [#1171](https://github.com/request/request/pull/1171) in post can send form data and use callback (@MiroRadenovic) +- [#1159](https://github.com/request/request/pull/1159) accept charset for x-www-form-urlencoded content-type (@seanstrom) +- [#1157](https://github.com/request/request/pull/1157) Update README.md: body with json=true (@Rob--W) +- [#1164](https://github.com/request/request/pull/1164) Disable tests/test-timeout.js on Travis (@nylen) +- [#1153](https://github.com/request/request/pull/1153) Document how to run a single test (@nylen) +- [#1144](https://github.com/request/request/pull/1144) adds documentation for the "response" event within the streaming section (@tbuchok) +- [#1162](https://github.com/request/request/pull/1162) Update eslintrc file to no longer allow past errors (@FredKSchott) +- [#1155](https://github.com/request/request/pull/1155) Support/use self everywhere (@seanstrom) +- [#1161](https://github.com/request/request/pull/1161) fix no-use-before-define lint warnings (@emkay) +- [#1156](https://github.com/request/request/pull/1156) adding curly brackets to get rid of lint errors (@emkay) +- [#1151](https://github.com/request/request/pull/1151) Fix localAddress test on OS X (@nylen) +- [#1145](https://github.com/request/request/pull/1145) documentation: fix outdated reference to setCookieSync old name in README (@FredKSchott) +- [#1131](https://github.com/request/request/pull/1131) Update pool documentation (@FredKSchott) +- [#1143](https://github.com/request/request/pull/1143) Rewrite all tests to use tape (@nylen) +- [#1137](https://github.com/request/request/pull/1137) Add ability to specifiy querystring lib in options. (@jgrund) +- [#1138](https://github.com/request/request/pull/1138) allow hostname and port in place of host on uri (@cappslock) +- [#1134](https://github.com/request/request/pull/1134) Fix multiple redirects and `self.followRedirect` (@blakeembrey) +- [#1130](https://github.com/request/request/pull/1130) documentation fix: add note about npm test for contributing (@FredKSchott) +- [#1120](https://github.com/request/request/pull/1120) Support/refactor request setup tunnel (@seanstrom) +- [#1129](https://github.com/request/request/pull/1129) linting fix: convert double quote strings to use single quotes (@FredKSchott) +- [#1124](https://github.com/request/request/pull/1124) linting fix: remove unneccesary semi-colons (@FredKSchott) + +### v2.45.0 (2014/10/06) +- [#1128](https://github.com/request/request/pull/1128) Add test for setCookie regression (@nylen) +- [#1127](https://github.com/request/request/pull/1127) added tests around using objects as values in a query string (@bcoe) +- [#1103](https://github.com/request/request/pull/1103) Support/refactor request constructor (@nylen, @seanstrom) +- [#1119](https://github.com/request/request/pull/1119) add basic linting to request library (@FredKSchott) +- [#1121](https://github.com/request/request/pull/1121) Revert "Explicitly use sync versions of cookie functions" (@nylen) +- [#1118](https://github.com/request/request/pull/1118) linting fix: Restructure bad empty if statement (@FredKSchott) +- [#1117](https://github.com/request/request/pull/1117) Fix a bad check for valid URIs (@FredKSchott) +- [#1113](https://github.com/request/request/pull/1113) linting fix: space out operators (@FredKSchott) +- [#1116](https://github.com/request/request/pull/1116) Fix typo in `noProxyHost` definition (@FredKSchott) +- [#1114](https://github.com/request/request/pull/1114) linting fix: Added a `new` operator that was missing when creating and throwing a new error (@FredKSchott) +- [#1096](https://github.com/request/request/pull/1096) No_proxy support (@samcday) +- [#1107](https://github.com/request/request/pull/1107) linting-fix: remove unused variables (@FredKSchott) +- [#1112](https://github.com/request/request/pull/1112) linting fix: Make return values consistent and more straitforward (@FredKSchott) +- [#1111](https://github.com/request/request/pull/1111) linting fix: authPieces was getting redeclared (@FredKSchott) +- [#1105](https://github.com/request/request/pull/1105) Use strict mode in request (@FredKSchott) +- [#1110](https://github.com/request/request/pull/1110) linting fix: replace lazy '==' with more strict '===' (@FredKSchott) +- [#1109](https://github.com/request/request/pull/1109) linting fix: remove function call from if-else conditional statement (@FredKSchott) +- [#1102](https://github.com/request/request/pull/1102) Fix to allow setting a `requester` on recursive calls to `request.defaults` (@tikotzky) +- [#1095](https://github.com/request/request/pull/1095) Tweaking engines in package.json (@pdehaan) +- [#1082](https://github.com/request/request/pull/1082) Forward the socket event from the httpModule request (@seanstrom) +- [#972](https://github.com/request/request/pull/972) Clarify gzip handling in the README (@kevinoid) +- [#1089](https://github.com/request/request/pull/1089) Mention that encoding defaults to utf8, not Buffer (@stuartpb) +- [#1088](https://github.com/request/request/pull/1088) Fix cookie example in README.md and make it more clear (@pipi32167) +- [#1027](https://github.com/request/request/pull/1027) Add support for multipart form data in request options. (@crocket) +- [#1076](https://github.com/request/request/pull/1076) use Request.abort() to abort the request when the request has timed-out (@seanstrom) +- [#1068](https://github.com/request/request/pull/1068) add optional postamble required by .NET multipart requests (@netpoetica) + +### v2.43.0 (2014/09/18) +- [#1057](https://github.com/request/request/pull/1057) Defaults should not overwrite defined options (@davidwood) +- [#1046](https://github.com/request/request/pull/1046) Propagate datastream errors, useful in case gzip fails. (@ZJONSSON, @Janpot) +- [#1063](https://github.com/request/request/pull/1063) copy the input headers object #1060 (@finnp) +- [#1031](https://github.com/request/request/pull/1031) Explicitly use sync versions of cookie functions (@ZJONSSON) +- [#1056](https://github.com/request/request/pull/1056) Fix redirects when passing url.parse(x) as URL to convenience method (@nylen) + +### v2.42.0 (2014/09/04) +- [#1053](https://github.com/request/request/pull/1053) Fix #1051 Parse auth properly when using non-tunneling proxy (@isaacs) + +### v2.41.0 (2014/09/04) +- [#1050](https://github.com/request/request/pull/1050) Pass whitelisted headers to tunneling proxy. Organize all tunneling logic. (@isaacs, @Feldhacker) +- [#1035](https://github.com/request/request/pull/1035) souped up nodei.co badge (@rvagg) +- [#1048](https://github.com/request/request/pull/1048) Aws is now possible over a proxy (@steven-aerts) +- [#1039](https://github.com/request/request/pull/1039) extract out helper functions to a helper file (@seanstrom) +- [#1021](https://github.com/request/request/pull/1021) Support/refactor indexjs (@seanstrom) +- [#1033](https://github.com/request/request/pull/1033) Improve and document debug options (@nylen) +- [#1034](https://github.com/request/request/pull/1034) Fix readme headings (@nylen) +- [#1030](https://github.com/request/request/pull/1030) Allow recursive request.defaults (@tikotzky) +- [#1029](https://github.com/request/request/pull/1029) Fix a couple of typos (@nylen) +- [#675](https://github.com/request/request/pull/675) Checking for SSL fault on connection before reading SSL properties (@VRMink) +- [#989](https://github.com/request/request/pull/989) Added allowRedirect function. Should return true if redirect is allowed or false otherwise (@doronin) +- [#1025](https://github.com/request/request/pull/1025) [fixes #1023] Set self._ended to true once response has ended (@mridgway) +- [#1020](https://github.com/request/request/pull/1020) Add back removed debug metadata (@FredKSchott) +- [#1008](https://github.com/request/request/pull/1008) Moving to module instead of cutomer buffer concatenation. (@mikeal) +- [#770](https://github.com/request/request/pull/770) Added dependency badge for README file; (@timgluz, @mafintosh, @lalitkapoor, @stash, @bobyrizov) +- [#1016](https://github.com/request/request/pull/1016) toJSON no longer results in an infinite loop, returns simple objects (@FredKSchott) +- [#1018](https://github.com/request/request/pull/1018) Remove pre-0.4.4 HTTPS fix (@mmalecki) +- [#1006](https://github.com/request/request/pull/1006) Migrate to caseless, fixes #1001 (@mikeal) +- [#995](https://github.com/request/request/pull/995) Fix parsing array of objects (@sjonnet19) +- [#999](https://github.com/request/request/pull/999) Fix fallback for browserify for optional modules. (@eiriksm) +- [#996](https://github.com/request/request/pull/996) Wrong oauth signature when multiple same param keys exist [updated] (@bengl) + +### v2.40.0 (2014/08/06) +- [#992](https://github.com/request/request/pull/992) Fix security vulnerability. Update qs (@poeticninja) +- [#988](https://github.com/request/request/pull/988) “--” -> “—” (@upisfree) +- [#987](https://github.com/request/request/pull/987) Show optional modules as being loaded by the module that reqeusted them (@iarna) + +### v2.39.0 (2014/07/24) +- [#976](https://github.com/request/request/pull/976) Update README.md (@pvoznenko) + +### v2.38.0 (2014/07/22) +- [#952](https://github.com/request/request/pull/952) Adding support to client certificate with proxy use case (@ofirshaked) +- [#884](https://github.com/request/request/pull/884) Documented tough-cookie installation. (@wbyoung) +- [#935](https://github.com/request/request/pull/935) Correct repository url (@fritx) +- [#963](https://github.com/request/request/pull/963) Update changelog (@nylen) +- [#960](https://github.com/request/request/pull/960) Support gzip with encoding on node pre-v0.9.4 (@kevinoid) +- [#953](https://github.com/request/request/pull/953) Add async Content-Length computation when using form-data (@LoicMahieu) +- [#844](https://github.com/request/request/pull/844) Add support for HTTP[S]_PROXY environment variables. Fixes #595. (@jvmccarthy) +- [#946](https://github.com/request/request/pull/946) defaults: merge headers (@aj0strow) + +### v2.37.0 (2014/07/07) +- [#957](https://github.com/request/request/pull/957) Silence EventEmitter memory leak warning #311 (@watson) +- [#955](https://github.com/request/request/pull/955) check for content-length header before setting it in nextTick (@camilleanne) +- [#951](https://github.com/request/request/pull/951) Add support for gzip content decoding (@kevinoid) +- [#949](https://github.com/request/request/pull/949) Manually enter querystring in form option (@charlespwd) +- [#944](https://github.com/request/request/pull/944) Make request work with browserify (@eiriksm) +- [#943](https://github.com/request/request/pull/943) New mime module (@eiriksm) +- [#927](https://github.com/request/request/pull/927) Bump version of hawk dep. (@samccone) +- [#907](https://github.com/request/request/pull/907) append secureOptions to poolKey (@medovob) + +### v2.35.0 (2014/05/17) +- [#901](https://github.com/request/request/pull/901) Fixes #555 (@pigulla) +- [#897](https://github.com/request/request/pull/897) merge with default options (@vohof) +- [#891](https://github.com/request/request/pull/891) fixes 857 - options object is mutated by calling request (@lalitkapoor) +- [#869](https://github.com/request/request/pull/869) Pipefilter test (@tgohn) +- [#866](https://github.com/request/request/pull/866) Fix typo (@dandv) +- [#861](https://github.com/request/request/pull/861) Add support for RFC 6750 Bearer Tokens (@phedny) +- [#809](https://github.com/request/request/pull/809) upgrade tunnel-proxy to 0.4.0 (@ksato9700) +- [#850](https://github.com/request/request/pull/850) Fix word consistency in readme (@0xNobody) +- [#810](https://github.com/request/request/pull/810) add some exposition to mpu example in README.md (@mikermcneil) +- [#840](https://github.com/request/request/pull/840) improve error reporting for invalid protocols (@FND) +- [#821](https://github.com/request/request/pull/821) added secureOptions back (@nw) +- [#815](https://github.com/request/request/pull/815) Create changelog based on pull requests (@lalitkapoor) + +### v2.34.0 (2014/02/18) +- [#516](https://github.com/request/request/pull/516) UNIX Socket URL Support (@lyuzashi) +- [#801](https://github.com/request/request/pull/801) 794 ignore cookie parsing and domain errors (@lalitkapoor) +- [#802](https://github.com/request/request/pull/802) Added the Apache license to the package.json. (@keskival) +- [#793](https://github.com/request/request/pull/793) Adds content-length calculation when submitting forms using form-data li... (@Juul) +- [#785](https://github.com/request/request/pull/785) Provide ability to override content-type when `json` option used (@vvo) +- [#781](https://github.com/request/request/pull/781) simpler isReadStream function (@joaojeronimo) + +### v2.32.0 (2014/01/16) +- [#767](https://github.com/request/request/pull/767) Use tough-cookie CookieJar sync API (@stash) +- [#764](https://github.com/request/request/pull/764) Case-insensitive authentication scheme (@bobyrizov) +- [#763](https://github.com/request/request/pull/763) Upgrade tough-cookie to 0.10.0 (@stash) +- [#744](https://github.com/request/request/pull/744) Use Cookie.parse (@lalitkapoor) +- [#757](https://github.com/request/request/pull/757) require aws-sign2 (@mafintosh) + +### v2.31.0 (2014/01/08) +- [#645](https://github.com/request/request/pull/645) update twitter api url to v1.1 (@mick) +- [#746](https://github.com/request/request/pull/746) README: Markdown code highlight (@weakish) +- [#745](https://github.com/request/request/pull/745) updating setCookie example to make it clear that the callback is required (@emkay) +- [#742](https://github.com/request/request/pull/742) Add note about JSON output body type (@iansltx) +- [#741](https://github.com/request/request/pull/741) README example is using old cookie jar api (@emkay) +- [#736](https://github.com/request/request/pull/736) Fix callback arguments documentation (@mmalecki) +- [#732](https://github.com/request/request/pull/732) JSHINT: Creating global 'for' variable. Should be 'for (var ...'. (@Fritz-Lium) +- [#730](https://github.com/request/request/pull/730) better HTTP DIGEST support (@dai-shi) +- [#728](https://github.com/request/request/pull/728) Fix TypeError when calling request.cookie (@scarletmeow) +- [#727](https://github.com/request/request/pull/727) fix requester bug (@jchris) +- [#724](https://github.com/request/request/pull/724) README.md: add custom HTTP Headers example. (@tcort) +- [#719](https://github.com/request/request/pull/719) Made a comment gender neutral. (@unsetbit) +- [#715](https://github.com/request/request/pull/715) Request.multipart no longer crashes when header 'Content-type' present (@pastaclub) +- [#710](https://github.com/request/request/pull/710) Fixing listing in callback part of docs. (@lukasz-zak) +- [#696](https://github.com/request/request/pull/696) Edited README.md for formatting and clarity of phrasing (@Zearin) +- [#694](https://github.com/request/request/pull/694) Typo in README (@VRMink) +- [#690](https://github.com/request/request/pull/690) Handle blank password in basic auth. (@diversario) +- [#682](https://github.com/request/request/pull/682) Optional dependencies (@Turbo87) +- [#683](https://github.com/request/request/pull/683) Travis CI support (@Turbo87) +- [#674](https://github.com/request/request/pull/674) change cookie module,to tough-cookie.please check it . (@sxyizhiren) +- [#666](https://github.com/request/request/pull/666) make `ciphers` and `secureProtocol` to work in https request (@richarddong) +- [#656](https://github.com/request/request/pull/656) Test case for #304. (@diversario) +- [#662](https://github.com/request/request/pull/662) option.tunnel to explicitly disable tunneling (@seanmonstar) +- [#659](https://github.com/request/request/pull/659) fix failure when running with NODE_DEBUG=request, and a test for that (@jrgm) +- [#630](https://github.com/request/request/pull/630) Send random cnonce for HTTP Digest requests (@wprl) +- [#619](https://github.com/request/request/pull/619) decouple things a bit (@joaojeronimo) +- [#613](https://github.com/request/request/pull/613) Fixes #583, moved initialization of self.uri.pathname (@lexander) +- [#605](https://github.com/request/request/pull/605) Only include ":" + pass in Basic Auth if it's defined (fixes #602) (@bendrucker) +- [#596](https://github.com/request/request/pull/596) Global agent is being used when pool is specified (@Cauldrath) +- [#594](https://github.com/request/request/pull/594) Emit complete event when there is no callback (@RomainLK) +- [#601](https://github.com/request/request/pull/601) Fixed a small typo (@michalstanko) +- [#589](https://github.com/request/request/pull/589) Prevent setting headers after they are sent (@geek) +- [#587](https://github.com/request/request/pull/587) Global cookie jar disabled by default (@threepointone) +- [#544](https://github.com/request/request/pull/544) Update http-signature version. (@davidlehn) +- [#581](https://github.com/request/request/pull/581) Fix spelling of "ignoring." (@bigeasy) +- [#568](https://github.com/request/request/pull/568) use agentOptions to create agent when specified in request (@SamPlacette) +- [#564](https://github.com/request/request/pull/564) Fix redirections (@criloz) +- [#541](https://github.com/request/request/pull/541) The exported request function doesn't have an auth method (@tschaub) +- [#542](https://github.com/request/request/pull/542) Expose Request class (@regality) +- [#536](https://github.com/request/request/pull/536) Allow explicitly empty user field for basic authentication. (@mikeando) +- [#532](https://github.com/request/request/pull/532) fix typo (@fredericosilva) +- [#497](https://github.com/request/request/pull/497) Added redirect event (@Cauldrath) +- [#503](https://github.com/request/request/pull/503) Fix basic auth for passwords that contain colons (@tonistiigi) +- [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway) +- [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka) +- [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway) +- [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway) +- [#519](https://github.com/request/request/pull/519) Update internal path state on post-creation QS changes (@jblebrun) +- [#510](https://github.com/request/request/pull/510) Add HTTP Signature support. (@davidlehn) +- [#502](https://github.com/request/request/pull/502) Fix POST (and probably other) requests that are retried after 401 Unauthorized (@nylen) +- [#508](https://github.com/request/request/pull/508) Honor the .strictSSL option when using proxies (tunnel-agent) (@jhs) +- [#512](https://github.com/request/request/pull/512) Make password optional to support the format: http://username@hostname/ (@pajato1) +- [#513](https://github.com/request/request/pull/513) add 'localAddress' support (@yyfrankyy) +- [#498](https://github.com/request/request/pull/498) Moving response emit above setHeaders on destination streams (@kenperkins) +- [#490](https://github.com/request/request/pull/490) Empty response body (3-rd argument) must be passed to callback as an empty string (@Olegas) +- [#479](https://github.com/request/request/pull/479) Changing so if Accept header is explicitly set, sending json does not ov... (@RoryH) +- [#475](https://github.com/request/request/pull/475) Use `unescape` from `querystring` (@shimaore) +- [#473](https://github.com/request/request/pull/473) V0.10 compat (@isaacs) +- [#471](https://github.com/request/request/pull/471) Using querystring library from visionmedia (@kbackowski) +- [#461](https://github.com/request/request/pull/461) Strip the UTF8 BOM from a UTF encoded response (@kppullin) +- [#460](https://github.com/request/request/pull/460) hawk 0.10.0 (@hueniverse) +- [#462](https://github.com/request/request/pull/462) if query params are empty, then request path shouldn't end with a '?' (merges cleanly now) (@jaipandya) +- [#456](https://github.com/request/request/pull/456) hawk 0.9.0 (@hueniverse) +- [#429](https://github.com/request/request/pull/429) Copy options before adding callback. (@nrn, @nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki) +- [#454](https://github.com/request/request/pull/454) Destroy the response if present when destroying the request (clean merge) (@mafintosh) +- [#310](https://github.com/request/request/pull/310) Twitter Oauth Stuff Out of Date; Now Updated (@joemccann, @isaacs, @mscdex) +- [#413](https://github.com/request/request/pull/413) rename googledoodle.png to .jpg (@nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki) +- [#448](https://github.com/request/request/pull/448) Convenience method for PATCH (@mloar) +- [#444](https://github.com/request/request/pull/444) protect against double callbacks on error path (@spollack) +- [#433](https://github.com/request/request/pull/433) Added support for HTTPS cert & key (@mmalecki) +- [#430](https://github.com/request/request/pull/430) Respect specified {Host,host} headers, not just {host} (@andrewschaaf) +- [#415](https://github.com/request/request/pull/415) Fixed a typo. (@jerem) +- [#338](https://github.com/request/request/pull/338) Add more auth options, including digest support (@nylen) +- [#403](https://github.com/request/request/pull/403) Optimize environment lookup to happen once only (@mmalecki) +- [#398](https://github.com/request/request/pull/398) Add more reporting to tests (@mmalecki) +- [#388](https://github.com/request/request/pull/388) Ensure "safe" toJSON doesn't break EventEmitters (@othiym23) +- [#381](https://github.com/request/request/pull/381) Resolving "Invalid signature. Expected signature base string: " (@landeiro) +- [#380](https://github.com/request/request/pull/380) Fixes missing host header on retried request when using forever agent (@mac-) +- [#376](https://github.com/request/request/pull/376) Headers lost on redirect (@kapetan) +- [#375](https://github.com/request/request/pull/375) Fix for missing oauth_timestamp parameter (@jplock) +- [#374](https://github.com/request/request/pull/374) Correct Host header for proxy tunnel CONNECT (@youurayy) +- [#370](https://github.com/request/request/pull/370) Twitter reverse auth uses x_auth_mode not x_auth_type (@drudge) +- [#369](https://github.com/request/request/pull/369) Don't remove x_auth_mode for Twitter reverse auth (@drudge) +- [#344](https://github.com/request/request/pull/344) Make AWS auth signing find headers correctly (@nlf) +- [#363](https://github.com/request/request/pull/363) rfc3986 on base_uri, now passes tests (@jeffmarshall) +- [#362](https://github.com/request/request/pull/362) Running `rfc3986` on `base_uri` in `oauth.hmacsign` instead of just `encodeURIComponent` (@jeffmarshall) +- [#361](https://github.com/request/request/pull/361) Don't create a Content-Length header if we already have it set (@danjenkins) +- [#360](https://github.com/request/request/pull/360) Delete self._form along with everything else on redirect (@jgautier) +- [#355](https://github.com/request/request/pull/355) stop sending erroneous headers on redirected requests (@azylman) +- [#332](https://github.com/request/request/pull/332) Fix #296 - Only set Content-Type if body exists (@Marsup) +- [#343](https://github.com/request/request/pull/343) Allow AWS to work in more situations, added a note in the README on its usage (@nlf) +- [#320](https://github.com/request/request/pull/320) request.defaults() doesn't need to wrap jar() (@StuartHarris) +- [#322](https://github.com/request/request/pull/322) Fix + test for piped into request bumped into redirect. #321 (@alexindigo) +- [#326](https://github.com/request/request/pull/326) Do not try to remove listener from an undefined connection (@CartoDB) +- [#318](https://github.com/request/request/pull/318) Pass servername to tunneling secure socket creation (@isaacs) +- [#317](https://github.com/request/request/pull/317) Workaround for #313 (@isaacs) +- [#293](https://github.com/request/request/pull/293) Allow parser errors to bubble up to request (@mscdex) +- [#290](https://github.com/request/request/pull/290) A test for #289 (@isaacs) +- [#280](https://github.com/request/request/pull/280) Like in node.js print options if NODE_DEBUG contains the word request (@Filirom1) +- [#207](https://github.com/request/request/pull/207) Fix #206 Change HTTP/HTTPS agent when redirecting between protocols (@isaacs) +- [#214](https://github.com/request/request/pull/214) documenting additional behavior of json option (@jphaas, @vpulim) +- [#272](https://github.com/request/request/pull/272) Boundary begins with CRLF? (@elspoono, @timshadel, @naholyr, @nanodocumet, @TehShrike) +- [#284](https://github.com/request/request/pull/284) Remove stray `console.log()` call in multipart generator. (@bcherry) +- [#241](https://github.com/request/request/pull/241) Composability updates suggested by issue #239 (@polotek) +- [#282](https://github.com/request/request/pull/282) OAuth Authorization header contains non-"oauth_" parameters (@jplock) +- [#279](https://github.com/request/request/pull/279) fix tests with boundary by injecting boundry from header (@benatkin) +- [#273](https://github.com/request/request/pull/273) Pipe back pressure issue (@mafintosh) +- [#268](https://github.com/request/request/pull/268) I'm not OCD seriously (@TehShrike) +- [#263](https://github.com/request/request/pull/263) Bug in OAuth key generation for sha1 (@nanodocumet) +- [#265](https://github.com/request/request/pull/265) uncaughtException when redirected to invalid URI (@naholyr) +- [#262](https://github.com/request/request/pull/262) JSON test should check for equality (@timshadel) +- [#261](https://github.com/request/request/pull/261) Setting 'pool' to 'false' does NOT disable Agent pooling (@timshadel) +- [#249](https://github.com/request/request/pull/249) Fix for the fix of your (closed) issue #89 where self.headers[content-length] is set to 0 for all methods (@sethbridges, @polotek, @zephrax, @jeromegn) +- [#255](https://github.com/request/request/pull/255) multipart allow body === '' ( the empty string ) (@Filirom1) +- [#260](https://github.com/request/request/pull/260) fixed just another leak of 'i' (@sreuter) +- [#246](https://github.com/request/request/pull/246) Fixing the set-cookie header (@jeromegn) +- [#243](https://github.com/request/request/pull/243) Dynamic boundary (@zephrax) +- [#240](https://github.com/request/request/pull/240) don't error when null is passed for options (@polotek) +- [#211](https://github.com/request/request/pull/211) Replace all occurrences of special chars in RFC3986 (@chriso, @vpulim) +- [#224](https://github.com/request/request/pull/224) Multipart content-type change (@janjongboom) +- [#217](https://github.com/request/request/pull/217) need to use Authorization (titlecase) header with Tumblr OAuth (@visnup) +- [#203](https://github.com/request/request/pull/203) Fix cookie and redirect bugs and add auth support for HTTPS tunnel (@vpulim) +- [#199](https://github.com/request/request/pull/199) Tunnel (@isaacs) +- [#198](https://github.com/request/request/pull/198) Bugfix on forever usage of util.inherits (@isaacs) +- [#197](https://github.com/request/request/pull/197) Make ForeverAgent work with HTTPS (@isaacs) +- [#193](https://github.com/request/request/pull/193) Fixes GH-119 (@goatslacker) +- [#188](https://github.com/request/request/pull/188) Add abort support to the returned request (@itay) +- [#176](https://github.com/request/request/pull/176) Querystring option (@csainty) +- [#182](https://github.com/request/request/pull/182) Fix request.defaults to support (uri, options, callback) api (@twilson63) +- [#180](https://github.com/request/request/pull/180) Modified the post, put, head and del shortcuts to support uri optional param (@twilson63) +- [#179](https://github.com/request/request/pull/179) fix to add opts in .pipe(stream, opts) (@substack) +- [#177](https://github.com/request/request/pull/177) Issue #173 Support uri as first and optional config as second argument (@twilson63) +- [#170](https://github.com/request/request/pull/170) can't create a cookie in a wrapped request (defaults) (@fabianonunes) +- [#168](https://github.com/request/request/pull/168) Picking off an EasyFix by adding some missing mimetypes. (@serby) +- [#161](https://github.com/request/request/pull/161) Fix cookie jar/headers.cookie collision (#125) (@papandreou) +- [#162](https://github.com/request/request/pull/162) Fix issue #159 (@dpetukhov) +- [#90](https://github.com/request/request/pull/90) add option followAllRedirects to follow post/put redirects (@jroes) +- [#148](https://github.com/request/request/pull/148) Retry Agent (@thejh) +- [#146](https://github.com/request/request/pull/146) Multipart should respect content-type if previously set (@apeace) +- [#144](https://github.com/request/request/pull/144) added "form" option to readme (@petejkim) +- [#133](https://github.com/request/request/pull/133) Fixed cookies parsing (@afanasy) +- [#135](https://github.com/request/request/pull/135) host vs hostname (@iangreenleaf) +- [#132](https://github.com/request/request/pull/132) return the body as a Buffer when encoding is set to null (@jahewson) +- [#112](https://github.com/request/request/pull/112) Support using a custom http-like module (@jhs) +- [#104](https://github.com/request/request/pull/104) Cookie handling contains bugs (@janjongboom) +- [#121](https://github.com/request/request/pull/121) Another patch for cookie handling regression (@jhurliman) +- [#117](https://github.com/request/request/pull/117) Remove the global `i` (@3rd-Eden) +- [#110](https://github.com/request/request/pull/110) Update to Iris Couch URL (@jhs) +- [#86](https://github.com/request/request/pull/86) Can't post binary to multipart requests (@kkaefer) +- [#105](https://github.com/request/request/pull/105) added test for proxy option. (@dominictarr) +- [#102](https://github.com/request/request/pull/102) Implemented cookies - closes issue 82: https://github.com/mikeal/request/issues/82 (@alessioalex) +- [#97](https://github.com/request/request/pull/97) Typo in previous pull causes TypeError in non-0.5.11 versions (@isaacs) +- [#96](https://github.com/request/request/pull/96) Authless parsed url host support (@isaacs) +- [#81](https://github.com/request/request/pull/81) Enhance redirect handling (@danmactough) +- [#78](https://github.com/request/request/pull/78) Don't try to do strictSSL for non-ssl connections (@isaacs) +- [#76](https://github.com/request/request/pull/76) Bug when a request fails and a timeout is set (@Marsup) +- [#70](https://github.com/request/request/pull/70) add test script to package.json (@isaacs, @aheckmann) +- [#73](https://github.com/request/request/pull/73) Fix #71 Respect the strictSSL flag (@isaacs) +- [#69](https://github.com/request/request/pull/69) Flatten chunked requests properly (@isaacs) +- [#67](https://github.com/request/request/pull/67) fixed global variable leaks (@aheckmann) +- [#66](https://github.com/request/request/pull/66) Do not overwrite established content-type headers for read stream deliver (@voodootikigod) +- [#53](https://github.com/request/request/pull/53) Parse json: Issue #51 (@benatkin) +- [#45](https://github.com/request/request/pull/45) Added timeout option (@mbrevoort) +- [#35](https://github.com/request/request/pull/35) The "end" event isn't emitted for some responses (@voxpelli) +- [#31](https://github.com/request/request/pull/31) Error on piping a request to a destination (@tobowers) \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/request/LICENSE b/node_modules/azure-storage/node_modules/request/LICENSE new file mode 100644 index 000000000..a4a9aee0c --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/LICENSE @@ -0,0 +1,55 @@ +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: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and + +You must cause any modified files to carry prominent notices stating that You changed the files; and + +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 + +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 \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/request/README.md b/node_modules/azure-storage/node_modules/request/README.md new file mode 100644 index 000000000..231739114 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/README.md @@ -0,0 +1,1115 @@ + +# Request - Simplified HTTP client + +[![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/) + +[![Build status](https://img.shields.io/travis/request/request/master.svg?style=flat-square)](https://travis-ci.org/request/request) +[![Coverage](https://img.shields.io/codecov/c/github/request/request.svg?style=flat-square)](https://codecov.io/github/request/request?branch=master) +[![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat-square)](https://coveralls.io/r/request/request) +[![Dependency Status](https://img.shields.io/david/request/request.svg?style=flat-square)](https://david-dm.org/request/request) +[![Known Vulnerabilities](https://snyk.io/test/npm/request/badge.svg?style=flat-square)](https://snyk.io/test/npm/request) +[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge) + + +## Super simple to use + +Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. + +```js +var request = require('request'); +request('http://www.google.com', function (error, response, body) { + console.log('error:', error); // Print the error if one occurred + console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received + console.log('body:', body); // Print the HTML for the Google homepage. +}); +``` + + +## Table of contents + +- [Streaming](#streaming) +- [Forms](#forms) +- [HTTP Authentication](#http-authentication) +- [Custom HTTP Headers](#custom-http-headers) +- [OAuth Signing](#oauth-signing) +- [Proxies](#proxies) +- [Unix Domain Sockets](#unix-domain-sockets) +- [TLS/SSL Protocol](#tlsssl-protocol) +- [Support for HAR 1.2](#support-for-har-12) +- [**All Available Options**](#requestoptions-callback) + +Request also offers [convenience methods](#convenience-methods) like +`request.defaults` and `request.post`, and there are +lots of [usage examples](#examples) and several +[debugging techniques](#debugging). + + +--- + + +## Streaming + +You can stream any response to a file stream. + +```js +request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) +``` + +You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one). + +```js +fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) +``` + +Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers. + +```js +request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) +``` + +Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage). + +```js +request + .get('http://google.com/img.png') + .on('response', function(response) { + console.log(response.statusCode) // 200 + console.log(response.headers['content-type']) // 'image/png' + }) + .pipe(request.put('http://mysite.com/img.png')) +``` + +To easily handle errors when streaming requests, listen to the `error` event before piping: + +```js +request + .get('http://mysite.com/doodle.png') + .on('error', function(err) { + console.log(err) + }) + .pipe(fs.createWriteStream('doodle.png')) +``` + +Now let’s get fancy. + +```js +http.createServer(function (req, resp) { + if (req.url === '/doodle.png') { + if (req.method === 'PUT') { + req.pipe(request.put('http://mysite.com/doodle.png')) + } else if (req.method === 'GET' || req.method === 'HEAD') { + request.get('http://mysite.com/doodle.png').pipe(resp) + } + } +}) +``` + +You can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do: + +```js +http.createServer(function (req, resp) { + if (req.url === '/doodle.png') { + var x = request('http://mysite.com/doodle.png') + req.pipe(x) + x.pipe(resp) + } +}) +``` + +And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :) + +```js +req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) +``` + +Also, none of this new functionality conflicts with requests previous features, it just expands them. + +```js +var r = request.defaults({'proxy':'http://localproxy.com'}) + +http.createServer(function (req, resp) { + if (req.url === '/doodle.png') { + r.get('http://google.com/doodle.png').pipe(resp) + } +}) +``` + +You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. + +[back to top](#table-of-contents) + + +--- + + +## Forms + +`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API. + + +#### application/x-www-form-urlencoded (URL-Encoded Forms) + +URL-encoded forms are simple. + +```js +request.post('http://service.com/upload', {form:{key:'value'}}) +// or +request.post('http://service.com/upload').form({key:'value'}) +// or +request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }) +``` + + +#### multipart/form-data (Multipart Form Uploads) + +For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option. + + +```js +var formData = { + // Pass a simple key-value pair + my_field: 'my_value', + // Pass data via Buffers + my_buffer: new Buffer([1, 2, 3]), + // Pass data via Streams + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), + // Pass multiple values /w an Array + attachments: [ + fs.createReadStream(__dirname + '/attachment1.jpg'), + fs.createReadStream(__dirname + '/attachment2.jpg') + ], + // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS} + // Use case: for some types of streams, you'll need to provide "file"-related information manually. + // See the `form-data` README for more information about options: https://github.com/form-data/form-data + custom_file: { + value: fs.createReadStream('/dev/urandom'), + options: { + filename: 'topsecret.jpg', + contentType: 'image/jpeg' + } + } +}; +request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.) + +```js +// NOTE: Advanced use-case, for normal use see 'formData' usage above +var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...}) +var form = r.form(); +form.append('my_field', 'my_value'); +form.append('my_buffer', new Buffer([1, 2, 3])); +form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'}); +``` +See the [form-data README](https://github.com/form-data/form-data) for more information & examples. + + +#### multipart/related + +Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options. + +```js + request({ + method: 'PUT', + preambleCRLF: true, + postambleCRLF: true, + uri: 'http://service.com/upload', + multipart: [ + { + 'content-type': 'application/json', + body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + }, + { body: 'I am an attachment' }, + { body: fs.createReadStream('image.png') } + ], + // alternatively pass an object containing additional options + multipart: { + chunked: false, + data: [ + { + 'content-type': 'application/json', + body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + }, + { body: 'I am an attachment' } + ] + } + }, + function (error, response, body) { + if (error) { + return console.error('upload failed:', error); + } + console.log('Upload successful! Server responded with:', body); + }) +``` + +[back to top](#table-of-contents) + + +--- + + +## HTTP Authentication + +```js +request.get('http://some.server.com/').auth('username', 'password', false); +// or +request.get('http://some.server.com/', { + 'auth': { + 'user': 'username', + 'pass': 'password', + 'sendImmediately': false + } +}); +// or +request.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); +// or +request.get('http://some.server.com/', { + 'auth': { + 'bearer': 'bearerToken' + } +}); +``` + +If passed as an option, `auth` should be a hash containing values: + +- `user` || `username` +- `pass` || `password` +- `sendImmediately` (optional) +- `bearer` (optional) + +The method form takes parameters +`auth(username, password, sendImmediately, bearer)`. + +`sendImmediately` defaults to `true`, which causes a basic or bearer +authentication header to be sent. If `sendImmediately` is `false`, then +`request` will retry with a proper authentication header after receiving a +`401` response from the server (which must contain a `WWW-Authenticate` header +indicating the required authentication method). + +Note that you can also specify basic authentication using the URL itself, as +detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the +`user:password` before the host with an `@` sign: + +```js +var username = 'username', + password = 'password', + url = 'http://' + username + ':' + password + '@some.server.com'; + +request({url: url}, function (error, response, body) { + // Do more stuff with 'body' here +}); +``` + +Digest authentication is supported, but it only works with `sendImmediately` +set to `false`; otherwise `request` will send basic authentication on the +initial request, which will probably cause the request to fail. + +Bearer authentication is supported, and is activated when the `bearer` value is +available. The value may be either a `String` or a `Function` returning a +`String`. Using a function to supply the bearer token is particularly useful if +used in conjunction with `defaults` to allow a single function to supply the +last known token at the time of sending a request, or to compute one on the fly. + +[back to top](#table-of-contents) + + +--- + + +## Custom HTTP Headers + +HTTP Headers, such as `User-Agent`, can be set in the `options` object. +In the example below, we call the github API to find out the number +of stars and forks for the request repository. This requires a +custom `User-Agent` header as well as https. + +```js +var request = require('request'); + +var options = { + url: 'https://api.github.com/repos/request/request', + headers: { + 'User-Agent': 'request' + } +}; + +function callback(error, response, body) { + if (!error && response.statusCode == 200) { + var info = JSON.parse(body); + console.log(info.stargazers_count + " Stars"); + console.log(info.forks_count + " Forks"); + } +} + +request(options, callback); +``` + +[back to top](#table-of-contents) + + +--- + + +## OAuth Signing + +[OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The +default signing algorithm is +[HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2): + +```js +// OAuth1.0 - 3-legged server side flow (Twitter example) +// step 1 +var qs = require('querystring') + , oauth = + { callback: 'http://mysite.com/callback/' + , consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + } + , url = 'https://api.twitter.com/oauth/request_token' + ; +request.post({url:url, oauth:oauth}, function (e, r, body) { + // Ideally, you would take the body in the response + // and construct a URL that a user clicks on (like a sign in button). + // The verifier is only available in the response after a user has + // verified with twitter that they are authorizing your app. + + // step 2 + var req_data = qs.parse(body) + var uri = 'https://api.twitter.com/oauth/authenticate' + + '?' + qs.stringify({oauth_token: req_data.oauth_token}) + // redirect the user to the authorize uri + + // step 3 + // after the user is redirected back to your server + var auth_data = qs.parse(body) + , oauth = + { consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + , token: auth_data.oauth_token + , token_secret: req_data.oauth_token_secret + , verifier: auth_data.oauth_verifier + } + , url = 'https://api.twitter.com/oauth/access_token' + ; + request.post({url:url, oauth:oauth}, function (e, r, body) { + // ready to make signed requests on behalf of the user + var perm_data = qs.parse(body) + , oauth = + { consumer_key: CONSUMER_KEY + , consumer_secret: CONSUMER_SECRET + , token: perm_data.oauth_token + , token_secret: perm_data.oauth_token_secret + } + , url = 'https://api.twitter.com/1.1/users/show.json' + , qs = + { screen_name: perm_data.screen_name + , user_id: perm_data.user_id + } + ; + request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) { + console.log(user) + }) + }) +}) +``` + +For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make +the following changes to the OAuth options object: +* Pass `signature_method : 'RSA-SHA1'` +* Instead of `consumer_secret`, specify a `private_key` string in + [PEM format](http://how2ssl.com/articles/working_with_pem_files/) + +For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make +the following changes to the OAuth options object: +* Pass `signature_method : 'PLAINTEXT'` + +To send OAuth parameters via query params or in a post body as described in The +[Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param) +section of the oauth1 spec: +* Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth + options object. +* `transport_method` defaults to `'header'` + +To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either +* Manually generate the body hash and pass it as a string `body_hash: '...'` +* Automatically generate the body hash by passing `body_hash: true` + +[back to top](#table-of-contents) + + +--- + + +## Proxies + +If you specify a `proxy` option, then the request (and any subsequent +redirects) will be sent via a connection to the proxy server. + +If your endpoint is an `https` url, and you are using a proxy, then +request will send a `CONNECT` request to the proxy server *first*, and +then use the supplied connection to connect to the endpoint. + +That is, first it will make a request like: + +``` +HTTP/1.1 CONNECT endpoint-server.com:80 +Host: proxy-server.com +User-Agent: whatever user agent you specify +``` + +and then the proxy server make a TCP connection to `endpoint-server` +on port `80`, and return a response that looks like: + +``` +HTTP/1.1 200 OK +``` + +At this point, the connection is left open, and the client is +communicating directly with the `endpoint-server.com` machine. + +See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel) +for more information. + +By default, when proxying `http` traffic, request will simply make a +standard proxied `http` request. This is done by making the `url` +section of the initial line of the request a fully qualified url to +the endpoint. + +For example, it will make a single request that looks like: + +``` +HTTP/1.1 GET http://endpoint-server.com/some-url +Host: proxy-server.com +Other-Headers: all go here + +request body or whatever +``` + +Because a pure "http over http" tunnel offers no additional security +or other features, it is generally simpler to go with a +straightforward HTTP proxy in this case. However, if you would like +to force a tunneling proxy, you may set the `tunnel` option to `true`. + +You can also make a standard proxied `http` request by explicitly setting +`tunnel : false`, but **note that this will allow the proxy to see the traffic +to/from the destination server**. + +If you are using a tunneling proxy, you may set the +`proxyHeaderWhiteList` to share certain headers with the proxy. + +You can also set the `proxyHeaderExclusiveList` to share certain +headers only with the proxy and not with destination host. + +By default, this set is: + +``` +accept +accept-charset +accept-encoding +accept-language +accept-ranges +cache-control +content-encoding +content-language +content-length +content-location +content-md5 +content-range +content-type +connection +date +expect +max-forwards +pragma +proxy-authorization +referer +te +transfer-encoding +user-agent +via +``` + +Note that, when using a tunneling proxy, the `proxy-authorization` +header and any headers from custom `proxyHeaderExclusiveList` are +*never* sent to the endpoint server, but only to the proxy server. + + +### Controlling proxy behaviour using environment variables + +The following environment variables are respected by `request`: + + * `HTTP_PROXY` / `http_proxy` + * `HTTPS_PROXY` / `https_proxy` + * `NO_PROXY` / `no_proxy` + +When `HTTP_PROXY` / `http_proxy` are set, they will be used to proxy non-SSL requests that do not have an explicit `proxy` configuration option present. Similarly, `HTTPS_PROXY` / `https_proxy` will be respected for SSL requests that do not have an explicit `proxy` configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the `proxy` configuration option. Furthermore, the `proxy` configuration option can be explicitly set to false / null to opt out of proxying altogether for that request. + +`request` is also aware of the `NO_PROXY`/`no_proxy` environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to `*` to opt out of the implicit proxy configuration of the other environment variables. + +Here's some examples of valid `no_proxy` values: + + * `google.com` - don't proxy HTTP/HTTPS requests to Google. + * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google. + * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo! + * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether. + +[back to top](#table-of-contents) + + +--- + + +## UNIX Domain Sockets + +`request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme: + +```js +/* Pattern */ 'http://unix:SOCKET:PATH' +/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path') +``` + +Note: The `SOCKET` path is assumed to be absolute to the root of the host file system. + +[back to top](#table-of-contents) + + +--- + + +## TLS/SSL Protocol + +TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be +set directly in `options` object, in the `agentOptions` property of the `options` object, or even in `https.globalAgent.options`. Keep in mind that, although `agentOptions` allows for a slightly wider range of configurations, the recommended way is via `options` object directly, as using `agentOptions` or `https.globalAgent.options` would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent). + +```js +var fs = require('fs') + , path = require('path') + , certFile = path.resolve(__dirname, 'ssl/client.crt') + , keyFile = path.resolve(__dirname, 'ssl/client.key') + , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem') + , request = require('request'); + +var options = { + url: 'https://api.some-server.com/', + cert: fs.readFileSync(certFile), + key: fs.readFileSync(keyFile), + passphrase: 'password', + ca: fs.readFileSync(caFile) +}; + +request.get(options); +``` + +### Using `options.agentOptions` + +In the example below, we call an API requires client side SSL certificate +(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol: + +```js +var fs = require('fs') + , path = require('path') + , certFile = path.resolve(__dirname, 'ssl/client.crt') + , keyFile = path.resolve(__dirname, 'ssl/client.key') + , request = require('request'); + +var options = { + url: 'https://api.some-server.com/', + agentOptions: { + cert: fs.readFileSync(certFile), + key: fs.readFileSync(keyFile), + // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format: + // pfx: fs.readFileSync(pfxFilePath), + passphrase: 'password', + securityOptions: 'SSL_OP_NO_SSLv3' + } +}; + +request.get(options); +``` + +It is able to force using SSLv3 only by specifying `secureProtocol`: + +```js +request.get({ + url: 'https://api.some-server.com/', + agentOptions: { + secureProtocol: 'SSLv3_method' + } +}); +``` + +It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs). +This can be useful, for example, when using self-signed certificates. +To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the `agentOptions`. +The certificate the domain presents must be signed by the root certificate specified: + +```js +request.get({ + url: 'https://api.some-server.com/', + agentOptions: { + ca: fs.readFileSync('ca.cert.pem') + } +}); +``` + +[back to top](#table-of-contents) + + +--- + +## Support for HAR 1.2 + +The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`. + +a validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching. + +```js + var request = require('request') + request({ + // will be ignored + method: 'GET', + uri: 'http://www.google.com', + + // HTTP Archive Request Object + har: { + url: 'http://www.mockbin.com/har', + method: 'POST', + headers: [ + { + name: 'content-type', + value: 'application/x-www-form-urlencoded' + } + ], + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { + name: 'foo', + value: 'bar' + }, + { + name: 'hello', + value: 'world' + } + ] + } + } + }) + + // a POST request will be sent to http://www.mockbin.com + // with body an application/x-www-form-urlencoded body: + // foo=bar&hello=world +``` + +[back to top](#table-of-contents) + + +--- + +## request(options, callback) + +The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional. + +- `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()` +- `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string. +- `method` - http method (default: `"GET"`) +- `headers` - http headers (default: `{}`) + +--- + +- `qs` - object containing querystring values to be appended to the `uri` +- `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}` +- `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat` +- `useQuerystring` - If true, use `querystring` to stringify and parse + querystrings, otherwise use `qs` (default: `false`). Set this option to + `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the + default `foo[0]=bar&foo[1]=baz`. + +--- + +- `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object. +- `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above. +- `formData` - Data to pass for a `multipart/form-data` request. See + [Forms](#forms) section above. +- `multipart` - array of objects which contain their own headers and `body` + attributes. Sends a `multipart/related` request. See [Forms](#forms) section + above. + - Alternatively you can pass in an object `{chunked: false, data: []}` where + `chunked` is used to specify whether the request is sent in + [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) + In non-chunked requests, data items with body streams are not allowed. +- `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request. +- `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request. +- `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON. +- `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body. +- `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body. + +--- + +- `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above. +- `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above. +- `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example). +- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. **Note:** you need to `npm install aws4` first. +- `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options. + +--- + +- `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise. +- `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`) +- `followOriginalHttpMethod` - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: `false`) +- `maxRedirects` - the maximum number of redirects to follow (default: `10`) +- `removeRefererHeader` - removes the referer header when a redirect happens (default: `false`). **Note:** if true, referer header set in the initial request is preserved during redirect chain. + +--- + +- `encoding` - Encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.) +- `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below. +- `jar` - If `true`, remember cookies for future use (or define your custom cookie jar; see examples section) + +--- + +- `agent` - `http(s).Agent` instance to use +- `agentClass` - alternatively specify your agent's class name +- `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions). +- `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+ +- `pool` - An object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified. + - A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`). + - Note that if you are sending multiple requests in a loop and creating + multiple new `pool` objects, `maxSockets` will not work as intended. To + work around this, either use [`request.defaults`](#requestdefaultsoptions) + with your pool options or create the pool object with the `maxSockets` + property outside of the loop. +- `timeout` - Integer containing the number of milliseconds to wait for a +server to send response headers (and start the response body) before aborting +the request. Note that if the underlying TCP connection cannot be established, +the OS-wide TCP connection timeout will overrule the `timeout` option ([the +default in Linux can be anywhere from 20-120 seconds][linux-timeout]). + +[linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout + +--- + +- `localAddress` - Local interface to bind for network connections. +- `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`) +- `strictSSL` - If `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option. +- `tunnel` - controls the behavior of + [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling) + as follows: + - `undefined` (default) - `true` if the destination is `https`, `false` otherwise + - `true` - always tunnel to the destination by making a `CONNECT` request to + the proxy + - `false` - request the destination as a `GET` request. +- `proxyHeaderWhiteList` - A whitelist of headers to send to a + tunneling proxy. +- `proxyHeaderExclusiveList` - A whitelist of headers to send + exclusively to a tunneling proxy and not to destination. + +--- + +- `time` - If `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object: + - `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*). + - `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*). + - `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds). + - `timings` Contains event timestamps in millisecond resolution relative to `timingStart`. If there were redirects, the properties reflect the timings of the final request in the redirect chain: + - `socket` Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_socket) module's `socket` event fires. This happens when the socket is assigned to the request. + - `lookup` Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_lookup) module's `lookup` event fires. This happens when the DNS has been resolved. + - `connect`: Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_connect) module's `connect` event fires. This happens when the server acknowledges the TCP connection. + - `response`: Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_response) module's `response` event fires. This happens when the first bytes are received from the server. + - `end`: Relative timestamp when the last bytes of the response are received. + - `timingPhases` Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain: + - `wait`: Duration of socket initialization (`timings.socket`) + - `dns`: Duration of DNS lookup (`timings.lookup` - `timings.socket`) + - `tcp`: Duration of TCP connection (`timings.connect` - `timings.socket`) + - `firstByte`: Duration of HTTP server response (`timings.response` - `timings.connect`) + - `download`: Duration of HTTP download (`timings.end` - `timings.response`) + - `total`: Duration entire HTTP round-trip (`timings.end`) + +- `har` - A [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)* +- `callback` - alternatively pass the request's callback in the options object + +The callback argument gets 3 arguments: + +1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object) +2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object (Response object) +3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied) + +[back to top](#table-of-contents) + + +--- + +## Convenience methods + +There are also shorthand methods for different HTTP METHODs and some other conveniences. + + +### request.defaults(options) + +This method **returns a wrapper** around the normal request API that defaults +to whatever options you pass to it. + +**Note:** `request.defaults()` **does not** modify the global request API; +instead, it **returns a wrapper** that has your default settings applied to it. + +**Note:** You can call `.defaults()` on the wrapper that is returned from +`request.defaults` to add/override defaults that were previously defaulted. + +For example: +```js +//requests using baseRequest() will set the 'x-token' header +var baseRequest = request.defaults({ + headers: {'x-token': 'my-token'} +}) + +//requests using specialRequest() will include the 'x-token' header set in +//baseRequest and will also include the 'special' header +var specialRequest = baseRequest.defaults({ + headers: {special: 'special value'} +}) +``` + +### request.put + +Same as `request()`, but defaults to `method: "PUT"`. + +```js +request.put(url) +``` + +### request.patch + +Same as `request()`, but defaults to `method: "PATCH"`. + +```js +request.patch(url) +``` + +### request.post + +Same as `request()`, but defaults to `method: "POST"`. + +```js +request.post(url) +``` + +### request.head + +Same as `request()`, but defaults to `method: "HEAD"`. + +```js +request.head(url) +``` + +### request.del / request.delete + +Same as `request()`, but defaults to `method: "DELETE"`. + +```js +request.del(url) +request.delete(url) +``` + +### request.get + +Same as `request()` (for uniformity). + +```js +request.get(url) +``` +### request.cookie + +Function that creates a new cookie. + +```js +request.cookie('key1=value1') +``` +### request.jar() + +Function that creates a new cookie jar. + +```js +request.jar() +``` + +[back to top](#table-of-contents) + + +--- + + +## Debugging + +There are at least three ways to debug the operation of `request`: + +1. Launch the node process like `NODE_DEBUG=request node script.js` + (`lib,request,otherlib` works too). + +2. Set `require('request').debug = true` at any time (this does the same thing + as #1). + +3. Use the [request-debug module](https://github.com/request/request-debug) to + view request and response headers and bodies. + +[back to top](#table-of-contents) + + +--- + +## Timeouts + +Most requests to external servers should have a timeout attached, in case the +server is not responding in a timely manner. Without a timeout, your code may +have a socket open/consume resources for minutes or more. + +There are two main types of timeouts: **connection timeouts** and **read +timeouts**. A connect timeout occurs if the timeout is hit while your client is +attempting to establish a connection to a remote machine (corresponding to the +[connect() call][connect] on the socket). A read timeout occurs any time the +server is too slow to send back a part of the response. + +These two situations have widely different implications for what went wrong +with the request, so it's useful to be able to distinguish them. You can detect +timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you +can detect whether the timeout was a connection timeout by checking if the +`err.connect` property is set to `true`. + +```js +request.get('http://10.255.255.1', {timeout: 1500}, function(err) { + console.log(err.code === 'ETIMEDOUT'); + // Set to `true` if the timeout was a connection timeout, `false` or + // `undefined` otherwise. + console.log(err.connect === true); + process.exit(0); +}); +``` + +[connect]: http://linux.die.net/man/2/connect + +## Examples: + +```js + var request = require('request') + , rand = Math.floor(Math.random()*100000000).toString() + ; + request( + { method: 'PUT' + , uri: 'http://mikeal.iriscouch.com/testjs/' + rand + , multipart: + [ { 'content-type': 'application/json' + , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) + } + , { body: 'I am an attachment' } + ] + } + , function (error, response, body) { + if(response.statusCode == 201){ + console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) + } else { + console.log('error: '+ response.statusCode) + console.log(body) + } + } + ) +``` + +For backwards-compatibility, response compression is not supported by default. +To accept gzip-compressed responses, set the `gzip` option to `true`. Note +that the body data passed through `request` is automatically decompressed +while the response object is unmodified and will contain compressed data if +the server sent a compressed response. + +```js + var request = require('request') + request( + { method: 'GET' + , uri: 'http://www.google.com' + , gzip: true + } + , function (error, response, body) { + // body is the decompressed response body + console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')) + console.log('the decoded data is: ' + body) + } + ).on('data', function(data) { + // decompressed data as it is received + console.log('decoded chunk: ' + data) + }) + .on('response', function(response) { + // unmodified http.IncomingMessage object + response.on('data', function(data) { + // compressed data as it is received + console.log('received ' + data.length + ' bytes of compressed data') + }) + }) +``` + +Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`). + +```js +var request = request.defaults({jar: true}) +request('http://www.google.com', function () { + request('http://images.google.com') +}) +``` + +To use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`) + +```js +var j = request.jar() +var request = request.defaults({jar:j}) +request('http://www.google.com', function () { + request('http://images.google.com') +}) +``` + +OR + +```js +var j = request.jar(); +var cookie = request.cookie('key1=value1'); +var url = 'http://www.google.com'; +j.setCookie(cookie, url); +request({url: url, jar: j}, function () { + request('http://images.google.com') +}) +``` + +To use a custom cookie store (such as a +[`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore) +which supports saving to and restoring from JSON files), pass it as a parameter +to `request.jar()`: + +```js +var FileCookieStore = require('tough-cookie-filestore'); +// NOTE - currently the 'cookies.json' file must already exist! +var j = request.jar(new FileCookieStore('cookies.json')); +request = request.defaults({ jar : j }) +request('http://www.google.com', function() { + request('http://images.google.com') +}) +``` + +The cookie store must be a +[`tough-cookie`](https://github.com/SalesforceEng/tough-cookie) +store and it must support synchronous operations; see the +[`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#cookiestore-api) +for details. + +To inspect your cookie jar after a request: + +```js +var j = request.jar() +request({url: 'http://www.google.com', jar: j}, function () { + var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." + var cookies = j.getCookies(url); + // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] +}) +``` + +[back to top](#table-of-contents) diff --git a/node_modules/azure-storage/node_modules/request/index.js b/node_modules/azure-storage/node_modules/request/index.js new file mode 100644 index 000000000..9ec65ea26 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/index.js @@ -0,0 +1,156 @@ +// Copyright 2010-2012 Mikeal Rogers +// +// 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. + +'use strict' + +var extend = require('extend') + , cookies = require('./lib/cookies') + , helpers = require('./lib/helpers') + +var paramsHaveRequestBody = helpers.paramsHaveRequestBody + + +// organize params for patch, post, put, head, del +function initParams(uri, options, callback) { + if (typeof options === 'function') { + callback = options + } + + var params = {} + if (typeof options === 'object') { + extend(params, options, {uri: uri}) + } else if (typeof uri === 'string') { + extend(params, {uri: uri}) + } else { + extend(params, uri) + } + + params.callback = callback || params.callback + return params +} + +function request (uri, options, callback) { + if (typeof uri === 'undefined') { + throw new Error('undefined is not a valid uri or options object.') + } + + var params = initParams(uri, options, callback) + + if (params.method === 'HEAD' && paramsHaveRequestBody(params)) { + throw new Error('HTTP HEAD requests MUST NOT include a request body.') + } + + return new request.Request(params) +} + +function verbFunc (verb) { + var method = verb.toUpperCase() + return function (uri, options, callback) { + var params = initParams(uri, options, callback) + params.method = method + return request(params, params.callback) + } +} + +// define like this to please codeintel/intellisense IDEs +request.get = verbFunc('get') +request.head = verbFunc('head') +request.post = verbFunc('post') +request.put = verbFunc('put') +request.patch = verbFunc('patch') +request.del = verbFunc('delete') +request['delete'] = verbFunc('delete') + +request.jar = function (store) { + return cookies.jar(store) +} + +request.cookie = function (str) { + return cookies.parse(str) +} + +function wrapRequestMethod (method, options, requester, verb) { + + return function (uri, opts, callback) { + var params = initParams(uri, opts, callback) + + var target = {} + extend(true, target, options, params) + + target.pool = params.pool || options.pool + + if (verb) { + target.method = verb.toUpperCase() + } + + if (typeof requester === 'function') { + method = requester + } + + return method(target, target.callback) + } +} + +request.defaults = function (options, requester) { + var self = this + + options = options || {} + + if (typeof options === 'function') { + requester = options + options = {} + } + + var defaults = wrapRequestMethod(self, options, requester) + + var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete'] + verbs.forEach(function(verb) { + defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb) + }) + + defaults.cookie = wrapRequestMethod(self.cookie, options, requester) + defaults.jar = self.jar + defaults.defaults = self.defaults + return defaults +} + +request.forever = function (agentOptions, optionsArg) { + var options = {} + if (optionsArg) { + extend(options, optionsArg) + } + if (agentOptions) { + options.agentOptions = agentOptions + } + + options.forever = true + return request.defaults(options) +} + +// Exports + +module.exports = request +request.Request = require('./request') +request.initParams = initParams + +// Backwards compatibility for request.debug +Object.defineProperty(request, 'debug', { + enumerable : true, + get : function() { + return request.Request.debug + }, + set : function(debug) { + request.Request.debug = debug + } +}) diff --git a/node_modules/azure-storage/node_modules/request/lib/auth.js b/node_modules/azure-storage/node_modules/request/lib/auth.js new file mode 100644 index 000000000..559ca57be --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/auth.js @@ -0,0 +1,168 @@ +'use strict' + +var caseless = require('caseless') + , uuid = require('uuid') + , helpers = require('./helpers') + +var md5 = helpers.md5 + , toBase64 = helpers.toBase64 + + +function Auth (request) { + // define all public properties here + this.request = request + this.hasAuth = false + this.sentAuth = false + this.bearerToken = null + this.user = null + this.pass = null +} + +Auth.prototype.basic = function (user, pass, sendImmediately) { + var self = this + if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) { + self.request.emit('error', new Error('auth() received invalid user or password')) + } + self.user = user + self.pass = pass + self.hasAuth = true + var header = user + ':' + (pass || '') + if (sendImmediately || typeof sendImmediately === 'undefined') { + var authHeader = 'Basic ' + toBase64(header) + self.sentAuth = true + return authHeader + } +} + +Auth.prototype.bearer = function (bearer, sendImmediately) { + var self = this + self.bearerToken = bearer + self.hasAuth = true + if (sendImmediately || typeof sendImmediately === 'undefined') { + if (typeof bearer === 'function') { + bearer = bearer() + } + var authHeader = 'Bearer ' + (bearer || '') + self.sentAuth = true + return authHeader + } +} + +Auth.prototype.digest = function (method, path, authHeader) { + // TODO: More complete implementation of RFC 2617. + // - handle challenge.domain + // - support qop="auth-int" only + // - handle Authentication-Info (not necessarily?) + // - check challenge.stale (not necessarily?) + // - increase nc (not necessarily?) + // For reference: + // http://tools.ietf.org/html/rfc2617#section-3 + // https://github.com/bagder/curl/blob/master/lib/http_digest.c + + var self = this + + var challenge = {} + var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi + for (;;) { + var match = re.exec(authHeader) + if (!match) { + break + } + challenge[match[1]] = match[2] || match[3] + } + + /** + * RFC 2617: handle both MD5 and MD5-sess algorithms. + * + * If the algorithm directive's value is "MD5" or unspecified, then HA1 is + * HA1=MD5(username:realm:password) + * If the algorithm directive's value is "MD5-sess", then HA1 is + * HA1=MD5(MD5(username:realm:password):nonce:cnonce) + */ + var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) { + var ha1 = md5(user + ':' + realm + ':' + pass) + if (algorithm && algorithm.toLowerCase() === 'md5-sess') { + return md5(ha1 + ':' + nonce + ':' + cnonce) + } else { + return ha1 + } + } + + var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' + var nc = qop && '00000001' + var cnonce = qop && uuid().replace(/-/g, '') + var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce) + var ha2 = md5(method + ':' + path) + var digestResponse = qop + ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) + : md5(ha1 + ':' + challenge.nonce + ':' + ha2) + var authValues = { + username: self.user, + realm: challenge.realm, + nonce: challenge.nonce, + uri: path, + qop: qop, + response: digestResponse, + nc: nc, + cnonce: cnonce, + algorithm: challenge.algorithm, + opaque: challenge.opaque + } + + authHeader = [] + for (var k in authValues) { + if (authValues[k]) { + if (k === 'qop' || k === 'nc' || k === 'algorithm') { + authHeader.push(k + '=' + authValues[k]) + } else { + authHeader.push(k + '="' + authValues[k] + '"') + } + } + } + authHeader = 'Digest ' + authHeader.join(', ') + self.sentAuth = true + return authHeader +} + +Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) { + var self = this + , request = self.request + + var authHeader + if (bearer === undefined && user === undefined) { + self.request.emit('error', new Error('no auth mechanism defined')) + } else if (bearer !== undefined) { + authHeader = self.bearer(bearer, sendImmediately) + } else { + authHeader = self.basic(user, pass, sendImmediately) + } + if (authHeader) { + request.setHeader('authorization', authHeader) + } +} + +Auth.prototype.onResponse = function (response) { + var self = this + , request = self.request + + if (!self.hasAuth || self.sentAuth) { return null } + + var c = caseless(response.headers) + + var authHeader = c.get('www-authenticate') + var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() + request.debug('reauth', authVerb) + + switch (authVerb) { + case 'basic': + return self.basic(self.user, self.pass, true) + + case 'bearer': + return self.bearer(self.bearerToken, true) + + case 'digest': + return self.digest(request.method, request.path, authHeader) + } +} + +exports.Auth = Auth diff --git a/node_modules/azure-storage/node_modules/request/lib/cookies.js b/node_modules/azure-storage/node_modules/request/lib/cookies.js new file mode 100644 index 000000000..412c07d63 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/cookies.js @@ -0,0 +1,39 @@ +'use strict' + +var tough = require('tough-cookie') + +var Cookie = tough.Cookie + , CookieJar = tough.CookieJar + + +exports.parse = function(str) { + if (str && str.uri) { + str = str.uri + } + if (typeof str !== 'string') { + throw new Error('The cookie function only accepts STRING as param') + } + return Cookie.parse(str, {loose: true}) +} + +// Adapt the sometimes-Async api of tough.CookieJar to our requirements +function RequestJar(store) { + var self = this + self._jar = new CookieJar(store, {looseMode: true}) +} +RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) { + var self = this + return self._jar.setCookieSync(cookieOrStr, uri, options || {}) +} +RequestJar.prototype.getCookieString = function(uri) { + var self = this + return self._jar.getCookieStringSync(uri) +} +RequestJar.prototype.getCookies = function(uri) { + var self = this + return self._jar.getCookiesSync(uri) +} + +exports.jar = function(store) { + return new RequestJar(store) +} diff --git a/node_modules/azure-storage/node_modules/request/lib/getProxyFromURI.js b/node_modules/azure-storage/node_modules/request/lib/getProxyFromURI.js new file mode 100644 index 000000000..c2013a6e1 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/getProxyFromURI.js @@ -0,0 +1,79 @@ +'use strict' + +function formatHostname(hostname) { + // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' + return hostname.replace(/^\.*/, '.').toLowerCase() +} + +function parseNoProxyZone(zone) { + zone = zone.trim().toLowerCase() + + var zoneParts = zone.split(':', 2) + , zoneHost = formatHostname(zoneParts[0]) + , zonePort = zoneParts[1] + , hasPort = zone.indexOf(':') > -1 + + return {hostname: zoneHost, port: zonePort, hasPort: hasPort} +} + +function uriInNoProxy(uri, noProxy) { + var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') + , hostname = formatHostname(uri.hostname) + , noProxyList = noProxy.split(',') + + // iterate through the noProxyList until it finds a match. + return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) { + var isMatchedAt = hostname.indexOf(noProxyZone.hostname) + , hostnameMatched = ( + isMatchedAt > -1 && + (isMatchedAt === hostname.length - noProxyZone.hostname.length) + ) + + if (noProxyZone.hasPort) { + return (port === noProxyZone.port) && hostnameMatched + } + + return hostnameMatched + }) +} + +function getProxyFromURI(uri) { + // Decide the proper request proxy to use based on the request URI object and the + // environmental variables (NO_PROXY, HTTP_PROXY, etc.) + // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html) + + var noProxy = process.env.NO_PROXY || process.env.no_proxy || '' + + // if the noProxy is a wildcard then return null + + if (noProxy === '*') { + return null + } + + // if the noProxy is not empty and the uri is found return null + + if (noProxy !== '' && uriInNoProxy(uri, noProxy)) { + return null + } + + // Check for HTTP or HTTPS Proxy in environment Else default to null + + if (uri.protocol === 'http:') { + return process.env.HTTP_PROXY || + process.env.http_proxy || null + } + + if (uri.protocol === 'https:') { + return process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy || null + } + + // if none of that works, return null + // (What uri protocol are you using then?) + + return null +} + +module.exports = getProxyFromURI diff --git a/node_modules/azure-storage/node_modules/request/lib/har.js b/node_modules/azure-storage/node_modules/request/lib/har.js new file mode 100644 index 000000000..305957487 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/har.js @@ -0,0 +1,215 @@ +'use strict' + +var fs = require('fs') +var qs = require('querystring') +var validate = require('har-validator') +var extend = require('extend') + +function Har (request) { + this.request = request +} + +Har.prototype.reducer = function (obj, pair) { + // new property ? + if (obj[pair.name] === undefined) { + obj[pair.name] = pair.value + return obj + } + + // existing? convert to array + var arr = [ + obj[pair.name], + pair.value + ] + + obj[pair.name] = arr + + return obj +} + +Har.prototype.prep = function (data) { + // construct utility properties + data.queryObj = {} + data.headersObj = {} + data.postData.jsonObj = false + data.postData.paramsObj = false + + // construct query objects + if (data.queryString && data.queryString.length) { + data.queryObj = data.queryString.reduce(this.reducer, {}) + } + + // construct headers objects + if (data.headers && data.headers.length) { + // loweCase header keys + data.headersObj = data.headers.reduceRight(function (headers, header) { + headers[header.name] = header.value + return headers + }, {}) + } + + // construct Cookie header + if (data.cookies && data.cookies.length) { + var cookies = data.cookies.map(function (cookie) { + return cookie.name + '=' + cookie.value + }) + + if (cookies.length) { + data.headersObj.cookie = cookies.join('; ') + } + } + + // prep body + function some (arr) { + return arr.some(function (type) { + return data.postData.mimeType.indexOf(type) === 0 + }) + } + + if (some([ + 'multipart/mixed', + 'multipart/related', + 'multipart/form-data', + 'multipart/alternative'])) { + + // reset values + data.postData.mimeType = 'multipart/form-data' + } + + else if (some([ + 'application/x-www-form-urlencoded'])) { + + if (!data.postData.params) { + data.postData.text = '' + } else { + data.postData.paramsObj = data.postData.params.reduce(this.reducer, {}) + + // always overwrite + data.postData.text = qs.stringify(data.postData.paramsObj) + } + } + + else if (some([ + 'text/json', + 'text/x-json', + 'application/json', + 'application/x-json'])) { + + data.postData.mimeType = 'application/json' + + if (data.postData.text) { + try { + data.postData.jsonObj = JSON.parse(data.postData.text) + } catch (e) { + this.request.debug(e) + + // force back to text/plain + data.postData.mimeType = 'text/plain' + } + } + } + + return data +} + +Har.prototype.options = function (options) { + // skip if no har property defined + if (!options.har) { + return options + } + + var har = {} + extend(har, options.har) + + // only process the first entry + if (har.log && har.log.entries) { + har = har.log.entries[0] + } + + // add optional properties to make validation successful + har.url = har.url || options.url || options.uri || options.baseUrl || '/' + har.httpVersion = har.httpVersion || 'HTTP/1.1' + har.queryString = har.queryString || [] + har.headers = har.headers || [] + har.cookies = har.cookies || [] + har.postData = har.postData || {} + har.postData.mimeType = har.postData.mimeType || 'application/octet-stream' + + har.bodySize = 0 + har.headersSize = 0 + har.postData.size = 0 + + if (!validate.request(har)) { + return options + } + + // clean up and get some utility properties + var req = this.prep(har) + + // construct new options + if (req.url) { + options.url = req.url + } + + if (req.method) { + options.method = req.method + } + + if (Object.keys(req.queryObj).length) { + options.qs = req.queryObj + } + + if (Object.keys(req.headersObj).length) { + options.headers = req.headersObj + } + + function test (type) { + return req.postData.mimeType.indexOf(type) === 0 + } + if (test('application/x-www-form-urlencoded')) { + options.form = req.postData.paramsObj + } + else if (test('application/json')) { + if (req.postData.jsonObj) { + options.body = req.postData.jsonObj + options.json = true + } + } + else if (test('multipart/form-data')) { + options.formData = {} + + req.postData.params.forEach(function (param) { + var attachment = {} + + if (!param.fileName && !param.fileName && !param.contentType) { + options.formData[param.name] = param.value + return + } + + // attempt to read from disk! + if (param.fileName && !param.value) { + attachment.value = fs.createReadStream(param.fileName) + } else if (param.value) { + attachment.value = param.value + } + + if (param.fileName) { + attachment.options = { + filename: param.fileName, + contentType: param.contentType ? param.contentType : null + } + } + + options.formData[param.name] = attachment + }) + } + else { + if (req.postData.text) { + options.body = req.postData.text + } + } + + return options +} + +exports.Har = Har diff --git a/node_modules/azure-storage/node_modules/request/lib/helpers.js b/node_modules/azure-storage/node_modules/request/lib/helpers.js new file mode 100644 index 000000000..05c77a0bd --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/helpers.js @@ -0,0 +1,66 @@ +'use strict' + +var jsonSafeStringify = require('json-stringify-safe') + , crypto = require('crypto') + , Buffer = require('safe-buffer').Buffer + +var defer = typeof setImmediate === 'undefined' + ? process.nextTick + : setImmediate + +function paramsHaveRequestBody(params) { + return ( + params.body || + params.requestBodyStream || + (params.json && typeof params.json !== 'boolean') || + params.multipart + ) +} + +function safeStringify (obj, replacer) { + var ret + try { + ret = JSON.stringify(obj, replacer) + } catch (e) { + ret = jsonSafeStringify(obj, replacer) + } + return ret +} + +function md5 (str) { + return crypto.createHash('md5').update(str).digest('hex') +} + +function isReadStream (rs) { + return rs.readable && rs.path && rs.mode +} + +function toBase64 (str) { + return Buffer.from(str || '', 'utf8').toString('base64') +} + +function copy (obj) { + var o = {} + Object.keys(obj).forEach(function (i) { + o[i] = obj[i] + }) + return o +} + +function version () { + var numbers = process.version.replace('v', '').split('.') + return { + major: parseInt(numbers[0], 10), + minor: parseInt(numbers[1], 10), + patch: parseInt(numbers[2], 10) + } +} + +exports.paramsHaveRequestBody = paramsHaveRequestBody +exports.safeStringify = safeStringify +exports.md5 = md5 +exports.isReadStream = isReadStream +exports.toBase64 = toBase64 +exports.copy = copy +exports.version = version +exports.defer = defer diff --git a/node_modules/azure-storage/node_modules/request/lib/multipart.js b/node_modules/azure-storage/node_modules/request/lib/multipart.js new file mode 100644 index 000000000..fc7b50276 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/multipart.js @@ -0,0 +1,113 @@ +'use strict' + +var uuid = require('uuid') + , CombinedStream = require('combined-stream') + , isstream = require('isstream') + , Buffer = require('safe-buffer').Buffer + + +function Multipart (request) { + this.request = request + this.boundary = uuid() + this.chunked = false + this.body = null +} + +Multipart.prototype.isChunked = function (options) { + var self = this + , chunked = false + , parts = options.data || options + + if (!parts.forEach) { + self.request.emit('error', new Error('Argument error, options.multipart.')) + } + + if (options.chunked !== undefined) { + chunked = options.chunked + } + + if (self.request.getHeader('transfer-encoding') === 'chunked') { + chunked = true + } + + if (!chunked) { + parts.forEach(function (part) { + if (typeof part.body === 'undefined') { + self.request.emit('error', new Error('Body attribute missing in multipart.')) + } + if (isstream(part.body)) { + chunked = true + } + }) + } + + return chunked +} + +Multipart.prototype.setHeaders = function (chunked) { + var self = this + + if (chunked && !self.request.hasHeader('transfer-encoding')) { + self.request.setHeader('transfer-encoding', 'chunked') + } + + var header = self.request.getHeader('content-type') + + if (!header || header.indexOf('multipart') === -1) { + self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary) + } else { + if (header.indexOf('boundary') !== -1) { + self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1') + } else { + self.request.setHeader('content-type', header + '; boundary=' + self.boundary) + } + } +} + +Multipart.prototype.build = function (parts, chunked) { + var self = this + var body = chunked ? new CombinedStream() : [] + + function add (part) { + if (typeof part === 'number') { + part = part.toString() + } + return chunked ? body.append(part) : body.push(Buffer.from(part)) + } + + if (self.request.preambleCRLF) { + add('\r\n') + } + + parts.forEach(function (part) { + var preamble = '--' + self.boundary + '\r\n' + Object.keys(part).forEach(function (key) { + if (key === 'body') { return } + preamble += key + ': ' + part[key] + '\r\n' + }) + preamble += '\r\n' + add(preamble) + add(part.body) + add('\r\n') + }) + add('--' + self.boundary + '--') + + if (self.request.postambleCRLF) { + add('\r\n') + } + + return body +} + +Multipart.prototype.onRequest = function (options) { + var self = this + + var chunked = self.isChunked(options) + , parts = options.data || options + + self.setHeaders(chunked) + self.chunked = chunked + self.body = self.build(parts, chunked) +} + +exports.Multipart = Multipart diff --git a/node_modules/azure-storage/node_modules/request/lib/oauth.js b/node_modules/azure-storage/node_modules/request/lib/oauth.js new file mode 100644 index 000000000..13b693773 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/oauth.js @@ -0,0 +1,148 @@ +'use strict' + +var url = require('url') + , qs = require('qs') + , caseless = require('caseless') + , uuid = require('uuid') + , oauth = require('oauth-sign') + , crypto = require('crypto') + , Buffer = require('safe-buffer').Buffer + + +function OAuth (request) { + this.request = request + this.params = null +} + +OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) { + var oa = {} + for (var i in _oauth) { + oa['oauth_' + i] = _oauth[i] + } + if (!oa.oauth_version) { + oa.oauth_version = '1.0' + } + if (!oa.oauth_timestamp) { + oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString() + } + if (!oa.oauth_nonce) { + oa.oauth_nonce = uuid().replace(/-/g, '') + } + if (!oa.oauth_signature_method) { + oa.oauth_signature_method = 'HMAC-SHA1' + } + + var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key + delete oa.oauth_consumer_secret + delete oa.oauth_private_key + + var token_secret = oa.oauth_token_secret + delete oa.oauth_token_secret + + var realm = oa.oauth_realm + delete oa.oauth_realm + delete oa.oauth_transport_method + + var baseurl = uri.protocol + '//' + uri.host + uri.pathname + var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&')) + + oa.oauth_signature = oauth.sign( + oa.oauth_signature_method, + method, + baseurl, + params, + consumer_secret_or_private_key, + token_secret) + + if (realm) { + oa.realm = realm + } + + return oa +} + +OAuth.prototype.buildBodyHash = function(_oauth, body) { + if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) { + this.request.emit('error', new Error('oauth: ' + _oauth.signature_method + + ' signature_method not supported with body_hash signing.')) + } + + var shasum = crypto.createHash('sha1') + shasum.update(body || '') + var sha1 = shasum.digest('hex') + + return Buffer.from(sha1).toString('base64') +} + +OAuth.prototype.concatParams = function (oa, sep, wrap) { + wrap = wrap || '' + + var params = Object.keys(oa).filter(function (i) { + return i !== 'realm' && i !== 'oauth_signature' + }).sort() + + if (oa.realm) { + params.splice(0, 0, 'realm') + } + params.push('oauth_signature') + + return params.map(function (i) { + return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap + }).join(sep) +} + +OAuth.prototype.onRequest = function (_oauth) { + var self = this + self.params = _oauth + + var uri = self.request.uri || {} + , method = self.request.method || '' + , headers = caseless(self.request.headers) + , body = self.request.body || '' + , qsLib = self.request.qsLib || qs + + var form + , query + , contentType = headers.get('content-type') || '' + , formContentType = 'application/x-www-form-urlencoded' + , transport = _oauth.transport_method || 'header' + + if (contentType.slice(0, formContentType.length) === formContentType) { + contentType = formContentType + form = body + } + if (uri.query) { + query = uri.query + } + if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) { + self.request.emit('error', new Error('oauth: transport_method of body requires POST ' + + 'and content-type ' + formContentType)) + } + + if (!form && typeof _oauth.body_hash === 'boolean') { + _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString()) + } + + var oa = self.buildParams(_oauth, uri, method, query, form, qsLib) + + switch (transport) { + case 'header': + self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"')) + break + + case 'query': + var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&') + self.request.uri = url.parse(href) + self.request.path = self.request.uri.path + break + + case 'body': + self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&') + break + + default: + self.request.emit('error', new Error('oauth: transport_method invalid')) + } +} + +exports.OAuth = OAuth diff --git a/node_modules/azure-storage/node_modules/request/lib/querystring.js b/node_modules/azure-storage/node_modules/request/lib/querystring.js new file mode 100644 index 000000000..baf5e8021 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/querystring.js @@ -0,0 +1,51 @@ +'use strict' + +var qs = require('qs') + , querystring = require('querystring') + + +function Querystring (request) { + this.request = request + this.lib = null + this.useQuerystring = null + this.parseOptions = null + this.stringifyOptions = null +} + +Querystring.prototype.init = function (options) { + if (this.lib) {return} + + this.useQuerystring = options.useQuerystring + this.lib = (this.useQuerystring ? querystring : qs) + + this.parseOptions = options.qsParseOptions || {} + this.stringifyOptions = options.qsStringifyOptions || {} +} + +Querystring.prototype.stringify = function (obj) { + return (this.useQuerystring) + ? this.rfc3986(this.lib.stringify(obj, + this.stringifyOptions.sep || null, + this.stringifyOptions.eq || null, + this.stringifyOptions)) + : this.lib.stringify(obj, this.stringifyOptions) +} + +Querystring.prototype.parse = function (str) { + return (this.useQuerystring) + ? this.lib.parse(str, + this.parseOptions.sep || null, + this.parseOptions.eq || null, + this.parseOptions) + : this.lib.parse(str, this.parseOptions) +} + +Querystring.prototype.rfc3986 = function (str) { + return str.replace(/[!'()*]/g, function (c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) +} + +Querystring.prototype.unescape = querystring.unescape + +exports.Querystring = Querystring diff --git a/node_modules/azure-storage/node_modules/request/lib/redirect.js b/node_modules/azure-storage/node_modules/request/lib/redirect.js new file mode 100644 index 000000000..f8604491f --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/redirect.js @@ -0,0 +1,157 @@ +'use strict' + +var url = require('url') +var isUrl = /^https?:/ + +function Redirect (request) { + this.request = request + this.followRedirect = true + this.followRedirects = true + this.followAllRedirects = false + this.followOriginalHttpMethod = false + this.allowRedirect = function () {return true} + this.maxRedirects = 10 + this.redirects = [] + this.redirectsFollowed = 0 + this.removeRefererHeader = false +} + +Redirect.prototype.onRequest = function (options) { + var self = this + + if (options.maxRedirects !== undefined) { + self.maxRedirects = options.maxRedirects + } + if (typeof options.followRedirect === 'function') { + self.allowRedirect = options.followRedirect + } + if (options.followRedirect !== undefined) { + self.followRedirects = !!options.followRedirect + } + if (options.followAllRedirects !== undefined) { + self.followAllRedirects = options.followAllRedirects + } + if (self.followRedirects || self.followAllRedirects) { + self.redirects = self.redirects || [] + } + if (options.removeRefererHeader !== undefined) { + self.removeRefererHeader = options.removeRefererHeader + } + if (options.followOriginalHttpMethod !== undefined) { + self.followOriginalHttpMethod = options.followOriginalHttpMethod + } +} + +Redirect.prototype.redirectTo = function (response) { + var self = this + , request = self.request + + var redirectTo = null + if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) { + var location = response.caseless.get('location') + request.debug('redirect', location) + + if (self.followAllRedirects) { + redirectTo = location + } else if (self.followRedirects) { + switch (request.method) { + case 'PATCH': + case 'PUT': + case 'POST': + case 'DELETE': + // Do not follow redirects + break + default: + redirectTo = location + break + } + } + } else if (response.statusCode === 401) { + var authHeader = request._auth.onResponse(response) + if (authHeader) { + request.setHeader('authorization', authHeader) + redirectTo = request.uri + } + } + return redirectTo +} + +Redirect.prototype.onResponse = function (response) { + var self = this + , request = self.request + + var redirectTo = self.redirectTo(response) + if (!redirectTo || !self.allowRedirect.call(request, response)) { + return false + } + + request.debug('redirect to', redirectTo) + + // ignore any potential response body. it cannot possibly be useful + // to us at this point. + // response.resume should be defined, but check anyway before calling. Workaround for browserify. + if (response.resume) { + response.resume() + } + + if (self.redirectsFollowed >= self.maxRedirects) { + request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href)) + return false + } + self.redirectsFollowed += 1 + + if (!isUrl.test(redirectTo)) { + redirectTo = url.resolve(request.uri.href, redirectTo) + } + + var uriPrev = request.uri + request.uri = url.parse(redirectTo) + + // handle the case where we change protocol from https to http or vice versa + if (request.uri.protocol !== uriPrev.protocol) { + delete request.agent + } + + self.redirects.push( + { statusCode : response.statusCode + , redirectUri: redirectTo + } + ) + if (self.followAllRedirects && request.method !== 'HEAD' + && response.statusCode !== 401 && response.statusCode !== 307) { + request.method = self.followOriginalHttpMethod ? request.method : 'GET' + } + // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215 + delete request.src + delete request.req + delete request._started + if (response.statusCode !== 401 && response.statusCode !== 307) { + // Remove parameters from the previous response, unless this is the second request + // for a server that requires digest authentication. + delete request.body + delete request._form + if (request.headers) { + request.removeHeader('host') + request.removeHeader('content-type') + request.removeHeader('content-length') + if (request.uri.hostname !== request.originalHost.split(':')[0]) { + // Remove authorization if changing hostnames (but not if just + // changing ports or protocols). This matches the behavior of curl: + // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710 + request.removeHeader('authorization') + } + } + } + + if (!self.removeRefererHeader) { + request.setHeader('referer', uriPrev.href) + } + + request.emit('redirect') + + request.init() + + return true +} + +exports.Redirect = Redirect diff --git a/node_modules/azure-storage/node_modules/request/lib/tunnel.js b/node_modules/azure-storage/node_modules/request/lib/tunnel.js new file mode 100644 index 000000000..bf96a8fec --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/lib/tunnel.js @@ -0,0 +1,176 @@ +'use strict' + +var url = require('url') + , tunnel = require('tunnel-agent') + +var defaultProxyHeaderWhiteList = [ + 'accept', + 'accept-charset', + 'accept-encoding', + 'accept-language', + 'accept-ranges', + 'cache-control', + 'content-encoding', + 'content-language', + 'content-location', + 'content-md5', + 'content-range', + 'content-type', + 'connection', + 'date', + 'expect', + 'max-forwards', + 'pragma', + 'referer', + 'te', + 'user-agent', + 'via' +] + +var defaultProxyHeaderExclusiveList = [ + 'proxy-authorization' +] + +function constructProxyHost(uriObject) { + var port = uriObject.port + , protocol = uriObject.protocol + , proxyHost = uriObject.hostname + ':' + + if (port) { + proxyHost += port + } else if (protocol === 'https:') { + proxyHost += '443' + } else { + proxyHost += '80' + } + + return proxyHost +} + +function constructProxyHeaderWhiteList(headers, proxyHeaderWhiteList) { + var whiteList = proxyHeaderWhiteList + .reduce(function (set, header) { + set[header.toLowerCase()] = true + return set + }, {}) + + return Object.keys(headers) + .filter(function (header) { + return whiteList[header.toLowerCase()] + }) + .reduce(function (set, header) { + set[header] = headers[header] + return set + }, {}) +} + +function constructTunnelOptions (request, proxyHeaders) { + var proxy = request.proxy + + var tunnelOptions = { + proxy : { + host : proxy.hostname, + port : +proxy.port, + proxyAuth : proxy.auth, + headers : proxyHeaders + }, + headers : request.headers, + ca : request.ca, + cert : request.cert, + key : request.key, + passphrase : request.passphrase, + pfx : request.pfx, + ciphers : request.ciphers, + rejectUnauthorized : request.rejectUnauthorized, + secureOptions : request.secureOptions, + secureProtocol : request.secureProtocol + } + + return tunnelOptions +} + +function constructTunnelFnName(uri, proxy) { + var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http') + var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http') + return [uriProtocol, proxyProtocol].join('Over') +} + +function getTunnelFn(request) { + var uri = request.uri + var proxy = request.proxy + var tunnelFnName = constructTunnelFnName(uri, proxy) + return tunnel[tunnelFnName] +} + + +function Tunnel (request) { + this.request = request + this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList + this.proxyHeaderExclusiveList = [] + if (typeof request.tunnel !== 'undefined') { + this.tunnelOverride = request.tunnel + } +} + +Tunnel.prototype.isEnabled = function () { + var self = this + , request = self.request + // Tunnel HTTPS by default. Allow the user to override this setting. + + // If self.tunnelOverride is set (the user specified a value), use it. + if (typeof self.tunnelOverride !== 'undefined') { + return self.tunnelOverride + } + + // If the destination is HTTPS, tunnel. + if (request.uri.protocol === 'https:') { + return true + } + + // Otherwise, do not use tunnel. + return false +} + +Tunnel.prototype.setup = function (options) { + var self = this + , request = self.request + + options = options || {} + + if (typeof request.proxy === 'string') { + request.proxy = url.parse(request.proxy) + } + + if (!request.proxy || !request.tunnel) { + return false + } + + // Setup Proxy Header Exclusive List and White List + if (options.proxyHeaderWhiteList) { + self.proxyHeaderWhiteList = options.proxyHeaderWhiteList + } + if (options.proxyHeaderExclusiveList) { + self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList + } + + var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList) + var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList) + + // Setup Proxy Headers and Proxy Headers Host + // Only send the Proxy White Listed Header names + var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList) + proxyHeaders.host = constructProxyHost(request.uri) + + proxyHeaderExclusiveList.forEach(request.removeHeader, request) + + // Set Agent from Tunnel Data + var tunnelFn = getTunnelFn(request) + var tunnelOptions = constructTunnelOptions(request, proxyHeaders) + request.agent = tunnelFn(tunnelOptions) + + return true +} + +Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList +Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList +exports.Tunnel = Tunnel diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/.eslintrc b/node_modules/azure-storage/node_modules/request/node_modules/extend/.eslintrc new file mode 100644 index 000000000..90b31938e --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 15], + "eqeqeq": [2, "allow-null"], + "func-name-matching": [1], + "max-depth": [1, 4], + "max-statements": [2, 26], + "no-extra-parens": [1], + "no-magic-numbers": [0], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + "sort-keys": [0], + } +} diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/.jscs.json b/node_modules/azure-storage/node_modules/request/node_modules/extend/.jscs.json new file mode 100644 index 000000000..0284c86da --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/.jscs.json @@ -0,0 +1,175 @@ +{ + "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": 6 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": false, + + "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/azure-storage/node_modules/request/node_modules/extend/.npmignore b/node_modules/azure-storage/node_modules/request/node_modules/extend/.npmignore new file mode 100644 index 000000000..30d74d258 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/.npmignore @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/.travis.yml b/node_modules/azure-storage/node_modules/request/node_modules/extend/.travis.yml new file mode 100644 index 000000000..6bf696c87 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/.travis.yml @@ -0,0 +1,179 @@ +language: node_js +os: + - linux +node_js: + - "7.9" + - "6.10" + - "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 npm install -g npm; 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: "node" + env: COVERAGE=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.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 + ##- node_js: "7" + #env: TEST=true + #os: osx + #- node_js: "6" + #env: TEST=true + #os: osx + #- node_js: "5" + #env: TEST=true + #os: osx + #- node_js: "4" + #env: TEST=true + #os: osx + #- node_js: "iojs" + #env: TEST=true + #os: osx + #- node_js: "0.12" + #env: TEST=true + #os: osx + #- node_js: "0.10" + #env: TEST=true + #os: osx + #- node_js: "0.8" + #env: TEST=true + #os: osx + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/CHANGELOG.md b/node_modules/azure-storage/node_modules/request/node_modules/extend/CHANGELOG.md new file mode 100644 index 000000000..0fe528764 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/CHANGELOG.md @@ -0,0 +1,77 @@ +3.0.1 / 2017-04-27 +================== + * [Fix] deep extending should work with a non-object (#46) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v7.9`, `v6.10`, `v4.8`; improve matrix + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. + * [Docs] Add example to readme (#34) + +3.0.0 / 2015-07-01 +================== + * [Possible breaking change] Use global "strict" directive (#32) + * [Tests] `int` is an ES3 reserved word + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Add `npm run eslint` + * [Dev Deps] Update `covert`, `jscs` + +2.0.1 / 2015-04-25 +================== + * Use an inline `isArray` check, for ES3 browsers. (#27) + * Some old browsers fail when an identifier is `toString` + * Test latest `node` and `io.js` versions on `travis-ci`; speed up builds + * Add license info to package.json (#25) + * Update `tape`, `jscs` + * Adding a CHANGELOG + +2.0.0 / 2014-10-01 +================== + * Increase code coverage to 100%; run code coverage as part of tests + * Add `npm run lint`; Run linter as part of tests + * Remove nodeType and setInterval checks in isPlainObject + * Updating `tape`, `jscs`, `covert` + * General style and README cleanup + +1.3.0 / 2014-06-20 +================== + * Add component.json for browser support (#18) + * Use SVG for badges in README (#16) + * Updating `tape`, `covert` + * Updating travis-ci to work with multiple node versions + * Fix `deep === false` bug (returning target as {}) (#14) + * Fixing constructor checks in isPlainObject + * Adding additional test coverage + * Adding `npm run coverage` + * Add LICENSE (#13) + * Adding a warning about `false`, per #11 + * General style and whitespace cleanup + +1.2.1 / 2013-09-14 +================== + * Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8 + * Updating `tape` + +1.2.0 / 2013-09-02 +================== + * Updating the README: add badges + * Adding a missing variable reference. + * Using `tape` instead of `buster` for tests; add more tests (#7) + * Adding node 0.10 to Travis CI (#6) + * Enabling "npm test" and cleaning up package.json (#5) + * Add Travis CI. + +1.1.3 / 2012-12-06 +================== + * Added unit tests. + * Ensure extend function is named. (Looks nicer in a stack trace.) + * README cleanup. + +1.1.1 / 2012-11-07 +================== + * README cleanup. + * Added installation instructions. + * Added a missing semicolon + +1.0.0 / 2012-04-08 +================== + * Initial commit + diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/LICENSE b/node_modules/azure-storage/node_modules/request/node_modules/extend/LICENSE new file mode 100644 index 000000000..e16d6a56c --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2014 Stefan Thomas + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +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/azure-storage/node_modules/request/node_modules/extend/README.md b/node_modules/azure-storage/node_modules/request/node_modules/extend/README.md new file mode 100644 index 000000000..5b8249aa9 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/README.md @@ -0,0 +1,81 @@ +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] + +# extend() for Node.js [![Version Badge][npm-version-png]][npm-url] + +`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true. + +Notes: + +* Since Node.js >= 4, + [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + now offers the same functionality natively (but without the "deep copy" option). + See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6). +* Some native implementations of `Object.assign` in both Node.js and many + browsers (since NPM modules are for the browser too) may not be fully + spec-compliant. + Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for + a compliant candidate. + +## Installation + +This package is available on [npm][npm-url] as: `extend` + +``` sh +npm install extend +``` + +## Usage + +**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)** + +*Extend one object with one or more others, returning the modified object.* + +**Example:** + +``` js +var extend = require('extend'); +extend(targetObject, object1, object2); +``` + +Keep in mind that the target object will be modified, and will be returned from extend(). + +If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s). +Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. +Warning: passing `false` as the first argument is not supported. + +### Arguments + +* `deep` *Boolean* (optional) +If set, the merge becomes recursive (i.e. deep copy). +* `target` *Object* +The object to extend. +* `object1` *Object* +The object that will be merged into the first. +* `objectN` *Object* (Optional) +More objects to merge into the first. + +## License + +`node-extend` is licensed under the [MIT License][mit-license-url]. + +## Acknowledgements + +All credit to the jQuery authors for perfecting this amazing utility. + +Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb]. + +[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg +[travis-url]: https://travis-ci.org/justmoon/node-extend +[npm-url]: https://npmjs.org/package/extend +[mit-license-url]: http://opensource.org/licenses/MIT +[github-justmoon]: https://github.com/justmoon +[github-insin]: https://github.com/insin +[github-ljharb]: https://github.com/ljharb +[npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg +[deps-svg]: https://david-dm.org/justmoon/node-extend.svg +[deps-url]: https://david-dm.org/justmoon/node-extend +[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg +[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies + diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/component.json b/node_modules/azure-storage/node_modules/request/node_modules/extend/component.json new file mode 100644 index 000000000..1500a2f37 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/component.json @@ -0,0 +1,32 @@ +{ + "name": "extend", + "author": "Stefan Thomas (http://www.justmoon.net)", + "version": "3.0.0", + "description": "Port of jQuery.extend for node.js and the browser.", + "scripts": [ + "index.js" + ], + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "keywords": [ + "extend", + "clone", + "merge" + ], + "repository" : { + "type": "git", + "url": "https://github.com/justmoon/node-extend.git" + }, + "dependencies": { + }, + "devDependencies": { + "tape" : "~3.0.0", + "covert": "~0.4.0", + "jscs": "~1.6.2" + } +} + diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/index.js b/node_modules/azure-storage/node_modules/request/node_modules/extend/index.js new file mode 100644 index 000000000..bbe53f660 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/index.js @@ -0,0 +1,86 @@ +'use strict'; + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = target[name]; + copy = options[name]; + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[name] = extend(deep, clone, copy); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + target[name] = copy; + } + } + } + } + } + + // Return the modified object + return target; +}; diff --git a/node_modules/azure-storage/node_modules/request/node_modules/extend/package.json b/node_modules/azure-storage/node_modules/request/node_modules/extend/package.json new file mode 100644 index 000000000..140e6e3b7 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/node_modules/extend/package.json @@ -0,0 +1,105 @@ +{ + "_args": [ + [ + "extend@~3.0.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request" + ] + ], + "_from": "extend@>=3.0.0-0 <3.1.0-0", + "_id": "extend@3.0.1", + "_inCache": true, + "_location": "/azure-storage/request/extend", + "_nodeVersion": "7.9.0", + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/extend-3.0.1.tgz_1493357803699_0.1708133383654058" + }, + "_npmUser": { + "email": "ljharb@gmail.com", + "name": "ljharb" + }, + "_npmVersion": "4.2.0", + "_phantomChildren": {}, + "_requested": { + "name": "extend", + "raw": "extend@~3.0.0", + "rawSpec": "~3.0.0", + "scope": null, + "spec": ">=3.0.0-0 <3.1.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage/request" + ], + "_resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", + "_shasum": "a755ea7bc1adfcc5a31ce7e762dbaadc5e636444", + "_shrinkwrap": null, + "_spec": "extend@~3.0.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request", + "author": { + "email": "justmoon@members.fsf.org", + "name": "Stefan Thomas", + "url": "http://www.justmoon.net" + }, + "bugs": { + "url": "https://github.com/justmoon/node-extend/issues" + }, + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "dependencies": {}, + "description": "Port of jQuery.extend for node.js and the browser", + "devDependencies": { + "@ljharb/eslint-config": "^11.0.0", + "covert": "^1.1.0", + "eslint": "^3.19.0", + "jscs": "^3.0.7", + "tape": "^4.6.3" + }, + "directories": {}, + "dist": { + "shasum": "a755ea7bc1adfcc5a31ce7e762dbaadc5e636444", + "tarball": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz" + }, + "gitHead": "138b515df4d628bb1742254ede5d2551c0fecae7", + "homepage": "https://github.com/justmoon/node-extend#readme", + "installable": true, + "keywords": [ + "clone", + "extend", + "merge" + ], + "license": "MIT", + "main": "index", + "maintainers": [ + { + "name": "justmoon", + "email": "justmoon@members.fsf.org" + }, + { + "name": "ljharb", + "email": "ljharb@gmail.com" + } + ], + "name": "extend", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/justmoon/node-extend.git" + }, + "scripts": { + "coverage": "covert test/index.js", + "coverage-quiet": "covert test/index.js --quiet", + "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" + }, + "version": "3.0.1" +} diff --git a/node_modules/azure-storage/node_modules/request/package.json b/node_modules/azure-storage/node_modules/request/package.json new file mode 100644 index 000000000..8e64f2b1c --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/package.json @@ -0,0 +1,156 @@ +{ + "_args": [ + [ + "request@~2.81.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage" + ] + ], + "_from": "request@>=2.81.0-0 <2.82.0-0", + "_id": "request@2.81.0", + "_inCache": true, + "_location": "/azure-storage/request", + "_nodeVersion": "7.2.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/request-2.81.0.tgz_1489075005134_0.036041518207639456" + }, + "_npmUser": { + "email": "simeonvelichkov@gmail.com", + "name": "simov" + }, + "_npmVersion": "2.15.11", + "_phantomChildren": {}, + "_requested": { + "name": "request", + "raw": "request@~2.81.0", + "rawSpec": "~2.81.0", + "scope": null, + "spec": ">=2.81.0-0 <2.82.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage" + ], + "_resolved": "https://registry.npmjs.org/request/-/request-2.81.0.tgz", + "_shasum": "c6928946a0e06c5f8d6f8a9333469ffda46298a0", + "_shrinkwrap": null, + "_spec": "request@~2.81.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage", + "author": { + "email": "mikeal.rogers@gmail.com", + "name": "Mikeal Rogers" + }, + "bugs": { + "url": "http://github.com/request/request/issues" + }, + "dependencies": { + "aws-sign2": "~0.6.0", + "aws4": "^1.2.1", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.0", + "forever-agent": "~0.6.1", + "form-data": "~2.1.1", + "har-validator": "~4.2.1", + "hawk": "~3.1.3", + "http-signature": "~1.1.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.7", + "oauth-sign": "~0.8.1", + "performance-now": "^0.2.0", + "qs": "~6.4.0", + "safe-buffer": "^5.0.1", + "stringstream": "~0.0.4", + "tough-cookie": "~2.3.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.0.0" + }, + "description": "Simplified HTTP request client.", + "devDependencies": { + "bluebird": "^3.2.1", + "browserify": "^13.0.1", + "browserify-istanbul": "^2.0.0", + "buffer-equal": "^1.0.0", + "codecov": "^1.0.1", + "coveralls": "^2.11.4", + "eslint": "^2.5.3", + "function-bind": "^1.0.2", + "istanbul": "^0.4.0", + "karma": "^1.1.1", + "karma-browserify": "^5.0.1", + "karma-cli": "^1.0.0", + "karma-coverage": "^1.0.0", + "karma-phantomjs-launcher": "^1.0.0", + "karma-tap": "^3.0.1", + "phantomjs-prebuilt": "^2.1.3", + "rimraf": "^2.2.8", + "server-destroy": "^1.0.1", + "tape": "^4.6.0", + "taper": "^0.5.0" + }, + "directories": {}, + "dist": { + "shasum": "c6928946a0e06c5f8d6f8a9333469ffda46298a0", + "tarball": "https://registry.npmjs.org/request/-/request-2.81.0.tgz" + }, + "engines": { + "node": ">= 4" + }, + "files": [ + "index.js", + "lib/", + "request.js" + ], + "gitHead": "a0cdc704c19e63e6f1740e173bb003c51eef524c", + "greenkeeper": { + "ignore": [ + "eslint", + "har-validator", + "hawk" + ] + }, + "homepage": "https://github.com/request/request#readme", + "installable": true, + "keywords": [ + "http", + "simple", + "util", + "utility" + ], + "license": "Apache-2.0", + "main": "index.js", + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "nylen", + "email": "jnylen@gmail.com" + }, + { + "name": "fredkschott", + "email": "fkschott@gmail.com" + }, + { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + } + ], + "name": "request", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/request/request.git" + }, + "scripts": { + "lint": "eslint lib/ *.js tests/ && echo Lint passed.", + "test": "npm run lint && npm run test-ci && npm run test-browser", + "test-browser": "node tests/browser/start.js", + "test-ci": "taper tests/test-*.js", + "test-cov": "istanbul cover tape tests/test-*.js" + }, + "version": "2.81.0" +} diff --git a/node_modules/azure-storage/node_modules/request/request.js b/node_modules/azure-storage/node_modules/request/request.js new file mode 100644 index 000000000..467524ba4 --- /dev/null +++ b/node_modules/azure-storage/node_modules/request/request.js @@ -0,0 +1,1565 @@ +'use strict' + +var http = require('http') + , https = require('https') + , url = require('url') + , util = require('util') + , stream = require('stream') + , zlib = require('zlib') + , hawk = require('hawk') + , aws2 = require('aws-sign2') + , aws4 = require('aws4') + , httpSignature = require('http-signature') + , mime = require('mime-types') + , stringstream = require('stringstream') + , caseless = require('caseless') + , ForeverAgent = require('forever-agent') + , FormData = require('form-data') + , extend = require('extend') + , isstream = require('isstream') + , isTypedArray = require('is-typedarray').strict + , helpers = require('./lib/helpers') + , cookies = require('./lib/cookies') + , getProxyFromURI = require('./lib/getProxyFromURI') + , Querystring = require('./lib/querystring').Querystring + , Har = require('./lib/har').Har + , Auth = require('./lib/auth').Auth + , OAuth = require('./lib/oauth').OAuth + , Multipart = require('./lib/multipart').Multipart + , Redirect = require('./lib/redirect').Redirect + , Tunnel = require('./lib/tunnel').Tunnel + , now = require('performance-now') + , Buffer = require('safe-buffer').Buffer + +var safeStringify = helpers.safeStringify + , isReadStream = helpers.isReadStream + , toBase64 = helpers.toBase64 + , defer = helpers.defer + , copy = helpers.copy + , version = helpers.version + , globalCookieJar = cookies.jar() + + +var globalPool = {} + +function filterForNonReserved(reserved, options) { + // Filter out properties that are not reserved. + // Reserved values are passed in at call site. + + var object = {} + for (var i in options) { + var notReserved = (reserved.indexOf(i) === -1) + if (notReserved) { + object[i] = options[i] + } + } + return object +} + +function filterOutReservedFunctions(reserved, options) { + // Filter out properties that are functions and are reserved. + // Reserved values are passed in at call site. + + var object = {} + for (var i in options) { + var isReserved = !(reserved.indexOf(i) === -1) + var isFunction = (typeof options[i] === 'function') + if (!(isReserved && isFunction)) { + object[i] = options[i] + } + } + return object + +} + +// Return a simpler request object to allow serialization +function requestToJSON() { + var self = this + return { + uri: self.uri, + method: self.method, + headers: self.headers + } +} + +// Return a simpler response object to allow serialization +function responseToJSON() { + var self = this + return { + statusCode: self.statusCode, + body: self.body, + headers: self.headers, + request: requestToJSON.call(self.request) + } +} + +function Request (options) { + // if given the method property in options, set property explicitMethod to true + + // extend the Request instance with any non-reserved properties + // remove any reserved functions from the options object + // set Request instance to be readable and writable + // call init + + var self = this + + // start with HAR, then override with additional options + if (options.har) { + self._har = new Har(self) + options = self._har.options(options) + } + + stream.Stream.call(self) + var reserved = Object.keys(Request.prototype) + var nonReserved = filterForNonReserved(reserved, options) + + extend(self, nonReserved) + options = filterOutReservedFunctions(reserved, options) + + self.readable = true + self.writable = true + if (options.method) { + self.explicitMethod = true + } + self._qs = new Querystring(self) + self._auth = new Auth(self) + self._oauth = new OAuth(self) + self._multipart = new Multipart(self) + self._redirect = new Redirect(self) + self._tunnel = new Tunnel(self) + self.init(options) +} + +util.inherits(Request, stream.Stream) + +// Debugging +Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) +function debug() { + if (Request.debug) { + console.error('REQUEST %s', util.format.apply(util, arguments)) + } +} +Request.prototype.debug = debug + +Request.prototype.init = function (options) { + // init() contains all the code to setup the request object. + // the actual outgoing request is not started until start() is called + // this function is called from both the constructor and on redirect. + var self = this + if (!options) { + options = {} + } + self.headers = self.headers ? copy(self.headers) : {} + + // Delete headers with value undefined since they break + // ClientRequest.OutgoingMessage.setHeader in node 0.12 + for (var headerName in self.headers) { + if (typeof self.headers[headerName] === 'undefined') { + delete self.headers[headerName] + } + } + + caseless.httpify(self, self.headers) + + if (!self.method) { + self.method = options.method || 'GET' + } + if (!self.localAddress) { + self.localAddress = options.localAddress + } + + self._qs.init(options) + + debug(options) + if (!self.pool && self.pool !== false) { + self.pool = globalPool + } + self.dests = self.dests || [] + self.__isRequestRequest = true + + // Protect against double callback + if (!self._callback && self.callback) { + self._callback = self.callback + self.callback = function () { + if (self._callbackCalled) { + return // Print a warning maybe? + } + self._callbackCalled = true + self._callback.apply(self, arguments) + } + self.on('error', self.callback.bind()) + self.on('complete', self.callback.bind(self, null)) + } + + // People use this property instead all the time, so support it + if (!self.uri && self.url) { + self.uri = self.url + delete self.url + } + + // If there's a baseUrl, then use it as the base URL (i.e. uri must be + // specified as a relative path and is appended to baseUrl). + if (self.baseUrl) { + if (typeof self.baseUrl !== 'string') { + return self.emit('error', new Error('options.baseUrl must be a string')) + } + + if (typeof self.uri !== 'string') { + return self.emit('error', new Error('options.uri must be a string when using options.baseUrl')) + } + + if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) { + return self.emit('error', new Error('options.uri must be a path when using options.baseUrl')) + } + + // Handle all cases to make sure that there's only one slash between + // baseUrl and uri. + var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1 + var uriStartsWithSlash = self.uri.indexOf('/') === 0 + + if (baseUrlEndsWithSlash && uriStartsWithSlash) { + self.uri = self.baseUrl + self.uri.slice(1) + } else if (baseUrlEndsWithSlash || uriStartsWithSlash) { + self.uri = self.baseUrl + self.uri + } else if (self.uri === '') { + self.uri = self.baseUrl + } else { + self.uri = self.baseUrl + '/' + self.uri + } + delete self.baseUrl + } + + // A URI is needed by this point, emit error if we haven't been able to get one + if (!self.uri) { + return self.emit('error', new Error('options.uri is a required argument')) + } + + // If a string URI/URL was given, parse it into a URL object + if (typeof self.uri === 'string') { + self.uri = url.parse(self.uri) + } + + // Some URL objects are not from a URL parsed string and need href added + if (!self.uri.href) { + self.uri.href = url.format(self.uri) + } + + // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme + if (self.uri.protocol === 'unix:') { + return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`')) + } + + // Support Unix Sockets + if (self.uri.host === 'unix') { + self.enableUnixSocket() + } + + if (self.strictSSL === false) { + self.rejectUnauthorized = false + } + + if (!self.uri.pathname) {self.uri.pathname = '/'} + + if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { + // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar + // Detect and reject it as soon as possible + var faultyUri = url.format(self.uri) + var message = 'Invalid URI "' + faultyUri + '"' + if (Object.keys(options).length === 0) { + // No option ? This can be the sign of a redirect + // As this is a case where the user cannot do anything (they didn't call request directly with this URL) + // they should be warned that it can be caused by a redirection (can save some hair) + message += '. This can be caused by a crappy redirection.' + } + // This error was fatal + self.abort() + return self.emit('error', new Error(message)) + } + + if (!self.hasOwnProperty('proxy')) { + self.proxy = getProxyFromURI(self.uri) + } + + self.tunnel = self._tunnel.isEnabled() + if (self.proxy) { + self._tunnel.setup(options) + } + + self._redirect.onRequest(options) + + self.setHost = false + if (!self.hasHeader('host')) { + var hostHeaderName = self.originalHostHeaderName || 'host' + // When used with an IPv6 address, `host` will provide + // the correct bracketed format, unlike using `hostname` and + // optionally adding the `port` when necessary. + self.setHeader(hostHeaderName, self.uri.host) + self.setHost = true + } + + self.jar(self._jar || options.jar) + + if (!self.uri.port) { + if (self.uri.protocol === 'http:') {self.uri.port = 80} + else if (self.uri.protocol === 'https:') {self.uri.port = 443} + } + + if (self.proxy && !self.tunnel) { + self.port = self.proxy.port + self.host = self.proxy.hostname + } else { + self.port = self.uri.port + self.host = self.uri.hostname + } + + if (options.form) { + self.form(options.form) + } + + if (options.formData) { + var formData = options.formData + var requestForm = self.form() + var appendFormValue = function (key, value) { + if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) { + requestForm.append(key, value.value, value.options) + } else { + requestForm.append(key, value) + } + } + for (var formKey in formData) { + if (formData.hasOwnProperty(formKey)) { + var formValue = formData[formKey] + if (formValue instanceof Array) { + for (var j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]) + } + } else { + appendFormValue(formKey, formValue) + } + } + } + } + + if (options.qs) { + self.qs(options.qs) + } + + if (self.uri.path) { + self.path = self.uri.path + } else { + self.path = self.uri.pathname + (self.uri.search || '') + } + + if (self.path.length === 0) { + self.path = '/' + } + + // Auth must happen last in case signing is dependent on other headers + if (options.aws) { + self.aws(options.aws) + } + + if (options.hawk) { + self.hawk(options.hawk) + } + + if (options.httpSignature) { + self.httpSignature(options.httpSignature) + } + + if (options.auth) { + if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) { + options.auth.user = options.auth.username + } + if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) { + options.auth.pass = options.auth.password + } + + self.auth( + options.auth.user, + options.auth.pass, + options.auth.sendImmediately, + options.auth.bearer + ) + } + + if (self.gzip && !self.hasHeader('accept-encoding')) { + self.setHeader('accept-encoding', 'gzip, deflate') + } + + if (self.uri.auth && !self.hasHeader('authorization')) { + var uriAuthPieces = self.uri.auth.split(':').map(function(item) {return self._qs.unescape(item)}) + self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) + } + + if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { + var proxyAuthPieces = self.proxy.auth.split(':').map(function(item) {return self._qs.unescape(item)}) + var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) + self.setHeader('proxy-authorization', authHeader) + } + + if (self.proxy && !self.tunnel) { + self.path = (self.uri.protocol + '//' + self.uri.host + self.path) + } + + if (options.json) { + self.json(options.json) + } + if (options.multipart) { + self.multipart(options.multipart) + } + + if (options.time) { + self.timing = true + + // NOTE: elapsedTime is deprecated in favor of .timings + self.elapsedTime = self.elapsedTime || 0 + } + + function setContentLength () { + if (isTypedArray(self.body)) { + self.body = Buffer.from(self.body) + } + + if (!self.hasHeader('content-length')) { + var length + if (typeof self.body === 'string') { + length = Buffer.byteLength(self.body) + } + else if (Array.isArray(self.body)) { + length = self.body.reduce(function (a, b) {return a + b.length}, 0) + } + else { + length = self.body.length + } + + if (length) { + self.setHeader('content-length', length) + } else { + self.emit('error', new Error('Argument error, options.body.')) + } + } + } + if (self.body && !isstream(self.body)) { + setContentLength() + } + + if (options.oauth) { + self.oauth(options.oauth) + } else if (self._oauth.params && self.hasHeader('authorization')) { + self.oauth(self._oauth.params) + } + + var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol + , defaultModules = {'http:':http, 'https:':https} + , httpModules = self.httpModules || {} + + self.httpModule = httpModules[protocol] || defaultModules[protocol] + + if (!self.httpModule) { + return self.emit('error', new Error('Invalid protocol: ' + protocol)) + } + + if (options.ca) { + self.ca = options.ca + } + + if (!self.agent) { + if (options.agentOptions) { + self.agentOptions = options.agentOptions + } + + if (options.agentClass) { + self.agentClass = options.agentClass + } else if (options.forever) { + var v = version() + // use ForeverAgent in node 0.10- only + if (v.major === 0 && v.minor <= 10) { + self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL + } else { + self.agentClass = self.httpModule.Agent + self.agentOptions = self.agentOptions || {} + self.agentOptions.keepAlive = true + } + } else { + self.agentClass = self.httpModule.Agent + } + } + + if (self.pool === false) { + self.agent = false + } else { + self.agent = self.agent || self.getNewAgent() + } + + self.on('pipe', function (src) { + if (self.ntick && self._started) { + self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.')) + } + self.src = src + if (isReadStream(src)) { + if (!self.hasHeader('content-type')) { + self.setHeader('content-type', mime.lookup(src.path)) + } + } else { + if (src.headers) { + for (var i in src.headers) { + if (!self.hasHeader(i)) { + self.setHeader(i, src.headers[i]) + } + } + } + if (self._json && !self.hasHeader('content-type')) { + self.setHeader('content-type', 'application/json') + } + if (src.method && !self.explicitMethod) { + self.method = src.method + } + } + + // self.on('pipe', function () { + // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') + // }) + }) + + defer(function () { + if (self._aborted) { + return + } + + var end = function () { + if (self._form) { + if (!self._auth.hasAuth) { + self._form.pipe(self) + } + else if (self._auth.hasAuth && self._auth.sentAuth) { + self._form.pipe(self) + } + } + if (self._multipart && self._multipart.chunked) { + self._multipart.body.pipe(self) + } + if (self.body) { + if (isstream(self.body)) { + self.body.pipe(self) + } else { + setContentLength() + if (Array.isArray(self.body)) { + self.body.forEach(function (part) { + self.write(part) + }) + } else { + self.write(self.body) + } + self.end() + } + } else if (self.requestBodyStream) { + console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.') + self.requestBodyStream.pipe(self) + } else if (!self.src) { + if (self._auth.hasAuth && !self._auth.sentAuth) { + self.end() + return + } + if (self.method !== 'GET' && typeof self.method !== 'undefined') { + self.setHeader('content-length', 0) + } + self.end() + } + } + + if (self._form && !self.hasHeader('content-length')) { + // Before ending the request, we had to compute the length of the whole form, asyncly + self.setHeader(self._form.getHeaders(), true) + self._form.getLength(function (err, length) { + if (!err && !isNaN(length)) { + self.setHeader('content-length', length) + } + end() + }) + } else { + end() + } + + self.ntick = true + }) + +} + +Request.prototype.getNewAgent = function () { + var self = this + var Agent = self.agentClass + var options = {} + if (self.agentOptions) { + for (var i in self.agentOptions) { + options[i] = self.agentOptions[i] + } + } + if (self.ca) { + options.ca = self.ca + } + if (self.ciphers) { + options.ciphers = self.ciphers + } + if (self.secureProtocol) { + options.secureProtocol = self.secureProtocol + } + if (self.secureOptions) { + options.secureOptions = self.secureOptions + } + if (typeof self.rejectUnauthorized !== 'undefined') { + options.rejectUnauthorized = self.rejectUnauthorized + } + + if (self.cert && self.key) { + options.key = self.key + options.cert = self.cert + } + + if (self.pfx) { + options.pfx = self.pfx + } + + if (self.passphrase) { + options.passphrase = self.passphrase + } + + var poolKey = '' + + // different types of agents are in different pools + if (Agent !== self.httpModule.Agent) { + poolKey += Agent.name + } + + // ca option is only relevant if proxy or destination are https + var proxy = self.proxy + if (typeof proxy === 'string') { + proxy = url.parse(proxy) + } + var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' + + if (isHttps) { + if (options.ca) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.ca + } + + if (typeof options.rejectUnauthorized !== 'undefined') { + if (poolKey) { + poolKey += ':' + } + poolKey += options.rejectUnauthorized + } + + if (options.cert) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.cert.toString('ascii') + options.key.toString('ascii') + } + + if (options.pfx) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.pfx.toString('ascii') + } + + if (options.ciphers) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.ciphers + } + + if (options.secureProtocol) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.secureProtocol + } + + if (options.secureOptions) { + if (poolKey) { + poolKey += ':' + } + poolKey += options.secureOptions + } + } + + if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) { + // not doing anything special. Use the globalAgent + return self.httpModule.globalAgent + } + + // we're using a stored agent. Make sure it's protocol-specific + poolKey = self.uri.protocol + poolKey + + // generate a new agent for this setting if none yet exists + if (!self.pool[poolKey]) { + self.pool[poolKey] = new Agent(options) + // properly set maxSockets on new agents + if (self.pool.maxSockets) { + self.pool[poolKey].maxSockets = self.pool.maxSockets + } + } + + return self.pool[poolKey] +} + +Request.prototype.start = function () { + // start() is called once we are ready to send the outgoing HTTP request. + // this is usually called on the first write(), end() or on nextTick() + var self = this + + if (self.timing) { + // All timings will be relative to this request's startTime. In order to do this, + // we need to capture the wall-clock start time (via Date), immediately followed + // by the high-resolution timer (via now()). While these two won't be set + // at the _exact_ same time, they should be close enough to be able to calculate + // high-resolution, monotonically non-decreasing timestamps relative to startTime. + var startTime = new Date().getTime() + var startTimeNow = now() + } + + if (self._aborted) { + return + } + + self._started = true + self.method = self.method || 'GET' + self.href = self.uri.href + + if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { + self.setHeader('content-length', self.src.stat.size) + } + if (self._aws) { + self.aws(self._aws, true) + } + + // We have a method named auth, which is completely different from the http.request + // auth option. If we don't remove it, we're gonna have a bad time. + var reqOptions = copy(self) + delete reqOptions.auth + + debug('make request', self.uri.href) + + // node v6.8.0 now supports a `timeout` value in `http.request()`, but we + // should delete it for now since we handle timeouts manually for better + // consistency with node versions before v6.8.0 + delete reqOptions.timeout + + try { + self.req = self.httpModule.request(reqOptions) + } catch (err) { + self.emit('error', err) + return + } + + if (self.timing) { + self.startTime = startTime + self.startTimeNow = startTimeNow + + // Timing values will all be relative to startTime (by comparing to startTimeNow + // so we have an accurate clock) + self.timings = {} + } + + var timeout + if (self.timeout && !self.timeoutTimer) { + if (self.timeout < 0) { + timeout = 0 + } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) { + timeout = self.timeout + } + } + + self.req.on('response', self.onRequestResponse.bind(self)) + self.req.on('error', self.onRequestError.bind(self)) + self.req.on('drain', function() { + self.emit('drain') + }) + self.req.on('socket', function(socket) { + // `._connecting` was the old property which was made public in node v6.1.0 + var isConnecting = socket._connecting || socket.connecting + if (self.timing) { + self.timings.socket = now() - self.startTimeNow + + if (isConnecting) { + var onLookupTiming = function() { + self.timings.lookup = now() - self.startTimeNow + } + + var onConnectTiming = function() { + self.timings.connect = now() - self.startTimeNow + } + + socket.once('lookup', onLookupTiming) + socket.once('connect', onConnectTiming) + + // clean up timing event listeners if needed on error + self.req.once('error', function() { + socket.removeListener('lookup', onLookupTiming) + socket.removeListener('connect', onConnectTiming) + }) + } + } + + var setReqTimeout = function() { + // This timeout sets the amount of time to wait *between* bytes sent + // from the server once connected. + // + // In particular, it's useful for erroring if the server fails to send + // data halfway through streaming a response. + self.req.setTimeout(timeout, function () { + if (self.req) { + self.abort() + var e = new Error('ESOCKETTIMEDOUT') + e.code = 'ESOCKETTIMEDOUT' + e.connect = false + self.emit('error', e) + } + }) + } + if (timeout !== undefined) { + // Only start the connection timer if we're actually connecting a new + // socket, otherwise if we're already connected (because this is a + // keep-alive connection) do not bother. This is important since we won't + // get a 'connect' event for an already connected socket. + if (isConnecting) { + var onReqSockConnect = function() { + socket.removeListener('connect', onReqSockConnect) + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + setReqTimeout() + } + + socket.on('connect', onReqSockConnect) + + self.req.on('error', function(err) { + socket.removeListener('connect', onReqSockConnect) + }) + + // Set a timeout in memory - this block will throw if the server takes more + // than `timeout` to write the HTTP status and headers (corresponding to + // the on('response') event on the client). NB: this measures wall-clock + // time, not the time between bytes sent by the server. + self.timeoutTimer = setTimeout(function () { + socket.removeListener('connect', onReqSockConnect) + self.abort() + var e = new Error('ETIMEDOUT') + e.code = 'ETIMEDOUT' + e.connect = true + self.emit('error', e) + }, timeout) + } else { + // We're already connected + setReqTimeout() + } + } + self.emit('socket', socket) + }) + + self.emit('request', self.req) +} + +Request.prototype.onRequestError = function (error) { + var self = this + if (self._aborted) { + return + } + if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' + && self.agent.addRequestNoreuse) { + self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } + self.start() + self.req.end() + return + } + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + self.emit('error', error) +} + +Request.prototype.onRequestResponse = function (response) { + var self = this + + if (self.timing) { + self.timings.response = now() - self.startTimeNow + } + + debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) + response.on('end', function() { + if (self.timing) { + self.timings.end = now() - self.startTimeNow + response.timingStart = self.startTime + + // fill in the blanks for any periods that didn't trigger, such as + // no lookup or connect due to keep alive + if (!self.timings.socket) { + self.timings.socket = 0 + } + if (!self.timings.lookup) { + self.timings.lookup = self.timings.socket + } + if (!self.timings.connect) { + self.timings.connect = self.timings.lookup + } + if (!self.timings.response) { + self.timings.response = self.timings.connect + } + + debug('elapsed time', self.timings.end) + + // elapsedTime includes all redirects + self.elapsedTime += Math.round(self.timings.end) + + // NOTE: elapsedTime is deprecated in favor of .timings + response.elapsedTime = self.elapsedTime + + // timings is just for the final fetch + response.timings = self.timings + + // pre-calculate phase timings as well + response.timingPhases = { + wait: self.timings.socket, + dns: self.timings.lookup - self.timings.socket, + tcp: self.timings.connect - self.timings.lookup, + firstByte: self.timings.response - self.timings.connect, + download: self.timings.end - self.timings.response, + total: self.timings.end + } + } + debug('response end', self.uri.href, response.statusCode, response.headers) + }) + + if (self._aborted) { + debug('aborted', self.uri.href) + response.resume() + return + } + + self.response = response + response.request = self + response.toJSON = responseToJSON + + // XXX This is different on 0.10, because SSL is strict by default + if (self.httpModule === https && + self.strictSSL && (!response.hasOwnProperty('socket') || + !response.socket.authorized)) { + debug('strict ssl error', self.uri.href) + var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' + self.emit('error', new Error('SSL Error: ' + sslErr)) + return + } + + // Save the original host before any redirect (if it changes, we need to + // remove any authorization headers). Also remember the case of the header + // name because lots of broken servers expect Host instead of host and we + // want the caller to be able to specify this. + self.originalHost = self.getHeader('host') + if (!self.originalHostHeaderName) { + self.originalHostHeaderName = self.hasHeader('host') + } + if (self.setHost) { + self.removeHeader('host') + } + if (self.timeout && self.timeoutTimer) { + clearTimeout(self.timeoutTimer) + self.timeoutTimer = null + } + + var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar + var addCookie = function (cookie) { + //set the cookie if it's domain in the href's domain. + try { + targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) + } catch (e) { + self.emit('error', e) + } + } + + response.caseless = caseless(response.headers) + + if (response.caseless.has('set-cookie') && (!self._disableCookies)) { + var headerName = response.caseless.has('set-cookie') + if (Array.isArray(response.headers[headerName])) { + response.headers[headerName].forEach(addCookie) + } else { + addCookie(response.headers[headerName]) + } + } + + if (self._redirect.onResponse(response)) { + return // Ignore the rest of the response + } else { + // Be a good stream and emit end when the response is finished. + // Hack to emit end on close because of a core bug that never fires end + response.on('close', function () { + if (!self._ended) { + self.response.emit('end') + } + }) + + response.once('end', function () { + self._ended = true + }) + + var noBody = function (code) { + return ( + self.method === 'HEAD' + // Informational + || (code >= 100 && code < 200) + // No Content + || code === 204 + // Not Modified + || code === 304 + ) + } + + var responseContent + if (self.gzip && !noBody(response.statusCode)) { + var contentEncoding = response.headers['content-encoding'] || 'identity' + contentEncoding = contentEncoding.trim().toLowerCase() + + // Be more lenient with decoding compressed responses, since (very rarely) + // servers send slightly invalid gzip responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + var zlibOptions = { + flush: zlib.Z_SYNC_FLUSH + , finishFlush: zlib.Z_SYNC_FLUSH + } + + if (contentEncoding === 'gzip') { + responseContent = zlib.createGunzip(zlibOptions) + response.pipe(responseContent) + } else if (contentEncoding === 'deflate') { + responseContent = zlib.createInflate(zlibOptions) + response.pipe(responseContent) + } else { + // Since previous versions didn't check for Content-Encoding header, + // ignore any invalid values to preserve backwards-compatibility + if (contentEncoding !== 'identity') { + debug('ignoring unrecognized Content-Encoding ' + contentEncoding) + } + responseContent = response + } + } else { + responseContent = response + } + + if (self.encoding) { + if (self.dests.length !== 0) { + console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') + } else if (responseContent.setEncoding) { + responseContent.setEncoding(self.encoding) + } else { + // Should only occur on node pre-v0.9.4 (joyent/node@9b5abe5) with + // zlib streams. + // If/When support for 0.9.4 is dropped, this should be unnecessary. + responseContent = responseContent.pipe(stringstream(self.encoding)) + } + } + + if (self._paused) { + responseContent.pause() + } + + self.responseContent = responseContent + + self.emit('response', response) + + self.dests.forEach(function (dest) { + self.pipeDest(dest) + }) + + responseContent.on('data', function (chunk) { + if (self.timing && !self.responseStarted) { + self.responseStartTime = (new Date()).getTime() + + // NOTE: responseStartTime is deprecated in favor of .timings + response.responseStartTime = self.responseStartTime + } + self._destdata = true + self.emit('data', chunk) + }) + responseContent.once('end', function (chunk) { + self.emit('end', chunk) + }) + responseContent.on('error', function (error) { + self.emit('error', error) + }) + responseContent.on('close', function () {self.emit('close')}) + + if (self.callback) { + self.readResponseBody(response) + } + //if no callback + else { + self.on('end', function () { + if (self._aborted) { + debug('aborted', self.uri.href) + return + } + self.emit('complete', response) + }) + } + } + debug('finish init function', self.uri.href) +} + +Request.prototype.readResponseBody = function (response) { + var self = this + debug('reading response\'s body') + var buffers = [] + , bufferLength = 0 + , strings = [] + + self.on('data', function (chunk) { + if (!Buffer.isBuffer(chunk)) { + strings.push(chunk) + } else if (chunk.length) { + bufferLength += chunk.length + buffers.push(chunk) + } + }) + self.on('end', function () { + debug('end event', self.uri.href) + if (self._aborted) { + debug('aborted', self.uri.href) + // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request. + // This can lead to leaky behavior if the user retains a reference to the request object. + buffers = [] + bufferLength = 0 + return + } + + if (bufferLength) { + debug('has body', self.uri.href, bufferLength) + response.body = Buffer.concat(buffers, bufferLength) + if (self.encoding !== null) { + response.body = response.body.toString(self.encoding) + } + // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request. + // This can lead to leaky behavior if the user retains a reference to the request object. + buffers = [] + bufferLength = 0 + } else if (strings.length) { + // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. + // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). + if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') { + strings[0] = strings[0].substring(1) + } + response.body = strings.join('') + } + + if (self._json) { + try { + response.body = JSON.parse(response.body, self._jsonReviver) + } catch (e) { + debug('invalid JSON received', self.uri.href) + } + } + debug('emitting complete', self.uri.href) + if (typeof response.body === 'undefined' && !self._json) { + response.body = self.encoding === null ? Buffer.alloc(0) : '' + } + self.emit('complete', response, response.body) + }) +} + +Request.prototype.abort = function () { + var self = this + self._aborted = true + + if (self.req) { + self.req.abort() + } + else if (self.response) { + self.response.destroy() + } + + self.emit('abort') +} + +Request.prototype.pipeDest = function (dest) { + var self = this + var response = self.response + // Called after the response is received + if (dest.headers && !dest.headersSent) { + if (response.caseless.has('content-type')) { + var ctname = response.caseless.has('content-type') + if (dest.setHeader) { + dest.setHeader(ctname, response.headers[ctname]) + } + else { + dest.headers[ctname] = response.headers[ctname] + } + } + + if (response.caseless.has('content-length')) { + var clname = response.caseless.has('content-length') + if (dest.setHeader) { + dest.setHeader(clname, response.headers[clname]) + } else { + dest.headers[clname] = response.headers[clname] + } + } + } + if (dest.setHeader && !dest.headersSent) { + for (var i in response.headers) { + // If the response content is being decoded, the Content-Encoding header + // of the response doesn't represent the piped content, so don't pass it. + if (!self.gzip || i !== 'content-encoding') { + dest.setHeader(i, response.headers[i]) + } + } + dest.statusCode = response.statusCode + } + if (self.pipefilter) { + self.pipefilter(response, dest) + } +} + +Request.prototype.qs = function (q, clobber) { + var self = this + var base + if (!clobber && self.uri.query) { + base = self._qs.parse(self.uri.query) + } else { + base = {} + } + + for (var i in q) { + base[i] = q[i] + } + + var qs = self._qs.stringify(base) + + if (qs === '') { + return self + } + + self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs) + self.url = self.uri + self.path = self.uri.path + + if (self.uri.host === 'unix') { + self.enableUnixSocket() + } + + return self +} +Request.prototype.form = function (form) { + var self = this + if (form) { + if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { + self.setHeader('content-type', 'application/x-www-form-urlencoded') + } + self.body = (typeof form === 'string') + ? self._qs.rfc3986(form.toString('utf8')) + : self._qs.stringify(form).toString('utf8') + return self + } + // create form-data object + self._form = new FormData() + self._form.on('error', function(err) { + err.message = 'form-data: ' + err.message + self.emit('error', err) + self.abort() + }) + return self._form +} +Request.prototype.multipart = function (multipart) { + var self = this + + self._multipart.onRequest(multipart) + + if (!self._multipart.chunked) { + self.body = self._multipart.body + } + + return self +} +Request.prototype.json = function (val) { + var self = this + + if (!self.hasHeader('accept')) { + self.setHeader('accept', 'application/json') + } + + if (typeof self.jsonReplacer === 'function') { + self._jsonReplacer = self.jsonReplacer + } + + self._json = true + if (typeof val === 'boolean') { + if (self.body !== undefined) { + if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { + self.body = safeStringify(self.body, self._jsonReplacer) + } else { + self.body = self._qs.rfc3986(self.body) + } + if (!self.hasHeader('content-type')) { + self.setHeader('content-type', 'application/json') + } + } + } else { + self.body = safeStringify(val, self._jsonReplacer) + if (!self.hasHeader('content-type')) { + self.setHeader('content-type', 'application/json') + } + } + + if (typeof self.jsonReviver === 'function') { + self._jsonReviver = self.jsonReviver + } + + return self +} +Request.prototype.getHeader = function (name, headers) { + var self = this + var result, re, match + if (!headers) { + headers = self.headers + } + Object.keys(headers).forEach(function (key) { + if (key.length !== name.length) { + return + } + re = new RegExp(name, 'i') + match = key.match(re) + if (match) { + result = headers[key] + } + }) + return result +} +Request.prototype.enableUnixSocket = function () { + // Get the socket & request paths from the URL + var unixParts = this.uri.path.split(':') + , host = unixParts[0] + , path = unixParts[1] + // Apply unix properties to request + this.socketPath = host + this.uri.pathname = path + this.uri.path = path + this.uri.host = host + this.uri.hostname = host + this.uri.isUnix = true +} + + +Request.prototype.auth = function (user, pass, sendImmediately, bearer) { + var self = this + + self._auth.onRequest(user, pass, sendImmediately, bearer) + + return self +} +Request.prototype.aws = function (opts, now) { + var self = this + + if (!now) { + self._aws = opts + return self + } + + if (opts.sign_version == 4 || opts.sign_version == '4') { + // use aws4 + var options = { + host: self.uri.host, + path: self.uri.path, + method: self.method, + headers: { + 'content-type': self.getHeader('content-type') || '' + }, + body: self.body + } + var signRes = aws4.sign(options, { + accessKeyId: opts.key, + secretAccessKey: opts.secret, + sessionToken: opts.session + }) + self.setHeader('authorization', signRes.headers.Authorization) + self.setHeader('x-amz-date', signRes.headers['X-Amz-Date']) + if (signRes.headers['X-Amz-Security-Token']) { + self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']) + } + } + else { + // default: use aws-sign2 + var date = new Date() + self.setHeader('date', date.toUTCString()) + var auth = + { key: opts.key + , secret: opts.secret + , verb: self.method.toUpperCase() + , date: date + , contentType: self.getHeader('content-type') || '' + , md5: self.getHeader('content-md5') || '' + , amazonHeaders: aws2.canonicalizeHeaders(self.headers) + } + var path = self.uri.path + if (opts.bucket && path) { + auth.resource = '/' + opts.bucket + path + } else if (opts.bucket && !path) { + auth.resource = '/' + opts.bucket + } else if (!opts.bucket && path) { + auth.resource = path + } else if (!opts.bucket && !path) { + auth.resource = '/' + } + auth.resource = aws2.canonicalizeResource(auth.resource) + self.setHeader('authorization', aws2.authorization(auth)) + } + + return self +} +Request.prototype.httpSignature = function (opts) { + var self = this + httpSignature.signRequest({ + getHeader: function(header) { + return self.getHeader(header, self.headers) + }, + setHeader: function(header, value) { + self.setHeader(header, value) + }, + method: self.method, + path: self.path + }, opts) + debug('httpSignature authorization', self.getHeader('authorization')) + + return self +} +Request.prototype.hawk = function (opts) { + var self = this + self.setHeader('Authorization', hawk.client.header(self.uri, self.method, opts).field) +} +Request.prototype.oauth = function (_oauth) { + var self = this + + self._oauth.onRequest(_oauth) + + return self +} + +Request.prototype.jar = function (jar) { + var self = this + var cookies + + if (self._redirect.redirectsFollowed === 0) { + self.originalCookieHeader = self.getHeader('cookie') + } + + if (!jar) { + // disable cookies + cookies = false + self._disableCookies = true + } else { + var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar + var urihref = self.uri.href + //fetch cookie in the Specified host + if (targetCookieJar) { + cookies = targetCookieJar.getCookieString(urihref) + } + } + + //if need cookie and cookie is not empty + if (cookies && cookies.length) { + if (self.originalCookieHeader) { + // Don't overwrite existing Cookie header + self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies) + } else { + self.setHeader('cookie', cookies) + } + } + self._jar = jar + return self +} + + +// Stream API +Request.prototype.pipe = function (dest, opts) { + var self = this + + if (self.response) { + if (self._destdata) { + self.emit('error', new Error('You cannot pipe after data has been emitted from the response.')) + } else if (self._ended) { + self.emit('error', new Error('You cannot pipe after the response has been ended.')) + } else { + stream.Stream.prototype.pipe.call(self, dest, opts) + self.pipeDest(dest) + return dest + } + } else { + self.dests.push(dest) + stream.Stream.prototype.pipe.call(self, dest, opts) + return dest + } +} +Request.prototype.write = function () { + var self = this + if (self._aborted) {return} + + if (!self._started) { + self.start() + } + if (self.req) { + return self.req.write.apply(self.req, arguments) + } +} +Request.prototype.end = function (chunk) { + var self = this + if (self._aborted) {return} + + if (chunk) { + self.write(chunk) + } + if (!self._started) { + self.start() + } + if (self.req) { + self.req.end() + } +} +Request.prototype.pause = function () { + var self = this + if (!self.responseContent) { + self._paused = true + } else { + self.responseContent.pause.apply(self.responseContent, arguments) + } +} +Request.prototype.resume = function () { + var self = this + if (!self.responseContent) { + self._paused = false + } else { + self.responseContent.resume.apply(self.responseContent, arguments) + } +} +Request.prototype.destroy = function () { + var self = this + if (!self._ended) { + self.end() + } else if (self.response) { + self.response.destroy() + } +} + +Request.defaultProxyHeaderWhiteList = + Tunnel.defaultProxyHeaderWhiteList.slice() + +Request.defaultProxyHeaderExclusiveList = + Tunnel.defaultProxyHeaderExclusiveList.slice() + +// Exports + +Request.prototype.toJSON = requestToJSON +module.exports = Request diff --git a/node_modules/azure-storage/node_modules/uuid/.eslintrc.json b/node_modules/azure-storage/node_modules/uuid/.eslintrc.json new file mode 100644 index 000000000..734a8e14c --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/.eslintrc.json @@ -0,0 +1,47 @@ +{ + "root": true, + "env": { + "browser": true, + "commonjs": true, + "node": true, + "mocha": true + }, + "extends": ["eslint:recommended"], + "rules": { + "array-bracket-spacing": ["warn", "never"], + "arrow-body-style": ["warn", "as-needed"], + "arrow-parens": ["warn", "as-needed"], + "arrow-spacing": "warn", + "brace-style": ["warn", "1tbs"], + "camelcase": "warn", + "comma-spacing": ["warn", {"after": true}], + "dot-notation": "warn", + "eqeqeq": ["warn", "smart"], + "indent": ["warn", 2, { + "SwitchCase": 1, + "FunctionDeclaration": {"parameters": 1}, + "MemberExpression": 1, + "CallExpression": {"arguments": 1} + }], + "key-spacing": ["warn", {"beforeColon": false, "afterColon": true, "mode": "minimum"}], + "keyword-spacing": "warn", + "no-console": "off", + "no-empty": "off", + "no-multi-spaces": "warn", + "no-redeclare": "off", + "no-restricted-globals": ["warn", "Promise"], + "no-trailing-spaces": "warn", + "no-undef": "error", + "no-unused-vars": ["warn", {"args": "none"}], + "one-var": ["warn", "never"], + "padded-blocks": ["warn", "never"], + "object-curly-spacing": ["warn", "never"], + "quotes": ["warn", "single"], + "react/prop-types": "off", + "react/jsx-no-bind": "off", + "semi": ["warn", "always"], + "space-before-blocks": ["warn", "always"], + "space-before-function-paren": ["warn", "never"], + "space-in-parens": ["warn", "never"] + } +} diff --git a/node_modules/azure-storage/node_modules/uuid/AUTHORS b/node_modules/azure-storage/node_modules/uuid/AUTHORS new file mode 100644 index 000000000..5a1052306 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/AUTHORS @@ -0,0 +1,5 @@ +Robert Kieffer +Christoph Tavan +AJ ONeal +Vincent Voyer +Roman Shtylman diff --git a/node_modules/azure-storage/node_modules/uuid/CHANGELOG.md b/node_modules/azure-storage/node_modules/uuid/CHANGELOG.md new file mode 100644 index 000000000..d9fe59c15 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,57 @@ +# 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.1](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.2.1) (2018-01-16) + + +### Bug Fixes + +* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b)) + + + + +# [3.2.0](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + + +### Bug Fixes + +* remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/kelektiv/node-uuid/commit/09fa824)) +* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b)) + + +### Features + +* Add v3 Support ([#217](https://github.com/kelektiv/node-uuid/issues/217)) ([d94f726](https://github.com/kelektiv/node-uuid/commit/d94f726)) + + + +# 3.0.1 (2016-11-28) + + * split uuid versions into separate files + +# 3.0.0 (2016-11-17) + + * remove .parse and .unparse + +# 2.0.0 + + * Removed uuid.BufferClass + +# 1.4.0 + + * Improved module context detection + * Removed public RNG functions + +# 1.3.2 + + * Improve tests and handling of v1() options (Issue #24) + * Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + + * Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! + * Support for node.js crypto API + * De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/azure-storage/node_modules/uuid/LICENSE.md b/node_modules/azure-storage/node_modules/uuid/LICENSE.md new file mode 100644 index 000000000..8c84e3986 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010-2016 Robert Kieffer 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/azure-storage/node_modules/uuid/README.md b/node_modules/azure-storage/node_modules/uuid/README.md new file mode 100644 index 000000000..cddaa1446 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/README.md @@ -0,0 +1,293 @@ + + +# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) # + +Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS. + +Features: + +* Support for version 1, 3, 4 and 5 UUIDs +* Cross-platform +* Uses cryptographically-strong random number APIs (when available) +* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883)) + +[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be +supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.] + +## Quickstart - CommonJS (Recommended) + +```shell +npm install uuid +``` + +Then generate your uuid version of choice ... + +Version 1 (timestamp): + +```javascript +const uuidv1 = require('uuid/v1'); +uuidv1(); // ⇨ 'f64f2940-fae4-11e7-8c5f-ef356f279131' + +``` + +Version 3 (namespace): + +```javascript +const uuidv3 = require('uuid/v3'); + +// ... using predefined DNS namespace (for domain names) +uuidv3('hello.example.com', uuidv3.DNS); // ⇨ '9125a8dc-52ee-365b-a5aa-81b0b3681cf6' + +// ... using predefined URL namespace (for, well, URLs) +uuidv3('http://example.com/hello', uuidv3.URL); // ⇨ 'c6235813-3ba4-3801-ae84-e0a6ebb7d138' + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv3('Hello, World!', MY_NAMESPACE); // ⇨ 'e8b5a51d-11c8-3310-a6ab-367563f20686' + +``` + +Version 4 (random): + +```javascript +const uuidv4 = require('uuid/v4'); +uuidv4(); // ⇨ '416ac246-e7ac-49ff-93b4-f7e94d997e6b' + +``` + +Version 5 (namespace): + +```javascript +const uuidv5 = require('uuid/v5'); + +// ... using predefined DNS namespace (for domain names) +uuidv5('hello.example.com', uuidv5.DNS); // ⇨ 'fdda765f-fc57-5604-a269-52a7df8164ec' + +// ... using predefined URL namespace (for, well, URLs) +uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ '3bbcee75-cecc-5b56-8031-b6641c1ed1f1' + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' + +``` + +## Quickstart - Browser-ready Versions + +Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in). + +For version 1 uuids: + +```html + + +``` + +For version 3 uuids: + +```html + + +``` + +For version 4 uuids: + +```html + + +``` + +For version 5 uuids: + +```html + + +``` + +## API + +### Version 1 + +```javascript +const uuidv1 = require('uuid/v1'); + +// Incantations +uuidv1(); +uuidv1(options); +uuidv1(options, buffer, offset); +``` + +Generate and return a RFC4122 v1 (timestamp-based) UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + + * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1. + * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. + * `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used. + * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. + +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Note: The id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.) + +Example: Generate string UUID with fully-specified options + +```javascript +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678 +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' + +``` + +Example: In-place generation of two binary IDs + +```javascript +// Generate two ids in an array +const arr = new Array(); +uuidv1(null, arr, 0); // ⇨ [ 246, 87, 141, 176, 250, 228, 17, 231, 146, 52, 239, 53, 111, 39, 145, 49 ] +uuidv1(null, arr, 16); // ⇨ [ 246, 87, 141, 176, 250, 228, 17, 231, 146, 52, 239, 53, 111, 39, 145, 49, 246, 87, 180, 192, 250, 228, 17, 231, 146, 52, 239, 53, 111, 39, 145, 49 ] + +``` + +### Version 3 + +```javascript +const uuidv3 = require('uuid/v3'); + +// Incantations +uuidv3(name, namespace); +uuidv3(name, namespace, buffer); +uuidv3(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v3 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript +uuidv3('hello world', MY_NAMESPACE); // ⇨ '042ffd34-d989-321c-ad06-f60826172424' + +``` + +### Version 4 + +```javascript +const uuidv4 = require('uuid/v4') + +// Incantations +uuidv4(); +uuidv4(options); +uuidv4(options, buffer, offset); +``` + +Generate and return a RFC4122 v4 UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values + * `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255) +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: Generate string UUID with predefined `random` values + +```javascript +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, + 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 + ] +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' + +``` + +Example: Generate two IDs in a single buffer + +```javascript +const buffer = new Array(); +uuidv4(null, buffer, 0); // ⇨ [ 175, 10, 162, 184, 217, 255, 77, 139, 161, 80, 41, 200, 70, 238, 196, 250 ] +uuidv4(null, buffer, 16); // ⇨ [ 175, 10, 162, 184, 217, 255, 77, 139, 161, 80, 41, 200, 70, 238, 196, 250, 75, 162, 105, 153, 48, 238, 77, 58, 169, 56, 158, 207, 106, 160, 47, 239 ] + +``` + +### Version 5 + +```javascript +const uuidv5 = require('uuid/v5'); + +// Incantations +uuidv5(name, namespace); +uuidv5(name, namespace, buffer); +uuidv5(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v5 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript +uuidv5('hello world', MY_NAMESPACE); // ⇨ '9f282611-e0fd-5650-8953-89c8e342da0b' + +``` + +## Command Line + +UUIDs can be generated from the command line with the `uuid` command. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 + +$ uuid v1 +02d37060-d446-11e7-a9fa-7bdae751ebe1 +``` + +Type `uuid --help` for usage details + +## Testing + +```shell +npm test +``` + +---- +Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/uuid/README_js.md b/node_modules/azure-storage/node_modules/uuid/README_js.md new file mode 100644 index 000000000..f34453be4 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/README_js.md @@ -0,0 +1,280 @@ +```javascript --hide +runmd.onRequire = path => path.replace(/^uuid/, './'); +``` + +# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) # + +Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS. + +Features: + +* Support for version 1, 3, 4 and 5 UUIDs +* Cross-platform +* Uses cryptographically-strong random number APIs (when available) +* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883)) + +[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be +supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.] + +## Quickstart - CommonJS (Recommended) + +```shell +npm install uuid +``` + +Then generate your uuid version of choice ... + +Version 1 (timestamp): + +```javascript --run v1 +const uuidv1 = require('uuid/v1'); +uuidv1(); // RESULT +``` + +Version 3 (namespace): + +```javascript --run v3 +const uuidv3 = require('uuid/v3'); + +// ... using predefined DNS namespace (for domain names) +uuidv3('hello.example.com', uuidv3.DNS); // RESULT + +// ... using predefined URL namespace (for, well, URLs) +uuidv3('http://example.com/hello', uuidv3.URL); // RESULT + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv3('Hello, World!', MY_NAMESPACE); // RESULT +``` + +Version 4 (random): + +```javascript --run v4 +const uuidv4 = require('uuid/v4'); +uuidv4(); // RESULT +``` + +Version 5 (namespace): + +```javascript --run v5 +const uuidv5 = require('uuid/v5'); + +// ... using predefined DNS namespace (for domain names) +uuidv5('hello.example.com', uuidv5.DNS); // RESULT + +// ... using predefined URL namespace (for, well, URLs) +uuidv5('http://example.com/hello', uuidv5.URL); // RESULT + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv5('Hello, World!', MY_NAMESPACE); // RESULT +``` + +## Quickstart - Browser-ready Versions + +Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in). + +For version 1 uuids: + +```html + + +``` + +For version 3 uuids: + +```html + + +``` + +For version 4 uuids: + +```html + + +``` + +For version 5 uuids: + +```html + + +``` + +## API + +### Version 1 + +```javascript +const uuidv1 = require('uuid/v1'); + +// Incantations +uuidv1(); +uuidv1(options); +uuidv1(options, buffer, offset); +``` + +Generate and return a RFC4122 v1 (timestamp-based) UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + + * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1. + * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. + * `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used. + * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. + +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Note: The id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.) + +Example: Generate string UUID with fully-specified options + +```javascript --run v1 +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678 +}; +uuidv1(v1options); // RESULT +``` + +Example: In-place generation of two binary IDs + +```javascript --run v1 +// Generate two ids in an array +const arr = new Array(); +uuidv1(null, arr, 0); // RESULT +uuidv1(null, arr, 16); // RESULT +``` + +### Version 3 + +```javascript +const uuidv3 = require('uuid/v3'); + +// Incantations +uuidv3(name, namespace); +uuidv3(name, namespace, buffer); +uuidv3(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v3 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript --run v3 +uuidv3('hello world', MY_NAMESPACE); // RESULT +``` + +### Version 4 + +```javascript +const uuidv4 = require('uuid/v4') + +// Incantations +uuidv4(); +uuidv4(options); +uuidv4(options, buffer, offset); +``` + +Generate and return a RFC4122 v4 UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values + * `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255) +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: Generate string UUID with predefined `random` values + +```javascript --run v4 +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, + 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 + ] +}; +uuidv4(v4options); // RESULT +``` + +Example: Generate two IDs in a single buffer + +```javascript --run v4 +const buffer = new Array(); +uuidv4(null, buffer, 0); // RESULT +uuidv4(null, buffer, 16); // RESULT +``` + +### Version 5 + +```javascript +const uuidv5 = require('uuid/v5'); + +// Incantations +uuidv5(name, namespace); +uuidv5(name, namespace, buffer); +uuidv5(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v5 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript --run v5 +uuidv5('hello world', MY_NAMESPACE); // RESULT +``` + +## Command Line + +UUIDs can be generated from the command line with the `uuid` command. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 + +$ uuid v1 +02d37060-d446-11e7-a9fa-7bdae751ebe1 +``` + +Type `uuid --help` for usage details + +## Testing + +```shell +npm test +``` diff --git a/node_modules/azure-storage/node_modules/uuid/bin/uuid b/node_modules/azure-storage/node_modules/uuid/bin/uuid new file mode 100644 index 000000000..502626e60 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/bin/uuid @@ -0,0 +1,65 @@ +#!/usr/bin/env node +var assert = require('assert'); + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +var args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +var version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + var uuidV1 = require('../v1'); + console.log(uuidV1()); + break; + + case 'v3': + var uuidV3 = require('../v3'); + + var name = args.shift(); + var namespace = args.shift(); + assert(name != null, 'v3 name not specified'); + assert(namespace != null, 'v3 namespace not specified'); + + if (namespace == 'URL') namespace = uuidV3.URL; + if (namespace == 'DNS') namespace = uuidV3.DNS; + + console.log(uuidV3(name, namespace)); + break; + + case 'v4': + var uuidV4 = require('../v4'); + console.log(uuidV4()); + break; + + case 'v5': + var uuidV5 = require('../v5'); + + var name = args.shift(); + var namespace = args.shift(); + assert(name != null, 'v5 name not specified'); + assert(namespace != null, 'v5 namespace not specified'); + + if (namespace == 'URL') namespace = uuidV5.URL; + if (namespace == 'DNS') namespace = uuidV5.DNS; + + console.log(uuidV5(name, namespace)); + break; + + default: + usage(); + process.exit(1); +} diff --git a/node_modules/azure-storage/node_modules/uuid/index.js b/node_modules/azure-storage/node_modules/uuid/index.js new file mode 100644 index 000000000..e96791ab4 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/index.js @@ -0,0 +1,8 @@ +var v1 = require('./v1'); +var v4 = require('./v4'); + +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; + +module.exports = uuid; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/bytesToUuid.js b/node_modules/azure-storage/node_modules/uuid/lib/bytesToUuid.js new file mode 100644 index 000000000..2c9a22309 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/bytesToUuid.js @@ -0,0 +1,23 @@ +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} + +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; +} + +module.exports = bytesToUuid; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/md5-browser.js b/node_modules/azure-storage/node_modules/uuid/lib/md5-browser.js new file mode 100644 index 000000000..9b3b6c7ef --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/md5-browser.js @@ -0,0 +1,216 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +'use strict'; + +function md5(bytes) { + if (typeof(bytes) == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + bytes = new Array(msg.length); + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); + } + + return md5ToHexEncodedArray( + wordsToMd5( + bytesToWords(bytes) + , bytes.length * 8) + ); +} + + +/* +* Convert an array of little-endian words to an array of bytes +*/ +function md5ToHexEncodedArray(input) { + var i; + var x; + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + var hex; + + for (i = 0; i < length32; i += 8) { + x = (input[i >> 5] >>> (i % 32)) & 0xFF; + + hex = parseInt(hexTab.charAt((x >>> 4) & 0x0F) + hexTab.charAt(x & 0x0F), 16); + + output.push(hex); + } + return output; +} + +/* +* Calculate the MD5 of an array of little-endian words, and a bit length. +*/ +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << (len % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var i; + var olda; + var oldb; + var oldc; + var oldd; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + + var d = 271733878; + + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; + + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return [a, b, c, d]; +} + +/* +* Convert an array bytes to an array of little-endian words +* Characters >255 have their high-byte silently ignored. +*/ +function bytesToWords(input) { + var i; + var output = []; + output[(input.length >> 2) - 1] = undefined; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; + } + var length8 = input.length * 8; + for (i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32); + } + + return output; +} + +/* +* Add integers, wrapping at 2^32. This uses 16-bit operations internally +* to work around bugs in some JS interpreters. +*/ +function safeAdd(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* +* Bitwise rotate a 32-bit number to the left. +*/ +function bitRotateLeft(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); +} + +/* +* These functions implement the four basic operations the algorithm uses. +*/ +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} +function md5ff(a, b, c, d, x, s, t) { + return md5cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5gg(a, b, c, d, x, s, t) { + return md5cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +module.exports = md5; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/md5.js b/node_modules/azure-storage/node_modules/uuid/lib/md5.js new file mode 100644 index 000000000..7044b872f --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/md5.js @@ -0,0 +1,25 @@ +'use strict'; + +var crypto = require('crypto'); + +function md5(bytes) { + if (typeof Buffer.from === 'function') { + // Modern Buffer API + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + } else { + // Pre-v4 Buffer API + if (Array.isArray(bytes)) { + bytes = new Buffer(bytes); + } else if (typeof bytes === 'string') { + bytes = new Buffer(bytes, 'utf8'); + } + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +module.exports = md5; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/rng-browser.js b/node_modules/azure-storage/node_modules/uuid/lib/rng-browser.js new file mode 100644 index 000000000..14d21170d --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/rng-browser.js @@ -0,0 +1,32 @@ +// Unique ID creation requires a high quality random # generator. In the +// browser this is a little complicated due to unknown quality of Math.random() +// and inconsistent support for the `crypto` API. We do the best we can via +// feature-detection + +// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. +var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) || + (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto)); +if (getRandomValues) { + // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto + var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef + + module.exports = function whatwgRNG() { + getRandomValues(rnds8); + return rnds8; + }; +} else { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var rnds = new Array(16); + + module.exports = function mathRNG() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return rnds; + }; +} diff --git a/node_modules/azure-storage/node_modules/uuid/lib/rng.js b/node_modules/azure-storage/node_modules/uuid/lib/rng.js new file mode 100644 index 000000000..58f0dc9cf --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/rng.js @@ -0,0 +1,8 @@ +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. + +var crypto = require('crypto'); + +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/sha1-browser.js b/node_modules/azure-storage/node_modules/uuid/lib/sha1-browser.js new file mode 100644 index 000000000..5758ed75c --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/sha1-browser.js @@ -0,0 +1,89 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +'use strict'; + +function f(s, x, y, z) { + switch (s) { + case 0: return (x & y) ^ (~x & z); + case 1: return x ^ y ^ z; + case 2: return (x & y) ^ (x & z) ^ (y & z); + case 3: return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return (x << n) | (x>>> (32 - n)); +} + +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof(bytes) == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + bytes = new Array(msg.length); + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); + } + + bytes.push(0x80); + + var l = bytes.length/4 + 2; + var N = Math.ceil(l/16); + var M = new Array(N); + + for (var i=0; i>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = (H[0] + a) >>> 0; + H[1] = (H[1] + b) >>> 0; + H[2] = (H[2] + c) >>> 0; + H[3] = (H[3] + d) >>> 0; + H[4] = (H[4] + e) >>> 0; + } + + return [ + H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, + H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, + H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, + H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, + H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff + ]; +} + +module.exports = sha1; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/sha1.js b/node_modules/azure-storage/node_modules/uuid/lib/sha1.js new file mode 100644 index 000000000..0b54b2507 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/sha1.js @@ -0,0 +1,25 @@ +'use strict'; + +var crypto = require('crypto'); + +function sha1(bytes) { + if (typeof Buffer.from === 'function') { + // Modern Buffer API + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + } else { + // Pre-v4 Buffer API + if (Array.isArray(bytes)) { + bytes = new Buffer(bytes); + } else if (typeof bytes === 'string') { + bytes = new Buffer(bytes, 'utf8'); + } + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +module.exports = sha1; diff --git a/node_modules/azure-storage/node_modules/uuid/lib/v35.js b/node_modules/azure-storage/node_modules/uuid/lib/v35.js new file mode 100644 index 000000000..842c60ea2 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/lib/v35.js @@ -0,0 +1,53 @@ +var bytesToUuid = require('./bytesToUuid'); + +function uuidToBytes(uuid) { + // Note: We assume we're being passed a valid uuid string + var bytes = []; + uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) { + bytes.push(parseInt(hex, 16)); + }); + + return bytes; +} + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + var bytes = new Array(str.length); + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} + +module.exports = function(name, version, hashfunc) { + var generateUUID = function(value, namespace, buf, offset) { + var off = buf && offset || 0; + + if (typeof(value) == 'string') value = stringToBytes(value); + if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace); + + if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); + if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); + + // Per 4.3 + var bytes = hashfunc(namespace.concat(value)); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + if (buf) { + for (var idx = 0; idx < 16; ++idx) { + buf[off+idx] = bytes[idx]; + } + } + + return buf || bytesToUuid(bytes); + }; + + generateUUID.name = name; + + // Pre-defined namespaces, per Appendix C + generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; + generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; + + return generateUUID; +}; diff --git a/node_modules/azure-storage/node_modules/uuid/package.json b/node_modules/azure-storage/node_modules/uuid/package.json new file mode 100644 index 000000000..0b0bb85dd --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/package.json @@ -0,0 +1,123 @@ +{ + "_args": [ + [ + "uuid@^3.0.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage" + ] + ], + "_from": "uuid@>=3.0.0-0 <4.0.0-0", + "_id": "uuid@3.2.1", + "_inCache": true, + "_location": "/azure-storage/uuid", + "_nodeVersion": "7.10.1", + "_npmOperationalInternal": { + "host": "s3://npm-registry-packages", + "tmp": "tmp/uuid-3.2.1.tgz_1516124697652_0.3172094284091145" + }, + "_npmUser": { + "email": "robert@broofa.com", + "name": "broofa" + }, + "_npmVersion": "5.5.1", + "_phantomChildren": {}, + "_requested": { + "name": "uuid", + "raw": "uuid@^3.0.0", + "rawSpec": "^3.0.0", + "scope": null, + "spec": ">=3.0.0-0 <4.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage", + "/azure-storage/request" + ], + "_resolved": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz", + "_shasum": "12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14", + "_shrinkwrap": null, + "_spec": "uuid@^3.0.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage", + "bin": { + "uuid": "./bin/uuid" + }, + "browser": { + "./lib/md5.js": "./lib/md5-browser.js", + "./lib/rng.js": "./lib/rng-browser.js", + "./lib/sha1.js": "./lib/sha1-browser.js" + }, + "bugs": { + "url": "https://github.com/kelektiv/node-uuid/issues" + }, + "contributors": [ + { + "name": "Robert Kieffer", + "email": "robert@broofa.com" + }, + { + "name": "Christoph Tavan", + "email": "dev@tavan.de" + }, + { + "name": "AJ ONeal", + "email": "coolaj86@gmail.com" + }, + { + "name": "Vincent Voyer", + "email": "vincent@zeroload.net" + }, + { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + } + ], + "dependencies": {}, + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "devDependencies": { + "eslint": "4.5.0", + "mocha": "3.1.2", + "runmd": "1.0.1", + "standard-version": "4.2.0" + }, + "directories": {}, + "dist": { + "integrity": "sha512-jZnMwlb9Iku/O3smGWvZhauCf6cvvpKi4BKRiliS3cxnI+Gz9j5MEpTz2UFuXiKPJocb7gnsLHwiS05ige5BEA==", + "shasum": "12c528bb9d58d0b9265d9a2f6f0fe8be17ff1f14", + "tarball": "https://registry.npmjs.org/uuid/-/uuid-3.2.1.tgz" + }, + "gitHead": "ce7d3176fc927ab83b4e29b8d5a37b7243ce3360", + "homepage": "https://github.com/kelektiv/node-uuid#readme", + "installable": true, + "keywords": [ + "guid", + "rfc4122", + "uuid" + ], + "license": "MIT", + "maintainers": [ + { + "name": "broofa", + "email": "robert@broofa.com" + }, + { + "name": "defunctzombie", + "email": "shtylman@gmail.com" + }, + { + "name": "vvo", + "email": "vincent.voyer@gmail.com" + } + ], + "name": "uuid", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/kelektiv/node-uuid.git" + }, + "scripts": { + "md": "runmd --watch --output=README.md README_js.md", + "prepare": "runmd --output=README.md README_js.md", + "release": "standard-version", + "test": "mocha test/test.js" + }, + "version": "3.2.1" +} diff --git a/node_modules/azure-storage/node_modules/uuid/v1.js b/node_modules/azure-storage/node_modules/uuid/v1.js new file mode 100644 index 000000000..d84c0f452 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/v1.js @@ -0,0 +1,109 @@ +var rng = require('./lib/rng'); +var bytesToUuid = require('./lib/bytesToUuid'); + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; +var _clockseq; + +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; + +// See https://github.com/broofa/node-uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = rng(); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [ + seedBytes[0] | 0x01, + seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] + ]; + } + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf ? buf : bytesToUuid(b); +} + +module.exports = v1; diff --git a/node_modules/azure-storage/node_modules/uuid/v3.js b/node_modules/azure-storage/node_modules/uuid/v3.js new file mode 100644 index 000000000..ee7e14c0f --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/v3.js @@ -0,0 +1,4 @@ +var v35 = require('./lib/v35.js'); +var md5 = require('./lib/md5'); + +module.exports = v35('v3', 0x30, md5); \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/uuid/v4.js b/node_modules/azure-storage/node_modules/uuid/v4.js new file mode 100644 index 000000000..1f07be1c5 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/v4.js @@ -0,0 +1,29 @@ +var rng = require('./lib/rng'); +var bytesToUuid = require('./lib/bytesToUuid'); + +function v4(options, buf, offset) { + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || bytesToUuid(rnds); +} + +module.exports = v4; diff --git a/node_modules/azure-storage/node_modules/uuid/v5.js b/node_modules/azure-storage/node_modules/uuid/v5.js new file mode 100644 index 000000000..4945baf38 --- /dev/null +++ b/node_modules/azure-storage/node_modules/uuid/v5.js @@ -0,0 +1,3 @@ +var v35 = require('./lib/v35.js'); +var sha1 = require('./lib/sha1'); +module.exports = v35('v5', 0x50, sha1); diff --git a/node_modules/azure-storage/package.json b/node_modules/azure-storage/package.json new file mode 100644 index 000000000..ab51f3350 --- /dev/null +++ b/node_modules/azure-storage/package.json @@ -0,0 +1,145 @@ +{ + "_args": [ + [ + "azure-storage@^2.6.0", + "c:\\users\\luis\\source\\repos\\AACharly" + ] + ], + "_from": "azure-storage@>=2.6.0-0 <3.0.0-0", + "_id": "azure-storage@2.8.0", + "_inCache": true, + "_location": "/azure-storage", + "_nodeVersion": "6.12.0", + "_npmOperationalInternal": { + "host": "s3://npm-registry-packages", + "tmp": "tmp/azure-storage-2.8.0.tgz_1517913446540_0.9182677648495883" + }, + "_npmUser": { + "email": "azuresdk@outlook.com", + "name": "windowsazure" + }, + "_npmVersion": "3.10.10", + "_phantomChildren": { + "aws-sign2": "0.6.0", + "aws4": "1.6.0", + "caseless": "0.12.0", + "combined-stream": "1.0.5", + "forever-agent": "0.6.1", + "form-data": "2.1.4", + "har-validator": "4.2.1", + "hawk": "3.1.3", + "http-signature": "1.1.1", + "is-typedarray": "1.0.0", + "isstream": "0.1.2", + "json-stringify-safe": "5.0.1", + "mime-types": "2.1.17", + "oauth-sign": "0.8.2", + "performance-now": "0.2.0", + "qs": "6.4.0", + "safe-buffer": "5.1.1", + "stringstream": "0.0.5", + "tough-cookie": "2.3.3", + "tunnel-agent": "0.6.0" + }, + "_requested": { + "name": "azure-storage", + "raw": "azure-storage@^2.6.0", + "rawSpec": "^2.6.0", + "scope": null, + "spec": ">=2.6.0-0 <3.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/azure-storage/-/azure-storage-2.8.0.tgz", + "_shasum": "3ad0d90f475ff9209d6565af3e0ec9c5641304a4", + "_shrinkwrap": null, + "_spec": "azure-storage@^2.6.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly", + "author": { + "name": "Microsoft Corporation" + }, + "bugs": { + "url": "http://github.com/Azure/azure-storage-node/issues" + }, + "dependencies": { + "browserify-mime": "~1.2.9", + "extend": "~1.2.1", + "json-edm-parser": "0.1.2", + "md5.js": "1.3.4", + "readable-stream": "~2.0.0", + "request": "~2.81.0", + "underscore": "~1.8.3", + "uuid": "^3.0.0", + "validator": "~3.35.0", + "xml2js": "0.2.8", + "xmlbuilder": "0.4.3" + }, + "description": "Microsoft Azure Storage Client Library for Node.js", + "devDependencies": { + "batchflow": "0.4.0", + "browserify": "^13.3.0", + "coveralls": "^2.11.4", + "factor-bundle": "^2.5.0", + "grunt": "~0.4.2", + "grunt-contrib-jshint": "~0.11.0", + "grunt-devserver": "^0.6.0", + "grunt-jsdoc": "~2.1.0", + "grunt-mocha": "^0.4.12", + "grunt-mocha-test": "^0.12.7", + "grunt-nsp": "^2.3.1", + "ink-docstrap": "^1.3.0", + "istanbul": "^0.3.22", + "jshint": ">= 2.1.4", + "mocha": ">= 1.18.0", + "mocha-lcov-reporter": "^1.0.0", + "nock": "0.16", + "nsp": "^2.2.0", + "should": "1.2.x" + }, + "directories": {}, + "dist": { + "shasum": "3ad0d90f475ff9209d6565af3e0ec9c5641304a4", + "tarball": "https://registry.npmjs.org/azure-storage/-/azure-storage-2.8.0.tgz" + }, + "engines": { + "node": ">= 0.8.26" + }, + "gitHead": "31a987804efc703b9b1f4503e14b0801fe33798d", + "homepage": "http://github.com/Azure/azure-storage-node", + "installable": true, + "keywords": [ + "azure", + "node", + "storage" + ], + "license": "Apache-2.0", + "main": "./lib/azure-storage.js", + "maintainers": [ + { + "name": "windowsazure", + "email": "azuresdk@outlook.com" + } + ], + "name": "azure-storage", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Azure/azure-storage-node.git" + }, + "scripts": { + "check": "jshint lib && nsp check", + "cover": "istanbul cover ./node_modules/mocha/bin/_mocha -- -R spec -u bdd --no-timeouts --recursive test", + "coveralls": "npm run cover && cat ./coverage/lcov.info | node ./node_modules/coveralls/bin/coveralls.js", + "genjs": "node ./browser/bundle.js", + "test": "jshint lib && nsp check && mocha --no-timeouts --recursive test" + }, + "tags": [ + "azure", + "sdk", + "storage" + ], + "typings": "typings/azure-storage/azure-storage.d.ts", + "version": "2.8.0" +} diff --git a/node_modules/azure-storage/tsconfig.json b/node_modules/azure-storage/tsconfig.json new file mode 100644 index 000000000..7141a7fa5 --- /dev/null +++ b/node_modules/azure-storage/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "es6", + "sourceMap": true, + "outDir": "built", + "noEmitOnError": true, + "module": "commonjs" + }, + "exclude": [ + "node_modules", + "built", + "docs" + ] +} \ No newline at end of file diff --git a/node_modules/azure-storage/typings.json b/node_modules/azure-storage/typings.json new file mode 100644 index 000000000..91b516347 --- /dev/null +++ b/node_modules/azure-storage/typings.json @@ -0,0 +1,6 @@ +{ + "globalDependencies": { + "node": "registry:env/node#0.10.0+20160918225031", + "node-uuid": "registry:dt/node-uuid#0.0.0+20160316155526" + } +} diff --git a/node_modules/azure-storage/typings/azure-storage/azure-storage.d.ts b/node_modules/azure-storage/typings/azure-storage/azure-storage.d.ts new file mode 100644 index 000000000..b1ff21495 --- /dev/null +++ b/node_modules/azure-storage/typings/azure-storage/azure-storage.d.ts @@ -0,0 +1,9520 @@ +// +// Copyright (c) Microsoft and contributors. 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. +// +import * as events from 'events'; +import * as url from 'url'; +import * as stream from 'stream'; + +interface Map { + [index: string]: T; +} + +interface SharedKeyGenerateSignatureArgs { + /** The resource type, if the resource is a blob or container. Null if the resource is a queue or table. */ + resourceType?: string; + /** The table name, if the resource is a table. Null if the resource is a blob orqueue. */ + tableName?: string; + /** The optional header values to set for a blob returned wth this SAS. */ + headers?: { + /** The value of the Cache-Control response header to be returned when this SAS is used. */ + CacheControl?: string; + /** The value of the Content-Type response header to be returned when this SAS is used. */ + ContentType?: string; + /** The value of the Content-Encoding response header to be returned when this SAS is used. */ + ContentEncoding?: string; + /** The value of the Content-Language response header to be returned when this SAS is used. */ + ContentLanguage?: string; + /** The value of the Content-Disposition response header to be returned when this SAS is used. */ + ContentDisposition: string; + }; +} + +interface SharedKeyGenerateQueryStringArgs extends SharedKeyGenerateSignatureArgs { + /** The query string, if additional parameters are desired. */ + queryString?: string; +} + +declare module azurestorage { + export interface StorageHost { + primaryHost: string; + secondaryHost?: string; + } + + module services { + module blob { + // ########################### + // ./services/blob/blobservice + // ########################### + module blobservice { + export class BlobService extends StorageServiceClient { + defaultEnableReuseSocket: boolean; + singleBlobPutThresholdInBytes: number; + parallelOperationThreadCount: number; + + /** + * Creates a new BlobService object. + * If no connection string or storageaccount and storageaccesskey are provided, + * the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. + * @class + * The BlobService class is used to perform operations on the Microsoft Azure Blob Service. + * The Blob Service provides storage for binary large objects, and provides + * functions for working with data stored in blobs as either streams or pages of data. + * + * For more information on the Blob Service, as well as task focused information on using it in a Node.js application, see + * [How to Use the Blob Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/). + * The following defaults can be set on the blob service. + * singleBlobPutThresholdInBytes The default maximum size, in bytes, of a blob before it must be separated into blocks. + * defaultEnableReuseSocket The default boolean value to enable socket reuse when uploading local files or streams. + * If the Node.js version is lower than 0.10.x, socket reuse will always be turned off. + * defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Blob service. + * defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Blob service. + * defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Blob service. + * defaultLocationMode The default location mode for requests made via the Blob service. + * parallelOperationThreadCount The number of parallel operations that may be performed when uploading a blob that is greater than + * the value specified by the singleBlobPutThresholdInBytes property in size. + * useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Blob service; true to use the + * Nagle algorithm; otherwise, false. The default value is false. + * @constructor + * @extends {StorageServiceClient} + * + * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} [sasToken] The Shared Access Signature token. + * @param {string} [endpointSuffix] The endpoint suffix. + */ + constructor(storageAccountOrConnectionString: string, storageAccessKey?: string, host?: string|StorageHost, sasToken?: string, endpointSuffix?: string); + + /** + * Associate a filtering operation with this BlobService. Filtering operations + * can include logging, automatically retrying, etc. Filter operations are objects + * that implement a method with the signature: + * + * "function handle (requestOptions, next)". + * + * After doing its preprocessing on the request options, the method needs to call + * "next" passing a callback with the following signature: + * signature: + * + * "function (returnObject, finalCallback, next)" + * + * In this callback, and after processing the returnObject (the response from the + * request to the server), the callback needs to either invoke next if it exists to + * continue processing other filters or simply invoke finalCallback otherwise to end + * up the service invocation. + * + * @function BlobService#withFilter + * @param {Object} filter The new filter object. + * @return {BlobService} A new service client with the filter applied. + */ + withFilter(newFilter: common.filters.IFilter): BlobService; + + /** + * Gets the service stats for a storage account’s Blob service. + * + * @this {BlobService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the stats and + * `response` will contain information related to this operation. + */ + getServiceStats(options: common.RequestOptions, callback: ErrorOrResult): void; + getServiceStats(callback: ErrorOrResult): void; + + /** + * Gets the properties of a storage account’s Blob service, including Azure Storage Analytics. + * + * @this {BlobService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the properties + * and `response` will contain information related to this operation. + */ + getServiceProperties(options: common.RequestOptions, callback?: ErrorOrResult): void; + getServiceProperties(callback?: ErrorOrResult): void; + /** + * Sets the properties of a storage account’s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + * When you set blob service properties (such as enabling soft delete), it may take up to 30 seconds to take effect. + * + * @this {BlobService} + * @param {Object} serviceProperties The service properties. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise, `response` + * will contain information related to this operation. + */ + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, options: common.RequestOptions, callback: ErrorOrResponse): void; + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, callback: ErrorOrResponse): void; + + /** + * Sets the tier of a blockblob under a blob storage LRS account, or the tier of a pageblob under a premium storage account. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} blobTier Please see BlobUtilities.BlobTier.StandardBlobTier or BlobUtilities.BlobTier.PremiumPageBlobTier for possible values. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise, `response` + * will contain information related to this operation. + */ + setBlobTier(container: string, blob: string, blobTier: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + setBlobTier(container: string, blob: string, blobTier: string, callback: ErrorOrResponse): void; + + /** + * Lists a segment containing a collection of container items under the specified account. + * + * @this {BlobService} + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage. + * @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata') + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of containers and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listContainersSegmented(currentToken: common.ContinuationToken, options: BlobService.ListContainerOptions, callback: ErrorOrResult): void; + listContainersSegmented(currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + /** + * Lists a segment containing a collection of container items whose names begin with the specified prefix under the specified account. + * + * @this {BlobService} + * @param {string} prefix The prefix of the container name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage. + * @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata') + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of containers and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listContainersSegmentedWithPrefix(prefix: string, currentToken: common.ContinuationToken, options: BlobService.ListContainerOptions, callback: ErrorOrResult): void; + listContainersSegmentedWithPrefix(prefix: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Checks whether or not a container exists on the service. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the container exists, or false if the container does not exist. + * `response` will contain information related to this operation. + */ + doesContainerExist(container: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + + /** + * Checks whether or not a container exists on the service. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the container exists, or false if the container does not exist. + * `response` will contain information related to this operation. + */ + doesContainerExist(container: string, callback: ErrorOrResult): void; + + /** + * Creates a new container under the specified account. + * If a container with the same name already exists, the operation fails. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the container information. + * `response` will contain information related to this operation. + */ + createContainer(container: string, callback: ErrorOrResult): void; + + + /** + * Creates a new container under the specified account. + * If a container with the same name already exists, the operation fails. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the container information. + * `response` will contain information related to this operation. + */ + createContainer(container: string, options: BlobService.CreateContainerOptions, callback: ErrorOrResult): void; + + /** + * Creates a new container under the specified account if the container does not exists. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the container was created, or false if the container + * already exists. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error) { + * if(!error) { + * // Container created or exists, and is public + * } + * }); + */ + createContainerIfNotExists(container: string, callback: ErrorOrResult): void; + + /** + * Creates a new container under the specified account if the container does not exists. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the container was created, or false if the container + * already exists. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error) { + * if(!error) { + * // Container created or exists, and is public + * } + * }); + */ + createContainerIfNotExists(container: string, options: BlobService.CreateContainerOptions, callback: ErrorOrResult): void; + + /** + * Retrieves a container and its properties from a specified account. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + getContainerProperties(container: string, callback: ErrorOrResult): void; + + /** + * Retrieves a container and its properties from a specified account. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {string} [options.leaseId] The container lease identifier. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + getContainerProperties(container: string, options: BlobService.ContainerOptions, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata for the container. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + getContainerMetadata(container: string, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata for the container. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The container lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + getContainerMetadata(container: string, options: BlobService.ContainerOptions, callback: ErrorOrResult): void; + + /** + * Sets the container's metadata. + * + * Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container. + * It's not possible to modify an individual name/value pair. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} metadata The metadata key/value pairs. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + setContainerMetadata(container: string, metadata: Map, callback: ErrorOrResult): void; + + /** + * Sets the container's metadata. + * + * Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container. + * It's not possible to modify an individual name/value pair. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} metadata The metadata key/value pairs. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The container lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + setContainerMetadata(container: string, metadata: Map, options: BlobService.ContainerOptions, callback: ErrorOrResult): void; + + /** + * Gets the container's ACL. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + getContainerAcl(container: string, callback: ErrorOrResult): void; + + /** + * Gets the container's ACL. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The container lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + getContainerAcl(container: string, options: BlobService.ContainerOptions, callback: ErrorOrResult): void; + + /** + * Updates the container's ACL. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {[key:string]: AccessPolicy} signedIdentifiers The container ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access. + * @param {string} [options.leaseId] The container lease identifier. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the container. + * `response` will contain information related to this operation. + */ + setContainerAcl(container: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, options: BlobService.ContainerAclOptions, callback: ErrorOrResult): void; + setContainerAcl(container: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, callback: ErrorOrResult): void; + + /** + * Marks the specified container for deletion. + * The container and any blobs contained within it are later deleted during garbage collection. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + deleteContainer(container: string, callback: ErrorOrResponse): void; + + /** + * Marks the specified container for deletion. + * The container and any blobs contained within it are later deleted during garbage collection. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {string} [options.leaseId] The container lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + deleteContainer(container: string, options: BlobService.ContainerOptions, callback: ErrorOrResponse): void; + + /** + * Marks the specified container for deletion if it exists. + * The container and any blobs contained within it are later deleted during garbage collection. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the container exists and was deleted, or false if the container + * did not exist. + * `response` will contain information related to this operation. + */ + deleteContainerIfExists(container: string, callback: ErrorOrResult): void; + + /** + * Marks the specified container for deletion if it exists. + * The container and any blobs contained within it are later deleted during garbage collection. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {string} [options.leaseId] The container lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the container exists and was deleted, or false if the container + * did not exist. + * `response` will contain information related to this operation. + */ + deleteContainerIfExists(container: string, options: BlobService.ContainerOptions, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of blob items in the container. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of blobs and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listBlobsSegmented(container: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of blob items in the container. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {string} [options.delimiter] Delimiter, i.e. '/', for specifying folder hierarchy. + * @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) + * @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy', 'deleted'). Multiple values can be added separated with a comma (,) + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of blobs and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listBlobsSegmented(container: string, currentToken: common.ContinuationToken, options: BlobService.ListBlobsSegmentedRequestOptions, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} prefix The prefix of the blob name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the entries of blobs and the continuation token for the next listing operation. + * `response` will contain information related to this operation. + */ + listBlobsSegmentedWithPrefix(container: string, prefix: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of blob items whose names begin with the specified prefix in the container. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} prefix The prefix of the blob name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {string} [options.delimiter] Delimiter, i.e. '/', for specifying folder hierarchy. + * @param {int} [options.maxResults] Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) + * @param {string} [options.include] Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs', 'copy', 'deleted'). Multiple values can be added separated with a comma (,) + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs]The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the entries of blobs and the continuation token for the next listing operation. + * `response` will contain information related to this operation. + */ + listBlobsSegmentedWithPrefix(container: string, prefix: string, currentToken: common.ContinuationToken, options: BlobService.ListBlobsSegmentedRequestOptions, callback: ErrorOrResult): void; + + /** + * Acquires a new lease. If container and blob are specified, acquires a blob lease. Otherwise, if only container is specified and blob is null, acquires a container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + acquireLease(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Acquires a new lease. If container and blob are specified, acquires a blob lease. Otherwise, if only container is specified and blob is null, acquires a container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.leaseDuration] The lease duration in seconds. A non-infinite lease can be between 15 and 60 seconds. Default is never to expire. + * @param {string} [options.proposedLeaseId] The proposed lease identifier. Must be a GUID. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + acquireLease(container: string, blob: string, options: BlobService.AcquireLeaseRequestOptions, callback: ErrorOrResult): void; + + /** + * Renews an existing lease. If container and blob are specified, renews the blob lease. Otherwise, if only container is specified and blob is null, renews the container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} leaseId The lease identifier. Must be a GUID. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + renewLease(container: string, blob: string, leaseId: string, callback: ErrorOrResult): void; + + /** + * Renews an existing lease. If container and blob are specified, renews the blob lease. Otherwise, if only container is specified and blob is null, renews the container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} leaseId The lease identifier. Must be a GUID. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + renewLease(container: string, blob: string, leaseId: string, options: BlobService.LeaseRequestOptions, callback: ErrorOrResult): void; + + /** + * Changes the lease ID of an active lease. If container and blob are specified, changes the blob lease. Otherwise, if only container is specified and blob is null, changes the + * container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} leaseId The current lease identifier. + * @param {string} proposedLeaseId The proposed lease identifier. Must be a GUID. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the lease information. + * `response` will contain information related to this operation. + */ + changeLease(container: string, blob: string, leaseId: string, proposedLeaseId: string, callback: ErrorOrResult): void; + + /** + * Changes the lease ID of an active lease. If container and blob are specified, changes the blob lease. Otherwise, if only container is specified and blob is null, changes the + * container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} leaseId The current lease identifier. + * @param {string} proposedLeaseId The proposed lease identifier. Must be a GUID. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the lease information. + * `response` will contain information related to this operation. + */ + changeLease(container: string, blob: string, leaseId: string, proposedLeaseId: string, options: BlobService.LeaseRequestOptions, callback: ErrorOrResult): void; + + /** + * Releases the lease. If container and blob are specified, releases the blob lease. Otherwise, if only container is specified and blob is null, releases the container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} leaseId The lease identifier. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + releaseLease(container: string, blob: string, leaseId: string, callback: ErrorOrResult): void; + + /** + * Releases the lease. If container and blob are specified, releases the blob lease. Otherwise, if only container is specified and blob is null, releases the container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} leaseId The lease identifier. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + releaseLease(container: string, blob: string, leaseId: string, options: BlobService.LeaseRequestOptions, callback: ErrorOrResult): void; + + /** + * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. If container and blob are specified, breaks the blob lease. + * Otherwise, if only container is specified and blob is null, breaks the container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + breakLease(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. If container and blob are specified, breaks the blob lease. + * Otherwise, if only container is specified and blob is null, breaks the container lease. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {int} [options.leaseBreakPeriod] The lease break period, between 0 and 60 seconds. If unspecified, a fixed-duration lease breaks after + * the remaining lease period elapses, and an infinite lease breaks immediately. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the lease information. + * `response` will contain information related to this operation. + */ + breakLease(container: string, blob: string, options: BlobService.BreakLeaseRequestOptions, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. + * It does not return or modify the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + getBlobProperties(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. + * It does not return or modify the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + getBlobProperties(container: string, blob: string, optionsOrCallback: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata for the specified blob or snapshot. + * It does not modify or return the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + getBlobMetadata(container: string, blob: string, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + getBlobMetadata(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Clears user-defined properties for the specified blob or snapshot. + * It does not modify or return the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + setBlobProperties(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Sets user-defined properties for the specified blob or snapshot. + * It does not modify or return the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentMD5] The blob's MD5 hash. + * @param {string} [options.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentDisposition] The blob's content disposition. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + setBlobProperties(container: string, blob: string, optionsOrCallback: BlobService.SetBlobPropertiesRequestOptions, callback: ErrorOrResult): void; + + /** + * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs + * It does not modify or return the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} metadata The metadata key/value pairs. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information on the blob. + * `response` will contain information related to this operation. + */ + setBlobMetadata(container: string, blob: string, metadata: Map, callback: ErrorOrResult): void; + + /** + * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs + * It does not modify or return the content of the blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} metadata The metadata key/value pairs. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information on the blob. + * `response` will contain information related to this operation. + */ + setBlobMetadata(container: string, blob: string, metadata: Map, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + + /** + * Downloads a blob into a file. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} localFileName The local path to the file to be downloaded. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The upload tracker objects. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + * + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.getBlobToLocalFile('taskcontainer', 'task1', 'task1-download.txt', function(error, serverBlob) { + * if(!error) { + * // Blob available in serverBlob.blob variable + * } + */ + getBlobToLocalFile(container: string, blob: string, localFileName: string, options: BlobService.GetBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + getBlobToLocalFile(container: string, blob: string, localFileName: string, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + /** + * Provides a stream to read from a blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the blob information. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * var writable = fs.createWriteStream(destinationFileNameTarget); + * blobService.createReadStream(containerName, blobName).pipe(writable); + */ + createReadStream(container: string, blob: string, options: BlobService.GetBlobRequestOptions, callback: ErrorOrResult): stream.Readable; + createReadStream(container: string, blob: string, callback: ErrorOrResult): stream.Readable; + + /** + * Downloads a blob into a stream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Stream} writeStream The write stream. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + * + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.getBlobToStream('taskcontainer', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverBlob) { + * if(!error) { + * // Blob available in serverBlob.blob variable + * } + * }); + */ + getBlobToStream(container: string, blob: string, writeStream: stream.Writable, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Downloads a blob into a stream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Stream} writeStream The write stream. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. + * @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the blob information. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.getBlobToStream('taskcontainer', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverBlob) { + * if(!error) { + * // Blob available in serverBlob.blob variable + * } + * }); + */ + getBlobToStream(container: string, blob: string, writeStream: stream.Writable, options: BlobService.GetBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Downloads a blob into a text string. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.rangeStart] Return only the bytes of the blob in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the blob in the specified range. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading blobs. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {BlobService~blobToText} callback `error` will contain information + * if an error occurs; otherwise `text` will contain the blob contents, + * and `blockBlob` will contain + * the blob information. + * `response` will contain information related to this operation. + */ + getBlobToText(container: string, blob: string, options: BlobService.GetBlobRequestOptions, callback: BlobService.BlobToText): void; + getBlobToText(container: string, blob: string, callback: BlobService.BlobToText): void; + + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; `response` will contain information related to this operation. + */ + deleteBlob(container: string, blob: string, callback: ErrorOrResponse): void; + + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; `response` will contain information related to this operation. + */ + deleteBlob(container: string, blob: string, options: BlobService.DeleteBlobRequestOptions, callback: ErrorOrResponse): void; + + /** + * The undelete Blob operation restores the contents and metadata of soft deleted blob or snapshot. + * Attempting to undelete a blob or snapshot that is not soft deleted will succeed without any changes. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; `response` will contain information related to this operation. + */ + undeleteBlob(container: string, blob: string, callback: ErrorOrResponse): void; + undeleteBlob(container: string, blob: string, options: BlobService.ConditionalRequestOption, callback: ErrorOrResponse): void; + + /** + * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the blob was deleted, or false if the blob + * does not exist. + * `response` will contain information related to this operation. + */ + deleteBlobIfExists(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.BlobUtilities.SnapshotDeleteOptions.*. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the blob was deleted, or false if the blob + * does not exist. + * `response` will contain information related to this operation. + */ + deleteBlobIfExists(container: string, blob: string, options: BlobService.DeleteBlobRequestOptions, callback: ErrorOrResult): void; + + /** + * Checks whether or not a blob exists on the service. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `errorOrResult` will + * be true if the blob exists, or false if the blob does not exist. + * `response` will contain information related to this operation. + */ + doesBlobExist(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Checks whether or not a blob exists on the service. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `errorOrResult` will + * be true if the blob exists, or false if the blob does not exist. + * `response` will contain information related to this operation. + */ + doesBlobExist(container: string, blob: string, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + + /** + * Creates a read-only snapshot of a blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {string} [options.leaseId] The lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the ID of the snapshot. + * `response` will contain information related to this operation. + */ + createBlobSnapshot(container: string, blob: string, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + createBlobSnapshot(container: string, blob: string, callback: ErrorOrResult): void; + + /** + * Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. + * + * @this {BlobService} + * @param {string} sourceUri The source blob URI. + * @param {string} targetContainer The target container name. + * @param {string} targetBlob The target blob name. + * @param {Object} [options] The request options. + * @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. + * @param {string} [options.snapshotId] The source blob snapshot identifier. + * @param {Object} [options.metadata] The target blob metadata key/value pairs. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {string} [options.sourceLeaseId] The source blob lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {AccessConditions} [options.sourceAccessConditions] The source access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the blob information. + * `response` will contain information related to this operation. + */ + startCopyBlob(sourceUri: string, targetcontainer: string, targetblob: string, options: BlobService.CopyBlobRequestOptions, callback: ErrorOrResult): void; + startCopyBlob(sourceUri: string, targetcontainer: string, targetblob: string, callback: ErrorOrResult): void; + + /** + * Abort a blob copy operation. + * + * @this {BlobService} + * @param {string} container The destination container name. + * @param {string} blob The destination blob name. + * @param {string} copyId The copy operation identifier. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {ErrorOrResponse} callback `error` will contain information. + * `response` will contain information related to this operation. + */ + abortCopyBlob(container: string, blob: string, copyId: string, options: BlobService.BlobRequestOptions, callback: ErrorOrResponse): void; + abortCopyBlob(container: string, blob: string, copyId: string, callback: ErrorOrResponse): void; + + /** + * Retrieves a shared access signature token. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} [blob] The blob name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {Object} [headers] The optional header values to set for a blob returned wth this SAS. + * @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used. + * @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used. + * @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used. + * @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used. + * @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used. + * @return {string} The shared access signature. Note this does not contain the leading "?". + */ + generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: common.SharedAccessPolicy, headers?: common.ContentSettingsHeaders): string; + + /** + * Retrieves a shared access signature token. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} [blob] The blob name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {string} [sasVersion] An optional string indicating the desired SAS version to use. Value must be 2012-02-12 or later. + * @param {Object} [headers] The optional header values to set for a blob returned wth this SAS. + * @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used. + * @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used. + * @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used. + * @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used. + * @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used. + * @return {string} The shared access signature query string. Note this string does not contain the leading "?". + */ + generateSharedAccessSignatureWithVersion(container: string, blob: string, sharedAccessPolicy: common.SharedAccessPolicy, sasVersion: string, headers?: common.ContentSettingsHeaders): string; + + /** + * Retrieves a blob or container URL. + * + * @param {string} container The container name. + * @param {string} [blob] The blob name. + * @param {string} [sasToken] The Shared Access Signature token. + * @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint. + * @return {string} The formatted URL string. + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * //create a SAS that expires in an hour + * var sasToken = blobService.generateSharedAccessSignature(containerName, blobName, { AccessPolicy: { Expiry: azure.date.minutesFromNow(60); } }); + * var sasUrl = blobService.getUrl(containerName, blobName, sasToken, true); + */ + getUrl(container: string, blob?: string, sasToken?: string, primary?: boolean): string + + createPageBlob(container: string, blob: string, length: number, callback: ErrorOrResponse): void; + + createPageBlob(container: string, blob: string, length: number, options: BlobService.CreatePageBlobOptions, callback: ErrorOrResponse): void; + + /** + * Uploads a page blob from file. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param (string) localFileName The local path to the file to be uploaded. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The upload tracker objects. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createPageBlobFromLocalFile(container: string, blob: string, localFileName: string, options: BlobService.CreatePageBlobOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createPageBlobFromLocalFile(container: string, blob: string, localFileName: string, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a page blob from an HTML file. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * (Only available in the JavaScript Client Library for Browsers) + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} browserFile The File object to be uploaded created by HTML File API. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The upload tracker objects. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + */ + createPageBlobFromBrowserFile(container: string, blob: string, browserFile: Object, options: BlobService.CreatePageBlobOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createPageBlobFromBrowserFile(container: string, blob: string, browserFile: Object, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a page blob from a stream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param (Stream) stream Stream to the data to store. + * @param {int} streamLength The length of the stream to upload. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createPageBlobFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, options: BlobService.CreatePageBlobOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createPageBlobFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Provides a stream to write to a page blob. Assumes that the blob exists. + * If it does not, please create the blob using createPageBlob before calling this method or use createWriteStreamNewPageBlob. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs and true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.createPageBlob(containerName, blobName, 1024, function (err) { + * // Pipe file to a blob + * var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToExistingPageBlob(containerName, blobName)); + * }); + */ + createWriteStreamToExistingPageBlob(container: string, blob: string, options: BlobService.CreatePageBlobOptions, callback: ErrorOrResult): stream.Writable; + createWriteStreamToExistingPageBlob(container: string, blob: string, callback: ErrorOrResult): stream.Writable; + + /** + * Provides a stream to write to a page blob. Creates the blob before writing data. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} length The blob length. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs and true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.blobTier] For page blobs on premium accounts only. Set the tier of the target blob. Refer to BlobUtilities.BlobTier.PremiumPageBlobTier. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.createPageBlob(containerName, blobName, 1024, function (err) { + * // Pipe file to a blob + * var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToNewPageBlob(containerName, blobName)); + * }); + */ + createWriteStreamToNewPageBlob(container: string, blob: string, length: number, options: BlobService.CreatePageBlobOptions, callback: ErrorOrResult): stream.Writable; + createWriteStreamToNewPageBlob(container: string, blob: string, length: number, callback: ErrorOrResult): stream.Writable; + + /** + * Updates a page blob from a stream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Stream} readStream The read stream. + * @param {int} rangeStart The range start. + * @param {int} rangeEnd The range end. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.transactionalContentMD5] An optional hash value used to ensure transactional integrity for the page. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the blob information. + * `response` will contain information related to this operation. + */ + createPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + createPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: ErrorOrResult): void; + + /** + * Lists page ranges. Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {int} [options.rangeStart] The range start. + * @param {int} [options.rangeEnd] The range end. + * @param {string} [options.snapshotId] The snapshot identifier. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the page range information. + * `response` will contain information related to this operation. + */ + listPageRanges(container: string, blob: string, options: BlobService.GetBlobRequestOptions, callback: ErrorOrResult): void; + listPageRanges(container: string, blob: string, callback: ErrorOrResult): void; + + getPageRangesDiff(container: string, blob: string, previousSnapshotTime: string, options: BlobService.GetBlobRequestOptions, callback: ErrorOrResult): void; + getPageRangesDiff(container: string, blob: string, previousSnapshotTime: string, callback: ErrorOrResult): void; + + /** + * Clears a range of pages. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {int} rangeStart The range start. + * @param {int} rangeEnd The range end. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + clearPageRange(container: string, blob: string, rangeStart: number, rangeEnd: number, options: BlobService.BlobRequestOptions, callback: ErrorOrResponse): void; + clearPageRange(container: string, blob: string, rangeStart: number, rangeEnd: number, callback: ErrorOrResponse): void; + + /** + * Resizes a page blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {String} size The size of the page blob, in bytes. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The blob lease identifier. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + resizePageBlob(container: string, blob: string, size: number, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + resizePageBlob(container: string, blob: string, size: number, callback: ErrorOrResult): void; + + /** + * Sets the page blob's sequence number. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {SequenceNumberAction} sequenceNumberAction A value indicating the operation to perform on the sequence number. + * The allowed values are defined in azure.BlobUtilities.SequenceNumberAction. + * @param {string} sequenceNumber The sequence number. The value of the sequence number must be between 0 and 2^63 - 1. + * Set this parameter to null if this operation is an increment action. + * @param {Object} [options] The request options. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: number, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: number, callback: ErrorOrResult): void; + + /** + * Creates a new block blob or updates the content of an existing block blob. + * Updating an existing block blob overwrites any existing metadata on the blob. + * Partial updates are not supported with Put Blob; The content of the existing blob is overwritten with the content of the new blob. + * To perform a partial update of the content of a block blob, use the Put Block List operation. + * Calling Put Blob to create a page blob only initializes the blob. To add content to a page blob, call the Put Page operation. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} localFileName The local path to the file to be uploaded. + * @param {Object} [options] The request options. + * @param {int} [options.blockSize] The size of each block. Maximum is 100MB. + * @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + */ + createBlockBlobFromLocalFile(container: string, blob: string, localFileName: string, options: BlobService.CreateBlockBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createBlockBlobFromLocalFile(container: string, blob: string, localFileName: string, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Creates a new block blob. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * (Only available in the JavaScript Client Library for Browsers) + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} browserFile The File object to be uploaded created by HTML File API. + * @param {Object} [options] The request options. + * @param {int} [options.blockSize] The size of each block. Maximum is 100MB. + * @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + */ + createBlockBlobFromBrowserFile(container: string, blob: string, browserFile: Object, options: BlobService.CreateBlockBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createBlockBlobFromBrowserFile(container: string, blob: string, browserFile: Object, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a block blob from a stream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param (Stream) stream Stream to the data to store. + * @param {int} streamLength The length of the stream to upload. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createBlockBlobFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a block blob from a stream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param (Stream) stream Stream to the data to store. + * @param {int} streamLength The length of the stream to upload. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects. + * @param {int} [options.blockSize] The size of each block. Maximum is 100MB. + * @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createBlockBlobFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, options: BlobService.CreateBlockBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a block blob from a text string. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string|object} text The blob text, as a string or in a Buffer. + * @param {Object} [options] The request options. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + createBlockBlobFromText(container: string, blob: string, text: string | Buffer, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): void; + createBlockBlobFromText(container: string, blob: string, text: string | Buffer, callback: ErrorOrResult): void; + + /** + * Provides a stream to write to a block blob. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {int} [options.blockSize] The size of each block. Maximum is 100MB. + * @param {string} [options.blockIdPrefix] The prefix to be used to generate the block id. + * @param {string} [options.leaseId] The lease identifier. + * @param {string} [options.transactionalContentMD5] The MD5 hash of the blob content. This hash is used to verify the integrity of the blob during transport. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.parallelOperationThreadCount] The number of parallel operations that may be performed when uploading. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs and true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToBlockBlob(containerName, blobName, { blockIdPrefix: 'block' })); + */ + createWriteStreamToBlockBlob(container: string, blob: string, options: BlobService.CreateBlockBlobRequestOptions, callback?: ErrorOrResult): stream.Writable; + createWriteStreamToBlockBlob(container: string, blob: string, callback?: ErrorOrResult): stream.Writable; + + /** + * Creates a new block to be committed as part of a blob. + * + * @this {BlobService} + * @param {string} blockId The block identifier. + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Stream} readStream The read stream. + * @param {int} streamLength The stream length. + * @param {Object} [options] The request options. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + createBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Readable, streamLength: number, options: BlobService.BlobRequestOptions, callback: ErrorOrResponse): void; + createBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Readable, streamLength: number, callback: ErrorOrResponse): void; + + /** + * Creates a new block to be committed as part of a blob. + * + * @this {BlobService} + * @param {string} blockId The block identifier. + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string|buffer} content The block content. + * @param {Object} [options] The request options. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + createBlockFromText(blockId: string, container: string, blob: string, content: string | Buffer, options: BlobService.BlobRequestOptions, callback: ErrorOrResponse): void; + createBlockFromText(blockId: string, container: string, blob: string, content: string | Buffer, callback: ErrorOrResponse): void; + + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written to the server in a prior + * createBlock operation. + * Note: If no valid list is specified in the blockList parameter, blob would be updated with empty content, + * i.e. existing blocks in the blob will be removed, this behavior is kept for backward compatibility consideration. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} blockList The wrapper for block ID list contains block IDs that make up the blob. + * Three kinds of list are provided, please choose one to use according to requirement. + * For more background knowledge, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-list + * @param {string[]} [blockList.LatestBlocks] The list contains block IDs that make up the blob sequentially. + * All the block IDs in this list will be specified within Latest element. + * Choose this list to contain block IDs indicates that the Blob service should first search + * the uncommitted block list, and then the committed block list for the named block. + * @param {string[]} [blockList.CommittedBlocks] The list contains block IDs that make up the blob sequentially. + * All the block IDs in this list will be specified within Committed element. + * Choose this list to contain block IDs indicates that the Blob service should only search + * the committed block list for the named block. + * @param {string[]} [blockList.UncommittedBlocks] The list contains block IDs that make up the blob sequentially. + * All the block IDs in this list will be specified within Uncommitted element. + * Choose this list to contain block IDs indicates that the Blob service should only search + * the uncommitted block list for the named block. + * @param {Object} [options] The request options. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the blocklist information. + * `response` will contain information related to this operation. + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * blobService.createBlockFromText("sampleBlockName", containerName, blobName, "sampleBlockContent", function(error) { + * assert.equal(error, null); + * // In this example, LatestBlocks is used, we hope the Blob service first search + * // the uncommitted block list, and then the committed block list for the named block "sampleBlockName", + * // and thus make sure the block is with latest content. + * blobService.commitBlocks(containerName, blobName, { LatestBlocks: ["sampleBlockName"] }, function(error) { + * assert.equal(error, null); + * }); + * }); + */ + commitBlocks(container: string, blob: string, blockList: BlobService.PutBlockListRequest, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): void; + commitBlocks(container: string, blob: string, blockList: BlobService.PutBlockListRequest, callback: ErrorOrResult): void; + + /** + * Retrieves the list of blocks that have been uploaded as part of a block blob. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {BlockListFilter} blocklisttype The type of block list to retrieve. + * @param {Object} [options] The request options. + * @param {string} [options.snapshotId] The source blob snapshot identifier. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the blocklist information. + * `response` will contain information related to this operation. + */ + listBlocks(container: string, blob: string, blocklisttype: string, options: BlobService.BlobRequestOptions, callback: ErrorOrResult): void; + listBlocks(container: string, blob: string, blocklisttype: string, callback: ErrorOrResult): void; + + /** + * Generate a random block id prefix + */ + generateBlockIdPrefix(): string; + + /** + * Get a block id according to prefix and block number + */ + getBlockId(prefix: string, number: number | string): string; + + /** + * Creates an empty append blob. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + createOrReplaceAppendBlob(container: string, blob: string, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResponse): void; + createOrReplaceAppendBlob(container: string, blob: string, callback: ErrorOrResponse): void; + + /** + * Creates a new append blob from a local file. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * If you want to append data to an already existing blob, please look at appendFromLocalFile. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} localFileName The local path to the file to be uploaded. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createAppendBlobFromLocalFile(container: string, blob: string, localFileName: string, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createAppendBlobFromLocalFile(container: string, blob: string, localFileName: string, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Creates a new append blob from an HTML File object. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * If you want to append data to an already existing blob, please look at appendFromBrowserFile. + * (Only available in the JavaScript Client Library for Browsers) + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} browserFile The File object to be uploaded created by HTML File API. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 ahash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + */ + createAppendBlobFromBrowserFile(container: string, blob: string, browserFile: Object, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createAppendBlobFromBrowserFile(container: string, blob: string, browserFile: Object, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads an append blob from a stream. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * If you want to append data to an already existing blob, please look at appendFromStream. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param (Stream) stream Stream to the data to store. + * @param {int} streamLength The length of the stream to upload. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createAppendBlobFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createAppendBlobFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads an append blob from a text string. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * If you want to append data to an already existing blob, please look at appendFromText. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string|object} text The blob text, as a string or in a Buffer. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + createAppendBlobFromText(container: string, blob: string, text: string | Buffer, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): void; + createAppendBlobFromText(container: string, blob: string, text: string | Buffer, callback: ErrorOrResult): void; + + /** + * Provides a stream to write to a new append blob. If the blob already exists on the service, it will be overwritten. + * To avoid overwriting and instead throw an error if the blob exists, please pass in an accessConditions parameter in the options object. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs and true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName)); + */ + createWriteStreamToNewAppendBlob(container: string, blob: string, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): stream.Writable; + createWriteStreamToNewAppendBlob(container: string, blob: string, callback: ErrorOrResult): stream.Writable; + + /** + * Provides a stream to write to an existing append blob. Assumes that the blob exists. + * If it does not, please create the blob using createAppendBlob before calling this method or use createWriteStreamToNewAppendBlob. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. + * The default value is false for page blobs and true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var blobService = azure.createBlobService(); + * var stream = fs.createReadStream(fileNameTarget).pipe(blobService.createWriteStreamToAppendBlob(containerName, blobName)); + */ + createWriteStreamToExistingAppendBlob(container: string, blob: string, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): stream.Writable; + createWriteStreamToExistingAppendBlob(container: string, blob: string, callback: ErrorOrResult): stream.Writable; + + /** + * Appends to an append blob from a local file. Assumes the blob already exists on the service. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string} localFileName The local path to the file to be uploaded. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + appendFromLocalFile(container: string, blob: string, localFileName: string, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + appendFromLocalFile(container: string, blob: string, localFileName: string, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Appends to an append blob from an HTML File object. Assumes the blob already exists on the service. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * (Only available in the JavaScript Client Library for Browsers) + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Object} browserFile The File object to be uploaded created by HTML File API. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link BlobResult}` will contain + * the blob information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + */ + appendFromBrowserFile(container: string, blob: string, browserFile: Object, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + appendFromBrowserFile(container: string, blob: string, browserFile: Object, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Appends to an append blob from a stream. Assumes the blob already exists on the service. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param (Stream) stream Stream to the data to store. + * @param {int} streamLength The length of the stream to upload. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + appendFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary;; + appendFromStream(container: string, blob: string, stream: stream.Readable, streamLength: number, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary;; + + /** + * Appends to an append blob from a text string. Assumes the blob already exists on the service. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string|object} text The blob text, as a string or in a Buffer. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {string} [options.leaseId] The lease identifier. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeBlobContentMD5] Specifies whether the blob's ContentMD5 header should be set on uploads. The default value is true for block blobs. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The content settings of the blob. + * @param {string} [options.contentSettings.contentType] The MIME content type of the blob. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the blob. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The Blob service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The blob's content disposition. + * @param {string} [options.contentSettings.contentMD5] The blob's MD5 hash. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + appendFromText(container: string, blob: string, text: string, options: BlobService.CreateBlobRequestOptions, callback: ErrorOrResult): void; + appendFromText(container: string, blob: string, text: string, callback: ErrorOrResult): void; + + /** + * Creates a new block from a read stream to be appended to an append blob. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {Stream} readStream The read stream. + * @param {int} streamLength The stream length. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to. + * @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + appendBlockFromStream(container: string, blob: string, readStream: stream.Readable, streamLength: number, options: BlobService.AppendBlobRequestOptions, callback: ErrorOrResult): void; + appendBlockFromStream(container: string, blob: string, readStream: stream.Readable, streamLength: number, callback: ErrorOrResult): void; + + /** + * Creates a new block from a text to be appended to an append blob. + * This API should be used strictly in a single writer scenario because the API internally uses the append-offset conditional header to avoid duplicate blocks. + * If you are guaranteed to have a single writer scenario, please look at options.absorbConditionalErrorsOnRetry and see if setting this flag to true is acceptable for you. + * + * @this {BlobService} + * @param {string} container The container name. + * @param {string} blob The blob name. + * @param {string|object} content The block text, as a string or in a Buffer. + * @param {Object} [options] The request options. + * @param {bool} [options.absorbConditionalErrorsOnRetry] Specifies whether to absorb the conditional error on retry. + * @param {int} [options.maxBlobSize] The max length in bytes allowed for the append blob to grow to. + * @param {int} [options.appendPosition] The number indicating the byte offset to check for. The append will succeed only if the end position of the blob is equal to this number. + * @param {string} [options.leaseId] The target blob lease identifier. + * @param {string} [options.transactionalContentMD5] An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the blob. + * `response` will contain information related to this operation. + */ + appendBlockFromText(container: string, blob: string, content: string | Buffer, options: BlobService.AppendBlobRequestOptions, callback: ErrorOrResult): void; + appendBlockFromText(container: string, blob: string, content: string | Buffer, callback: ErrorOrResult): void; + + /** + * The callback for {BlobService~getBlobToText}. + * @typedef {function} BlobService~blobToText + * @param {Object} error If an error occurs, the error information. + * @param {string} text The text returned from the blob. + * @param {Object} blockBlob Information about the blob. + * @param {Object} response Information related to this operation. + */ + static SpeedSummary: common.streams.speedsummary.SpeedSummary; + } + export module BlobService { + export interface CreateContainerOptions extends common.RequestOptions { + metadata?: Map; + publicAccessLevel?: string; + } + + export interface ListContainerOptions extends common.RequestOptions { + maxResults?: number; + include?: string; + } + + export interface ConditionalRequestOption extends common.RequestOptions { + accessConditions?: AccessConditions; + } + + export interface ContainerOptions extends ConditionalRequestOption { + leaseId?: string; + } + + export interface ContainerAclOptions extends ContainerOptions { + publicAccessLevel?: string; + } + + export interface LeaseRequestOptions extends ConditionalRequestOption { + } + + export interface AcquireLeaseRequestOptions extends LeaseRequestOptions { + leaseDuration?: number; + proposedLeaseId?: string; + } + + export interface BreakLeaseRequestOptions extends LeaseRequestOptions { + leaseBreakPeriod?: number; + } + + export interface ListBlobsSegmentedRequestOptions extends common.RequestOptions { + /** + * {string} Delimiter, i.e. '/', for specifying folder hierarchy. + */ + delimiter?: string; + /** + * {int} Specifies the maximum number of blobs to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) + */ + maxResults?: number; + + /** + * {string} Specifies that the response should include one or more of the following subsets: '', 'metadata', 'snapshots', 'uncommittedblobs'). Multiple values can be added separated with a comma (,) + */ + include?: string; + } + + export interface LeaseResult { + container: string; + blob: string; + id: string; + time: number; + etag: string; + lastModified: string; + } + + export interface ListBlobsResult { + entries: BlobResult[]; + continuationToken?: common.ContinuationToken; + } + + export interface ContainerAclResult extends ContainerResult { + signedIdentifiers: {[key:string]: common.AccessPolicy} + } + + export interface ContainerResult { + name: string; + publicAccessLevel: string; + etag: string; + lastModified: string; + metadata?: { [key: string]: string; }; + requestId?: string; + lease?: { + duration?: string; + status: string; + state: string; + }; + exists?: boolean; + created?: boolean; + } + + export interface ListContainerResult { + continuationToken: common.ContinuationToken; + entries: ContainerResult[]; + } + + export interface BlobResult { + name: string; + snapshot?: string; + deleted?: boolean; + container: string; + metadata?: { [key: string]: string; }; + etag: string; + lastModified: string; + contentLength: string; + blobType: string; + accessTier?: string; + accessTierChangeTime?: string; + accessTierInferred?: boolean; + archiveStatus?: string; + isIncrementalCopy?: boolean; + requestId: string; + sequenceNumber?: string; + contentRange?: string; + committedBlockCount?: string; + serverEncrypted?: string; + deletedTime?: string; + remainingRetentionDays?: string; + appendOffset? : string; + contentSettings?: { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + cacheControl?: string; + contentDisposition?: string; + contentMD5?: string; + } + lease?: { + id?: string; + status?: string; + state?: string; + duration?: string; + } + copy?: { + id?: string; + status?: string; + completionTime?: string; + statusDescription?: string; + destinationSnapshot?: string; + progress?: string; + source?: string; + }, + exists?: boolean; + created?: boolean; + } + + export interface CreatePageBlobOptions { + metadata?: Object; + leaseId?: string; + transactionalContentMD5?: string; + blobTier?: string; + contentSettings?: { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + cacheControl?: string; + contentDisposition?: string; + contentMD5?: string; + } + sequenceNumber?: string; + accessConditions?: AccessConditions; + locationMode?: StorageUtilities.LocationMode; + timeoutIntervalInMs?: number; + clientRequestTimeoutInMs?: number; + maximumExecutionTimeInMs?: number; + useNagleAlgorithm?: boolean; + } + + export interface BlobRequestOptions extends ConditionalRequestOption { + snapshotId?: string; // TODO: Not valid for most write requests... + leaseId?: string; + } + + export interface AppendBlobRequestOptions extends ConditionalRequestOption, BlobRequestOptions { + absorbConditionalErrorsOnRetry?: boolean; + maxBlobSize?: number; + appendPosition?: number; + } + + export interface SetBlobPropertiesRequestOptions extends BlobRequestOptions { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; + } + + export interface GetBlobRequestOptions extends BlobRequestOptions { + speedSummary?: common.streams.speedsummary.SpeedSummary; + parallelOperationThreadCount?: number; + rangeStart?: number; + rangeEnd?: number; + useTransactionalMD5?: boolean; + disableContentMD5Validation?: boolean; + } + + export interface CopyBlobRequestOptions extends BlobRequestOptions { + metadata?: { [k: string]: string; }; + sourceLeaseId?: string; + accessConditions?: AccessConditions; + sourceAccessConditions?: AccessConditions; + isIncrementalCopy?: boolean; + } + + export interface DeleteBlobRequestOptions extends BlobRequestOptions { + deleteSnapshots?: string; + } + + export interface CreateBlobRequestOptions extends BlobRequestOptions { + speedSummary?: common.streams.speedsummary.SpeedSummary; + parallelOperationThreadCount?: number; + useTransactionalMD5?: boolean; + blockIdPrefix?: string; + metadata?: {[k: string]: string}; + storeBlobContentMD5?: boolean; + transactionalContentMD5?: string; + contentSettings?: { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + cacheControl?: string; + contentDisposition?: string; + contentMD5?: string; + } + } + + export interface CreateBlockBlobRequestOptions extends CreateBlobRequestOptions { + blockSize?: number; + } + + export interface BlobToText { + (error: Error, text: string, result: BlobResult, response: ServiceResponse): void + } + + export interface ListPageRangesRequestOptions extends common.RequestOptions { + rangeStart?: number; + rangeEnd?: number; + } + + export interface BlockListResult { + CommittedBlocks?: Block[]; + UncommittedBlocks?: Block[]; + } + + export interface PutBlockListRequest { + LatestBlocks?: string[]; + CommittedBlocks?: string[]; + UncommittedBlocks?: string[]; + } + + export interface Block { + Name?: string; + Size?: string; + } + } + } + + // ########################### + // ./services/blob/blobutilities + // ########################### + module blobutilities { + export var BlobUtilities: { + SharedAccessPermissions: { + READ: string; + WRITE: string; + DELETE: string; + LIST: string; + }; + BlobListingDetails: { + SNAPSHOTS: string; + METADATA: string; + UNCOMMITTED_BLOBS: string; + COPY: string; + DELETED: string; + }; + SnapshotDeleteOptions: { + SNAPSHOTS_ONLY: string; + BLOB_AND_SNAPSHOTS: string; + }; + BlockListFilter: { + ALL: string; + COMMITTED: string; + UNCOMMITTED: string; + }; + BlobContainerPublicAccessType: { + OFF: string; + CONTAINER: string; + BLOB: string; + }; + SequenceNumberAction: { + MAX: string; + UPDATE: string; + INCREMENT: string; + }; + BlobTier: { + PremiumPageBlobTier: { + P4: string; + P6: string; + P10: string; + P20: string; + P30: string; + P40: string; + P50: string; + P60: string; + }; + StandardBlobTier: { + HOT: string; + COOL: string; + ARCHIVE: string; + }; + } + }; + } + } + + module queue { + export class QueueService extends StorageServiceClient { + /** + * @property {boolean} QueueService#queueMessagEncoder + * @defaultvalue {boolean} true + * A flag indicating whether the message should be base-64 encoded. Default is true. + */ + messageEncoder: QueueMessageEncoder; + + /** + * Creates a new QueueService object. + * + * The QueueService class is used to perform operations on the Microsoft Azure Queue Service. + * + * For more information on using the Queue Service, as well as task focused information on using it from a Node.js application, see + * [How to Use the Queue Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-queues/). + * The following defaults can be set on the Queue service. + * messageEncoder The message encoder to specify how QueueService encodes and decodes the queue message. Default is `[TextXmlQueueMessageEncoder]{@link TextXmlQueueMessageEncoder}`. + * defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Queue service. + * defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Queue service. + * defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Queue service. + * defaultLocationMode The default location mode for requests made via the Queue service. + * useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Queue service; true to use the + * Nagle algorithm; otherwise, false. The default value is false. + * If no connection string or storageaccount and storageaccesskey are provided, + * the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. + * @augments {StorageServiceClient} + * @constructor QueueService + * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} [sasToken] The Shared Access Signature token. + * @param {string} [endpointSuffix] The endpoint suffix. + */ + constructor(storageAccountOrConnectionString?: string, storageAccessKey?: string, host?: string|StorageHost, sasToken?: string, endpointSuffix?: string); + + /** + * Associate a filtering operation with this QueueService. Filtering operations + * can include logging, automatically retrying, etc. Filter operations are objects + * that implement a method with the signature: + * + * "function handle (requestOptions, next)". + * + * After doing its preprocessing on the request options, the method needs to call + * "next" passing a callback with the following signature: + * signature: + * + * "function (returnObject, finalCallback, next)" + * + * In this callback, and after processing the returnObject (the response from the + * request to the server), the callback needs to either invoke next if it exists to + * continue processing other filters or simply invoke finalCallback otherwise to end + * up the service invocation. + * + * @function QueueService#withFilter + * @param {Object} filter The new filter object. + * @return {QueueService} A new service client with the filter applied. + */ + withFilter(newFilter: common.filters.IFilter): QueueService; + + /** + * Gets the service stats for a storage account’s Queue service. + * + * @function QueueService#getServiceStats + * + * @this {QueueService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise, `result` + * will contain the stats and `response` + * will contain information related to this operation. + */ + getServiceStats(options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Gets the service stats for a storage account’s Queue service. + * + * @function QueueService#getServiceStats + * + * @this {QueueService} + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise, `result` + * will contain the stats and `response` + * will contain information related to this operation. + */ + getServiceStats(callback: ErrorOrResult): void; + + /** + * Gets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics. + * + * @this {QueueService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise, `errorOrResult` + * will contain the properties and `response` + * will contain information related to this operation. + */ + getServiceProperties(options: common.RequestOptions, callback?: ErrorOrResult): void; + + /** + * Gets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics. + * + * @this {QueueService} + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise, `errorOrResult` + * will contain the properties and `response` + * will contain information related to this operation. + */ + getServiceProperties(callback?: ErrorOrResult): void; + + /** + * Sets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + * + * @this {QueueService} + * @param {Object} serviceProperties The service properties. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise, `response` + * will contain information related to this operation. + */ + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, options: common.RequestOptions, callback?: ErrorOrResponse): void; + + /** + * Sets the properties of a storage account’s Queue service, including Microsoft Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + * + * @this {QueueService} + * @param {Object} serviceProperties The service properties. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise, `response` + * will contain information related to this operation. + */ + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, callback?: ErrorOrResponse): void; + + /** + * Lists a segment containing a collection of queue items whose names begin with the specified prefix under the given account. + * + * @this {QueueService} + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {int} [options.maxResults] Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000) + * @param {string} [options.include] Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata') + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of queues and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listQueuesSegmented(currentToken: common.ContinuationToken, options: QueueService.ListQueuesRequestOptions, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of queue items whose names begin with the specified prefix under the given account. + * + * @function QueueService#listQueuesSegmented + * + * @this {QueueService} + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of queues and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listQueuesSegmented(currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of queue items under the given account. + * + * @function QueueService#listQueuesSegmentedWithPrefix + * + * @this {QueueService} + * @param {string} prefix The prefix of the queue name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.* + * @param {Object} [options] The request options. + * @param {string} [options.marker] String value that identifies the portion of the list to be returned with the next list operation. + * @param {int} [options.maxResults] Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000) + * @param {string} [options.include] Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata') + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of queues and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listQueuesSegmentedWithPrefix(prefix: string, currentToken: common.ContinuationToken, options: QueueService.ListQueuesRequestOptions, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of queue items under the given account. + * + * @function QueueService#listQueuesSegmentedWithPrefix + * + * @this {QueueService} + * @param {string} prefix The prefix of the queue name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.* + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of queues and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listQueuesSegmentedWithPrefix(prefix: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Checks to see if a queue exists. + * + * @function QueueService#doesQueueExist + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise, `result` + * will be true if the queue exists and false if not, + * and `response` will contain information related to this operation. + */ + doesQueueExist(queue: string, options: common.RequestOptions, callback?: ErrorOrResult): void; + + /** + * Checks to see if a queue exists. + * + * @function QueueService#doesQueueExist + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise, `result` + * will be true if the queue exists and false if not, + * and `response` will contain information related to this operation. + */ + doesQueueExist(queue: string, callback?: ErrorOrResult): void; + + /** + * Creates a new queue under the given account. + * + * @function QueueService#createQueue + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the queue information. + * `response` will contain information related to this operation. + */ + createQueue(queue: string, optionsOrCallback: QueueService.CreateQueueRequestOptions, callback?: ErrorOrResult): void; + + /** + * Creates a new queue under the given account. + * + * @function QueueService#createQueue + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the queue information. + * `response` will contain information related to this operation. + */ + createQueue(queue: string, callback?: ErrorOrResult): void; + + /** + * Creates a new queue under the given account if it doesn't exist. + * + * @function QueueService#createQueueIfNotExists + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will be true if the + * queue was created by this operation and false if not, and + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * queueService.createQueueIfNotExists('taskqueue', function(error) { + * if(!error) { + * // Queue created or exists + * } + * }); + */ + createQueueIfNotExists(queue: string, optionsOrCallback: QueueService.CreateQueueRequestOptions, callback?: ErrorOrResult): void; + + /** + * Creates a new queue under the given account if it doesn't exist. + * + * @function QueueService#createQueueIfNotExists + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will be true if the + * queue was created by this operation and false if not, and + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * queueService.createQueueIfNotExists('taskqueue', function(error) { + * if(!error) { + * // Queue created or exists + * } + * }); + */ + createQueueIfNotExists(queue: string, callback?: ErrorOrResult): void; + + /** + * Permanently deletes the specified queue. + * + * @function QueueService#deleteQueue + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteQueue(queue: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + + /** + * Permanently deletes the specified queue. + * + * @function QueueService#deleteQueue + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteQueue(queue: string, callback: ErrorOrResponse): void; + + /** + * Permanently deletes the specified queue if it exists. + * + * @function QueueService#deleteQueueIfExists + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * 'true' if the queue was deleted and 'false' if the queue did not exist. + * `response` will contain information related to this operation. + */ + deleteQueueIfExists(queue: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Permanently deletes the specified queue if it exists. + * + * @function QueueService#deleteQueueIfExists + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * 'true' if the queue was deleted and 'false' if the queue did not exist. + * `response` will contain information related to this operation. + */ + deleteQueueIfExists(queue: string, callback: ErrorOrResult): void; + + /** + * Returns queue properties, including user-defined metadata. + * + * @function QueueService#getQueueMetadata + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the queue information. + * `response` will contain information related to this operation. + */ + getQueueMetadata(queue: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Returns queue properties, including user-defined metadata. + * + * @function QueueService#getQueueMetadata + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the queue information. + * `response` will contain information related to this operation. + */ + getQueueMetadata(queue: string, callback: ErrorOrResult): void; + + /** + * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. + * + * @function QueueService#setQueueMetadata + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} metadata The metadata key/value pairs. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the queue information. + * `response` will contain information related to this operation. + */ + setQueueMetadata(queue: string, metadata: { [key: string]: string; }, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. + * + * @function QueueService#setQueueMetadata + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} metadata The metadata key/value pairs. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the queue information. + * `response` will contain information related to this operation. + */ + setQueueMetadata(queue: string, metadata: { [key: string]: string; }, callback: ErrorOrResult): void; + + /** + * Adds a new message to the back of the message queue. + * The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size for previous versions. + * Unencoded messages must be in a format that can be included in an XML request with UTF-8 encoding. + * Queue messages are encoded by default. See queueService.messageEncoder to set encoding defaults. + * + * @function QueueService#createMessage + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {string|Buffer} messageText The message text. + * @param {Object} [options] The request options. + * @param {int} [options.messageTimeToLive] The time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter is omitted, the default time-to-live is 7 days + * @param {int} [options.visibilityTimeout] Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `[result]{@link QueueMessageResult}` will contain + * the message. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * queueService.createMessage('taskqueue', 'Hello world!', function(error) { + * if(!error) { + * // Message inserted + * } + * }); + */ + createMessage(queue: string, messageText: string|Buffer, options: QueueService.CreateMessageRequestOptions, callback?: ErrorOrResult): void; + + /** + * Adds a new message to the back of the message queue. + * The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size for previous versions. + * Unencoded messages must be in a format that can be included in an XML request with UTF-8 encoding. + * Queue messages are encoded by default. See queueService.messageEncoder to set encoding defaults. + * + * @function QueueService#createMessage + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {string|Buffer} messageText The message text. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * queueService.createMessage('taskqueue', 'Hello world!', function(error) { + * if(!error) { + * // Message inserted + * } + * }); + */ + createMessage(queue: string, messageText: string|Buffer, callback?: ErrorOrResult): void; + + /** + * Retrieves messages from the queue and makes them invisible to other consumers. + * + * @function QueueService#getMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {int} [options.numOfMessages] A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation. + * @param {int} [options.visibilityTimeout] Required if not peek only. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the messages. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * var queueName = 'taskqueue'; + * queueService.getMessages(queueName, function(error, serverMessages) { + * if(!error) { + * // Process the message in less than 30 seconds, the message + * // text is available in serverMessages[0].messagetext + * queueService.deleteMessage(queueName, serverMessages[0].messageId, serverMessages[0].popReceipt, function(error) { + * if(!error){ + * // Message deleted + * } + * }); + * } + * }); + */ + getMessages(queue: string, options: QueueService.GetMessagesRequestOptions, callback?: ErrorOrResult): void; + + /** + * Retrieves messages from the queue and makes them invisible to other consumers. + * + * @function QueueService#getMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the messages. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * var queueName = 'taskqueue'; + * queueService.getMessages(queueName, function(error, serverMessages) { + * if(!error) { + * // Process the message in less than 30 seconds, the message + * // text is available in serverMessages[0].messagetext + * queueService.deleteMessage(queueName, serverMessages[0].messageId, serverMessages[0].popReceipt, function(error) { + * if(!error){ + * // Message deleted + * } + * }); + * } + * }); + */ + getMessages(queue: string, callback?: ErrorOrResult): void; + + /** + * Retrieves a message from the queue and makes it invisible to other consumers. + * + * @function QueueService#getMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {int} [options.visibilityTimeout] Required if not peek only. Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the message. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * var queueName = 'taskqueue'; + * queueService.getMessage(queueName, function(error, serverMessage) { + * if(!error) { + * // Process the message in less than 30 seconds, the message + * // text is available in serverMessage.messagetext + * queueService.deleteMessage(queueName, serverMessage.messageId, serverMessage.popReceipt, function(error) { + * if(!error){ + * // Message deleted + * } + * }); + * } + * }); + */ + getMessage(queue: string, options: QueueService.GetMessageRequestOptions, callback?: ErrorOrResult): void; + + /** + * Retrieves a message from the queue and makes it invisible to other consumers. + * + * @function QueueService#getMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the message. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var queueService = azure.createQueueService(); + * var queueName = 'taskqueue'; + * queueService.getMessage(queueName, function(error, serverMessages) { + * if(!error) { + * // Process the message in less than 30 seconds, the message + * // text is available in serverMessages.messagetext + * queueService.deleteMessage(queueName, serverMessages.messageId, serverMessages.popReceipt, function(error) { + * if(!error){ + * // Message deleted + * } + * }); + * } + * }); + */ + getMessage(queue: string, callback?: ErrorOrResult): void; + + /** + * Retrieves messages from the front of the queue, without changing the messages visibility. + * + * @function QueueService#peekMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {int} [options.numOfMessages] A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the messages. + * `response` will contain information related to this operation. + */ + peekMessages(queue: string, options: QueueService.PeekMessagesRequestOptions, callback?: ErrorOrResult): void; + + /** + * Retrieves messages from the front of the queue, without changing the messages visibility. + * + * @function QueueService#peekMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the messages. + * `response` will contain information related to this operation. + */ + peekMessages(queue: string, callback?: ErrorOrResult): void; + + /** + * Retrieves a message from the front of the queue, without changing the message visibility. + * + * @function QueueService#peekMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the message. + * `response` will contain information related to this operation. + */ + peekMessage(queue: string, options: common.RequestOptions, callback?: ErrorOrResult): void; + + /** + * Retrieves a message from the front of the queue, without changing the message visibility. + * + * @function QueueService#peekMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the message. + * `response` will contain information related to this operation. + */ + peekMessage(queue: string, callback?: ErrorOrResult): void; + + /** + * Deletes a specified message from the queue. + * + * @function QueueService#deleteMessage + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {string} messageId The message identifier of the message to delete. + * @param {string} popReceipt A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteMessage(queue: string, messageId: string, popReceipt: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + + /** + * Deletes a specified message from the queue. + * + * @function QueueService#deleteMessage + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {string} messageId The message identifier of the message to delete. + * @param {string} popReceipt A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteMessage(queue: string, messageId: string, popReceipt: string, callback: ErrorOrResponse): void; + + /** + * Clears all messages from the queue. + * + * @function QueueService#clearMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + clearMessages(queue: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + + /** + * Clears all messages from the queue. + * + * @function QueueService#clearMessages + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + clearMessages(queue: string, callback: ErrorOrResponse): void; + + /** + * Updates the visibility timeout of a message. You can also use this operation to update the contents of a message. + * A message must be in a format that can be included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in size. + * + * @function QueueService#updateMessage + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {string} messageId The message identifier of the message to update. + * @param {string} popReceipt A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation + * @param {int} visibilityTimeout Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. + * @param {Object} [options] The request options. + * @param {Object} [options.messageText] The new message text. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the message result information. + * `response` will contain information related to this operation. + */ + updateMessage(queue: string, messageId: string, popReceipt: string, visibilityTimeout: number, options: QueueService.UpdateMessageRequestOptions, callback: ErrorOrResult): void; + + /** + * Updates the visibility timeout of a message. You can also use this operation to update the contents of a message. + * A message must be in a format that can be included in an XML request with UTF-8 encoding, and the encoded message can be up to 64KB in size. + * + * @function QueueService#updateMessage + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {string} messageId The message identifier of the message to update. + * @param {string} popReceipt A valid pop receipt value returned from an earlier call to the Get Messages or Update Message operation + * @param {int} visibilityTimeout Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or equal to 0, and cannot be larger than 7 days. The visibility timeout of a message can be set to a value later than the expiry time. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the message result information. + * `response` will contain information related to this operation. + */ + updateMessage(queue: string, messageId: string, popReceipt: string, visibilityTimeout: number, callback?: ErrorOrResult): void; + + /** + * Gets the queue's ACL. + * + * @function QueueService#getQueueAcl + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the queue. + * `response` will contain information related to this operation. + */ + getQueueAcl(queue: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Gets the queue's ACL. + * + * @function QueueService#getQueueAcl + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the queue. + * `response` will contain information related to this operation. + */ + getQueueAcl(queue: string, callback: ErrorOrResult): void; + + /** + * Updates the queue's ACL. + * + * @function QueueService#setQueueAcl + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the queue. + * `response` will contain information related to this operation. + * @example + * var azure = require('azure-storage'); + * var SharedAccessPermissions = azure.QueueUtilities.SharedAccessPermissions; + * var queueService = azure.createQueueService(); + * var sharedAccessPolicy = [ + * {AccessPolicy: { + * Permissions: PROCESS, + * Start: startDate, + * Expiry: expiryDate + * }, + * Id: processOnly, + * }, + * {AccessPolicy: { + * Permissions: SharedAccessPermissions.PROCESS + SharedAccessPermissions.DELETE, + * Start: startDate, + * Expiry: expiryDate + * }, + * Id: processAndDelete, + * }]; + * + * queueService.setQueueAcl(queueName, sharedAccessPolicy, function(error, queueResult, response) { + * // do whatever + * }); + */ + setQueueAcl(queue: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, options: common.RequestOptions, callback?: ErrorOrResult): void; + + /** + * Updates the queue's ACL. + * + * @function QueueService#setQueueAcl + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the queue. + * `response` will contain information related to this operation. + * @example + * var azure = require('azure-storage'); + * var SharedAccessPermissions = azure.QueueUtilities.SharedAccessPermissions; + * var queueService = azure.createQueueService(); + * var sharedAccessPolicy = [ + * {AccessPolicy: { + * Permissions: PROCESS, + * Start: startDate, + * Expiry: expiryDate + * }, + * Id: processOnly, + * }, + * {AccessPolicy: { + * Permissions: SharedAccessPermissions.PROCESS + SharedAccessPermissions.DELETE, + * Start: startDate, + * Expiry: expiryDate + * }, + * Id: processAndDelete, + * }]; + * + * queueService.setQueueAcl(queueName, sharedAccessPolicy, function(error, queueResult, response) { + * // do whatever + * }); + */ + setQueueAcl(queue: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, callback?: ErrorOrResult): void; + + /** + * Retrieves a shared access signature token. + * + * @function QueueService#generateSharedAccessSignature + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @return {string} The shared access signature query string. Note this string does not contain the leading "?". + */ + generateSharedAccessSignature(queue: string, sharedAccessPolicy: common.SharedAccessPolicy): string; + + /** + * Retrieves a shared access signature token. + * + * @function QueueService#generateSharedAccessSignatureWithVersion + * + * @this {QueueService} + * @param {string} queue The queue name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {string} [sasVersion] An optional string indicating the desired SAS version to use. Value must be 2012-02-12 or later. + * @return {string} The shared access signature query string. Note this string does not contain the leading "?". + */ + generateSharedAccessSignatureWithVersion(queue: string, sharedAccessPolicy: common.SharedAccessPolicy, sasVersion: string): string; + + getUrl(queue: string, sasToken?: string, primary?: boolean): string; + } + + module QueueService { + + export interface ListQueueResult { + entries: QueueResult[]; + continuationToken?: common.ContinuationToken; + } + + export interface QueueMessageResult { + queue?: string; + messageId?: string; + popReceipt?: string; + messageText?: string; + timeNextVisible?: string; + insertionTime?: string; + expirationTime?: string; + dequeueCount?: number; + } + + export interface QueueResult { + name: string; + metadata?: { [key: string]: string; }; + approximateMessageCount?: number; + signedIdentifiers: {[key:string]: common.AccessPolicy}; + exists?: boolean; + created?: boolean; + } + + export interface CreateQueueRequestOptions extends common.RequestOptions { + /** {Object} The metadata key/value pairs. */ + metadata?: { [key: string]: string; }; + } + + export interface ListQueuesRequestOptions extends common.RequestOptions { + /** {string} String value that identifies the portion of the list to be returned with the next list operation. */ + marker?: string; + /** {int} Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000) */ + maxResults?: number; + /** {string} Include this parameter to specify that the queue's metadata be returned as part of the response body. (allowed values: '', 'metadata') */ + include?: string; + } + + export interface PeekMessagesRequestOptions extends common.RequestOptions { + numOfMessages?: number; + } + + export interface GetMessagesRequestOptions extends common.RequestOptions { + numOfMessages?: number; + visibilityTimeout?: number; + } + + export interface GetMessageRequestOptions extends common.RequestOptions { + visibilityTimeout?: number; + } + + export interface UpdateMessageRequestOptions extends common.RequestOptions { + messageText?: string|Buffer; + } + + export interface CreateMessageRequestOptions extends common.RequestOptions { + /** + * {int} The time-to-live interval for the message, in seconds. The maximum time-to-live allowed is 7 days. If this parameter + * is omitted, the default time-to-live is 7 days + */ + messageTimeToLive?: number; + /** + * {int} Specifies the new visibility timeout value, in seconds, relative to server time. The new value must be larger than or + * equal to 0, and cannot be larger than 7 days. The visibility timeout of a message cannot be set to a value later than + * the expiry time. visibilitytimeout should be set to a value smaller than the time-to-live value. + */ + visibilityTimeout?: number; + } + } + + export interface QueueMessageEncoder { + encode(input: any) : string; + decode(textToBeDecoded: string) : any; + } + + module QueueMessageEncoder{ + export class TextBase64QueueMessageEncoder implements QueueMessageEncoder { + encode(input: string) : string; + decode(textToBeDecoded: string) : string; + } + + export class BinaryBase64QueueMessageEncoder implements QueueMessageEncoder { + encode(input: Buffer) : string; + decode(textToBeDecoded: string) : Buffer; + } + + export class TextXmlQueueMessageEncoder implements QueueMessageEncoder { + encode(input: string) : string; + decode(textToBeDecoded: string) : string; + } + } + + /** + * Defines enums for use with the Queue service. + * @namespace QueueUtilities + */ + var QueueUtilities: { + /** + * Permission types. + * + * @const + * @enum {string} + */ + SharedAccessPermissions: { + READ: string; + ADD: string; + UPDATE: string; + PROCESS: string; + }; + }; + } + + module table { + export interface TableService extends StorageServiceClient { + defaultPayloadFormat: string; + + /** + * Associate a filtering operation with this TableService. Filtering operations + * can include logging, automatically retrying, etc. Filter operations are objects + * that implement a method with the signature: + * + * "function handle (requestOptions, next)". + * + * After doing its preprocessing on the request options, the method needs to call + * "next" passing a callback with the following signature: + * signature: + * + * "function (returnObject, finalCallback, next)" + * + * In this callback, and after processing the returnObject (the response from the + * request to the server), the callback needs to either invoke next if it exists to + * continue processing other filters or simply invoke finalCallback otherwise to end + * up the service invocation. + * + * @function TableService#withFilter + * @param {Object} filter The new filter object. + * @return {TableService} A new service client with the filter applied. + */ + withFilter(newFilter: common.filters.IFilter): TableService; + + /** + * Gets the service stats for a storage account’s Table service. + * + * @this {TableService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the properties. + * `response` will contain information related to this operation. + */ + getServiceStats(options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Gets the service stats for a storage account’s Table service. + * + * @this {TableService} + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the properties. + * `response` will contain information related to this operation. + */ + getServiceStats(callback: ErrorOrResult): void; + + /** + * Gets the properties of a storage account’s Table service, including Azure Storage Analytics. + * + * @this {TableService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the properties. + * `response` will contain information related to this operation. + */ + getServiceProperties(options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Gets the properties of a storage account’s Table service, including Azure Storage Analytics. + * + * @this {TableService} + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the properties. + * `response` will contain information related to this operation. + */ + getServiceProperties(callback: ErrorOrResult): void; + + /** + * Sets the properties of a storage account’s Table service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + * + * @this {TableService} + * @param {Object} serviceProperties The service properties. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, options: common.RequestOptions, callback: ErrorOrResponse): void; + + /** + * Sets the properties of a storage account’s Table service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + * + * @this {TableService} + * @param {Object} serviceProperties The service properties. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, callback: ErrorOrResponse): void; + + /** + * Lists a segment containing a collection of table items under the specified account. + * + * @this {TableService} + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The create options or callback function. + * @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of tables and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listTablesSegmented(currentToken: TableService.ListTablesContinuationToken, options: TableService.ListTablesRequestOptions, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of table items under the specified account. + * + * @this {TableService} + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of tables and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listTablesSegmented(currentToken: TableService.ListTablesContinuationToken, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of table items under the specified account. + * + * @this {TableService} + * @param {string} prefix The prefix of the table name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The create options or callback function. + * @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of tables and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listTablesSegmentedWithPrefix(prefix: string, currentToken: TableService.ListTablesContinuationToken, options: TableService.ListTablesRequestOptions, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of table items under the specified account. + * + * @this {TableService} + * @param {string} prefix The prefix of the table name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of tables and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listTablesSegmentedWithPrefix(prefix: string, currentToken: TableService.ListTablesContinuationToken, callback: ErrorOrResult): void; + + /** + * Gets the table's ACL. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the ACL information for the table. + * `response` will contain information related to this operation. + */ + getTableAcl(table: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Gets the table's ACL. + * + * @this {TableService} + * @param {string} table The table name. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the ACL information for the table. + * `response` will contain information related to this operation. + */ + getTableAcl(table: string, callback: ErrorOrResult): void; + + /** + * Updates the table's ACL. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain information for the table. + * `response` will contain information related to this operation. + */ + setTableAcl(table: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, options: common.RequestOptions, callback: ErrorOrResult<{ + TableName: string; + signedIdentifiers: {[key:string]: common.AccessPolicy}; + }>): void; + + /** + * Updates the table's ACL. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain information for the table. + * `response` will contain information related to this operation. + */ + setTableAcl(table: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, callback: ErrorOrResult<{ + TableName: string; + signedIdentifiers: {[key:string]: common.AccessPolicy}; + }>): void; + + /** + * Retrieves a shared access signature token. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {string} [sharedAccessPolicy.AccessPolicy.StartPk] The starting Partition Key for which the SAS will be valid. + * @param {string} [sharedAccessPolicy.AccessPolicy.EndPk] The ending Partition Key for which the SAS will be valid. + * @param {string} [sharedAccessPolicy.AccessPolicy.StartRk] The starting Row Key for which the SAS will be valid. + * @param {string} [sharedAccessPolicy.AccessPolicy.EndRk] The ending Row Key for which the SAS will be valid. + * @return {Object} An object with the shared access signature. + */ + generateSharedAccessSignature(table: string, sharedAccessPolicy: TableService.TableSharedAccessPolicy): string; + + /** + * Retrieves a shared access signature token. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {string} [sharedAccessPolicy.AccessPolicy.StartPk] The starting Partition Key for which the SAS will be valid. + * @param {string} [sharedAccessPolicy.AccessPolicy.EndPk] The ending Partition Key for which the SAS will be valid. + * @param {string} [sharedAccessPolicy.AccessPolicy.StartRk] The starting Row Key for which the SAS will be valid. + * @param {string} [sharedAccessPolicy.AccessPolicy.EndRk] The ending Row Key for which the SAS will be valid. + * @param {string} [sasVersion] An optional string indicating the desired SAS version to use. Value must be 2012-02-12 or later. + * @return {Object} An object with the shared access signature. + */ + generateSharedAccessSignatureWithVersion(table: string, sharedAccessPolicy: TableService.TableSharedAccessPolicy, sasVersion: string): string; + + /** + * Checks whether or not a table exists on the service. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain be true if the table exists, or false if the table does not exist. + * `response` will contain information related to this operation. + */ + doesTableExist(table: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Checks whether or not a table exists on the service. + * + * @this {TableService} + * @param {string} table The table name. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain be true if the table exists, or false if the table does not exist. + * `response` will contain information related to this operation. + */ + doesTableExist(table: string, callback: ErrorOrResult): void; + + /** + * Creates a new table within a storage account. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the new table information. + * `response` will contain information related to this operation. + */ + createTable(table: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Creates a new table within a storage account. + * + * @this {TableService} + * @param {string} table The table name. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the new table information. + * `response` will contain information related to this operation. + */ + createTable(table: string, callback: ErrorOrResult): void; + + /** + * Creates a new table within a storage account if it does not exists. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * `result` will be `true` if table was created, false otherwise + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var tableService = azure.createTableService(); + * tableService.createTableIfNotExists('tasktable', function(error) { + * if(!error) { + * // Table created or exists + * } + * }); + */ + createTableIfNotExists(table: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Creates a new table within a storage account if it does not exists. + * + * @this {TableService} + * @param {string} table The table name. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * `result` will be `true` if table was created, false otherwise + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var tableService = azure.createTableService(); + * tableService.createTableIfNotExists('tasktable', function(error) { + * if(!error) { + * // Table created or exists + * } + * }); + */ + createTableIfNotExists(table: string, callback: ErrorOrResult): void; + + /** + * Deletes a table from a storage account. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteTable(table: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + + /** + * Deletes a table from a storage account. + * + * @this {TableService} + * @param {string} table The table name. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteTable(table: string, callback: ErrorOrResponse): void; + + /** + * Deletes a table from a storage account, if it exists. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * `result` will be `true` if table was deleted, false otherwise + * `response` will contain information related to this operation. + */ + deleteTableIfExists(table: string, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Deletes a table from a storage account, if it exists. + * + * @this {TableService} + * @param {string} table The table name. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * `result` will be `true` if table was deleted, false otherwise + * `response` will contain information related to this operation. + */ + deleteTableIfExists(table: string, callback: ErrorOrResult): void; + + /** + * Queries data in a table. To retrieve a single entity by partition key and row key, use retrieve entity. + * + * @this {TableService} + * @param {string} table The table name. + * @param {TableQuery} tableQuery The query to perform. Use null, undefined, or new TableQuery() to get all of the entities in the table. + * @param {Object} currentToken A continuation token returned by a previous listing operation. + * Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {bool} [options.autoResolveProperties] If true, guess at all property types. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {Function(entity)} [options.entityResolver] The entity resolver. Given a single entity returned by the query, returns a modified object which is added to + * the entities array. + * @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, + * and the property Edm type if given by the service, returns the Edm type of the property. + * @param {TableService~queryResponse} callback `error` will contain information if an error occurs; + * otherwise `entities` will contain the entities returned by the query. + * If more matching entities exist, and could not be returned, + * `queryResultContinuation` will contain a continuation token that can be used + * to retrieve the next set of results. + * `response` will contain information related to this operation. + * + * The logic for returning entity types can get complicated. Here is the algorithm used: + * ``` + * var propertyType; + * + * if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it + * propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService); + * } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur. + * propertyType = propertyTypeFromService; + * } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true + * if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does. + * propertyType = 'Edm.String'; + * } else if (javascript type is boolean) { + * propertyType = 'Edm.Boolean'; + * } + * } + * + * if (propertyType) { + * // Set the property type on the property. + * } else { + * // Property gets no EdmType. + * } + * ``` + * Notes: + * + * * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime. + * * Explanation of autoResolveProperties: + * * String gets correctly resolved to 'Edm.String'. + * * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step). + * * Boolean gets correctly resolved to 'Edm.Boolean'. + * * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an + * inability to distinguish between the two in certain cases. + * + * @example + * var azure = require('azure-storage'); + * var tableService = azure.createTableService(); + * // tasktable should already exist and have entities + * + * // returns all entities in tasktable, and a continuation token for the next page of results if necessary + * tableService.queryEntities('tasktable', null, null \/*currentToken*\/, function(error, result) { + * if(!error) { + * var entities = result.entities; + * // do stuff with the returned entities if there are any + * } + * }); + * + * // returns field1 and field2 of the entities in tasktable, and a continuation token for the next page of results if necessary + * var tableQuery = new TableQuery().select('field1', 'field2'); + * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) { + * if(!error) { + * var entities = result.entities; + * // do stuff with the returned entities if there are any + * } + * }); + */ + queryEntities(table: string, tableQuery: TableQuery, currentToken: TableService.TableContinuationToken, options: TableService.TableEntityRequestOptions, callback: ErrorOrResult>): void; + + /** + * Queries data in a table. To retrieve a single entity by partition key and row key, use retrieve entity. + * + * @this {TableService} + * @param {string} table The table name. + * @param {TableQuery} tableQuery The query to perform. Use null, undefined, or new TableQuery() to get all of the entities in the table. + * @param {Object} currentToken A continuation token returned by a previous listing operation. + * Please use 'null' or 'undefined' if this is the first operation. + * @param {TableService~queryResponse} callback `error` will contain information if an error occurs; + * otherwise `entities` will contain the entities returned by the query. + * If more matching entities exist, and could not be returned, + * `queryResultContinuation` will contain a continuation token that can be used + * to retrieve the next set of results. + * `response` will contain information related to this operation. + */ + queryEntities(table: string, tableQuery: TableQuery, currentToken: TableService.TableContinuationToken, callback: ErrorOrResult>): void; + + /** + * Retrieves an entity from a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {string} partitionKey The partition key. + * @param {string} rowKey The row key. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {bool} [options.autoResolveProperties] If true, guess at all property types. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, + * and the property Edm type if given by the service, returns the Edm type of the property. + * @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will be the matching entity. + * `response` will contain information related to this operation. + * + * The logic for returning entity types can get complicated. Here is the algorithm used: + * ``` + * var propertyType; + * + * if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it + * propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService); + * } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur. + * propertyType = propertyTypeFromService; + * } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true + * if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does. + * propertyType = 'Edm.String'; + * } else if (javascript type is boolean) { + * propertyType = 'Edm.Boolean'; + * } + * } + * + * if (propertyType) { + * // Set the property type on the property. + * } else { + * // Property gets no EdmType. + * } + * ``` + * Notes: + * + * * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime. + * * Explanation of autoResolveProperties: + * * String gets correctly resolved to 'Edm.String'. + * * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step). + * * Boolean gets correctly resolved to 'Edm.Boolean'. + * * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an + * inability to distinguish between the two in certain cases. + * + * @example + * var azure = require('azure-storage'); + * var tableService = azure.createTableService(); + * tableService.retrieveEntity('tasktable', 'tasksSeattle', '1', function(error, serverEntity) { + * if(!error) { + * // Entity available in serverEntity variable + * } + * }); + */ + retrieveEntity(table: string, partitionKey: string, rowKey: string, options: TableService.TableEntityRequestOptions, callback: ErrorOrResult): void; + + /** + * Retrieves an entity from a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {string} partitionKey The partition key. + * @param {string} rowKey The row key. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {bool} [options.autoResolveProperties] If true, guess at all property types. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, + * and the property Edm type if given by the service, returns the Edm type of the property. + * @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will be the matching entity. + * `response` will contain information related to this operation. + */ + retrieveEntity(table: string, partitionKey: string, rowKey: string, callback: ErrorOrResult): void; + + /** + * Inserts a new entity into a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {bool} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false. + * @param {string} [options.payloadFormat] The payload format to use in the response, if options.echoContent is true. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name, + * property value, and the property Edm type if given by the service, returns the Edm type of the property. + * @param {Function(entity)} [options.entityResolver] The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns + * a modified object. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var tableService = azure.createTableService(); + * var task1 = { + * PartitionKey : {'_': 'tasksSeattle', '$':'Edm.String'}, + * RowKey: {'_': '1', '$':'Edm.String'}, + * Description: {'_': 'Take out the trash', '$':'Edm.String'}, + * DueDate: {'_': new Date(2011, 12, 14, 12), '$':'Edm.DateTime'} + * }; + * tableService.insertEntity('tasktable', task1, function(error) { + * if(!error) { + * // Entity inserted + * } + * }); + */ + insertEntity(table: string, entityDescriptor: T, options: TableService.InsertEntityRequestOptions, callback: ErrorOrResult): void; + + /** + * Inserts a new entity into a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + insertEntity(table: string, entityDescriptor: T, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Inserts a new entity into a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + insertEntity(table: string, entityDescriptor: T, callback: ErrorOrResult): void; + + /** + * Inserts or updates a new entity into a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + insertOrReplaceEntity(table: string, entityDescriptor: T, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Inserts or updates a new entity into a table. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + insertOrReplaceEntity(table: string, entityDescriptor: T, callback: ErrorOrResult): void; + + /** + * Replaces an existing entity within a table. To replace conditionally based on etag, set entity['.metadata']['etag']. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + replaceEntity(table: string, entityDescriptor: T, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Replaces an existing entity within a table. To replace conditionally based on etag, set entity['.metadata']['etag']. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + replaceEntity(table: string, entityDescriptor: T, callback: ErrorOrResult): void; + + /** + * Updates an existing entity within a table by merging new property values into the entity. To merge conditionally based on etag, set entity['.metadata']['etag']. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * response` will contain information related to this operation. + */ + mergeEntity(table: string, entityDescriptor: T, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Updates an existing entity within a table by merging new property values into the entity. To merge conditionally based on etag, set entity['.metadata']['etag']. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * response` will contain information related to this operation. + */ + mergeEntity(table: string, entityDescriptor: T, callback: ErrorOrResult): void; + + /** + * Inserts or updates an existing entity within a table by merging new property values into the entity. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + insertOrMergeEntity(table: string, entityDescriptor: T, options: common.RequestOptions, callback: ErrorOrResult): void; + + /** + * Inserts or updates an existing entity within a table by merging new property values into the entity. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the entity information. + * `response` will contain information related to this operation. + */ + insertOrMergeEntity(table: string, entityDescriptor: T, callback: ErrorOrResult): void; + + /** + * Deletes an entity within a table. To delete conditionally based on etag, set entity['.metadata']['etag']. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteEntity(table: string, entityDescriptor: T, options: common.RequestOptions, callback: ErrorOrResponse): void; + + /** + * Deletes an entity within a table. To delete conditionally based on etag, set entity['.metadata']['etag']. + * + * @this {TableService} + * @param {string} table The table name. + * @param {Object} entityDescriptor The entity descriptor. + * @param {errorOrResponse} callback `error` will contain information if an error occurs; + * `response` will contain information related to this operation. + */ + deleteEntity(table: string, entityDescriptor: T, callback: ErrorOrResponse): void; + + /** + * Executes the operations in the batch. + * + * @this {TableService} + * @param {string} table The table name. + * @param {TableBatch} batch The table batch to execute. + * @param {Object} [options] The create options or callback function. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain responses for each operation executed in the batch; + * `result.entity` will contain the entity information for each operation executed. + * `result.response` will contain the response for each operations executed. + * `response` will contain information related to this operation. + */ + executeBatch(table: string, batch: TableBatch, options: TableService.TableEntityRequestOptions, callback: ErrorOrResult): void; + + /** + * Executes the operations in the batch. + * + * @this {TableService} + * @param {string} table The table name. + * @param {TableBatch} batch The table batch to execute. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain responses for each operation executed in the batch; + * `result.entity` will contain the entity information for each operation executed. + * `result.response` will contain the response for each operations executed. + * `response` will contain information related to this operation. + */ + executeBatch(table: string, batch: TableBatch, callback: ErrorOrResult): void; + + getUrl(table: string, sasToken?: string, primary?: boolean): string; + } + + export module TableService { + + export interface TableResult { + isSuccessful?: boolean; + statusCode?: string | number; + TableName?: string; + exists?: boolean; + created?: boolean; + } + + export interface TableAccessPolicy extends common.AccessPolicy { + StartPk?: string; + EndPk?: string; + StartRk?: string; + EndRk?: string; + } + + export interface TableSharedAccessPolicy { + /** The signed identifier. */ + Id?: string; + /** The Table Access Policy information */ + AccessPolicy: TableAccessPolicy; + } + + export interface ListTablesRequestOptions extends common.RequestOptions { + maxResults?: number; + payloadFormat?: string; + } + + export interface ListTablesContinuationToken { + nextTableName: string; + targetLocation?: Constants.StorageLocation; + } + + export interface ListTablesResponse { + continuationToken: ListTablesContinuationToken; + entries: string[]; + } + + export interface TableContinuationToken { + nextPartitionKey: string; + nextRowKey: string; + targetLocation: Constants.StorageLocation; + } + + export interface GetTableAclResult { + signedIdentifiers: {[key:string]: common.AccessPolicy}; + } + + export interface QueryEntitiesResult { + entries: T[]; + continuationToken?: TableContinuationToken; + } + + export interface EntityMetadata { + '.metadata': { etag: string; } + } + + export interface PropertyResolver { + (partitionKey: string, rowKey: string, propertyName: string, propertyValue: Object, entityPropertyType: string): string; + } + + export interface TableEntityRequestOptions extends common.RequestOptions { + payloadFormat?: string; + autoResolveProperties?: boolean; + propertyResolver?: PropertyResolver; + entityResolver?: (entityResult: Object) => Object; + echoContent?: boolean; + } + + export interface InsertEntityRequestOptions extends TableEntityRequestOptions { + echoContent: boolean; + } + + export interface BatchResponse { + statusCode?: number; + headers?: Object; + body?: Object; + isSuccessful?: boolean; + } + + export interface BatchResult { + entity?: Object; + error?: Error; + response: BatchResponse; + } + + export interface EntityProperty { + _: T; + $: string; + } + } + + export var TableService: { + /** + * Creates a new TableService object. + * If no connection string or storageaccount and storageaccesskey are provided, + * the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. + * @class + * The TableService object allows you to peform management operations with the Microsoft Azure Table Service. + * The Table Service stores data in rows of key-value pairs. A table is composed of multiple rows, and each row + * contains key-value pairs. There is no schema, so each row in a table may store a different set of keys. + * + * For more information on the Table Service, as well as task focused information on using it from a Node.js application, see + * [How to Use the Table Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-table-storage/). + * The following defaults can be set on the Table service. + * defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Table service. + * defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Table service. + * defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Table service. + * defaultLocationMode The default location mode for requests made via the Table service. + * defaultPayloadFormat The default payload format for requests made via the Table service. + * useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Table service.; true to use the + * Nagle algorithm; otherwise, false. The default value is false. + * @constructor + * @extends {StorageServiceClient} + * + * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} [sasToken] The Shared Access Signature token. + * @param {string} [endpointSuffix] The endpoint suffix. + */ + new (storageAccountOrConnectionString?: string, storageAccessKey?: string, host?: string|StorageHost, sasToken?: string, endpointSuffix?: string): TableService; + } + + export module TableUtilities { + /** + * Permission types. + * + * @const + * @enum {string} + */ + var SharedAccessPermissions: { + QUERY: string; + ADD: string; + UPDATE: string; + DELETE: string; + }; + + /** + * Payload Format. + * + * @const + * @enum {string} + */ + var PayloadFormat: { + FULL_METADATA: string; + MINIMAL_METADATA: string; + NO_METADATA: string; + }; + + /** + * Defines the set of Boolean operators for constructing queries. + * + * @const + * @enum {string} + */ + var TableOperators: { + AND: string; + NOT: string; + OR: string; + }; + + /** + * Filter property comparison operators. + * + * @const + * @enum {string} + */ + var QueryComparisons: { + EQUAL: string; + NOT_EQUAL: string; + GREATER_THAN: string; + GREATER_THAN_OR_EQUAL: string; + LESS_THAN: string; + LESS_THAN_OR_EQUAL: string; + }; + + /** + * Edm types. + * + * @const + * @enum {string} + */ + var EdmType: { + STRING: string; + BINARY: string; + INT64: string; + INT32: string; + DOUBLE: string; + DATETIME: string; + GUID: string; + BOOLEAN: string; + }; + + /** + * A helper to create table entities. + * + * @example + * var entGen = TableUtilities.entityGenerator; + * var entity = { PartitionKey: entGen.String('part2'), + * RowKey: entGen.String('row1'), + * boolValue: entGen.Boolean(true), + * intValue: entGen.Int32(42), + * dateValue: entGen.DateTime(new Date(Date.UTC(2011, 10, 25))), + * }; + */ + module entityGenerator { + class EntityProperty { + _: T; + $: string; + constructor(value: T, type?: string); + } + function Int32(value: number|string): EntityProperty; + function Int64(value: number|string): EntityProperty; + function Binary(value: Buffer|string): EntityProperty; + function Boolean(value: boolean|string): EntityProperty; + function String(value: string): EntityProperty; + function Guid(value: string|Buffer|any): EntityProperty; + function Double(value: number|string): EntityProperty; + function DateTime(value: Date|string): EntityProperty; + } + } + + export interface TableQuery { + /** + * Specifies the select clause. If no arguments are given, all fields will be selected. + * + * @param {array} fields The fields to be selected. + * @return {TableQuery} A table query object with the select clause. + * @example + * var tableQuery = new TableQuery().select('field1', 'field2'); + */ + select(...args: string[]): TableQuery; + select(args: string[]): TableQuery; + + /** + * Specifies the top clause. + * + * @param {int} top The number of items to fetch. + * @return {TableQuery} A table query object with the top clause. + * @example + * var tableQuery = new TableQuery().top(10); + * + * // tasktable should already exist and have entities + * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) { + * if(!error) { + * var entities = result.entities; // there will be 10 or less entities + * // do stuff with the returned entities if there are any + * // if result.continuationToken exists, to get the next 10 (or less) entities + * // call queryEntities as above, but with the returned token instead of null + * } + * }); + */ + top(top: number): TableQuery; + + /** + * Specifies the where clause. + * + * Valid type specifier strings include: ?string?, ?bool?, ?int32?, ?double?, ?date?, ?guid?, ?int64?, ?binary? + * A type must be specified for guid, int64, and binaries or the filter produced will be incorrect. + * + * @param {string} condition The condition string. + * @param {string|array} value Value(s) to insert in question mark (?) parameters. + * @return {TableQuery} A table query object with the where clause. + * @example + * var tableQuery = new TableQuery().where(TableQuery.guidFilter('GuidField', QueryComparisons.EQUAL, guidVal)); + * OR + * var tableQuery = new TableQuery().where('Name == ? or Name <= ?', name1, name2); + * OR + * var tableQuery = new TableQuery().where('Name == ?string? && Value == ?int64?, name1, int64Val); + * + * // tasktable should already exist and have entities + * tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result, response) { + * if(!error) { + * var entities = result.entities; + * // do stuff with the returned entities if there are any + * } + * }); + */ + where(condition: string, ...args: any[]): TableQuery; + + /** + * Specifies an AND where condition. + * + * @param {string} condition The condition string. + * @param {array} arguments Any number of arguments to be replaced in the condition by the question mark (?). + * @return {TableQuery} A table query object with the and clause. + * @example + * var tableQuery = new TableQuery() + * .where('Name == ? or Name <= ?', 'Person1', 'Person2'); + * .and('Age >= ?', 18); + */ + and(condition: string, ...args: any[]): TableQuery; + + /** + * Specifies an OR where condition. + * + * @param {string} condition The condition. + * @param {array} arguments Any number of arguments to be replaced in the condition by the question mark (?). + * @return {TableQuery} A table query object with the or clause. + * @example + * var tableQuery = new TableQuery() + * .where('Name == ? or Name <= ?', 'Person1', 'Person2'); + * .or('Age >= ?', 18); + */ + or(condition: string, ...args: any[]): TableQuery; + + /** + * Returns the query string object for the query. + * + * @return {Object} JSON object representing the query string arguments for the query. + */ + toQueryObject(): Object; + } + + export var TableQuery: { + new(): TableQuery; + + /** + * Generates a property filter condition string for an 'int' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|int} value An 'int' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.int32Filter('IntField', QueryComparisons.EQUAL, 5); + */ + int32Filter(propertyName: string, operation: string, value: string | number): string; + + /** + * Generates a property filter condition string for a 'int64' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|int64} value An 'int64' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.int64Filter('Int64Field', QueryComparisons.EQUAL, 123); + */ + int64Filter(propertyName: string, operation: string, value: string | number): string; + + /** + * Generates a property filter condition string for a 'double' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|double}value A 'double' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.doubleFilter('DoubleField', QueryComparisons.EQUAL, 123.45); + */ + doubleFilter(propertyName: string, operation: string, value: string | number): string; + + /** + * Generates a property filter condition string for a 'boolean' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|boolean} value A 'boolean' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.booleanFilter('BooleanField', QueryComparisons.EQUAL, false); + */ + booleanFilter(propertyName: string, operation: string, value: boolean | string): string; + + /** + * Generates a property filter condition string for a 'datetime' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|date} value A 'datetime' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.dateFilter('DateTimeField', QueryComparisons.EQUAL, new Date(Date.UTC(2001, 1, 3, 4, 5, 6))); + */ + dateFilter(propertyName: string, operation: string, value: Date | string): string; + + /** + * Generates a property filter condition string for a 'guid' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|guid} value A 'guid' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.guidFilter('GuidField', QueryComparisons.EQUAL, guid.v1()); + */ + guidFilter(propertyName: string, operation: string, value: string | any): string; + + /** + * Generates a property filter condition string for a 'binary' value. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string|buffer}value A 'buffer' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.binaryFilter('BinaryField', QueryComparisons.EQUAL, new Buffer('hello')); + */ + binaryFilter(propertyName: string, operation: string, value: Buffer | string): string; + + /** + * Generates a property filter condition string. + * + * @param {string} propertyName A string containing the name of the property to compare. + * @param {string} operation A string containing the comparison operator to use. + * See Constants.TableConstants.QueryComparisons for a list of allowed operations. + * @param {string} value A 'string' containing the value to compare with the property. + * @return {string} A string containing the formatted filter condition. + * @example + * var query = TableQuery.stringFilter('StringField', QueryComparisons.EQUAL, 'name'); + */ + stringFilter(propertyName: string, operation: string, value: string): string; + + /** + * Creates a filter condition using the specified logical operator on two filter conditions. + * + * @param {string} filterA A string containing the first formatted filter condition. + * @param {string} operatorString A string containing the operator to use (AND, OR). + * @param {string} filterB A string containing the second formatted filter condition. + * @return {string} A string containing the combined filter expression. + * @example + * var filter1 = TableQuery.stringFilter('Name', QueryComparisons.EQUAL, 'Person'); + * var filter2 = TableQuery.booleanFilter('Visible', QueryComparisons.EQUAL, true); + * var combinedFilter = TableQuery.combineFilters(filter1, TablUtilities.TableOperators.AND, filter2); + */ + combineFilters(filterA: string, operatorString: string, filterB: string): string; + }; + + export interface TableOperation{ + type: string; + entity: Object; + options: common.RequestOptions; + } + + export interface TableBatch { + operations: TableOperation[]; + pk: string; + retrieve: boolean; + + /** + * Removes all of the operations from the batch. + * + */ + clear(): void; + + /** + * Returns a boolean value indicating weather there are operations in the batch. + * + * @return {Boolean} True if there are operations queued up; false otherwise. + */ + hasOperations(): boolean; + + /** + * Returns the number of operations in the batch. + * + * @return {number} The number of operations in the batch. + */ + size(): number; + + /** + * Adds a retrieve operation to the batch. Note that this must be the only operation in the batch. + * + * @param {string} partitionKey The partition key. + * @param {string} rowKey The row key. + * @param {Object} [options] The request options. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value, + * and the property Edm type if given by the service, returns the Edm type of the property. + * @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object. + */ + retrieveEntity(partitionKey: string, rowKey: string, options?: TableService.TableEntityRequestOptions): void; + + /** + * Adds an insert operation to the batch. + * + * @param {Object} entity The entity. + * @param {Object} [options] The request options. + * @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Inserts only, default to false. + * @param {string} [options.payloadFormat] The payload format to use for the request. + * @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name, + * property value, and the property Edm type if given by the service, returns the Edm type of the property. + * @param {Function(entity)} [options.entityResolver] The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns + * a modified object. + */ + insertEntity(entity: Object, options: TableService.TableEntityRequestOptions): void; + + /** + * Adds a delete operation to the batch. + * + * @param {Object} entity The entity. + */ + deleteEntity(entity: Object): void; + + /** + * Adds a merge operation to the batch. + * + * @param {Object} entity The entity. + */ + mergeEntity(entity: Object): void; + + /** + * Adds an replace operation to the batch. + * + * @param {Object} entity The entity. + */ + replaceEntity(entity: Object): void; + + /** + * Adds an insert or replace operation to the batch. + * + * @param {Object} entity The entity. + */ + insertOrReplaceEntity(entity: Object): void; + + /** + * Adds an insert or merge operation to the batch. + * + * @param {Object} entity The entity. + */ + insertOrMergeEntity(entity: Object): void; + + /** + * Adds an operation to the batch after performing checks. + * + * @param {string} operationType The type of operation to perform. See Constants.TableConstants.Operations + * @param {Object} entity The entity. + * @param {Object} [options] The request options. + */ + addOperation(operationType: string, entity: Object, options?: TableService.TableEntityRequestOptions): void; + + /** + * Gets an operation from the batch. Returns null if the index does not exist. + * + * @param {number} index The index in the operations array at which to remove an element. + * @return {Object} The removed operation. + */ + getOperation(index: number): TableOperation; + + /** + * Removes an operation from the batch. Returns null if the index does not exist. + * + * @param {number} index The index in the operations array at which to remove an element. + * @return {Object} The removed operation. + */ + removeOperation(index: number): Object; + } + + export var TableBatch: { + new (): TableBatch; + }; + } + + module file { + export interface FileService extends StorageServiceClient { + defaultEnableReuseSocket: boolean; + singleFileThresholdInBytes: number; + parallelOperationThreadCount: number; + + /** + * Associate a filtering operation with this FileService. Filtering operations + * can include logging, automatically retrying, etc. Filter operations are objects + * that implement a method with the signature: + * + * "function handle (requestOptions, next)". + * + * After doing its preprocessing on the request options, the method needs to call + * "next" passing a callback with the following signature: + * signature: + * + * "function (returnObject, finalCallback, next)" + * + * In this callback, and after processing the returnObject (the response from the + * request to the server), the callback needs to either invoke next if it exists to + * continue processing other filters or simply invoke finalCallback otherwise to end + * up the service invocation. + * + * @function FileService#withFilter + * @param {Object} filter The new filter object. + * @return {FileService} A new service client with the filter applied. + */ + withFilter(newFilter: common.filters.IFilter): FileService; + + /** + * Gets the properties of a storage account's File service, including Azure Storage Analytics. + * + * @this {FileService} + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the properties + * and `response` will contain information related to this operation. + */ + getServiceProperties(options: common.RequestOptions, callback: ErrorOrResult): void; + getServiceProperties(callback: ErrorOrResult): void; + + /** + * Sets the properties of a storage account's File service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + * + * @this {FileService} + * @param {Object} serviceProperties The service properties. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise, `response` + * will contain information related to this operation. + */ + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, options: common.RequestOptions, callback: ErrorOrResponse): void; + setServiceProperties(serviceProperties: common.models.ServicePropertiesResult.ServiceProperties, callback: ErrorOrResponse): void; + + /** + * Lists a segment containing a collection of share items under the specified account. + * + * @this {FileService} + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.maxResults] Specifies the maximum number of shares to return per call to Azure storage. + * @param {string} [options.include] Include this parameter to specify that the share's metadata be returned as part of the response body. (allowed values: '', 'metadata', 'snapshots' or any combination of them) + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of shares and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listSharesSegmented(currentToken: common.ContinuationToken, options: FileService.ListShareRequestOptions, callback: ErrorOrResult): void; + listSharesSegmented(currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of share items whose names begin with the specified prefix under the specified account. + * + * @this {FileService} + * @param {string} prefix The prefix of the share name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {string} [options.prefix] Filters the results to return only shares whose name begins with the specified prefix. + * @param {int} [options.maxResults] Specifies the maximum number of shares to return per call to Azure storage. + * @param {string} [options.include] Include this parameter to specify that the share's metadata be returned as part of the response body. (allowed values: '', 'metadata', 'snapshots' or any combination of them) + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain `entries` and `continuationToken`. + * `entries` gives a list of shares and the `continuationToken` is used for the next listing operation. + * `response` will contain information related to this operation. + */ + listSharesSegmentedWithPrefix(prefix: string, currentToken: common.ContinuationToken, options: FileService.ListShareRequestOptions, callback: ErrorOrResult): void; + listSharesSegmentedWithPrefix(prefix: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Checks whether or not a share exists on the service. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the share exists, or false if the share does not exist. + * `response` will contain information related to this operation. + */ + doesShareExist(share: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + doesShareExist(share: string, callback: ErrorOrResult): void; + + /** + * Creates a new share under the specified account. + * If a share with the same name already exists, the operation fails. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {int} [options.quota] Specifies the maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB (5120). + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the share information. + * `response` will contain information related to this operation. + */ + createShare(share: string, options: FileService.CreateShareRequestOptions, callback: ErrorOrResult): void; + createShare(share: string, callback: ErrorOrResult): void; + + createShareSnapshot(share: string, options: common.RequestOptions, callback: ErrorOrResult): void; + createShareSnapshot(share: string, callback: ErrorOrResult): void; + + /** + * Creates a new share under the specified account if the share does not exists. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {int} [options.quota] Specifies the maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5TB (5120). + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the share was created, or false if the share + * already exists. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * FileService.createShareIfNotExists('taskshare', function(error) { + * if(!error) { + * // Share created or already existed + * } + * }); + */ + createShareIfNotExists(share: string, options: FileService.CreateShareRequestOptions, callback: ErrorOrResult): void; + createShareIfNotExists(share: string, callback: ErrorOrResult): void; + + /** + * Retrieves a share and its properties from a specified account. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the share. + * `response` will contain information related to this operation. + */ + getShareProperties(share: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + getShareProperties(share: string, callback: ErrorOrResult): void; + + /** + * Sets the properties for the specified share. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [properties] The share properties to set. + * @param {string|int} [properties.quota] Specifies the maximum size of the share, in gigabytes. + * @param {Object} [options] The request options. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the share. + * `response` will contain information related to this operation. + */ + setShareProperties(share: string, properties: FileService.ShareProperties, options: common.RequestOptions, callback: ErrorOrResult): void; + setShareProperties(share: string, properties: FileService.ShareProperties, callback: ErrorOrResult): void; + + /** + * Gets the share statistics for a share. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; otherwise, `result` will contain the stats and + * `response` will contain information related to this operation. + */ + getShareStats(share: string, options: common.RequestOptions, callback: ErrorOrResult): void; + getShareStats(share: string, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata for the share. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the share. + * `response` will contain information related to this operation. + */ + getShareMetadata(share: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + getShareMetadata(share: string, callback: ErrorOrResult): void; + + /** + * Sets the share's metadata. + * + * Calling the Set Share Metadata operation overwrites all existing metadata that is associated with the share. + * It's not possible to modify an individual name/value pair. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} metadata The metadata key/value pairs. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + setShareMetadata(share: string, metadata: Map, options: common.RequestOptions, callback: ErrorOrResult): void; + setShareMetadata(share: string, metadata: Map, callback: ErrorOrResult): void; + + /** + * Gets the share's ACL. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.FileUtilities.ShareSnapshotDeleteOptions.*. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the share. + * `response` will contain information related to this operation. + */ + getShareAcl(share: string, options: common.RequestOptions, callback: ErrorOrResult): void; + getShareAcl(share: string, callback: ErrorOrResult): void; + + /** + * Updates the share's ACL. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} signedIdentifiers The signed identifiers. Signed identifiers must be in an array. + * @param {Object} [options] The request options. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the share. + * `response` will contain information related to this operation. + */ + setShareAcl(share: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, options: common.RequestOptions, callback: ErrorOrResult): void; + setShareAcl(share: string, signedIdentifiers: {[key:string]: common.AccessPolicy}, callback: ErrorOrResult): void; + + /** + * Marks the specified share for deletion. + * The share and any files contained within it are later deleted during garbage collection. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {string} [options.deleteSnapshots] The snapshot delete option. See azure.FileUtilities.ShareSnapshotDeleteOptions.*. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + deleteShare(share: string, options: FileService.DeleteShareOptions, callback: ErrorOrResponse): void; + deleteShare(share: string, callback: ErrorOrResponse): void; + + /** + * Marks the specified share for deletion if it exists. + * The share and any files contained within it are later deleted during garbage collection. + * + * @this {FileService} + * @param {string} share The share name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the share exists and was deleted, or false if the share + * did not exist. + * `response` will contain information related to this operation. + */ + deleteShareIfExists(share: string, options: FileService.DeleteShareOptions, callback: ErrorOrResult): void; + deleteShareIfExists(share: string, callback: ErrorOrResult): void; + + /** + * Checks whether or not a directory exists on the service. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the directory exists, or false if the directory does not exist. + * `response` will contain information related to this operation. + */ + doesDirectoryExist(share: string, directory: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + doesDirectoryExist(share: string, directory: string, callback: ErrorOrResult): void; + + /** + * Creates a new directory under the specified account. + * If a directory with the same name already exists, the operation fails. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the directory information. + * `response` will contain information related to this operation. + */ + createDirectory(share: string, directory: string, options: FileService.CreateDirectoryRequestOptions, callback: ErrorOrResult): void; + createDirectory(share: string, directory: string, callback: ErrorOrResult): void; + + /** + * Creates a new directory under the specified account if the directory does not exists. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the directory was created, or false if the directory + * already exists. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * FileService.createDirectoryIfNotExists('taskshare', taskdirectory', function(error) { + * if(!error) { + * // Directory created or already existed + * } + * }); + */ + createDirectoryIfNotExists(share: string, directory: string, options: FileService.CreateDirectoryRequestOptions, callback: ErrorOrResult): void; + createDirectoryIfNotExists(share: string, directory: string, callback: ErrorOrResult): void; + + /** + * Retrieves a directory and its properties from a specified account. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information for the directory. + * `response` will contain information related to this operation. + */ + getDirectoryProperties(share: string, directory: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + getDirectoryProperties(share: string, directory: string, callback: ErrorOrResult): void; + + /** + * Marks the specified directory for deletion. The directory must be empty before it can be deleted. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; otherwise + * `response` will contain information related to this operation. + */ + deleteDirectory(share: string, directory: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + deleteDirectory(share: string, directory: string, callback: ErrorOrResponse): void; + + /** + * Marks the specified directory for deletion if it exists. The directory must be empty before it can be deleted. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the directory exists and was deleted, or false if the directory + * did not exist. + * `response` will contain information related to this operation. + */ + deleteDirectoryIfExists(share: string, directory: string, options: common.RequestOptions, callback: ErrorOrResult): void; + deleteDirectoryIfExists(share: string, directory: string, callback: ErrorOrResult): void; + + /** + * Lists a segment containing a collection of file items in the directory. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {int} [options.maxResults] Specifies the maximum number of files to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs]The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * entries.files, entries.directories and the continuationToken for the next listing operation. + * `response` will contain information related to this operation. + */ + listFilesAndDirectoriesSegmented(share: string, directory: string, currentToken: common.ContinuationToken, options: FileService.ListRequestOptions, callback: ErrorOrResult): void; + listFilesAndDirectoriesSegmented(share: string, directory: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + + /** + * Lists a segment containing a collection of file items in the directory. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} prefix The prefix of the directory/files name. + * @param {Object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {int} [options.maxResults] Specifies the maximum number of files to return per call to Azure ServiceClient. This does NOT affect list size returned by this function. (maximum: 5000) + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs]The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * entries.files, entries.directories and the continuationToken for the next listing operation. + * `response` will contain information related to this operation. + */ + listFilesAndDirectoriesSegmentedWithPrefix(share: string, directory: string, prefix: string, currentToken: common.ContinuationToken, options: FileService.ListRequestOptions, callback: ErrorOrResult): void; + listFilesAndDirectoriesSegmentedWithPrefix(share: string, directory: string,prefix: string, currentToken: common.ContinuationToken, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata for the specified directory. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the file. + * `response` will contain information related to this operation. + */ + getDirectoryMetadata(share: string, directory: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + getDirectoryMetadata(share: string, directory: string, callback: ErrorOrResult): void; + + /** + * Sets user-defined metadata for the specified directory as one or more name-value pairs + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {Object} metadata The metadata key/value pairs. + * @param {Object} [options] The request options. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information on the file. + * `response` will contain information related to this operation. + */ + setDirectoryMetadata(share: string, directory: string, metadata: Map, options: common.RequestOptions, callback: ErrorOrResult): void; + setDirectoryMetadata(share: string, directory: string, metadata: Map, callback: ErrorOrResult): void; + + /** + * Retrieves a shared access signature token. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} [directory] The directory name. Use '' to refer to the base directory. + * @param {string} [file] The file name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {Object} [headers] The optional header values to set for a file returned wth this SAS. + * @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used. + * @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used. + * @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used. + * @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used. + * @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used. + * @return {string} The shared access signature. Note this does not contain the leading "?". + */ + generateSharedAccessSignature(share: string, directory: string, file: string, sharedAccessPolicy: common.SharedAccessPolicy, headers?: common.ContentSettingsHeaders): string; + + /** + * Retrieves a shared access signature token. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} [directory] The directory name. Use '' to refer to the base directory. + * @param {string} [file] The file name. + * @param {Object} sharedAccessPolicy The shared access policy. + * @param {string} [sharedAccessPolicy.Id] The signed identifier. + * @param {Object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type. + * @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used). + * @param {date|string} sharedAccessPolicy.AccessPolicy.Expiry The time at which the Shared Access Signature becomes expired (The UTC value will be used). + * @param {string} [sasVersion] An optional string indicating the desired SAS version to use. Value must be 2012-02-12 or later. + * @param {Object} [headers] The optional header values to set for a file returned wth this SAS. + * @param {string} [headers.cacheControl] The optional value of the Cache-Control response header to be returned when this SAS is used. + * @param {string} [headers.contentType] The optional value of the Content-Type response header to be returned when this SAS is used. + * @param {string} [headers.contentEncoding] The optional value of the Content-Encoding response header to be returned when this SAS is used. + * @param {string} [headers.contentLanguage] The optional value of the Content-Language response header to be returned when this SAS is used. + * @param {string} [headers.contentDisposition] The optional value of the Content-Disposition response header to be returned when this SAS is used. + * @return {string} The shared access signature query string. Note this string does not contain the leading "?". + */ + generateSharedAccessSignatureWithVersion(share: string, directory: string, file: string, sharedAccessPolicy: common.SharedAccessPolicy, sasVersion: string, headers?: common.ContentSettingsHeaders): string; + + /** + * Retrieves a file or directory URL. + * + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} [file] The file name. File names may not start or end with the delimiter '/'. + * @param {string} [sasToken] The Shared Access Signature token. + * @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint. + * @param {boolean} [shareSnapshotId] The snapshot identifier of the share. + * @return {string} The formatted URL string. + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * var url = FileService.getUrl(shareName, directoryName, fileName, sasToken, true); + */ + getUrl(share: string, directory: string, file?: string, sasToken?: string, primary?: boolean, shareSnapshotId?: string): string; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the file. + * It does not return or modify the content of the file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the file. + * `response` will contain information related to this operation. + */ + getFileProperties(share: string, directory: string, file: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + getFileProperties(share: string, directory: string, file: string, callback: ErrorOrResult): void; + + /** + * Returns all user-defined metadata for the specified file. + * It does not modify or return the content of the file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the file. + * `response` will contain information related to this operation. + */ + getFileMetadata(share: string, directory: string, file: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + getFileMetadata(share: string, directory: string, file: string, callback: ErrorOrResult): void; + + /** + * Sets user-defined properties for the specified file. + * It does not modify or return the content of the file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {string} [options.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentMD5] The file's MD5 hash. + * @param {string} [options.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentDisposition] The file's content disposition. + * @param {string} [options.contentLength] Resizes a file to the specified size. If the specified byte value is less than the current size of the file, + * then all ranges above the specified byte value are cleared. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the file. + * `response` will contain information related to this operation. + */ + setFileProperties(share: string, directory: string, file: string, options: FileService.SetFilePropertiesRequestOptions, callback: ErrorOrResult): void; + setFileProperties(share: string, directory: string, file: string, callback: ErrorOrResult): void; + + /** + * Sets user-defined metadata for the specified file as one or more name-value pairs + * It does not modify or return the content of the file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} metadata The metadata key/value pairs. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information on the file. + * `response` will contain information related to this operation. + */ + setFileMetadata(share: string, directory: string, file: string, metadata: Map, options: common.RequestOptions, callback: ErrorOrResult): void; + setFileMetadata(share: string, directory: string, file: string, metadata: Map, callback: ErrorOrResult): void; + + /** + * Resizes a file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {String} size The size of the file, in bytes. + * @param {Object} [options] The request options. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * information about the file. + * `response` will contain information related to this operation. + */ + resizeFile(share: string, directory: string, file: string, size: number, options: common.RequestOptions, callback: ErrorOrResult): void; + resizeFile(share: string, directory: string, file: string, size: number, callback: ErrorOrResult): void; + + /** + * Checks whether or not a file exists on the service. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `errorOrResult` will + * be true if the file exists, or false if the file does not exist. + * `response` will contain information related to this operation. + */ + doesFileExist(share: string, directory: string, file: string, options: FileService.FileServiceOptions, callback: ErrorOrResult): void; + doesFileExist(share: string, directory: string, file: string, callback: ErrorOrResult): void; + + /** + * Creates a file of the specified length. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {int} length The length of the file in bytes. + * @param {Object} [options] The request options. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the directory information. + * `response` will contain information related to this operation. + */ + createFile(share: string, directory: string, file: string, length: number, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): void; + createFile(share: string, directory: string, file: string, length: number, callback: ErrorOrResult): void; + + /** + * Marks the specified file for deletion. The file is later deleted during garbage collection. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information + * if an error occurs; `response` will contain information related to this operation. + */ + deleteFile(share: string, directory: string, file: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + deleteFile(share: string, directory: string, file: string, callback: ErrorOrResponse): void; + + /** + * Marks the specified file for deletion if it exists. The file is later deleted during garbage collection. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will + * be true if the file was deleted, or false if the file + * does not exist. + * `response` will contain information related to this operation. + */ + deleteFileIfExists(share: string, directory: string, file: string, options: common.RequestOptions, callback: ErrorOrResult): void; + deleteFileIfExists(share: string, directory: string, file: string, callback: ErrorOrResult): void; + + /** + * Downloads a file into a text string. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {int} [options.rangeStart] The range start. + * @param {int} [options.rangeEnd] The range end. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {FileService~FileToText} callback `error` will contain information + * if an error occurs; otherwise `text` will contain the file contents, + * and `file` will contain the file information. + * `response` will contain information related to this operation. + */ + getFileToText(share: string, directory: string, file: string, options: FileService.GetFileRequestOptions, callback: FileService.FileToText): void; + getFileToText(share: string, directory: string, file: string, callback: FileService.FileToText): void; + + /** + * Downloads an Azure file into a file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {string} localFileName The local path to the file to be downloaded. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. + * @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the file information. + * `response` will contain information related to this operation. + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * FileService.getFileToLocalFile('taskshare', taskdirectory', 'task1', 'task1-download.txt', function(error, serverFile) { + * if(!error) { + * // file available in serverFile.file variable + * } + */ + getFileToLocalFile(share: string, directory: string, file: string, localFileName: string, options: FileService.GetFileRequestOptions, callback: ErrorOrResult): void; + getFileToLocalFile(share: string, directory: string, file: string, localFileName: string, callback: ErrorOrResult): void; + + /** + * Provides a stream to read from a file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. + * @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the file information. + * `response` will contain information related to this operation. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var fileService = azure.createFileService(); + * var writable = fs.createWriteStream(destinationFileNameTarget); + * fileService.createReadStream(shareName, directoryName, fileName).pipe(writable); + */ + createReadStream(share: string, directory: string, file: string, options: FileService.GetFileRequestOptions, callback: ErrorOrResult): stream.Readable; + createReadStream(share: string, directory: string, file: string, callback: ErrorOrResult): stream.Readable; + + /** + * Downloads a file into a stream. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Stream} writeStream The write stream. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {string} [options.rangeStart] Return only the bytes of the file in the specified range. + * @param {string} [options.rangeEnd] Return only the bytes of the file in the specified range. + * @param {boolean} [options.useTransactionalMD5] When set to true, Calculate and send/validate content MD5 for transactions. + * @param {boolean} [options.disableContentMD5Validation] When set to true, MD5 validation will be disabled when downloading files. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `result` will contain the file information. + * `response` will contain information related to this operation. + * + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * FileService.getFileToStream('taskshare', taskdirectory', 'task1', fs.createWriteStream('task1-download.txt'), function(error, serverFile) { + * if(!error) { + * // file available in serverFile.file variable + * } + * }); + */ + getFileToStream(share: string, directory: string, file: string, writeStream: stream.Writable, options: FileService.GetFileRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + getFileToStream(share: string, directory: string, file: string, writeStream: stream.Writable, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Lists file ranges. Lists all of the ranges by default, or only the ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {string} [options.shareSnapshotId] The snapshot identifier of the share. + * @param {int} [options.rangeStart] The range start. + * @param {int} [options.rangeEnd] The range end. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the range information. + * `response` will contain information related to this operation. + */ + listRanges(share: string, directory: string, file: string, options: FileService.ListRangeRequestOptions, callback: ErrorOrResult): void; + listRanges(share: string, directory: string, file: string, callback: ErrorOrResult): void; + + /** + * Clears a range. Clears all of the ranges by default, or only the ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {int} rangeStart The range start. + * @param {int} rangeEnd The range end. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the directory information. + * `response` will contain information related to this operation. + */ + clearRange(share: string, directory: string, file: string, rangeStart: number, rangeEnd: number, options: common.RequestOptions, callback: ErrorOrResult): void; + clearRange(share: string, directory: string, file: string, rangeStart: number, rangeEnd: number, callback: ErrorOrResult): void; + + /** + * Updates a range from a stream. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Stream} readStream The read stream. + * @param {int} rangeStart The range start. + * @param {int} rangeEnd The range end. + * @param {Object} [options] The request options. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {string} [options.transactionalContentMD5] An optional hash value used to ensure transactional integrity for the page. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the file information. + * `response` will contain information related to this operation. + */ + createRangesFromStream(share: string, directory: string, file: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: FileService.CreateRangeRequestOptions, callback: ErrorOrResult): void; + createRangesFromStream(share: string, directory: string, file: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: ErrorOrResult): void; + + /** + * Uploads a file from a text string. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {string|object} text The file text, as a string or in a Buffer. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. + * The default value is false for files. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {ErrorOrResult} callback `error` will contain information + * if an error occurs; `result` will contain the file information. + * `response` will contain information related to this operation. + */ + createFileFromText(share: string, directory: string, file: string, text: string | Buffer, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): void; + createFileFromText(share: string, directory: string, file: string, text: string | Buffer, callback: ErrorOrResult): void; + + /** + * Uploads a file to storage from a local file. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param (string) localFileName The local path to the file to be uploaded. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. + * The default value is false for files. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createFileFromLocalFile(share: string, directory: string, file: string, localFileName: string, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createFileFromLocalFile(share: string, directory: string, file: string, localFileName: string, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a file to storage from an HTML File object. If the file already exists on the service, it will be overwritten. + * (Only available in the JavaScript Client Library for Browsers) + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} browserFile The File object to be uploaded created by HTML File API. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. + * The default value is false for files. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information if an error occurs; + * otherwise `[result]{@link FileResult}` will contain the file information. + * `response` will contain information related to this operation. + * @return {SpeedSummary} + */ + createFileFromBrowserFile(share: string, directory: string, file: string, browserFile: Object, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createFileFromBrowserFile(share: string, directory: string, file: string, browserFile: Object, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Uploads a file from a stream. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param (Stream) stream Stream to the data to store. + * @param {int} streamLength The length of the stream to upload. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. + * The default value is false for files. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {SpeedSummary} + */ + createFileFromStream(share: string, directory: string, file: string, stream: stream.Readable, streamLength: number, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + createFileFromStream(share: string, directory: string, file: string, stream: stream.Readable, streamLength: number, callback: ErrorOrResult): common.streams.speedsummary.SpeedSummary; + + /** + * Provides a stream to write to a file. Assumes that the file exists. + * If it does not, please create the file using createFile before calling this method or use createWriteStreamNewFile. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. + * The default value is false for files. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * FileService.createFile(shareName, directoryName, fileName, 1024, function (err) { + * // Pipe file to a file + * var stream = fs.createReadStream(fileNameTarget).pipe(FileService.createWriteStreamToExistingFile(shareName, directoryName, fileName)); + * }); + */ + createWriteStreamToExistingFile(share: string, directory: string, file: string, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): stream.Writable; + createWriteStreamToExistingFile(share: string, directory: string, file: string, callback: ErrorOrResult): stream.Writable; + + /** + * Provides a stream to write to a file. Creates the file before writing data. + * Please note the `Stream` returned by this API should be used with piping. + * + * @this {FileService} + * @param {string} share The share name. + * @param {string} directory The directory name. Use '' to refer to the base directory. + * @param {string} file The file name. File names may not start or end with the delimiter '/'. + * @param {string} length The file length. + * @param {Object} [options] The request options. + * @param {SpeedSummary} [options.speedSummary] The download tracker objects; + * @param {Object} [options.metadata] The metadata key/value pairs. + * @param {bool} [options.storeFileContentMD5] Specifies whether the file's ContentMD5 header should be set on uploads. + * The default value is false for files. + * @param {bool} [options.useTransactionalMD5] Calculate and send/validate content MD5 for transactions. + * @param {Object} [options.contentSettings] The file's content settings. + * @param {string} [options.contentSettings.contentType] The MIME content type of the file. The default type is application/octet-stream. + * @param {string} [options.contentSettings.contentEncoding] The content encodings that have been applied to the file. + * @param {string} [options.contentSettings.contentLanguage] The natural languages used by this resource. + * @param {string} [options.contentSettings.cacheControl] The file service stores this value but does not use or modify it. + * @param {string} [options.contentSettings.contentDisposition] The file's content disposition. + * @param {string} [options.contentSettings.contentMD5] The file's MD5 hash. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback The callback function. + * @return {Stream} + * @example + * var azure = require('azure-storage'); + * var FileService = azure.createFileService(); + * var stream = fs.createReadStream(fileNameTarget).pipe(FileService.createWriteStreamToNewFile(shareName, directoryName, fileName)); + */ + createWriteStreamToNewFile(share: string, directory: string, file: string, length: number, options: FileService.CreateFileRequestOptions, callback: ErrorOrResult): stream.Writable; + createWriteStreamToNewFile(share: string, directory: string, file: string, length: number, callback: ErrorOrResult): stream.Writable; + + /** + * Starts to copy a file to a destination within the storage account. + * + * @this {FileService} + * @param {string} sourceUri The source file or blob URI. + * @param {string} targetShare The target share name. + * @param {string} targetDirectory The target directory name. + * @param {string} targetFile The target file name. + * @param {Object} [options] The request options. + * @param {Object} [options.metadata] The target file metadata key/value pairs. + * @param {AccessConditions} [options.accessConditions] The access conditions. + * @param {AccessConditions} [options.sourceAccessConditions] The source access conditions. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResult} callback `error` will contain information + * if an error occurs; otherwise `result` will contain + * the file information. + * `response` will contain information related to this operation. + */ + startCopyFile(sourceUri: string, targetshare: string, targetdirectory: string, targetfile: string, options: FileService.CopyFileRequestOptions, callback: ErrorOrResult): void; + startCopyFile(sourceUri: string, targetshare: string, targetdirectory: string, targetfile: string, callback: ErrorOrResult): void; + + /** + * Abort a file copy operation. + * + * @this {FileService} + * @param {string} share The destination share name. + * @param {string} directory The destination directory name. + * @param {string} file The destination file name. + * @param {string} copyId The copy operation identifier. + * @param {Object} [options] The request options. + * @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to. + * Please see StorageUtilities.LocationMode for the possible values. + * @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request. + * @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + * The maximum execution time interval begins at the time that the client begins building the request. The maximum + * execution time is checked intermittently while performing requests, and before executing retries. + * @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit. + * @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + * The default value is false. + * @param {errorOrResponse} callback `error` will contain information if an error occurs. + * `response` will contain information related to this operation. + */ + abortCopyFile(share: string, directory: string, file: string, copyId: string, options: common.RequestOptions, callback: ErrorOrResponse): void; + abortCopyFile(share: string, directory: string, file: string, copyId: string, callback: ErrorOrResponse): void; + } + + export module FileService { + export interface ListSharesResult { + entries: ShareResult[]; + continuationToken?: common.ContinuationToken + } + + export interface ListFilesAndDirectoriesResult { + entries: { + directories: DirectoryResult[]; + files: FileResult[]; + } + continuationToken?: common.ContinuationToken; + } + + export interface ShareResult { + name: string; + snapshot?: string; + etag: string; + lastModified: string; + metadata?: { [key: string]: string; }; + requestId?: string; + quota?: string; + shareStats? : { + shareUsage?: string; + } + exists?: boolean; + created?: boolean; + } + + export interface ShareAclResult extends ShareResult { + signedIdentifiers?: Map + } + + export interface DirectoryResult { + name: string; + etag: string; + lastModified: string; + requestId?: string; + metadata?: { [key: string]: string; }; + serverEncrypted?: string; + exists?: boolean; + created?: boolean; + } + + export interface FileResult { + share: string; + directory: string; + name: string; + etag: string; + lastModified: string; + requestId?: string; + acceptRanges: string; + contentRange: string; + contentLength: string; + metadata?: { [key: string]: string; }; + serverEncrypted?: string; + contentSettings?:{ + contentEncoding: string; + contentLanguage: string; + contentType: string; + cacheControl: string; + contentDisposition: string; + contentMD5: string; + } + copy?: { + id?: string; + source?: string; + status?: string; + completionTime?: string; + statusDescription?: string; + progress?: string; + }; + exists?: boolean; + created?: boolean; + } + + export interface ShareProperties { + quota: number + } + + export interface FileServiceOptions extends common.RequestOptions { + shareSnapshotId?: string; + } + + export interface DeleteShareOptions extends FileServiceOptions { + deleteSnapshots?: string; + } + + export interface ListRangeRequestOptions extends FileServiceOptions { + rangeStart?: number; + rangeEnd?: number; + } + + export interface GetFileRequestOptions extends FileServiceOptions { + parallelOperationThreadCount?: number; + rangeStart?: number; + rangeEnd?: number; + useTransactionalMD5?: boolean; + disableContentMD5Validation?: boolean; + } + + export interface ListRequestOptions extends FileServiceOptions { + maxResults?: number; + include?: string; + } + + export interface ListShareRequestOptions extends common.RequestOptions { + maxResults?: number; + include?: string; + } + + export interface CreateShareRequestOptions extends common.RequestOptions { + quota?: string | number; + } + + export interface CreateFileRequestOptions extends common.RequestOptions { + speedsummary?: common.streams.speedsummary.SpeedSummary; + metadata?: { [key: string]: string; }; + contentSettings?: { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; + }; + useTransactionalMD5?: boolean; + storeFileContentMD5?: boolean; + } + + export interface CopyFileRequestOptions extends common.RequestOptions { + metadata?: { [key: string]: string; }; + accessConditions?: AccessConditions; + sourceAccessConditions?: AccessConditions; + } + + export interface CreateRangeRequestOptions extends common.RequestOptions { + useTransactionalMD5?: boolean; + transactionalContentMD5?: string; + } + + export interface CreateDirectoryRequestOptions extends common.RequestOptions { + metadata?: { [key: string]: string; }; + } + + export interface SetFilePropertiesRequestOptions extends common.RequestOptions { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; + } + + export interface FileToText { + (error: Error, text: string, result: FileResult, response: ServiceResponse): void + } + } + + export var FileService: { + /** + * Creates a new FileService object. + * If no connection string or storageaccount and storageaccesskey are provided, + * the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used. + * @class + * The FileService class is used to perform operations on the Microsoft Azure File Service. + * The File Service provides storage for binary large objects, and provides functions for working with data stored in files. + * + * For more information on the File Service, as well as task focused information on using it in a Node.js application, see + * [How to Use the File Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-file-storage/). + * The following defaults can be set on the file service. + * defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the file service. + * defaultEnableReuseSocket The default boolean value to enable socket reuse when uploading local files or streams. + * If the Node.js version is lower than 0.10.x, socket reuse will always be turned off. + * defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the file service. + * defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the file service. + * defaultLocationMode The default location mode for requests made via the file service. + * parallelOperationThreadCount The number of parallel operations that may be performed when uploading a file. + * useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the file service; true to use the + * Nagle algorithm; otherwise, false. The default value is false. + * @constructor + * @extends {StorageServiceClient} + * + * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} [sasToken] The Shared Access Signature token. + * @param {string} [endpointSuffix] The endpoint suffix. + */ + new (storageAccountOrConnectionString?: string, storageAccessKey?: string, host?: string|StorageHost, sasToken?: string, endpointSuffix?: string): FileService; + } + + // ########################### + // ./services/file/fileutilities + // ########################### + export module FileUtilities { + var SharedAccessPermissions: { + READ: string; + CREATE: string; + WRITE: string; + DELETE: string; + LIST: string; + }; + + var ListingDetails: { + METADATA: string; + }; + + var SharePublicAccessType: { + OFF: string; + SHARE: string; + FILE: string; + }; + + var ShareSnapshotDeleteOptions: { + SHARE_AND_SNAPSHOTS: string + }; + } + } + } + + module common { + module filters { + + export interface IFilter { + handle(requestOptions: common.RequestOptions, next: Next) : void + } + + export interface Next { + (returnedObject: any, finalCallback: Post, nextPostCallback: Post) : void; + } + + export interface Post { + (returnedObject: any) : void; + } + + // ########################### + // ./common/filters/retrypolicyfilter + // ########################### + module retrypolicyfilter { + export interface RetryPolicyFilter extends RetryPolicyFilter.IRetryPolicy { + retryCount: number; + retryInterval: number; + /** + * Creates a new RetryPolicyFilter instance. + * @class + * The RetryPolicyFilter allows you to retry operations, + * using a custom retry policy. Users are responsible to + * define the shouldRetry method. + * To apply a filter to service operations, use `withFilter` + * and specify the filter to be used when creating a service. + * @constructor + * @param {number} [retryCount=30000] The client retry count. + * @param {number} [retryInterval=3] The client retry interval, in milliseconds. + * + * @example + * var azure = require('azure-storage'); + * var retryPolicy = new azure.RetryPolicyFilter(); + * retryPolicy.retryCount = 3; + * retryPolicy.retryInterval = 3000; + * retryPolicy.shouldRetry = function(statusCode, retryRequestOption) { + * + * }; + * var blobService = azure.createBlobService().withFilter(retryPolicy); + */ + constructor(retryCount?: number, retryInterval?: number): RetryPolicyFilter; + + shouldRetry(statusCode: number, retryData: RetryPolicyFilter.IRetryRequestOptions): { + retryInterval: number; + retryable: boolean; + }; + } + export module RetryPolicyFilter { + /** + * Represents the default client retry interval, in milliseconds. + */ + export var DEFAULT_CLIENT_RETRY_INTERVAL: number; + /** + * Represents the default client retry count. + */ + export var DEFAULT_CLIENT_RETRY_COUNT: number; + + export interface IRetryRequestOptions { + retryInterval: number; + locationMode: StorageUtilities.LocationMode; + currentLocation: Constants.StorageLocation; + retryContext: IRetryContext; + } + export interface IRetryContext { + retryCount: number; + error: Error; + retryInterval: number; + locationMode: StorageUtilities.LocationMode; + currentLocation: Constants.StorageLocation; + } + export interface IRetryPolicy extends IFilter { + retryInterval: number; + shouldRetry(statusCode: number, retryData: IRetryRequestOptions): { + retryInterval: number; + retryable: boolean; + }; + } + } + } + + // ########################### + // ./common/filters/linearretrypolicyfilter + // ########################### + module linearretrypolicyfilter { + export class LinearRetryPolicyFilter implements RetryPolicyFilter.IRetryPolicy { + retryCount: number; + retryInterval: number; + /** + * Creates a new LinearRetryPolicyFilter instance. + * @class + * The LinearRetryPolicyFilter allows you to retry operations, + * using an linear back-off interval between retries. + * To apply a filter to service operations, use `withFilter` + * and specify the filter to be used when creating a service. + * @constructor + * @param {number} [retryCount=30000] The client retry count. + * @param {number} [retryInterval=3] The client retry interval, in milliseconds. + * + * @example + * var azure = require('azure-storage'); + * var retryOperations = new azure.LinearRetryPolicyFilter(); + * var blobService = azure.createBlobService().withFilter(retryOperations) + */ + constructor(retryCount?: number, retryInterval?: number); + /** + * Represents the default client retry interval, in milliseconds. + */ + static DEFAULT_CLIENT_RETRY_INTERVAL: number; + /** + * Represents the default client retry count. + */ + static DEFAULT_CLIENT_RETRY_COUNT: number; + /** + * Determines if the operation should be retried and how long to wait until the next retry. + * + * @param {number} statusCode The HTTP status code. + * @param {Object} retryData The retry data. + * @return {retryInfo} Information about whether the operation qualifies for a retry and the retryInterval. + */ + shouldRetry(statusCode: number, retryData: RetryPolicyFilter.IRetryRequestOptions): { + retryInterval: number; + retryable: boolean; + }; + handle(requestOptions: common.RequestOptions, next: Next) : void + } + } + + // ########################### + // ./common/filters/exponentialretrypolicyfilter + // ########################### + module exponentialretrypolicyfilter { + export class ExponentialRetryPolicyFilter implements RetryPolicyFilter.IRetryPolicy { + retryCount: number; + retryInterval: number; + minRetryInterval: number; + maxRetryInterval: number; + /** + * Creates a new 'ExponentialRetryPolicyFilter' instance. + * @class + * The ExponentialRetryPolicyFilter allows you to retry operations, + * using an exponential back-off interval between retries. + * To apply a filter to service operations, use `withFilter` + * and specify the filter to be used when creating a service. + * @constructor + * @param {number} [retryCount=3] The client retry count. + * @param {number} [retryInterval=30000] The client retry interval, in milliseconds. + * @param {number} [minRetryInterval=3000] The minimum retry interval, in milliseconds. + * @param {number} [maxRetryInterval=90000] The maximum retry interval, in milliseconds. + * + * @example + * var azure = require('azure-storage'); + * var retryOperations = new azure.ExponentialRetryPolicyFilter(); + * var blobService = azure.createBlobService().withFilter(retryOperations) + */ + constructor(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number); + /** + * Represents the default client retry interval, in milliseconds. + */ + static DEFAULT_CLIENT_RETRY_INTERVAL: number; + /** + * Represents the default client retry count. + */ + static DEFAULT_CLIENT_RETRY_COUNT: number; + /** + * Represents the default maximum retry interval, in milliseconds. + */ + static DEFAULT_CLIENT_MAX_RETRY_INTERVAL: number; + /** + * Represents the default minimum retry interval, in milliseconds. + */ + static DEFAULT_CLIENT_MIN_RETRY_INTERVAL: number; + /** + * Determines if the operation should be retried and how long to wait until the next retry. + * + * @param {number} statusCode The HTTP status code. + * @param {Object} retryData The retry data. + * @return {retryInfo} Information about whether the operation qualifies for a retry and the retryInterval. + */ + shouldRetry(statusCode: number, retryData: RetryPolicyFilter.IRetryRequestOptions): { + retryInterval: number; + retryable: boolean; + }; + handle(requestOptions: common.RequestOptions, next: Next) : void + } + } + } + + module util { + + // ########################### + // ./common/util/constants + // ########################### + module constants { + export var USER_AGENT_PRODUCT_NAME: string; + export var USER_AGENT_PRODUCT_VERSION: string; + /** + * The number of default concurrent requests for parallel operation. + * + * @const + * @type {string} + */ + export var DEFAULT_PARALLEL_OPERATION_THREAD_COUNT: number; + /** + * The boolean of default value for enabling reuseSocket. + * + * @const + * @type {bool} + */ + export var DEFAULT_ENABLE_REUSE_SOCKET: boolean; + /** + * Constant representing a kilobyte (Non-SI version). + * + * @const + * @type {string} + */ + export var KB: number; + /** + * Constant representing a megabyte (Non-SI version). + * + * @const + * @type {string} + */ + export var MB: number; + /** + * Constant representing a gigabyte (Non-SI version). + * + * @const + * @type {string} + */ + export var GB: number; + /** + * Specifies HTTP. + * + * @const + * @type {string} + */ + export var HTTP: string; + /** + * Specifies HTTPS. + * + * @const + * @type {string} + */ + export var HTTPS: string; + /** + * Marker for atom metadata. + * + * @const + * @type {string} + */ + export var XML_METADATA_MARKER: string; + /** + * Marker for atom value. + * + * @const + * @type {string} + */ + export var XML_VALUE_MARKER: string; + /** + * Specifies the location used to indicate which location the operation can be performed against. + * + * @const + * @enum + */ + export enum RequestLocationMode { + PRIMARY_ONLY = 0, + SECONDARY_ONLY = 1, + PRIMARY_OR_SECONDARY = 2, + } + /** + * Represents a storage service location. + * + * @const + * @enum + */ + export enum StorageLocation { + PRIMARY = 0, + SECONDARY = 1, + } + + export var AccountSasConstants: { + /** + * Permission types + * + * @const + * @enum {string} + */ + Permissions: { + READ: string, + ADD: string, + CREATE: string, + UPDATE: string, + PROCESS: string, + WRITE: string, + DELETE: string, + LIST: string + }, + + /** + * Services types + * + * @const + * @enum {string} + */ + Services: { + BLOB: string, + FILE: string, + QUEUE: string, + TABLE: string, + }, + + /** + * Resources types + * + * @const + * @enum {string} + */ + Resources: { + SERVICE: string, + CONTAINER: string, + OBJECT: string + }, + + Protocols: { + HTTPSONLY: string, + HTTPSORHTTP: string + }, + }; + + /** + * Defines constants for use with shared access policies. + */ + export var AclConstants: { + ACCESS_POLICY: string; + EXPIRY: string; + ID: string; + PERMISSION: string; + SIGNED_IDENTIFIER_ELEMENT: string; + SIGNED_IDENTIFIERS_ELEMENT: string; + START: string; + }; + /** + * Defines constants for use with service properties. + */ + export var ServicePropertiesConstants: { + STORAGE_SERVICE_PROPERTIES_ELEMENT: string; + DEFAULT_ANALYTICS_VERSION: string; + LOGGING_ELEMENT: string; + VERSION_ELEMENT: string; + DELETE_ELEMENT: string; + READ_ELEMENT: string; + WRITE_ELEMENT: string; + RETENTION_POLICY_ELEMENT: string; + ENABLED_ELEMENT: string; + DAYS_ELEMENT: string; + HOUR_METRICS_ELEMENT: string; + MINUTE_METRICS_ELEMENT: string; + CORS_ELEMENT: string; + CORS_RULE_ELEMENT: string; + ALLOWED_ORIGINS_ELEMENT: string; + ALLOWED_METHODS_ELEMENT: string; + MAX_AGE_IN_SECONDS_ELEMENT: string; + EXPOSED_HEADERS_ELEMENT: string; + ALLOWED_HEADERS_ELEMENT: string; + INCLUDE_APIS_ELEMENT: string; + DEFAULT_SERVICE_VERSION_ELEMENT: string; + DEFAULT_DELETE_RETENTION_POLICY_ELEMENT: string; + }; + /** + * Defines constants for use with blob operations. + */ + export var BlobConstants: { + LATEST_ELEMENT: string; + UNCOMMITTED_ELEMENT: string; + BLOCK_LIST_ELEMENT: string; + COMMITTED_ELEMENT: string; + DEFAULT_WRITE_PAGE_SIZE_IN_BYTES: number; + MIN_WRITE_PAGE_SIZE_IN_BYTES: number; + DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES: number; + DEFAULT_WRITE_BLOCK_SIZE_IN_BYTES: number; + MAX_BLOCK_SIZE: number; + MAX_SINGLE_UPLOAD_BLOB_SIZE_IN_BYTES: number; + MAX_RANGE_GET_SIZE_WITH_MD5: number; + MAX_UPDATE_PAGE_SIZE: number; + MAX_QUEUED_WRITE_DISK_BUFFER_SIZE: number; + MAX_SINGLE_GET_PAGE_RANGE_SIZE: number; + PAGE_SIZE: number; + ResourceTypes: { + CONTAINER: string; + BLOB: string; + }; + PageWriteOptions: { + UPDATE: string; + CLEAR: string; + }; + BlobTypes: { + BLOCK: string; + PAGE: string; + }; + LeaseOperation: { + ACQUIRE: string; + RENEW: string; + CHANGE: string; + RELEASE: string; + BREAK: string; + }; + }; + /** + * Defines constants for use with file operations. + */ + export var FileConstants: { + DEFAULT_WRITE_SIZE_IN_BYTES: number; + MAX_RANGE_GET_SIZE_WITH_MD5: number; + MAX_UPDATE_FILE_SIZE: number; + DEFAULT_SINGLE_FILE_GET_THRESHOLD_IN_BYTES: number; + MIN_WRITE_FILE_SIZE_IN_BYTES: number; + RangeWriteOptions: { + UPDATE: string; + CLEAR: string; + }; + }; + /** + * Defines constants for use with queue storage. + * + * @const + * @type {string} + */ + export var QueueConstants: { + QUEUE_MESSAGE_ELEMENT: string; + MESSAGE_TEXT_ELEMENT: string; + }; + /** + * Defines constants for use with table storage. + * + * @const + * @type {string} + */ + export var TableConstants: { + CHANGESET_DELIMITER: string; + BATCH_DELIMITER: string; + CONTINUATION_NEXT_ROW_KEY: string; + CONTINUATION_NEXT_PARTITION_KEY: string; + CONTINUATION_NEXT_TABLE_NAME: string; + NEXT_ROW_KEY: string; + NEXT_PARTITION_KEY: string; + NEXT_TABLE_NAME: string; + ODATA_PREFIX: string; + ODATA_TYPE_SUFFIX: string; + ODATA_METADATA_MARKER: string; + ODATA_VALUE_MARKER: string; + ODATA_TYPE_MARKER: string; + DEFAULT_DATA_SERVICE_VERSION: string; + TABLE_NAME: string; + TABLE_SERVICE_TABLE_NAME: string; + Operations: { + RETRIEVE: string; + INSERT: string; + UPDATE: string; + MERGE: string; + DELETE: string; + INSERT_OR_REPLACE: string; + INSERT_OR_MERGE: string; + }; + }; + /** + * Defines constants for use with HTTP headers. + */ + export var HeaderConstants: { + ACCEPT_RANGES: string; + CONTENT_TRANSFER_ENCODING_HEADER: string; + TRANSFER_ENCODING_HEADER: string; + SERVER_HEADER: string; + LOCATION_HEADER: string; + LAST_MODIFIED: string; + DATA_SERVICE_VERSION: string; + MAX_DATA_SERVICE_VERSION: string; + PREFIX_FOR_STORAGE_HEADER: string; + CLIENT_REQUEST_ID_HEADER: string; + APPROXIMATE_MESSAGES_COUNT: string; + AUTHORIZATION: string; + BLOB_PUBLIC_ACCESS_HEADER: string; + BLOB_TYPE_HEADER: string; + TYPE_HEADER: string; + BLOCK_BLOB: string; + CACHE_CONTROL: string; + BLOB_CACHE_CONTROL_HEADER: string; + CACHE_CONTROL_HEADER: string; + COPY_STATUS: string; + COPY_COMPLETION_TIME: string; + COPY_STATUS_DESCRIPTION: string; + COPY_ID: string; + COPY_PROGRESS: string; + COPY_ACTION: string; + CONTENT_ID: string; + CONTENT_ENCODING: string; + BLOB_CONTENT_ENCODING_HEADER: string; + CONTENT_ENCODING_HEADER: string; + CONTENT_LANGUAGE: string; + BLOB_CONTENT_LANGUAGE_HEADER: string; + CONTENT_LANGUAGE_HEADER: string; + CONTENT_LENGTH: string; + BLOB_CONTENT_LENGTH_HEADER: string; + CONTENT_LENGTH_HEADER: string; + CONTENT_DISPOSITION: string; + BLOB_CONTENT_DISPOSITION_HEADER: string; + CONTENT_DISPOSITION_HEADER: string; + CONTENT_MD5: string; + BLOB_CONTENT_MD5_HEADER: string; + CONTENT_MD5_HEADER: string; + CONTENT_RANGE: string; + CONTENT_TYPE: string; + BLOB_CONTENT_TYPE_HEADER: string; + CONTENT_TYPE_HEADER: string; + COPY_SOURCE_HEADER: string; + DATE: string; + DATE_HEADER: string; + DELETE_SNAPSHOT_HEADER: string; + ETAG: string; + IF_MATCH: string; + IF_MODIFIED_SINCE: string; + IF_NONE_MATCH: string; + IF_UNMODIFIED_SINCE: string; + INCLUDE_SNAPSHOTS_VALUE: string; + JSON_CONTENT_TYPE_VALUE: string; + LEASE_ID_HEADER: string; + LEASE_BREAK_PERIOD: string; + PROPOSED_LEASE_ID: string; + LEASE_DURATION: string; + SOURCE_LEASE_ID_HEADER: string; + LEASE_TIME_HEADER: string; + LEASE_STATUS: string; + LEASE_STATE: string; + PAGE_BLOB: string; + PAGE_WRITE: string; + FILE_WRITE: string; + PREFER: string; + PREFER_CONTENT: string; + PREFER_NO_CONTENT: string; + PREFIX_FOR_STORAGE_METADATA: string; + PREFIX_FOR_STORAGE_PROPERTIES: string; + RANGE: string; + RANGE_GET_CONTENT_MD5: string; + RANGE_HEADER_FORMAT: string; + REQUEST_ID_HEADER: string; + SEQUENCE_NUMBER: string; + SEQUENCE_NUMBER_EQUAL: string; + SEQUENCE_NUMBER_LESS_THAN: string; + SEQUENCE_NUMBER_LESS_THAN_OR_EQUAL: string; + SEQUENCE_NUMBER_ACTION: string; + SIZE: string; + SNAPSHOT_HEADER: string; + SNAPSHOTS_ONLY_VALUE: string; + SOURCE_IF_MATCH_HEADER: string; + SOURCE_IF_MODIFIED_SINCE_HEADER: string; + SOURCE_IF_NONE_MATCH_HEADER: string; + SOURCE_IF_UNMODIFIED_SINCE_HEADER: string; + STORAGE_RANGE_HEADER: string; + STORAGE_VERSION_HEADER: string; + TARGET_STORAGE_VERSION: string; + USER_AGENT: string; + POP_RECEIPT_HEADER: string; + TIME_NEXT_VISIBLE_HEADER: string; + APPROXIMATE_MESSAGE_COUNT_HEADER: string; + LEASE_ACTION_HEADER: string; + ACCEPT_HEADER: string; + ACCEPT_CHARSET_HEADER: string; + HOST_HEADER: string; + CORRELATION_ID_HEADER: string; + GROUP_ID_HEADER: string; + }; + export var QueryStringConstants: { + API_VERSION: string; + COMP: string; + RESTYPE: string; + COPY_ID: string; + SNAPSHOT: string; + TIMEOUT: string; + SIGNED_START: string; + SIGNED_EXPIRY: string; + SIGNED_RESOURCE: string; + SIGNED_PERMISSIONS: string; + SIGNED_IDENTIFIER: string; + SIGNATURE: string; + SIGNED_VERSION: string; + CACHE_CONTROL: string; + CONTENT_TYPE: string; + CONTENT_ENCODING: string; + CONTENT_LANGUAGE: string; + CONTENT_DISPOSITION: string; + BLOCK_ID: string; + BLOCK_LIST_TYPE: string; + PREFIX: string; + MARKER: string; + MAX_RESULTS: string; + DELIMITER: string; + INCLUDE: string; + PEEK_ONLY: string; + NUM_OF_MESSAGES: string; + POP_RECEIPT: string; + VISIBILITY_TIMEOUT: string; + MESSAGE_TTL: string; + SELECT: string; + FILTER: string; + TOP: string; + SKIP: string; + NEXT_PARTITION_KEY: string; + NEXT_ROW_KEY: string; + LOCK_ID: string; + TABLENAME: string; + STARTPK: string; + STARTRK: string; + ENDPK: string; + ENDRK: string; + }; + export var StorageServiceClientConstants: { + DEFAULT_PROTOCOL: string; + EnvironmentVariables: { + AZURE_STORAGE_ACCOUNT: string; + AZURE_STORAGE_ACCESS_KEY: string; + AZURE_STORAGE_DNS_SUFFIX: string; + AZURE_STORAGE_CONNECTION_STRING: string; + HTTP_PROXY: string; + HTTPS_PROXY: string; + EMULATED: string; + }; + DEVSTORE_STORAGE_ACCOUNT: string; + DEVSTORE_STORAGE_ACCESS_KEY: string; + DEV_STORE_URI: string; + DEVSTORE_DEFAULT_PROTOCOL: string; + DEVSTORE_BLOB_HOST: string; + DEVSTORE_QUEUE_HOST: string; + DEVSTORE_TABLE_HOST: string; + CLOUD_BLOB_HOST: string; + CLOUD_QUEUE_HOST: string; + CLOUD_TABLE_HOST: string; + CLOUD_FILE_HOST: string; + }; + export module HttpConstants { + /** + * Http Verbs + * + * @const + * @enum {string} + */ + var HttpVerbs: { + PUT: string; + GET: string; + DELETE: string; + POST: string; + MERGE: string; + HEAD: string; + }; + /** + * Response codes. + * + * @const + * @enum {int} + */ + enum HttpResponseCodes { + Ok = 200, + Created = 201, + Accepted = 202, + NoContent = 204, + PartialContent = 206, + BadRequest = 400, + Unauthorized = 401, + Forbidden = 403, + NotFound = 404, + Conflict = 409, + LengthRequired = 411, + PreconditionFailed = 412, + } + } + export var VersionConstants: { + AUGUST_2013: string; + FEBRUARY_2012: string; + }; + export var BlobErrorCodeStrings: { + INVALID_BLOCK_ID: string; + BLOB_NOT_FOUND: string; + BLOB_ALREADY_EXISTS: string; + CONTAINER_ALREADY_EXISTS: string; + CONTAINER_NOT_FOUND: string; + INVALID_BLOB_OR_BLOCK: string; + INVALID_BLOCK_LIST: string; + }; + export var FileErrorCodeStrings: { + SHARE_ALREADY_EXISTS: string; + SHARE_NOT_FOUND: string; + FILE_NOT_FOUND: string; + }; + export var QueueErrorCodeStrings: { + QUEUE_NOT_FOUND: string; + QUEUE_DISABLED: string; + QUEUE_ALREADY_EXISTS: string; + QUEUE_NOT_EMPTY: string; + QUEUE_BEING_DELETED: string; + POP_RECEIPT_MISMATCH: string; + INVALID_PARAMETER: string; + MESSAGE_NOT_FOUND: string; + MESSAGE_TOO_LARGE: string; + INVALID_MARKER: string; + }; + export var StorageErrorCodeStrings: { + UNSUPPORTED_HTTP_VERB: string; + MISSING_CONTENT_LENGTH_HEADER: string; + MISSING_REQUIRED_HEADER: string; + MISSING_REQUIRED_XML_NODE: string; + UNSUPPORTED_HEADER: string; + UNSUPPORTED_XML_NODE: string; + INVALID_HEADER_VALUE: string; + INVALID_XML_NODE_VALUE: string; + MISSING_REQUIRED_QUERY_PARAMETER: string; + UNSUPPORTED_QUERY_PARAMETER: string; + INVALID_QUERY_PARAMETER_VALUE: string; + OUT_OF_RANGE_QUERY_PARAMETER_VALUE: string; + INVALID_URI: string; + INVALID_HTTP_VERB: string; + EMPTY_METADATA_KEY: string; + REQUEST_BODY_TOO_LARGE: string; + INVALID_XML_DOCUMENT: string; + INTERNAL_ERROR: string; + AUTHENTICATION_FAILED: string; + MD5_MISMATCH: string; + INVALID_MD5: string; + OUT_OF_RANGE_INPUT: string; + INVALID_INPUT: string; + OPERATION_TIMED_OUT: string; + RESOURCE_NOT_FOUND: string; + RESOURCE_ALREADY_EXISTS: string; + INVALID_METADATA: string; + METADATA_TOO_LARGE: string; + CONDITION_NOT_MET: string; + UPDATE_CONDITION_NOT_SATISFIED: string; + INVALID_RANGE: string; + CONTAINER_NOT_FOUND: string; + CONTAINER_ALREADY_EXISTS: string; + CONTAINER_DISABLED: string; + CONTAINER_BEING_DELETED: string; + SERVER_BUSY: string; + }; + export var TableErrorCodeStrings: { + XMETHOD_NOT_USING_POST: string; + XMETHOD_INCORRECT_VALUE: string; + XMETHOD_INCORRECT_COUNT: string; + TABLE_HAS_NO_PROPERTIES: string; + DUPLICATE_PROPERTIES_SPECIFIED: string; + TABLE_HAS_NO_SUCH_PROPERTY: string; + DUPLICATE_KEY_PROPERTY_SPECIFIED: string; + TABLE_ALREADY_EXISTS: string; + TABLE_NOT_FOUND: string; + ENTITY_NOT_FOUND: string; + ENTITY_ALREADY_EXISTS: string; + PARTITION_KEY_NOT_SPECIFIED: string; + OPERATOR_INVALID: string; + UPDATE_CONDITION_NOT_SATISFIED: string; + PROPERTIES_NEED_VALUE: string; + PARTITION_KEY_PROPERTY_CANNOT_BE_UPDATED: string; + TOO_MANY_PROPERTIES: string; + ENTITY_TOO_LARGE: string; + PROPERTY_VALUE_TOO_LARGE: string; + INVALID_VALUE_TYPE: string; + TABLE_BEING_DELETED: string; + TABLE_SERVER_OUT_OF_MEMORY: string; + PRIMARY_KEY_PROPERTY_IS_INVALID_TYPE: string; + PROPERTY_NAME_TOO_LONG: string; + PROPERTY_NAME_INVALID: string; + BATCH_OPERATION_NOT_SUPPORTED: string; + JSON_FORMAT_NOT_SUPPORTED: string; + METHOD_NOT_ALLOWED: string; + NOT_IMPLEMENTED: string; + }; + export var ConnectionStringKeys: { + USE_DEVELOPMENT_STORAGE_NAME: string; + DEVELOPMENT_STORAGE_PROXY_URI_NAME: string; + DEFAULT_ENDPOINTS_PROTOCOL_NAME: string; + ACCOUNT_NAME_NAME: string; + ACCOUNT_KEY_NAME: string; + BLOB_ENDPOINT_NAME: string; + FILE_ENDPOINT_NAME: string; + QUEUE_ENDPOINT_NAME: string; + TABLE_ENDPOINT_NAME: string; + SHARED_ACCESS_SIGNATURE_NAME: string; + BLOB_BASE_DNS_NAME: string; + FILE_BASE_DNS_NAME: string; + QUEUE_BASE_DNS_NAME: string; + TABLE_BASE_DNS_NAME: string; + }; + + } + + // ########################### + // ./common/util/storageutilities + // ########################### + module storageutilities { + /** + * Defines constants, enums, and utility functions for use with storage. + * @namespace StorageUtilities + */ + /** + * Specifies the location mode used to decide which location the request should be sent to. + * + * @const + * @enum {number} + * @alias StorageUtilities.LocationMode + */ + export enum LocationMode { + /** + * The primary location only + * @property LocationMode.PRIMARY_ONLY + */ + PRIMARY_ONLY = 0, + /** + * The primary location first, then the secondary + * @property LocationMode.PRIMARY_THEN_SECONDARY + */ + PRIMARY_THEN_SECONDARY = 1, + /** + * The secondary location only + * @property LocationMode.SECONDARY_ONLY + */ + SECONDARY_ONLY = 2, + /** + * The secondary location first, then the primary + * @property LocationMode.SECONDARY_THEN_PRIMARY + */ + SECONDARY_THEN_PRIMARY = 3, + } + } + + // ########################### + // ./common/util/accesscondition + // ########################### + module accesscondition { + /** + * Constructs an empty access condition. + * + * @return {AccessConditions} An empty AccessConditions object + */ + export function generateEmptyCondition() : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource does not exist on the service + * + * Setting this access condition modifies the request to include the HTTP If-None-Match conditional header + + * @return {AccessConditions} An AccessConditions object that represents a condition that checks for nonexistence + */ + export function generateIfNotExistsCondition(): AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource exists on the service + * + * Setting this access condition modifies the request to include the HTTP If-Match conditional header + + * @return {AccessConditions} An AccessConditions object that represents a condition that checks for existence + */ + export function generateIfExistsCondition(): AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource's ETag value + * does not match the specified ETag value + * + * Setting this access condition modifies the request to include the HTTP If-None-Match conditional header + * + * @param {string} etag The ETag value to check against the resource's ETag + * @return {AccessConditions} An AccessConditions object that represents the If-None-Match condition + */ + export function generateIfNoneMatchCondition(etag: string) : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource's ETag value + * matches the specified ETag value + * + * Setting this access condition modifies the request to include the HTTP If-Match conditional header + * + * @param {string} etag The ETag value to check against the resource's ETag + * @return {AccessConditions} An AccessConditions object that represents the If-Match condition + */ + export function generateIfMatchCondition(etag: string) : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource has been + * modified since the specified time + * + * Setting this access condition modifies the request to include the HTTP If-Modified-Since conditional header + * + * @param {Date|string} time A date object specifying the time since which the resource must have been modified + * @return {AccessConditions} An AccessConditions object that represents the If-Modified-Since condition + */ + export function generateIfModifiedSinceCondition(time: Date|string) : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource has not been + * modified since the specified time + * + * Setting this access condition modifies the request to include the HTTP If-Unmodified-Since conditional header + * + * @param {Date|string} time A date object specifying the time since which the resource must have not been modified + * @return {AccessConditions} An AccessConditions object that represents the If-Unmodified-Since condition + */ + export function generateIfNotModifiedSinceCondition(time: Date|string) : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource's sequence number + * is equal to the specified value + * + * Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-eq conditional header + * + * @param {Number|string} sequenceNumber A date object specifying the time since which the resource must have not been modified + * @return {AccessConditions} An AccessConditions object that represents the If-Unmodified-Since condition + */ + export function generateSequenceNumberEqualCondition(sequenceNumber: Number|string) : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource's sequence number + * is less than the specified value + * + * Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-lt conditional header + * + * @param {Number|string} sequenceNumber A date object specifying the time since which the resource must have not been modified + * @return {AccessConditions} An AccessConditions object that represents the If-Unmodified-Since condition + */ + export function generateSequenceNumberLessThanCondition(sequenceNumber: Number|string) : AccessConditions; + + /** + * Constructs an access condition such that an operation will be performed only if the resource's sequence number + * is less than or equal to the specified value + * + * Setting this access condition modifies the request to include the HTTP x-ms-if-sequence-number-le conditional header + * + * @param {Number|string} sequenceNumber A date object specifying the time since which the resource must have not been modified + * @return {AccessConditions} An AccessConditions object that represents the If-Unmodified-Since condition + */ + export function generateSequenceNumberLessThanOrEqualCondition(sequenceNumber: Number|string) : AccessConditions; + } + + // ########################### + // ./common/util/sr + // ########################### + module sr { + export var SR: { + ANONYMOUS_ACCESS_BLOBSERVICE_ONLY: string; + ARGUMENT_NULL_OR_EMPTY: string; + ARGUMENT_NULL_OR_UNDEFINED: string; + ARGUMENT_OUT_OF_RANGE_ERROR: string; + BATCH_ONE_PARTITION_KEY: string; + BATCH_ONE_RETRIEVE: string; + BATCH_TOO_LARGE: string; + HASH_MISMATCH: string; + BLOB_INVALID_SEQUENCE_NUMBER: string; + BLOB_TYPE_MISMATCH: string; + CONTENT_LENGTH_MISMATCH: string; + INVALID_DELETE_SNAPSHOT_OPTION: string; + CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY: string; + CONTENT_TYPE_MISSING: string; + EMPTY_BATCH: string; + EXCEEDED_SIZE_LIMITATION: string; + INCORRECT_ENTITY_KEYS: string; + INVALID_BLOB_LENGTH: string; + INVALID_FILE_LENGTH: string; + INVALID_CONNECTION_STRING: string; + INVALID_CONNECTION_STRING_BAD_KEY: string; + INVALID_CONNECTION_STRING_DUPLICATE_KEY: string; + INVALID_CONNECTION_STRING_EMPTY_KEY: string; + INVALID_EDM_TYPE: string; + INVALID_HEADERS: string; + INVALID_MESSAGE_ID: string; + INVALID_PAGE_BLOB_LENGTH: string; + INVALID_PAGE_END_OFFSET: string; + INVALID_PAGE_START_OFFSET: string; + INVALID_FILE_RANGE_FOR_UPDATE: string; + INVALID_PAGE_RANGE_FOR_UPDATE: string; + INVALID_POP_RECEIPT: string; + INVALID_PROPERTY_RESOLVER: string; + INVALID_RANGE_FOR_MD5: string; + INVALID_SAS_VERSION: string; + INVALID_SIGNED_IDENTIFIERS: string; + INVALID_STREAM_LENGTH: string; + INVALID_STRING_ERROR: string; + INVALID_TEXT_LENGTH: string; + QUERY_OPERATOR_REQUIRES_WHERE: string; + MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION: string; + MD5_NOT_PRESENT_ERROR: string; + METADATA_KEY_INVALID: string; + METADATA_VALUE_INVALID: string; + NO_CREDENTIALS_PROVIDED: string; + INVALID_TABLE_OPERATION: string; + PRIMARY_ONLY_COMMAND: string; + SECONDARY_ONLY_COMMAND: string; + STORAGE_HOST_LOCATION_REQUIRED: string; + STORAGE_HOST_MISSING_LOCATION: string; + TYPE_NOT_SUPPORTED: string; + NO_LIST_FUNC_PROVIDED: string; + }; + } + + // ########################### + // ./common/util/validate + // ########################### + module validate { + /** + * Checks if the given value is a valid enumeration or not. + * + * @param {Object} value The value to validate. + * @param {Object} list The enumeration values. + * @return {boolean} + */ + export function isValidEnumValue(value: string, list: string[], callback: Function): boolean; + /** + * Creates a anonymous function that check if the given uri is valid or not. + * + * @param {string} uri The uri to validate. + * @return {boolean} + */ + export function isValidUri(uri: string): boolean; + /** + * Checks if the given host is valid or not. + * + * @param {string|object} host The host to validate. + * @return {boolean} + */ + export function isValidHost(host: string): boolean; + export function isValidHost(host: StorageHost): boolean; + /** + * Checks if the given value is a valid UUID or not. + * + * @param {string|object} uuid The uuid to validate. + * @return {boolean} + */ + export function isValidUuid(uuid: string, callback?: Function): boolean; + /** + * Creates a anonymous function that check if a given key is base 64 encoded. + * + * @param {string} key The key to validate. + * @return {boolean} + */ + export function isBase64Encoded(key: string): boolean; + /** + * Validates a function. + * + * @param {Object} function The function to validate. + * @return {boolean} + */ + export function isValidFunction(functionObject: any, functionName: string): boolean; + /** + * Validates a container name. + * + * @param {string} containerName The container name. + */ + export function containerNameIsValid(containerName: string, callback?: Function): boolean; + /** + * Validates a blob name. + * + * @param {string} containerName The container name. + * @param {string} blobname The blob name. + */ + export function blobNameIsValid(containerName: string, blobName: string, callback?: Function): boolean; + /** + * Validates a share name. + * + * @param {string} shareName The share name. + */ + export function shareNameIsValid(shareName: string, callback?: Function): boolean; + /** + * Validates a queue name. + * + * @param {string} queueName The queue name. + */ + export function queueNameIsValid(queueName: string, callback?: Function): boolean; + /** + * Validates a table name. + * + * @param {string} table The table name. + */ + export function tableNameIsValid(table: string, callback?: Function): boolean; + /** + * Validates page ranges. + * + * @param {int} rangeStart The range starting position. + * @param {int} rangeEnd The range ending position. + * @param {int} writeBlockSizeInBytes The block size. + */ + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback?: Function): boolean; + /** + * Validates a blob type. + * + * @param {string} type The type name. + */ + export function blobTypeIsValid(type: string, callback?: Function): boolean; + export class ArgumentValidator { + func: string; + tableNameIsValid: (tableName: string, callback?: Function) => boolean; + containerNameIsValid: (containerName: string, callback?: Function) => boolean; + shareNameIsValid: (shareName: string, callback?: Function) => boolean; + blobNameIsValid: (containerName: string, blobName: string, callback?: Function) => boolean; + pageRangesAreValid: (rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback?: Function) => boolean; + queueNameIsValid: (queueName: string, callback?: Function) => boolean; + blobTypeIsValid: (shareName: string, callback?: Function) => boolean; + isValidEnumValue: (value: string, list: string[], callback?: Function) => boolean; + constructor(functionName: string); + string(val: any, name: string): void; + stringAllowEmpty(val: any, name: string): void; + object(val: any, name: string): void; + exists(val: any, name: string): void; + function(val: any, name: string): void; + value(val: any, name: string): void; + nonEmptyArray(val: T[], name: string): void; + callback(val: any): void; + test(predicate: () => boolean, message: string): void; + } + export function validateArgs(functionName: string, validationRules: (validator: ArgumentValidator) => void): void; + } + + // ########################### + // ./common/util/date + // ########################### + module date { + /** + * Date/time related helper functions + * @module date + * + */ + /** + * Generates a Date object which is in the given days from now. + * + * @param {int} days The days timespan. + * @return {Date} + */ + export function daysFromNow(days: number): Date; + /** + * Generates a Date object which is in the given hours from now. + * + * @param {int} hours The hours timespan. + * @return {Date} + */ + export function hoursFromNow(hours: number): Date; + /** + * Generates a Date object which is in the given minutes from now. + * + * @param {int} minutes The minutes timespan. + * @return {Date} + */ + export function minutesFromNow(minutes: number): Date; + /** + * Generates a Date object which is in the given seconds from now. + * + * @param {int} seconds The seconds timespan. + * @return {Date} + */ + export function secondsFromNow(seconds: number): Date; + + } + } + + module http { + // ########################### + // ./common/http/webresource + // ########################### + module webresource { + export class WebResource { + rawResponse: boolean; + queryString: any; + path: string; + method: string; + properties: Map; + body: any; + headersOnly: boolean; + uri: string; + headers: Map; + /** + * Creates a new WebResource object. + */ + constructor(); + /** + * Creates a new put request web resource. + * + * @function WebResource#put + * @static + * @param {string} path The path for the put operation. + * @return {WebResource} A new webresource with a put operation for the given path. + */ + static put(path?: string): WebResource; + /** + * Creates a new get request web resource. + * + * @function WebResource#get + * @static + * @param {string} path The path for the get operation. + * @return {WebResource} A new webresource with a get operation for the given path. + */ + static get(path?: string): WebResource; + /** + * Creates a new head request web resource. + * + * @function WebResource#head + * @static + * @param {string} path The path for the head operation. + * @return {WebResource} A new webresource with a head operation for the given path. + */ + static head(path: string): WebResource; + /** + * Creates a new delete request web resource. + * + * @function WebResource#del + * @static + * @param {string} path The path for the delete operation. + * @return {WebResource} A new webresource with a delete operation for the given path. + */ + static del(path: string): WebResource; + /** + * Creates a new post request web resource. + * + * @function WebResource#post + * @static + * @param {string} path The path for the post operation. + * @return {WebResource} A new webresource with a post operation for the given path. + */ + static post(path: string): WebResource; + /** + * Creates a new merge request web resource. + * + * @function WebResource#merge + * @static + * @param {string} path The path for the merge operation. + * @return {WebResource} A new webresource with a merge operation for the given path. + */ + static merge(path: string): WebResource; + /** + * Specifies a custom property in the web resource. + * + * @function WebResource#withProperty + * @param {string} name The property name. + * @param {string} value The property value. + * @return {WebResource} The webresource. + */ + withProperty(name: string, value: string): WebResource; + /** + * Specifies if the response should be parsed or not. + * + * @function WebResource#withRawResponse + * @param {bool} [rawResponse=true] true if the response should not be parsed; false otherwise. + * @return {WebResource} The webresource. + */ + withRawResponse(rawResponse?: boolean): WebResource; + /** + * Specifies if the request only has headers. + * + * @function WebResource#withHeadersOnly + * @param {bool} [headersOnly=true] true if the request only has headers; false otherwise. + * @return {WebResource} The webresource. + */ + withHeadersOnly(headersOnly?: boolean): WebResource; + /** + * Adds an optional query string parameter. + * + * @function WebResource#withQueryOption + * @param {Object} name The name of the query string parameter. + * @param {Object} value The value of the query string parameter. + * @param {Object} defaultValue The default value for the query string parameter to be used if no value is passed. + * @return {Object} The web resource. + */ + withQueryOption(name: any, value: T, defaultValue?: T): WebResource; + /** + * Adds optional query string parameters. + * + * Additional arguments will be the needles to search in the haystack. + * + * @function WebResource#withQueryOptions + * @param {Object} object The haystack of query string parameters. + * @return {Object} The web resource. + */ + withQueryOptions(object: any, ...queryArgs: any[]): WebResource; + /** + * Adds an optional header parameter. + * + * @function WebResource#withHeader + * @param {Object} name The name of the header parameter. + * @param {Object} value The value of the header parameter. + * @return {Object} The web resource. + */ + withHeader(name: string, value: T): WebResource; + /** + * Adds an optional body. + * + * @function WebResource#withBody + * @param {Object} body The request body. + * @return {Object} The web resource. + */ + withBody(body: any): WebResource; + /** + * Adds optional query string parameters. + * + * Additional arguments will be the needles to search in the haystack. + * + * @function WebResource#withHeaders + * @param {Object} object The haystack of headers. + * @return {Object} The web resource. + withHeaders(object: { + [x: string]: any; + }, ...args: string[]): WebResource; + addOptionalMetadataHeaders(metadata: any): WebResource; + /** + * Determines if a status code corresponds to a valid response according to the WebResource's expected status codes. + * + * @function WebResource#validResponse + * @static + * @param {int} statusCode The response status code. + * @return true if the response is valid; false otherwise. + */ + static validResponse(statusCode: number): boolean; + /** + * Hook up the given input stream to a destination output stream if the WebResource method + * requires a request body and a body is not already set. + * + * @function WebResource#pipeInput + * @param {Stream} inputStream the stream to pipe from + * @param {Stream} outputStream the stream to pipe to + * + * @return destStream + */ + pipeInput(inputStream: NodeJS.ReadableStream, destStream: NodeJS.WritableStream): NodeJS.WritableStream; + } + } + } + + module diagnostics { + // ########################### + // ./common/loggerdiagnostics/logger + // ########################### + module logger { + export class Logger { + level: string; + loggerFunction: (level: string, message: string) => void; + constructor(level: any, loggerFunction?: (level: string, message: string) => void); + static LogLevels: { + EMERGENCY: string; + ALERT: string; + CRITICAL: string; + ERROR: string; + WARNING: string; + NOTICE: string; + INFO: string; + DEBUG: string; + }; + log(level: any, msg: any): void; + emergency(msg: any): void; + critical(msg: any): void; + alert(msg: any): void; + error(msg: any): void; + warn(msg: any): void; + notice(msg: any): void; + info(msg: any): void; + debug(msg: any): void; + defaultLoggerFunction(logLevel: string, msg: string): void; + } + } + } + + module streams { + // ########################### + // ./common/util/speedsummary + // ########################### + module speedsummary { + export interface SpeedSummary { + name: string; + totalSize: number; + completeSize: number; + /** + * Get running seconds + */ + getElapsedSeconds(humanReadable: boolean): number; + /** + * Get complete percentage + * @param {int} len The number of digits after the decimal point. + */ + getCompletePercent(len: number): number; + /** + * Get average upload/download speed + */ + getAverageSpeed(humanReadable: boolean): string; + /** + * Get instant speed + */ + getSpeed(humanReadable: boolean): string | number; + /** + * Increment the complete data size + */ + increment(len: number): number; + /** + * Get auto increment function + */ + getAutoIncrementFunction(size: number): (error: any, retValue: number) => void; + /** + * Get total size + */ + getTotalSize(humanReadable: boolean): string | number; + /** + * Get completed data size + */ + getCompleteSize(humanReadable: boolean): string | number; + } + } + } + + module models { + export interface ServiceStats { + GeoReplication?: { + Status?: string; + LastSyncTime?: Date; + }; + } + + module ServicePropertiesResult { + export interface RetentionPolicy { + Enabled: boolean; + Days: number; + } + export interface MetricsProperties { + Version: string; + Enabled: boolean; + IncludeAPIs: boolean; + RetentionPolicy: RetentionPolicy; + } + export interface CorsRule { + AllowedMethods: string[]; + AllowedOrigins: string[]; + AllowedHeaders: string[]; + ExposedHeaders: string[]; + MaxAgeInSeconds: number; + } + export interface LoggingProperties { + Version: string; + Delete: boolean; + Read: boolean; + Write: boolean; + RetentionPolicy: RetentionPolicy; + } + export interface DeleteRetentionPolicyProperties { + Enabled: boolean; + Days?: number; + } + export interface ServiceProperties { + DefaultServiceVersion?: string; + Logging?: LoggingProperties; + DeleteRetentionPolicy?: DeleteRetentionPolicyProperties; + HourMetrics?: MetricsProperties; + MinuteMetrics?: MetricsProperties; + Cors?: { + CorsRule: CorsRule[]; + }; + } + export function serialize(servicePropertiesJs: ServiceProperties): string; + export function parse(servicePropertiesXml: any): ServiceProperties; + } + } + + module services { + // ########################### + // ./common/services/storageserviceclient + // ########################### + module storageserviceclient { + export interface Proxy { + host: string; + port: number; + proxyAuth: string; + headers: Map; + key: string; + ca: string; + cert: string; + } + + export class StorageServiceClient extends events.EventEmitter { + /** + * The default location mode for requests made via the service. + * @member {StorageUtilities.LocationMode} StorageServiceClient#defaultLocationMode + */ + defaultLocationMode: common.util.storageutilities.LocationMode; + /** + * The default maximum execution time across all potential retries, for requests made via the service. + * @member {int} StorageServiceClient#defaultMaximumExecutionTimeInMs + */ + defaultMaximumExecutionTimeInMs: number; + /** + * The default timeout interval, in milliseconds, to use for request made via the service. + * @member {int} StorageServiceClient#defaultTimeoutIntervalInMs + */ + defaultTimeoutIntervalInMs: number; + /** + * The default timeout of client requests, in milliseconds, to use for the request. + * @member {int} StorageServiceClient#defaultClientRequestTimeoutInMs + */ + defaultClientRequestTimeoutInMs: number; + /** + * Determines whether the Nagle algorithm is used for requests made via the Queue service; true to use the + * Nagle algorithm; otherwise, false. The default value is false. + * @member {bool} StorageServiceClient#useNagleAlgorithm + */ + useNagleAlgorithm: boolean; + /** The proxy object specified by caller. + * @member {Proxy} StorageServiceClient#proxy + */ + proxy: Proxy; + /** The logging settings object. + * @member {diagnostics.logger.Logger} StorageServiceClient#logger + */ + logger: diagnostics.logger.Logger; + + /** + * Creates a new StorageServiceClient object. + * + * @constructor StorageServiceClient + * @param {string} storageAccount The storage account. + * @param {string} storageAccessKey The storage access key. + * @param {Object} host The host for the service. + * @param {bool} usePathStyleUri Boolean value indicating wether to use path style uris. + * @param {string} sasToken The Shared Access Signature token. + */ + constructor(storageAccount?: string, storageAccessKey?: string, host?: StorageHost, usePathStyleUri?: boolean, sasToken?: string); + /** + * Associate a filtering operation with this StorageServiceClient. Filtering operations + * can include logging, automatically retrying, etc. Filter operations are objects + * that implement a method with the signature: + * + * "function handle (requestOptions, next)". + * + * After doing its preprocessing on the request options, the method needs to call + * "next" passing a callback with the following signature: + * signature: + * + * "function (returnObject, finalCallback, next)" + * + * In this callback, and after processing the returnObject (the response from the + * request to the server), the callback needs to either invoke next if it exists to + * continue processing other filters or simply invoke finalCallback otherwise to end + * up the service invocation. + * + * @function StorageServiceClient#withFilter + * @param {Object} filter The new filter object. + * @return {StorageServiceClient} A new service client with the filter applied. + */ + withFilter(newFilter: common.filters.IFilter): StorageServiceClient; + /** + * Sets proxy object specified by caller. + * + * @function StorageServiceClient#setProxy + * @param {(object|string)} proxy proxy to use for tunneling + * { + * host: hostname + * port: port number + * proxyAuth: 'user:password' for basic auth + * headers: {...} headers for proxy server + * key: key for proxy server + * ca: ca for proxy server + * cert: cert for proxy server + * } + * if null or undefined, clears proxy + */ + setProxy(proxy: Proxy): void; + } + } + } + + export interface AccessPolicy { + /** The permission type. */ + Permissions: string; + /** The time at which the Shared Access Signature becomes valid. */ + Start?: Date | string; + /** The time at which the Shared Access Signature becomes expired. */ + Expiry?: Date | string; + /** An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive. */ + IPAddressOrRange?: string; + /** The protocol permitted for a request made with the SAS. */ + Protocols?: string; + /** The services (blob, file, queue, table) for a shared access signature associated with this shared access policy. */ + Services?: string; + /** The resource type for a shared access signature associated with this shared access policy. */ + ResourceTypes?: string; + } + + export interface SharedAccessPolicy { + /** The signed identifier. */ + Id?: string; + /** The Access Policy information */ + AccessPolicy: AccessPolicy; + } + + export interface ContentSettingsHeaders { + cacheControl?: string; + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentDisposition?: string; + } + + /** + * Common request options for azure storage services + */ + export interface RequestOptions { + /** + * {LocationMode} Specifies the location mode used to decide which location the request should be sent to. + */ + locationMode?: StorageUtilities.LocationMode; + /** + * {int} The server timeout interval, in milliseconds, to use for the request. + */ + timeoutIntervalInMs?: number; + /** + * {int} The timeout of client requests, in milliseconds, to use for the request. + */ + clientRequestTimeoutInMs?: number; + + /** + * {int} The maximum execution time, in milliseconds, across all potential retries, to use when making this request. + */ + maximumExecutionTimeInMs?: number; + /** + * {bool} Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false. + */ + useNagleAlgorithm?: boolean; + /** + * {string} A string that represents the client request ID with a 1KB character limit. + */ + clientRequestId?: string; + } + + export interface ContinuationToken { + nextMarker: string; + targetLocation?: Constants.StorageLocation; + } + + export interface Range { + start?: number; + end?: number; + } + + export interface RangeDiff { + start?: number; + end?: number; + isCleared?: boolean + } + } + + /** + * Creates a connection string that can be used to create a service which runs on the storage emulator. The emulator must be downloaded separately. + * + * @param {string} [proxyUri] The proxyUri. By default, http://127.0.0.1 + * @return {string} A connection string representing the development storage credentials. + * @example + * var azure = require('azure-storage'); + * var devStoreCreds = azure.generateDevelopmentStorageCredentials(); + * var blobService = azure.createBlobService(devStoreCreds); + */ + export function generateDevelopmentStorageCredentials(proxyUri?: string): string; + + /** + * Table client exports + * @ignore + */ + export import TableService = services.table.TableService; + export import TableQuery = services.table.TableQuery; + export import TableBatch = services.table.TableBatch; + export import TableUtilities = services.table.TableUtilities; + + /** + * Creates a new {@link TableService} object. + * If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY + * environment variables will be used. + * + * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @return {TableService} A new TableService object. + * + */ + export function createTableService(): TableService; + export function createTableService(connectionString: string): TableService; + export function createTableService(storageAccountOrConnectionString: string, storageAccessKey: string, host?: StorageHost): TableService; + + /** + * Creates a new {@link TableService} object using the host Uri and the SAS credentials provided. + * + * @param {string|object} host The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} sasToken The Shared Access Signature token. + * @return {TableService} A new TableService object with the SAS credentials. + */ + export function createTableServiceWithSas(hostUri: string | StorageHost, sasToken: string): TableService; + + /** + * Blob client exports + * @ignore + */ + export import BlobService = services.blob.blobservice.BlobService; + export import BlobUtilities = services.blob.blobutilities.BlobUtilities; + + /** + * Creates a new {@link BlobService} object. + * If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY + * environment variables will be used. + * + * @param {string} storageAccountOrConnectionString The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @return {BlobService} A new BlobService object. + */ + export function createBlobService(storageAccount: string, storageAccessKey: string, host?: string|StorageHost): BlobService; + export function createBlobService(connectionString: string): BlobService; + export function createBlobService(): BlobService; + /** + * Creates a new {@link BlobService} object using the host Uri and the SAS credentials provided. + * + * @param {string|object} host The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} sasToken The Shared Access Signature token. + * @return {BlobService} A new BlobService object with the SAS credentials. + */ + export function createBlobServiceWithSas(host: string|StorageHost, sasToken: string): BlobService; + + /** + * Creates a new {@link BlobService} object using the host uri and anonymous access. + * + * @param {string|object} host The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @return {BlobService} A new BlobService object with the anonymous credentials. + */ + export function createBlobServiceAnonymous(host?: string|StorageHost): BlobService; + + ///** + // * File client exports + // * @ignore + // */ + export import FileService = services.file.FileService; + export import FileUtilities = services.file.FileUtilities; + + ///** + //* Creates a new {@link FileService} object. + //* If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY + //* environment variables will be used. + //* + //* @param {string} storageAccountOrConnectionString The storage account or the connection string. + //* @param {string} [storageAccessKey] The storage access key. + //* @param {string|object} [host] The host address. To define primary only, pass a string. + //* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + //* @return {FileService} A new FileService object. + //*/ + export function createFileService(storageAccount: string, storageAccessKey: string, host?: string | StorageHost): FileService; + export function createFileService(connectionString: string): FileService; + export function createFileService(): FileService; + + /** + * Creates a new {@link FileService} object using the host Uri and the SAS credentials provided. + * + * @param {string|object} host The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} sasToken The Shared Access Signature token. + * @return {FileService} A new FileService object with the SAS credentials. + */ + export function createFileServiceWithSas(hostUri: string | StorageHost, sasToken: string): FileService; + + /** + * Queue client exports + * @ignore + */ + export import QueueService = services.queue.QueueService; + export import QueueMessageEncoder = services.queue.QueueMessageEncoder; + export import QueueUtilities = services.queue.QueueUtilities; + + /** + * Creates a new {@link QueueService} object. + * If no storageaccount or storageaccesskey are provided, the AZURE_STORAGE_CONNECTION_STRING and then the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY + * environment variables will be used. + * + * @param {string} [storageAccountOrConnectionString] The storage account or the connection string. + * @param {string} [storageAccessKey] The storage access key. + * @param {string|object} [host] The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @return {QueueService} A new QueueService object. + */ + export function createQueueService(storageAccount: string, storageAccessKey: string, host?: string | StorageHost): QueueService; + export function createQueueService(connectionString: string): QueueService; + export function createQueueService(): QueueService; + + /** + * Creates a new {@link QueueService} object using the host Uri and the SAS credentials provided. + * + * @param {string|object} host The host address. To define primary only, pass a string. + * Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host. + * @param {string} sasToken The Shared Access Signature token. + * @return {QueueService} A new QueueService object with the SAS credentials. + */ + export function createQueueServiceWithSas(hostUri: string | StorageHost, sasToken: string): QueueService; + + export function generateAccountSharedAccessSignature(storageAccountOrConnectionString: string, storageAccessKey: string, sharedAccessAccountPolicy: common.SharedAccessPolicy): string; + + interface StorageError extends Error { + statusCode?: number; + requestId?: string; + code?: string; + } + + interface ServiceResponse { + isSuccessful: boolean; + statusCode: number; + body?: string | Buffer; + headers?: Map; + md5: string; + error?: StorageError | Error; + requestServerEncrypted?: boolean; + } + + interface ServiceResult { + error: StorageError | Error; + response: ServiceResponse; + contentMD5: string; + length?: number; + operationEndTime: Date; + targetLocation: Constants.StorageLocation; + } + + /** + * A callback that returns a response object. + * @callback errorOrResponse + * @param {Object} error If an error occurs, will contain information about the error. + * @param {Object} response Contains information about the response returned for the operation. + * For example, HTTP status codes and headers. + */ + interface ErrorOrResponse { + (error: Error, response: ServiceResponse): void + } + /** + * A callback that returns result and response objects. + * @callback errorOrResult + * @param {Object} error If an error occurs, will contain information about the error. + * @param {Object} result The result of the operation. + * @param {Object} response Contains information about the response returned for the operation. + * For example, HTTP status codes and headers. + */ + interface ErrorOrResult { + (error: Error, result: TResult, response: ServiceResponse): void + } + /** + * Specifying conditional headers for blob service operations. See http://msdn.microsoft.com/en-us/library/dd179371.aspx for more information. + * @typedef {Object} AccessConditions + * @property {string} EtagMatch If the ETag for the blob matches the specified ETag. + * Specify the wildcard character (*) to perform the operation only if the resource does exist, and fail the operation if it does not exist. + * @property {string} EtagNonMatch If the ETag for the blob does not match the specified ETag. + * Specify the wildcard character (*) to perform the operation only if the resource does not exist, and fail the operation if it does exist. + * @property {Date|string} DateModifedSince If the blob has been modified since the specified date. + * @property {Date|string} DateUnModifiedSince If the blob has not been modified since the specified date. + * @property {Number|string} SequenceNumberLessThanOrEqual If the blob’s sequence number is less than or equal to the specified value. + * For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information. + * @property {Number|string} SequenceNumberLessThan If the blob’s sequence number is less than the specified value. + * For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information. + * @property {Number|string} SequenceNumberEqual If the blob’s sequence number is equal to the specified value. + * For Put Page operation only. See https://msdn.microsoft.com/en-us/library/azure/ee691975.aspx for more information. + * @property {Number|string} MaxBlobSize If the Append Block operation would cause the blob to exceed that limit or if the blob size is already greater than the specified value. + * For Append Block operation only. See https://msdn.microsoft.com/en-us/library/mt427365.aspx for more information. + * @property {Number|string} MaxAppendPosition If the append position is equal to the specified value. + * For Append Block operation only. See https://msdn.microsoft.com/en-us/library/mt427365.aspx for more information. + */ + export interface AccessConditions { + EtagMatch?: string; + EtagNonMatch?: string; + DateModifedSince?: Date | string; + DateUnModifiedSince?: Date | string; + SequenceNumberLessThanOrEqual?: Number | string; + SequenceNumberLessThan?: Number | string; + SequenceNumberEqual?: Number | string; + MaxBlobSize?: Number | string; + MaxAppendPosition?: Number | string; + } + + export import Constants = common.util.constants; + export import StorageUtilities = common.util.storageutilities; + export import AccessCondition = common.util.accesscondition; + export import SR = common.util.sr.SR; + export import StorageServiceClient = common.services.storageserviceclient.StorageServiceClient; + export import Logger = common.diagnostics.logger.Logger; + export import WebResource = common.http.webresource.WebResource; + export import Validate = common.util.validate; + export import date = common.util.date; + export import LinearRetryPolicyFilter = common.filters.linearretrypolicyfilter.LinearRetryPolicyFilter; + export import ExponentialRetryPolicyFilter = common.filters.exponentialretrypolicyfilter.ExponentialRetryPolicyFilter; + export import RetryPolicyFilter = common.filters.retrypolicyfilter.RetryPolicyFilter; +} + +export = azurestorage; diff --git a/node_modules/azure-storage/typings/globals/node/index.d.ts b/node_modules/azure-storage/typings/globals/node/index.d.ts new file mode 100644 index 000000000..af29a7118 --- /dev/null +++ b/node_modules/azure-storage/typings/globals/node/index.d.ts @@ -0,0 +1,1440 @@ +// Generated by typings +// Source: https://raw.githubusercontent.com/types/env-node/959285e4da295481cf634f7d11f6ccccc863e430/0.10/node.d.ts +declare var process: NodeJS.Process; +declare var global: any; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve (id: string): string; + cache: { [filename: string]: NodeModule }; + extensions: { [ext: string]: (m: NodeModule, filename: string) => any }; + main: any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + parent: NodeModule; + loaded: boolean; + children: NodeModule[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + +// Console class (compatible with TypeScript `lib.d.ts`). +declare interface Console { + log (msg: any, ...params: any[]): void; + info (msg: any, ...params: any[]): void; + warn (msg: any, ...params: any[]): void; + error (msg: any, ...params: any[]): void; + dir (value: any, ...params: any[]): void; + time (timerName?: string): void; + timeEnd (timerName?: string): void; + trace (msg: any, ...params: any[]): void; + assert (test?: boolean, msg?: string, ...params: any[]): void; + + Console: new (stdout: NodeJS.WritableStream) => Console; +} + +declare var console: Console; + +// Buffer class +interface Buffer extends NodeBuffer {} +declare var Buffer: { + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + +/************************************************ +* * +* GLOBAL INTERFACES * +* * +************************************************/ +declare namespace NodeJS { + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export interface EventEmitter { + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream {} + + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + /** + * The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent. + */ + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: { + PATH: string; + [key: string]: string; + }; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid:number, signal?: string|number): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?:number[]): number[]; + + // Worker + send?(message: any, sendHandle?: any): void; + } + + export interface Timer { + ref() : void; + unref() : void; + } +} + +/** + * @deprecated + */ +interface NodeBuffer { + [index: number]: number; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + length: number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + 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; + writeUInt8(value: number, offset: number, noAssert?: boolean): void; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeInt8(value: number, offset: number, noAssert?: boolean): void; + writeInt16LE(value: number, offset: number, noAssert?: boolean): void; + writeInt16BE(value: number, offset: number, noAssert?: boolean): void; + writeInt32LE(value: number, offset: number, noAssert?: boolean): void; + writeInt32BE(value: number, offset: number, noAssert?: boolean): void; + writeFloatLE(value: number, offset: number, noAssert?: boolean): void; + writeFloatBE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; + fill(value: any, offset?: number, end?: number): void; +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; +} + +declare module "querystring" { + export function stringify(obj: any, sep?: string, eq?: string): string; + export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export function escape(): any; + export function unescape(): any; +} + +declare module "events" { + export class EventEmitter implements NodeJS.EventEmitter { + static listenerCount(emitter: EventEmitter, event: string): number; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + +declare module "http" { + import events = require("events"); + import net = require("net"); + import stream = require("stream"); + + export interface OutgoingHeaders { + [header: string]: number | string | string[]; + } + + export interface IncomingHeaders { + [header: string]: string | string[]; + } + + export interface Server extends events.EventEmitter { + listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; + listen(path: string, callback?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(cb?: any): Server; + address(): { port: number; family: string; address: string; }; + maxHeadersCount: number; + } + + export interface IncomingMessage extends events.EventEmitter, stream.Readable { + httpVersion: string; + headers: IncomingHeaders; + rawHeaders: string[]; + trailers: IncomingHeaders; + rawTrailers: string[]; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + } + + export interface ServerResponse extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, statusText?: string, headers?: OutgoingHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHeaders): void; + statusCode: number; + setHeader(name: string, value: string): void; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: OutgoingHeaders): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + /** + * Object returned by http.request() + */ + export interface ClientRequest extends events.EventEmitter, NodeJS.WritableStream { + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } + + export class Agent { + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + /** + * Options for http.request() + */ + export interface RequestOptions { + /** + * A domain name or IP address of the server to issue the request to. Defaults to 'localhost'. + */ + host?: string; + /** + * To support url.parse() hostname is preferred over host + */ + hostname?: string; + /** + * Port of remote server. Defaults to 80. + */ + port?: number | string; + /** + * Local interface to bind for network connections. + */ + localAddress?: string; + /** + * Unix Domain Socket (use one of host:port or socketPath) + */ + socketPath?: string; + /** + * A string specifying the HTTP request method. Defaults to 'GET'. + */ + method?: string; + /** + * Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12' + */ + path?: string; + /** + * An object containing request headers. + */ + headers?: OutgoingHeaders; + /** + * Basic authentication i.e. 'user:password' to compute an Authorization header. + */ + auth?: string; + /** + * Controls Agent behavior. When an Agent is used request will default to Connection: keep-alive. Possible values: + * - undefined (default): use global Agent for this host and port. + * - Agent object: explicitly use the passed in Agent. + * - false: opts out of connection pooling with an Agent, defaults request to Connection: close. + */ + agent?: Agent | boolean; + } + + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: string | RequestOptions, callback?: (response: IncomingMessage) => void): ClientRequest; + export function get(options: string | RequestOptions, callback?: (response: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; +} +declare module "cluster" { + import child = require("child_process"); + import events = require("events"); + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + } + + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: Worker[]; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; +} + +declare module "zlib" { + import stream = require("stream"); + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + export interface ZlibCallback { (error: Error, result: any): void } + + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: Buffer | string, callback: ZlibCallback): void; + export function deflateRaw(buf: Buffer | string, callback: ZlibCallback): void; + export function gzip(buf: Buffer | string, callback: ZlibCallback): void; + export function gunzip(buf: Buffer | string, callback: ZlibCallback): void; + export function inflate(buf: Buffer | string, callback: ZlibCallback): void; + export function inflateRaw(buf: Buffer | string, callback: ZlibCallback): void; + export function unzip(buf: Buffer | string, callback: ZlibCallback): void; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; +} + +declare module "os" { + export function tmpdir(): string; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; + export function networkInterfaces(): any; + export var EOL: string; +} + +declare module "https" { + import tls = require("tls"); + import events = require("events"); + import http = require("http"); + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } + + export interface RequestOptions extends http.RequestOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer | Array; + ciphers?: string; + rejectUnauthorized?: boolean; + } + + export interface Agent { + maxSockets: number; + sockets: any; + requests: any; + } + + export var Agent: { + new (options?: RequestOptions): Agent; + }; + + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: string | RequestOptions, callback?: (res: http.IncomingMessage) =>void): http.ClientRequest; + export function get(options: string | RequestOptions, callback?: (res: http.IncomingMessage) =>void): http.ClientRequest; + export var globalAgent: Agent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): string; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import stream = require("stream"); + import events = require("events"); + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): events.EventEmitter; +} + +declare module "readline" { + import events = require("events"); + import stream = require("stream"); + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string, length: number): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: Function): void; + pause(): void; + resume(): void; + close(): void; + write(data: any, key?: any): void; + } + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output: NodeJS.WritableStream; + completer?: Function; + terminal?: boolean; + } + export function createInterface(options: ReadLineOptions): ReadLine; +} + +declare module "vm" { + export interface Context { } + export interface Script { + runInThisContext(): void; + runInNewContext(sandbox?: Context): void; + } + export function runInThisContext(code: string, filename?: string): void; + export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; + export function runInContext(code: string, context: Context, filename?: string): void; + export function createContext(initSandbox?: Context): Context; + export function createScript(code: string, filename?: string): Script; +} + +declare module "child_process" { + import events = require("events"); + import stream = require("stream"); + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle: any): void; + connected: boolean; + disconnect(): void; + } + + export function spawn(command: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + custom?: any; + env?: any; + detached?: boolean; + }): ChildProcess; + export function exec(command: string, options: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], + callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: { + cwd?: string; + stdio?: any; + customFds?: any; + env?: any; + encoding?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + }, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function fork(modulePath: string, args?: string[], options?: { + cwd?: string; + env?: any; + encoding?: string; + }): ChildProcess; +} + +declare module "url" { + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } + + export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; +} + +declare module "dns" { + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; +} + +declare module "net" { + import stream = require("stream"); + + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; + + remoteAddress: string; + remotePort: number; + bytesRead: number; + bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface Server extends Socket { + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + maxConnections: number; + connections: number; + } + export function createServer(connectionListener?: (socket: Socket) =>void ): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; + export function connect(options: { port: number, host?: string, localAddress? : string, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress? : string, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import events = require("events"); + + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } +} + +declare module "fs" { + import stream = require("stream"); + import events = require("events"); + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + } + + export interface ReadStream extends stream.Readable { + close(): void; + } + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + } + + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, cache?: {[path: string]: string}): string; + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function unlinkSync(path: string): void; + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function rmdirSync(path: string): void; + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdirSync(path: string, mode?: number): void; + export function mkdirSync(path: string, mode?: string): void; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ): void; + export function readFileSync(filename: string, encoding: string): string; + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: number; + bufferSize?: number; + }): ReadStream; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: string; + bufferSize?: number; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + string?: string; + }): WriteStream; +} + +declare module "path" { + export function normalize(p: string): string; + export function join(...paths: string[]): string; + export function resolve(...pathSegments: string[]): string; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; + } + export var StringDecoder: { + new (encoding: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import crypto = require("crypto"); + import net = require("net"); + import stream = require("stream"); + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer | Array; + crl?: string | string[]; + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: Array; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number | string; + socket?: net.Socket; + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer | Array; + rejectUnauthorized?: boolean; + NPNProtocols?: Array; + servername?: string; + } + + export interface Server extends net.Server { + // Extended base methods + listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + + listen(port: number, host?: string, callback?: Function): Server; + close(): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; +} + +declare module "crypto" { + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: any; //string | string array + crl: any; //string | string array + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + interface Hmac { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + interface Cipher { + update(data: Buffer): Buffer; + update(data: string, input_encoding?: string, output_encoding?: string): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + interface Decipher { + update(data: Buffer): Buffer; + update(data: string, input_encoding?: string, output_encoding?: string): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + } + export function createSign(algorithm: string): Signer; + interface Signer { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + interface Verify { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; +} + +declare module "stream" { + import events = require("events"); + + export interface Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(data: Buffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(data: Buffer, encoding: string, callback: Function): void; + _write(data: string, encoding: string, callback: Function): void; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: Buffer, encoding: string, callback: Function): void; + _transform(chunk: string, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform {} +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; +} + +declare module "assert" { + function internal (value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: {message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function}); + } + + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; +} + +declare module "tty" { + import net = require("net"); + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + } +} + +declare module "domain" { + import events = require("events"); + + export class Domain extends events.EventEmitter { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + } + + export function create(): Domain; +} + +declare module "module" { + class Module implements NodeModule { + static runMain (): void; + static wrap (code: string): string; + static _nodeModulePaths (path: string): string[]; + static _load (request: string, parent?: Module, isMain?: boolean): any; + static _resolveFilename (request: string, parent?: Module, isMain?: boolean): string; + static _extensions: { [ext: string]: (m: Module, fileName: string) => any } + + constructor (filename: string); + + id: string; + parent: Module; + filename: string; + paths: string[]; + children: Module[]; + exports: any; + loaded: boolean; + require: NodeRequireFunction; + } + + export = Module; +} diff --git a/node_modules/azure-storage/typings/globals/node/typings.json b/node_modules/azure-storage/typings/globals/node/typings.json new file mode 100644 index 000000000..24054ce08 --- /dev/null +++ b/node_modules/azure-storage/typings/globals/node/typings.json @@ -0,0 +1,13 @@ +{ + "resolution": "main", + "tree": { + "src": "https://raw.githubusercontent.com/types/env-node/959285e4da295481cf634f7d11f6ccccc863e430/0.10/typings.json", + "raw": "registry:env/node#0.10.0+20160918225031", + "version": "0.10", + "files": [ + "node.d.ts" + ], + "name": "node", + "type": "typings" + } +} diff --git a/node_modules/azure-storage/typings/index.d.ts b/node_modules/azure-storage/typings/index.d.ts new file mode 100644 index 000000000..22e4de57a --- /dev/null +++ b/node_modules/azure-storage/typings/index.d.ts @@ -0,0 +1 @@ +/// diff --git a/node_modules/bcrypt-pbkdf/README.md b/node_modules/bcrypt-pbkdf/README.md new file mode 100644 index 000000000..12018090b --- /dev/null +++ b/node_modules/bcrypt-pbkdf/README.md @@ -0,0 +1,39 @@ +Port of the OpenBSD `bcrypt_pbkdf` function to pure Javascript. `npm`-ified +version of [Devi Mandiri's port] +(https://github.com/devi/tmp/blob/master/js/bcrypt_pbkdf.js), +with some minor performance improvements. The code is copied verbatim (and +un-styled) from Devi's work. + +This product includes software developed by Niels Provos. + +## API + +### `bcrypt_pbkdf.pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds)` + +Derive a cryptographic key of arbitrary length from a given password and salt, +using the OpenBSD `bcrypt_pbkdf` function. This is a combination of Blowfish and +SHA-512. + +See [this article](http://www.tedunangst.com/flak/post/bcrypt-pbkdf) for +further information. + +Parameters: + + * `pass`, a Uint8Array of length `passlen` + * `passlen`, an integer Number + * `salt`, a Uint8Array of length `saltlen` + * `saltlen`, an integer Number + * `key`, a Uint8Array of length `keylen`, will be filled with output + * `keylen`, an integer Number + * `rounds`, an integer Number, number of rounds of the PBKDF to run + +### `bcrypt_pbkdf.hash(sha2pass, sha2salt, out)` + +Calculate a Blowfish hash, given SHA2-512 output of a password and salt. Used as +part of the inner round function in the PBKDF. + +Parameters: + + * `sha2pass`, a Uint8Array of length 64 + * `sha2salt`, a Uint8Array of length 64 + * `out`, a Uint8Array of length 32, will be filled with output diff --git a/node_modules/bcrypt-pbkdf/index.js b/node_modules/bcrypt-pbkdf/index.js new file mode 100644 index 000000000..b1b5ad4b7 --- /dev/null +++ b/node_modules/bcrypt-pbkdf/index.js @@ -0,0 +1,556 @@ +'use strict'; + +var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash; + +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri + */ + +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos + * All rights reserved. + * + * Implementation advice by David Mazieres . + * + * 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. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. + */ + +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst + * + * Permission to use, copy, modify, and 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. + */ + +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson + * + * Permission to use, copy, modify, and 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. + */ + +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + +var BLF_J = 0; + +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; + +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; + +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; +}; + +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; + +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; + +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; + + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } +}; + +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; + + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; + } + } + BLF_J = 0; +}; + +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; + +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; + +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; + +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" + + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } + + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); + + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; + } +}; + +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; + + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; + + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); + + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; + + crypto_hash_sha512(sha2pass, pass, passlen); + + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; + + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; + + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; + } + + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } + + return 0; +}; + +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf +}; diff --git a/node_modules/bcrypt-pbkdf/package.json b/node_modules/bcrypt-pbkdf/package.json new file mode 100644 index 000000000..e1dea6112 --- /dev/null +++ b/node_modules/bcrypt-pbkdf/package.json @@ -0,0 +1,75 @@ +{ + "_args": [ + [ + "bcrypt-pbkdf@^1.0.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\sshpk" + ] + ], + "_from": "bcrypt-pbkdf@>=1.0.0-0 <2.0.0-0", + "_id": "bcrypt-pbkdf@1.0.1", + "_inCache": true, + "_location": "/bcrypt-pbkdf", + "_nodeVersion": "0.12.9", + "_npmOperationalInternal": { + "host": "packages-18-east.internal.npmjs.com", + "tmp": "tmp/bcrypt-pbkdf-1.0.1.tgz_1486007687899_0.974529881728813" + }, + "_npmUser": { + "email": "alex@cooperi.net", + "name": "arekinath" + }, + "_npmVersion": "2.14.9", + "_phantomChildren": {}, + "_requested": { + "name": "bcrypt-pbkdf", + "raw": "bcrypt-pbkdf@^1.0.0", + "rawSpec": "^1.0.0", + "scope": null, + "spec": ">=1.0.0-0 <2.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/sshpk" + ], + "_resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz", + "_shasum": "63bc5dcb61331b92bc05fd528953c33462a06f8d", + "_shrinkwrap": null, + "_spec": "bcrypt-pbkdf@^1.0.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\sshpk", + "dependencies": { + "tweetnacl": "^0.14.3" + }, + "description": "Port of the OpenBSD bcrypt_pbkdf function to pure JS", + "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "63bc5dcb61331b92bc05fd528953c33462a06f8d", + "tarball": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.1.tgz" + }, + "gitHead": "fa2ab3ae9efa15367264151398635a915c7b411d", + "installable": true, + "license": "BSD-3-Clause", + "main": "index.js", + "maintainers": [ + { + "name": "arekinath", + "email": "alex@cooperi.net" + }, + { + "name": "dap", + "email": "dap@cs.brown.edu" + }, + { + "name": "jclulow", + "email": "josh@sysmgr.org" + }, + { + "name": "trentm", + "email": "trentm@gmail.com" + } + ], + "name": "bcrypt-pbkdf", + "optionalDependencies": {}, + "scripts": {}, + "version": "1.0.1" +} diff --git a/node_modules/boom/.npmignore b/node_modules/boom/.npmignore new file mode 100644 index 000000000..77ba16cb0 --- /dev/null +++ b/node_modules/boom/.npmignore @@ -0,0 +1,18 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov + diff --git a/node_modules/boom/.travis.yml b/node_modules/boom/.travis.yml new file mode 100644 index 000000000..dd1b24f13 --- /dev/null +++ b/node_modules/boom/.travis.yml @@ -0,0 +1,8 @@ +language: node_js + +node_js: + - 0.10 + - 4.0 + +sudo: false + diff --git a/node_modules/boom/CONTRIBUTING.md b/node_modules/boom/CONTRIBUTING.md new file mode 100644 index 000000000..892836159 --- /dev/null +++ b/node_modules/boom/CONTRIBUTING.md @@ -0,0 +1 @@ +Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md). diff --git a/node_modules/boom/LICENSE b/node_modules/boom/LICENSE new file mode 100644 index 000000000..394688939 --- /dev/null +++ b/node_modules/boom/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2012-2014, Walmart and other contributors. +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. + * The names of any contributors may not 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 HOLDERS AND 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. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/boom/graphs/contributors \ No newline at end of file diff --git a/node_modules/boom/README.md b/node_modules/boom/README.md new file mode 100644 index 000000000..cbd91c931 --- /dev/null +++ b/node_modules/boom/README.md @@ -0,0 +1,652 @@ +![boom Logo](https://raw.github.com/hapijs/boom/master/images/boom.png) + +HTTP-friendly error objects + +[![Build Status](https://secure.travis-ci.org/hapijs/boom.png)](http://travis-ci.org/hapijs/boom) +[![Current Version](https://img.shields.io/npm/v/boom.svg)](https://www.npmjs.com/package/boom) + +Lead Maintainer: [Adam Bretz](https://github.com/arb) + +**boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response +object (instance of `Error`) which includes the following properties: +- `isBoom` - if `true`, indicates this is a `Boom` object instance. +- `isServer` - convenience bool indicating status code >= 500. +- `message` - the error message. +- `output` - the formatted response. Can be directly manipulated after object construction to return a custom + error response. Allowed root keys: + - `statusCode` - the HTTP status code (typically 4xx or 5xx). + - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. + - `payload` - the formatted object used as the response payload (stringified). Can be directly manipulated but any + changes will be lost + if `reformat()` is called. Any content allowed and by default includes the following content: + - `statusCode` - the HTTP status code, derived from `error.output.statusCode`. + - `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`. + - `message` - the error message derived from `error.message`. +- inherited `Error` properties. + +The `Boom` object also supports the following method: +- `reformat()` - rebuilds `error.output` using the other object properties. + +## Overview + +- Helper methods + - [`wrap(error, [statusCode], [message])`](#wraperror-statuscode-message) + - [`create(statusCode, [message], [data])`](#createstatuscode-message-data) +- HTTP 4xx Errors + - 400: [`Boom.badRequest([message], [data])`](#boombadrequestmessage-data) + - 401: [`Boom.unauthorized([message], [scheme], [attributes])`](#boomunauthorizedmessage-scheme-attributes) + - 403: [`Boom.forbidden([message], [data])`](#boomforbiddenmessage-data) + - 404: [`Boom.notFound([message], [data])`](#boomnotfoundmessage-data) + - 405: [`Boom.methodNotAllowed([message], [data])`](#boommethodnotallowedmessage-data) + - 406: [`Boom.notAcceptable([message], [data])`](#boomnotacceptablemessage-data) + - 407: [`Boom.proxyAuthRequired([message], [data])`](#boomproxyauthrequiredmessage-data) + - 408: [`Boom.clientTimeout([message], [data])`](#boomclienttimeoutmessage-data) + - 409: [`Boom.conflict([message], [data])`](#boomconflictmessage-data) + - 410: [`Boom.resourceGone([message], [data])`](#boomresourcegonemessage-data) + - 411: [`Boom.lengthRequired([message], [data])`](#boomlengthrequiredmessage-data) + - 412: [`Boom.preconditionFailed([message], [data])`](#boompreconditionfailedmessage-data) + - 413: [`Boom.entityTooLarge([message], [data])`](#boomentitytoolargemessage-data) + - 414: [`Boom.uriTooLong([message], [data])`](#boomuritoolongmessage-data) + - 415: [`Boom.unsupportedMediaType([message], [data])`](#boomunsupportedmediatypemessage-data) + - 416: [`Boom.rangeNotSatisfiable([message], [data])`](#boomrangenotsatisfiablemessage-data) + - 417: [`Boom.expectationFailed([message], [data])`](#boomexpectationfailedmessage-data) + - 422: [`Boom.badData([message], [data])`](#boombaddatamessage-data) + - 428: [`Boom.preconditionRequired([message], [data])`](#boompreconditionrequiredmessage-data) + - 429: [`Boom.tooManyRequests([message], [data])`](#boomtoomanyrequestsmessage-data) +- HTTP 5xx Errors + - 500: [`Boom.badImplementation([message], [data])`](#boombadimplementationmessage-data) + - 501: [`Boom.notImplemented([message], [data])`](#boomnotimplementedmessage-data) + - 502: [`Boom.badGateway([message], [data])`](#boombadgatewaymessage-data) + - 503: [`Boom.serverTimeout([message], [data])`](#boomservertimeoutmessage-data) + - 504: [`Boom.gatewayTimeout([message], [data])`](#boomgatewaytimeoutmessage-data) +- [FAQ](#faq) + + +## Helper Methods + +### `wrap(error, [statusCode], [message])` + +Decorates an error with the **boom** properties where: +- `error` - the error object to wrap. If `error` is already a **boom** object, returns back the same object. +- `statusCode` - optional HTTP status code. Defaults to `500`. +- `message` - optional message string. If the error already has a message, it adds the message as a prefix. + Defaults to no message. + +```js +var error = new Error('Unexpected input'); +Boom.wrap(error, 400); +``` + +### `create(statusCode, [message], [data])` + +Generates an `Error` object with the **boom** decorations where: +- `statusCode` - an HTTP error code number. Must be greater or equal 400. +- `message` - optional message string. +- `data` - additional error data set to `error.data` property. + +```js +var error = Boom.create(400, 'Bad request', { timestamp: Date.now() }); +``` + +## HTTP 4xx Errors + +### `Boom.badRequest([message], [data])` + +Returns a 400 Bad Request error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.badRequest('invalid query'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 400, + "error": "Bad Request", + "message": "invalid query" +} +``` + +### `Boom.unauthorized([message], [scheme], [attributes])` + +Returns a 401 Unauthorized error where: +- `message` - optional message. +- `scheme` can be one of the following: + - an authentication scheme name + - an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header. +- `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used + when `schema` is a string, otherwise it is ignored. Every key/value pair will be included in the + 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the `attributes` key. + `null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as + the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header + will not be present and `isMissing` will be true on the error object. + +If either `scheme` or `attributes` are set, the resultant `Boom` object will have the 'WWW-Authenticate' header set for the response. + +```js +Boom.unauthorized('invalid password'); +``` + +Generates the following response: + +```json +"payload": { + "statusCode": 401, + "error": "Unauthorized", + "message": "invalid password" +}, +"headers" {} +``` + +```js +Boom.unauthorized('invalid password', 'sample'); +``` + +Generates the following response: + +```json +"payload": { + "statusCode": 401, + "error": "Unauthorized", + "message": "invalid password", + "attributes": { + "error": "invalid password" + } +}, +"headers" { + "WWW-Authenticate": "sample error=\"invalid password\"" +} +``` + +```js +Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' }); +``` + +Generates the following response: + +```json +"payload": { + "statusCode": 401, + "error": "Unauthorized", + "message": "invalid password", + "attributes": { + "error": "invalid password", + "ttl": 0, + "cache": "", + "foo": "bar" + } +}, +"headers" { + "WWW-Authenticate": "sample ttl=\"0\", cache=\"\", foo=\"bar\", error=\"invalid password\"" +} +``` + +### `Boom.forbidden([message], [data])` + +Returns a 403 Forbidden error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.forbidden('try again some time'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 403, + "error": "Forbidden", + "message": "try again some time" +} +``` + +### `Boom.notFound([message], [data])` + +Returns a 404 Not Found error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.notFound('missing'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 404, + "error": "Not Found", + "message": "missing" +} +``` + +### `Boom.methodNotAllowed([message], [data])` + +Returns a 405 Method Not Allowed error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.methodNotAllowed('that method is not allowed'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 405, + "error": "Method Not Allowed", + "message": "that method is not allowed" +} +``` + +### `Boom.notAcceptable([message], [data])` + +Returns a 406 Not Acceptable error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.notAcceptable('unacceptable'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 406, + "error": "Not Acceptable", + "message": "unacceptable" +} +``` + +### `Boom.proxyAuthRequired([message], [data])` + +Returns a 407 Proxy Authentication Required error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.proxyAuthRequired('auth missing'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 407, + "error": "Proxy Authentication Required", + "message": "auth missing" +} +``` + +### `Boom.clientTimeout([message], [data])` + +Returns a 408 Request Time-out error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.clientTimeout('timed out'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 408, + "error": "Request Time-out", + "message": "timed out" +} +``` + +### `Boom.conflict([message], [data])` + +Returns a 409 Conflict error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.conflict('there was a conflict'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 409, + "error": "Conflict", + "message": "there was a conflict" +} +``` + +### `Boom.resourceGone([message], [data])` + +Returns a 410 Gone error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.resourceGone('it is gone'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 410, + "error": "Gone", + "message": "it is gone" +} +``` + +### `Boom.lengthRequired([message], [data])` + +Returns a 411 Length Required error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.lengthRequired('length needed'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 411, + "error": "Length Required", + "message": "length needed" +} +``` + +### `Boom.preconditionFailed([message], [data])` + +Returns a 412 Precondition Failed error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.preconditionFailed(); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 412, + "error": "Precondition Failed" +} +``` + +### `Boom.entityTooLarge([message], [data])` + +Returns a 413 Request Entity Too Large error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.entityTooLarge('too big'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 413, + "error": "Request Entity Too Large", + "message": "too big" +} +``` + +### `Boom.uriTooLong([message], [data])` + +Returns a 414 Request-URI Too Large error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.uriTooLong('uri is too long'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 414, + "error": "Request-URI Too Large", + "message": "uri is too long" +} +``` + +### `Boom.unsupportedMediaType([message], [data])` + +Returns a 415 Unsupported Media Type error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.unsupportedMediaType('that media is not supported'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 415, + "error": "Unsupported Media Type", + "message": "that media is not supported" +} +``` + +### `Boom.rangeNotSatisfiable([message], [data])` + +Returns a 416 Requested Range Not Satisfiable error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.rangeNotSatisfiable(); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 416, + "error": "Requested Range Not Satisfiable" +} +``` + +### `Boom.expectationFailed([message], [data])` + +Returns a 417 Expectation Failed error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.expectationFailed('expected this to work'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 417, + "error": "Expectation Failed", + "message": "expected this to work" +} +``` + +### `Boom.badData([message], [data])` + +Returns a 422 Unprocessable Entity error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.badData('your data is bad and you should feel bad'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 422, + "error": "Unprocessable Entity", + "message": "your data is bad and you should feel bad" +} +``` + +### `Boom.preconditionRequired([message], [data])` + +Returns a 428 Precondition Required error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.preconditionRequired('you must supply an If-Match header'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 428, + "error": "Precondition Required", + "message": "you must supply an If-Match header" +} +``` + +### `Boom.tooManyRequests([message], [data])` + +Returns a 429 Too Many Requests error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.tooManyRequests('you have exceeded your request limit'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 429, + "error": "Too Many Requests", + "message": "you have exceeded your request limit" +} +``` + +## HTTP 5xx Errors + +All 500 errors hide your message from the end user. Your message is recorded in the server log. + +### `Boom.badImplementation([message], [data])` + +Returns a 500 Internal Server Error error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.badImplementation('terrible implementation'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 500, + "error": "Internal Server Error", + "message": "An internal server error occurred" +} +``` + +### `Boom.notImplemented([message], [data])` + +Returns a 501 Not Implemented error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.notImplemented('method not implemented'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 501, + "error": "Not Implemented", + "message": "method not implemented" +} +``` + +### `Boom.badGateway([message], [data])` + +Returns a 502 Bad Gateway error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.badGateway('that is a bad gateway'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 502, + "error": "Bad Gateway", + "message": "that is a bad gateway" +} +``` + +### `Boom.serverTimeout([message], [data])` + +Returns a 503 Service Unavailable error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.serverTimeout('unavailable'); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 503, + "error": "Service Unavailable", + "message": "unavailable" +} +``` + +### `Boom.gatewayTimeout([message], [data])` + +Returns a 504 Gateway Time-out error where: +- `message` - optional message. +- `data` - optional additional error data. + +```js +Boom.gatewayTimeout(); +``` + +Generates the following response payload: + +```json +{ + "statusCode": 504, + "error": "Gateway Time-out" +} +``` + +## F.A.Q. + +###### How do I include extra information in my responses? `output.payload` is missing `data`, what gives? + +There is a reason the values passed back in the response payloads are pretty locked down. It's mostly for security and to not leak any important information back to the client. This means you will need to put in a little more effort to include extra information about your custom error. Check out the ["Error transformation"](https://github.com/hapijs/hapi/blob/master/API.md#error-transformation) section in the hapi documentation. diff --git a/node_modules/boom/images/boom.png b/node_modules/boom/images/boom.png new file mode 100644 index 0000000000000000000000000000000000000000..373bc13455bc0a71a6a4538158aee59c6994b761 GIT binary patch literal 29479 zcmX_nRal#C(`}IA?(QuPMT!QexVux_9g0iPQmhm!ZUu@2cXxM+y9ReHw!{1V*FH$X zL9Wa^Gi%npX6_+UMM)YRg#-lv0HDjtNU8w8=!YmpG3?_c$V#GxO^&N8}g002hs z+Y2U%8G{r6KvA}lkWf*vc5-)evvzW(l9iC4a&~pHw6V7U0KAqm)vYwt4+wwbiV4_CGlKV!TyNIvah5h+6Jn3N0H@Mi?plEzm7PRju3y3?^ zd9fk+-@Xq&Zu;ii&9&a`jlI;(3q#7TGHWIfJCV?mWw=y71)&v-Q($j|4D|MI?y!l1 zQ0SZiSV%SI)NaqTFo632Ads1+6R{lt<28ed1n5*u@BBy>@rrpUo@xLS6bjSn9?vI_ z6ody5^@$ZP1c*w(1ZDpEpbp4^2YeYZGu;NLumZl&2ky-Pf->(@ePICliPZQoIq?80 zT#Ij#0Bb=&*@V{j&j6i|06a_iUVgv=E8wH7wxtZ9vH{RJj)htcKtcn2RQ(pl2!Qtm zd>N#r^#X*Z0`R0RwSgDRNf7wezt!I06yK_Y_xCDfjA98((v~i-J{nE1!NOHkwZ;a_Tr?U8c<)K$Y*GJ zWlfuOnDDk$aa>|0)1t393uq$6e=_#HpMEvpT4#BL6JGxWsI(P^@r`HwV`v6h;4Nz$=t4A+PZAOQf9IUuG= zG1BWUB9=}BvaWY4U8qlActXYLdb`E3#8J$H$XvfLmIaG5gpXB{GkszID@xAYscIdb z;Eci6t=WhnSO;mZp=0%1JRqdvyN%$jQ z`=J^8p_j;%lOsY$hJ|(xCk~e#%lDf^FE1TVqy#5@(+^nLs^1#ZIMY(oj%u_AEXC>E zG9SJv&@Gq&w7?`Y4&EqAtJh)wdYbhHd4Dcd>T4cM&Xp zaf)f?r>U*}$<@IA6sIQ+&aGFgP>uM5%k7cIKNdnDD_;Q4OPV3ECbYh@sn~aK#$HXL zP)eE9o*p@n-cQ+wyY@sw562G~_-4gGoKA#DWJT;rRPjrpka#AFctGPLFUQd@NGfKk zlco++J(C}P{4h$AT+)XmQYLnd;*!FWwGvd#E6ov&xMCx9|8gl!F7@qVgvUB1)|OIBAId4$ys$M9}R~=uwvVt(sG1yxrPQg=$7zD4~+#Tz&~IIWFxQwW~x+5yb6ZF83MkO2`m~qLizE?`wExj9ZMP zh1?2F92N$4CCMqtI;AqDs-@CLZ9L^CMVWHJJkD|SeX)9HT0GDoF=p-_&58Mv7x# zeO{*kMM3Xjtl%O+Vjz9k$9o??>W)|ufn|%^>ctbW=$s}oe6hG-aPV#ynA&>q_y?H! z4)SX}e%uBlOeJ7{ZW7UC&m^iR0F6E@B1}76B-Z(x4#^Zp$|ujM6$!U>$$yf`l56Q! z9LoF^ta6{2giF|LflIv2+|45WY?ivCvpShNvi9<1{A^6+JdXD5>rW?F5nGvCsN24T zzt{&2oxO9%yRXBF2#VQoSOk(q6}~C)C7z36G5sNket(JU`92oKyPLe*iiUlPXX@L6 zgaH$U(xnWOqR-Fc_|{L}bbVX}EW1si^u<3~70?w{(*?2!(!NqTa0&^uafJMg|KTED zLamrkZ*^$3XZdxc%p$D%rOz>{ft?}=amcRbN7*}FR+M`2!hH=rhIuB$YAXwE%Z{%!-8h>+>kGo=wOPq^_S(v9`Ky60-peT4`0tp*wGhgH zjo<5;9A=eEPqb6Y1KK|LDB6LHx`uR{}SP&H9@!~Bm{=1&Zjb=Y;+>rDQIXOarz zM}9BITP94w4_sha@!BPga2oDNT}iAhF70hHpRk;^JlI=f&C+bf=im-`{f+`%VCieLZ`mf|4CPmH zD{^*Q@wCe{sdV+UM}1TMX5~@gsky^7pC{>MO3Vyypsu&vmBx_G(n0V{g4N|jbY@bf ze*oLV%9rK5dS8gy__{5o(^)f?`{wlL*C>c!tKhi7WuyCL_3|#RcB6J$g@Cccq5C25 zC1FN+pe3Uvt-Q&=uIbdLt6vpiwIY3o5Ee4=5`PniDe*2Y zHEtvvJ^Uz(Pne&7OT_j0;HgMr!hGUG7U4_Y%SbsP0eisx?9u%A)UT=Bl*^Qa4hO%2 z=fln;;)><|?tY5)Aulctqie0llP=E{Px7<;bxh?QKdL~6SL=tW8}-Se#{}YpgjaaD zUsq3NT&&Aby-8&zqoxP|_`C-Ifls-mkC1R+jZ=Cz{%Z)jKqV29+=o6zbxbx$xo@xpbni)G?vlY5|Nt ze#q_nb;(*6npJjvsjRBfH2C{?V&R+WI(`}BVrkdOOq1{W&9nFEaH@ZUjVnZO_wRH{ZrSrO6+`aqz3{^U46L*dOIJB>3T2Aw{D!8~m zcK#hj+f|E<9as7}M3>I%K$EF-Rg?W39T^!}Z_b&zQt4u*FPv@Ma`Q9lF_uCoxgC<_ z>(i>onrT1MzqBkk{b0(W4^CXZ@I#~y))6@IaIf{$O(yp=)RtuorG(c45|sL6N!RI( zwUi%Oa;2&P2`U=PNp+I1RhF1jyAH%ruqF)`T&PuPDAVD9EOZ4@ zMl@m0rsdgpHzOzuwMt!9J?7(w%!w!{ESKvYRvr?vC+C-=uwX~3e`TfSc2vaqv?&Q^ zOEZQg{!Djlj-*`orZ>yaw_j^bg$8hPeO*~u855A7pPx8lF;`(c(c25(WDu)as-+6n zO8xb#v)+Mar27iURaYnVlk; z3@R2<>k?YImJEFRT%vmrqK4diK={A_ce{3!r$BdVgR3>Ea6VJoek~qDlS~28lc4_uA0m zOeHH$9DYoAyjAKot>PGPp&$^C)=~S{KaB9^Bn<>s3<>10ERk#>V%DtY(|tWPoKy~R z7}6+NEX}0rSZNC{-6lqGh!CTfLWsoM>V;_TWKW6acwFnzr74wNF>t(_LgtGb5!*c741s}mWA^=P&CjBpp(Sy1$GK|XwiM#~EyT)y=AjGT< z@3rO_x!&xIL1*uh5WALYG=7(*-!TAKZV&LUDPblY?2Jo@?9eoyz`y8#+H;>onV;fR zAiCh%+JhQ0w#fJ1->nDc(*TN$Dv2JVip;LVkVb8*-YX*1L-M;F`T65(CNhxKa%8CI z{r(g&SW^te+c~G>_0eUyU0SY50*OPI`3dcR(X$HsB8&X3kq|!Ju)ydt>CEr({fmO5 z10v0hd=(mR-Q7j6IjK-R9IRgfa!}qSvJ$OnFE9+bHB5ZP7_88L%GPgC4=|>bE_!n8|QaZ5(LZPf&q$=vDQ{j;g@LP5m}M`?-$eK zvq09_t{hwm8^zCza!g*KojQMh=>A=IBf-YY$f7`N58Wq9G`7w53t1G~M+K?DsD zHvb5lqy6$JyVfwTR#8!wuqKl*ZNNrnxP#KqBG2-z#RH}KKK0(voE+G~kdGAFSyls^ zJBevhHZi4Q(%9lS3md&nW&S}8^>D6JRECW0{<$!c{;F_?I(9JK>V>MJ4!}=z8z?kk~xb42b0~N_fUDI(Kj7Ku&~3 zTp~iw8{v$NT}tnbKV^=b9GspukJX<9Ctiv%?t(@84AlM)fgA|7)L7yx&i3}l%C@_g z2|RYG_YrG~K%rG7IlX&5bu`!~>&t%0qzv8j(HG*JAx4q13tIRPt?2c^+w(jH!UWL3 zxKCIGVNpxF;3xl{F25Iq&`A=MdW(~@qoc=?@Cj7vuhR7#i1ScJLzCJWeaHA-e0a78 z7x#=$*zakK9OM`%?JH8@bXGLs`e#4L6w6WynbvWS)dvW6@d$!vq26yWMJw0_GOrFb zp1F8}pQz-Kw^o(XYdelT0{+?7^SvFUaihQY$QJ8&jbt41U}<40%n8dO-G> zzNqR|;D#38ezRU~AK`c06A?jyr`AUd$^fIhe1Gl!NPoI`89xa*?@=!&Cn$_0)L6*egx&4Yu1N@qfr9>n<+#0=BzfM@ zAg3o)$SBMkFO!)zsrk0p!M?yVm2H8qBH$v9OpzdSwICV3Zhf?i+Q%p?^y%v==%Dy$ zdhxiFD{_Z0JUm<&Jvwz{;w_PcWrI~LQ3ko^B@q+>_nz`$-SzWUzFx|AwsVUvC`?~~ z=Xn9j%t(w9O*E2!>(q1MFgs3h8Z}`Xq*U1RVKIM8qL316ni6!2>x~~2{KS>eo6E0_ zl0qW2S=?M_MWhCQq*|yJ7sK=Z-aXuZg)3atFT}{L4vKqc?~d~%c4uq!^JKFW>SHEl z$L*I~XNNkY*BAw+8(Hv8Ana#1ViIViHiNPGRkg+s#haeGDA!#EMtI=qL>g^TJ2H-` zCcj5^O3WPEY{W+(V85%ku0=sQ#81>7xU;pch`qFBSf^DH7B4ln&d1{R8>RbKJ65S= z$v-s6Oji(Ai!-Q0HX=)9Cd(oi{^RS;0l&oiT`3QP>!A#k%Fr*FxDZ3b()*iRBS%KX ztEtp@=2$%WKyZPVrjzHL2#%%s?C7pFG=AY%T04?pBK!HfZ12~s)xac%gwT_$0>3w^s(g1o4*AraTh1e=)Rc-@6Ce^0CIN20-^w7o2&jk8y^brhTY6Mn z?bz7Z7f)%YiK~R69ZDHSO76@lbSNn}uSJrLRIA9LCzs6L#iC<&JP+$kzifjPR}v4S zm)PN1PnuF=GN-a4jM+CeUA>ZELB_9PpbmZ<#nC_qaDH($)6Ev%bS%`3Zv_IC>cqb- z@--@R__97q$aCN_R8MckwP;`E+4EA4$9!W~QfS-A72iCZ^?#;RC{oM5^6#)^`>&uf z2x$hYS%B*u7cYh_FRrHMJ1J|Eb0cS-6}c1DsYu;SeP9;n-@7?*aXtY*eOz!lv;?qW zTh&PPvsRR2E)8wNTn@vKO%E_|9NPGbF)HDi&I#$h!mG@GuM%}pWf=;*aoV#P!gw(~ z++TW@j(gEI4t!0pUw$EF++}m~eglxn=P0s~`XR`bldu5i6Nqhs@(I$8{%_Wyt$Q}@ zqSMLcEJjp@wBlzGryE&^9+28`=ewdMA${QlH%S99M0*TZ-V@vDsPB6bb}~AXDEk)@ zc>otknYc^7deuIP{^2pzL|BC9mUP<1asTY-(Q3furSI;!)1dH;mw%<;n(E>wJ5;RI zIIR!dk^}EI>GdMJ^yloiH68r(a`3!omuA$FV8qoj`ISuUDFf=f#8nb;0U_08}a%6MPZ`)0M9=D)y08k z%y$4&cb$wf@L|F~@LAO9jP!RRX4=T?8>_Igy4o+-hYv^@xB1>>br{7QKOD8AL)lnS z_?+=i&U;@)WSg)t<~9MxI#HF1ycJF(@ZVn1tvNiwn*Gjvql_G*jLyiS$byz{1SDOd%1LPNN>AYaWJ4?phxUu(kZ_k~K$Ddp) zfI%Vh^5TyveBHuZu+$gfGw%|g@P!G5&5_>)w{HdBC`m7Xtby;d^Kkoj)MmltZ>l*|M3rDKenFn#*Eq(zTl>+x?|Yzs0&I@OR*AWKAebx7-2Q&B-BL!s%mEvPM#(X zqnhTF_%P4bo&_<1*OT56}nua-vZYtqz6 zf9zJPVd?**FvcGDu|kxHOVCl{1#v*Pwuwb?s(iOpb*b1;=9e;@o1k{bON;C@D^1u* z2qCQ7f4ze`10LJ+V(g=cr6PpwIj(E$Nv}RV z0|jXkOivmrs>c&hCuwsGFlw_eEJ~yDqJ!OSNi2%}Nx7!j#!a3TI=yFL0)hRdDlC*d z7API;eSCjWw9;TUU{yDlLXvCtW~J~u8TeC`PV~^wP-%eQ-74=uq3isM@9PJnUk9c% z=ST#T7&-jbp_MUP*XLf?sD3+yN>_v>~hzJOP5!%wQ_yth4 zao2X_Z9I>Ko1f1MY;`>ru+W`5H#8Q)L%#`7G?+S)P?4i4@t{PzY4MSzYLc$(w?QUGQE>es zzb67i=(fUV?lM?`kP8%NTR=pH{WZA+B2}DHhzu14T2mRB*nA`O9^w_T+RUmXtI{QQ zpQ>)xD$8SqYbJ|r`Wi324E5Qq$67vMfceXAismYeo=K>CF-PN}5;PpuUKYV?{OAOPDztu z{0Lg}C~MeG+?)JWbr4dR_(v{&df!N{XQp`?{a{!x;%lc|uShRUV^-L=-c?WK6JMUx3U#0ScidJ1`$g}eH8&p%HdDBLulNZW+P<=1a;%zTWnPrtZuVM-cCf5afWe=ap+T$`!;9*lzI&fK?& z^rRQxS&_bwj?d%{TOsFt$&mUIlj|-#!o6=#`t6_-f_~z!;okX3A6FK*u^I8|w){Q? zNJ^AysNG;N_TjC3Sa`0|%29#=1scnkXRTKi3fgYtI&Ftgr% zkbYJds}eQouX>!I(oYG)kTLR*);j;7r|WA?M5tr(j0FXCS(%nX5YsmXNQyCJO4@s( z9&jmh3cPCxbpJAuMgOWhPg1UInTn!Un%`JUcG$=Gq}QdO3U*J;$FF-LQfelrKKWSp zL?%8kla_~a|C}{@{3qppbElUXg97NKY;3&VVZT@%X3rC)HcVy&^`0;L^LV*o%ic9~ zj?%y8|Cr^yeA3W%@U9qRZF)*s*cu$W)m@F$DlmIsX6?YVk%8%T!+Ens7a1$2w5O3N zzt6y_^AzY$>V0|TSIB-5v1PXRnpF(uYA3%?(}_!193r)Aa~Wk^1?iGDhsoALXntFtyQ$2<5Dwt@{qZEfF?BhK zB^P}8bp8zW(h{TWjk6#N6Fze_B$otO zeuV||SAM3qT8L^q%f^E#KqKSQvpM`;7d*P^xqdTeSJAX5pU&gZyxO}9ZBu)^SzKSv zF<&dIV5E>-!@A`Q<1n54H6c_-CqxOLb%BGe>Fx@=KMLe94k#~~6*L1CNzitsOcH@4 z;{(2^>bq-wjE+VA&I##T0qI!ESJHWpY>KEpl)XWyitX`ca`o}`onUm#t6lC@K5K*U z{$q_W9&_K$Rjrj$sldY7on=rY6EE#V%DB?ovtGGGD>f(fiA}02N}RZw$z1t)uooCh z-f`OgcosNvm3`ORaRHnl(|bb;Ym|w{js!S=y8q6sbfdM5^1HCf}?^roMB7v}i zhySX=R#s66Rf6xL&B?ij9i-r=jhckNrynJy*kSW#>+G>b%f6saboSUpp1N*2NAG^53{(J!>ih`a@g4P^R--5m z0<}|Ak+(@<`qbuTl&Agr3v=xDFSs{N2cf=Qv<Iyls@V`K5*Rr z$T=nW`ew*kM9MX8e#e(5%MHc`74wvw(r==7oPB4puo&R|dV6yAi;T48QfSqVsMhSS z{(B1pnZz?Sb|tBh%y@o66j-EI5~!Hhxb$|AIA>0E>>n7IClherZ}tMlCSGDky@gPV z=eD!6(`J2A&uxHQ#OEm!3b&(i3bX;6|ti) zKHr_>w zGKaYy{m5D;z)OSwNpC4|zw|dAJY7#&W9xh#1bN&$e}nl0jVlJZz%>I5^`ze2vDbd? z`uYx?m)!uB91^fVf6$m_5~RG5PUA?(MpCfn^h%{yE^l#=hBFr*ze$>O7T9+eGyHat zUPc?x5C>5jwU%+!Umyg3nHkdbH@fbT;Z%LVsKus1WM%Yo127^j;3W?EK`D z-y8hE_?8UKol{qF+1Np)_?gptCFaRnJ3C3cwie(yk^;OBJOghT6~2YiozfF+lEP)% zvZJpPSjXUIZw>ug55ufI!Xh>y_nm40d9A>du|qk0(EE*QbCRNu$t1+2EzLjKURRLF z-YQjDa{L(G5T)y4b8~=7b$QHvgA`=O*Aa#Ty-fHmuY)JITjV>tL_aGY z><^`D=o8Qkco+h3F1+T)5h?C#atsb0YI5ZxQNdep(}Y|dBTduQ`7`8shv` z_zC&CT}4A#DF|Ezy!B>S9k!-TTMbD5Frfd>CbRL5ecS!kHE+jjo5OssI@$t8mKG~J zh5H6>qb98@n|nO%$>;cO;k4RH8EToLnGlntwQ85xg7KBOn*&B>R(9Ue30I^NoyJ630u(8TTA$ zrV7P{b%vBF{qE%Cr0t>OoeB#mCMQWEHVn(Upm=W}#sghuL>DiW)H){QOH4wJ7F&fp zUBW8#UMCge5`ne#+-b5wJKB=c{6;(D;cZ7CL>^rvgkv3|Q}LtzZ6q7jOkpJzc2f57 zFz~vVOfStlB)jfg42iF3w!6piw9*KyjL>e#@gK+&#tCLg+1svv;V<-;(x_Zdo9@@U!&! zH?3BTryuIys)2MN`$gnD-3p6OY6prWi5kgq1>uh7k$PQ=fjj-myr1_4lz#mCBGq_%=#7UgzmXNx0d$Bj zyA(8u^Kf|y5UB|Ztg``h&f0a70I#fh3tg=VSYFcXp637IX^eSKO<(aEA7^xE~=@ZU6USG7?oo9yl%j|&s|MQSG)Y_XqRtx2zw{n}& zj029U(lqk3UEAab)^@FNj?;N>7E!F)7)3>)08skaxXCJ`nfe=af}!(Y`S2d8C{%K) ztP|uShSA#DchOQZkRm*3CyxIK(hQQ;38BxD`AgXNAQ^Jx zExM@lcG^Pmm8hm8{snpJU$q!Bi=bGu6S)kkL+JRs$b?b0X^kXvtF~^3q>KeAz77pU zKWf;4dirFU9U}HvD9*X%cj$g1?=pvpS0FjXstH$VAQorUQAJNSRZhwXhVRl5khuYm z5dUe|pfI27D(|bgNWf?y#IiYCk!F^29&En_oF(2&zg}P})h#SXLo}}~&V62m`7-p-lWw+RT|&ydO4Ar%%21dO4vxkDkwlQqprCeR$Oc|>LR4!tN()N&8dW(t z-!q`A8020TQN~ZiL3Uzs^Kz~JTUZ`oT^G<`s8D&C*LR)fk&HQJvX~D9@|)%@Q=o<% zhdwNLy{pt|JRAIvUf%~nm3$jSIjp5?t20;5#>UwVovTi@Vnx_clF40cCB4Vpn^Qk~ z!s2ghYb()UdsWfVdWSXfu0F->Y3(n^mJAN_RDM1zbX0GGE4@9TTLmkPBwOwKsoRwR z&%O*)_WnV)Z4|r z$+%|eK-F;*i_8!_YfXS|7wv2(d))oTipJV&f8jjO=IVKJa7Y_xDh>=v;WFHddtN~wAE`T>!s%OB<(cya^?`fH6A}4z zHx4rcbj=Ja*d5wpFLN;NGD~g%=(r5&eCKj%O>;B(SgD<-p2kLzkayj%O_uIy=U@tv z;NmDfd(b_NJ!UlxpfA*C{+L>iUtOa`BxvD#7bH24sugXpUZd}5UFXVldzR|#4o*&< zWj`b}LwD~Z5rREB)oZsx5~T0ry5Ucz^>jlD)fO(ei?cl9h$PX$Os-TE6QQ>_bHUZc zRM9myxCF-RkVY`D2N!AENl7t1E$JjbNTFc3O2^&_NI_2#$9@gr<}|d}a)ENoOuy$w zgYs1~;N?`DAE|zuFMeAB@o28>VX3#b_X4F()_3j7;j2|fA5o)x&8FqkC2=^+P zw4fz@5Tw%_rE%uNln^ncN2_Jt)N^IHVQs1uY)3dh5Xn+1Qnl?;wO&M+<4}hl@431_(goM>yDStS;{B30yK8yV zUK;MJ%!h<^J|5uH`2;3eqbs^exo+xYzPc*R8HI>Ubs%lW&%?LNQNWZIrO+p=ANFU6 zU`Azf7+QBdr45~Fnwbvlco}w`4eRb(I-X#W3<0^m(hG&|gFnWNfFQNn1+nuUX!|&i z6A7L-4bDzf;2QVWpg45fh0{p4=cdsnB6}5{xgjNV(E~#;+87uw*KXO523YVWI+ucL7qJfkZ3m)` z(0hi2QV@N%S*AQ_9_Dpwt7BKOQ=*gn>Y;L_!HKeF1UhG0fUchLZdK`kvCsjMa1u!$ z)octmE}E;J{W`RA)?Kxt6($*KQDnZNP0n>-kH|{uYJX6&;(r&5phh0jEAVfstDCDB zZ_;M*xJ3Iw#qpOsQj}z45jJ1VD+NrMxoc}p{`Oj~W~ok_&!h^}2E1pd1OOHCmx^>>Un2Mr=jc*5iY9Fza zy1M||W{oHPg~-_@URKSJ*Puy|A@dn9B{8Iopej=Heu5Hwk82f)mu$$$y*E$xW z@W9Yk*j2z`tyz`yT3nJ^-BEeVX}U<`Zt@7q6m7BRuzEG(6OMDm*=7IK^ON1{2S>U3 zcy(qvB3-Bqpv~l41daW@GShIQ{bQZh+k40o(;1I6y=wQ(10yG~V?)CQNhr=i?b0|* zwp}MmKzt?A7iE^OR#@&A%()lx$ImdzziWpHefS+MhPb|B##W<7zt zbek=1pC+v5Hc1^cUrxQkAllA=4bf|>E;3uQ2!btg?lmoh?uE=ixNv>**Os6PKoP>{ z^2~-oe!u&3S|cp+N|V)QrvTgl2%q!2IQJXGsT>z{EKFd4o4v^EWCsXRBrsSEP(H$) zF<=#%EK&LSUI5W$nq0$5>Q9Q55?(f!X;CT;;?I*dX#OQ!nvh_n;T)#70vd*ml_;(B z>7G~J{2Wovb6@__3mt%ZxC3+e5lQ9}vCN#Fu%=hVqBo1MJXGs*x{b z0t5fHJN-M`rd*Y|0i=RNf-IkiyNQya|C#ZE=H-ui{3^AP{$#4P&|1p9yruf?B@}BR z*(31va2E4K@ayqU)=;tZu6%?#Kxa;MQ-PO#shUIkWUjw&e59q0EW zFAnpB3cJFFW)uTHRrG>Qa4X2XFv9CDO~slmxKmYBO=ei{qCB#P?n!_b$A^4Yx0O%q z`hI?D+1GQl-ZM5XZrgj!^y#luO=;nta}DJ;$IF_)TkPAsgXrYrGA`zS(bB)jbfbV$ zP5a@2@C$H2Q9k_!HSA80PShX>_MQ|Ap?@b=o<(v`C%E%2&*BN#Ru)697d1cWwce`k z&3dlf8Edg}M;cTiC7${jm!FoFwu28K!{25xQ^>yVeZ25Kp|eEhFECAx&V7q%<9R!R zfw50;`EjU%A-4zlOp#?ZEWsXn`|B*v<&^{!+sL{nmpW%rSdp=bw?Cp?t3wGjNK8gY zsl@&rx|5j@v1r74eiR>c!GCpKOjj1;M&`A(oATNS20OT#o5NS}X||F2yJiOb{Zhq7 zLdW)wZR@vhAbHHd1GgiA7gi(reZcj#h9OMROyR!N3kktTa>>w6#PlP=Hvl^sAr*TlzoRF3kKZaToIh9rcwyFcx1IwCP2TO*d~SBnbhXP)A3QidehMRG9ihRF zJJac~nTfkQUG<%@n945}=n++qG;afcqRbMOQe=Lqbo-WuajvDer-t_{8cXMbZpiDW zq%S2%zpE7Qoavok1FYWXkU!W!D_lM$pklKpoEDJ0@Z#u;YT+L~YG<;Snvdg%^l>g` zba!^>I-hZsG{Jf`mh=BSj@o%SIdSIH^~gvRhx~j|Q<=$;%XtCWA4YAh!{}Eb07^i) zkTM&p7?Fy%8TVuW*}e7`oD3bd#Nvdy|6E!k1EaBbFeKCpb{Mp zGDRC-tb~)X@#&IX`9m}F`!0UEIs52wfejnItEz+Tr>?)MEY#3`gHF1X(Ny}~X5x1& zok*6Ua_VXceH+T=P-v25jwI*pdu-ri6X<3duv2AnYbhy4J`?a6m+su>7n>R6;-|R$ zE9oz4sV)qXrPdMRzV@c>m1#2?@K}{*L8Yqe9=jur=YBR#_+X!~mn!2lFjvjHon=((1eaD_zMp0&SJ!J(b8zKb|)xf1K9Jc6;q!8Ab%1zP$8I z1fIHy7=yJ4nF*|t7reg=kMD=SDr|r=_;CZPB5^H!S_P-`31Mk)64_xKV}T!9QoOUH z$@O|LVlJ~jugqoR_OpCq=E%*iw3;*ceDx$bo_ZL3->$6ed6zX(Z~t&A1YI2|VGX68 zI3%-@$#k|o^6q2}lQqJJ_p1)X^-u2c+5j8mx*duVBa_gl_C;Eqm-5?&A-BrG;47LL zelwNEy@i*z^p(9XgK6UH>MKIQ3kqQFZ(!zM<8=8^rVSYi73+`jLIYdZ3c~{}N0OJ{ zG*3_6QeNCTIV4`!7|xzH<4k02=WK~gXw@(PBuqPsQQd*^gnCXNs_P;jQzc=ykgGcP z`LS82?7QSl_9qi#c9{0ACnll^<(<~cqzd46`pL=3ta89*Lc_Y--D(9Nf|hZJm2~DL z;f>!$`Yy4NaD80dZMjtfzLmH)Wb9mov}OBuOC_#@R~?O`H$p`QEmEt@apwbNLw*kn z{Rs7H8$uBnkzDbPwZ0R&E!?h}y6LbTF?jEhMS+}=)8){cFU_Tm#GbAYa0_j>wul8| z*WG6nuT~8qK(6z;&dgA;qOtF~_ZAz0e7c0Y;{6B#sP{M4l@HfA0njS3TQFg3P3XI; zZ;Puenq8oAypruqAw0+8tKfEhtY3B%yi%{Q*j%`6ctk{?SP>HNdBC4?_Ah4y>E_}h zW}*63WNe46ISNm=fQ;oVQ!!evAe@sV_+CiV&T8a*#XP~c0j;(a4H-QZ1j=MpS7R-1 zoXcoxscc*1Av%%n3?#LBy=O4`NX-RfV+D+BLf*fO*0*KjJ1Xt${qu2xV44f zz6;r~PP)HO+JZke`cgyYn!O`4QreC!tcW{4JwHD~ujwhRF!NGt={a4rd`Eq$G-b#g z4kO90b@t2h1?hRx`9{=g z3WGN0DtgkhQG}j8!>~)NQL^h0%)+>ff^PVE+(O|DaN5NI*3>Nqj3dx! zx7w^u5f9j3w%ErHa%BqC?gq9m%=&EWO37BcAe7Cb zhAZ;@&LnH(o{^?zNVcT&l{Hvn>uzXGIsVcVhE3!lwL~_^M)@9EK;akaKMOnYVRWr@ z{K`?~!|~4i%>3Q6xNzVfH8yrjhYWT8^=;yMm{*KeSD58N!0X7ca)Yt0(K`c0B4lT4 z?0T!?Ns_O>Fgu2UMb3Mj6#!)z$MgZAbIb0?jJ~{(NqJ#<6Gloy(w(U&h&ObJ;~##C z@k>)R7Fnd^xL|JiWqngW1AdKFFH5jX2f@Mam#11_b zq-c&<|ATlzq0kdut&>y;y|G;6yT^-?9*BM1XlHAO3feT-N|Pb4Ye z@#XNSv64ehda;J=@6*(#+>@oT;H@jdFAZVWqgsX8mhQSeXqwy(UG!NdCXVa3hj`Rh zOXDM1hMj)XjQO>r{$okM=!EzuL_BnC;mu>$b7CMx@r*(UGnb-kz%7q2%=HeBO2)>N zR!rHINOVmf@1?tO&fUg38-G^b#+tlbP!n2`8z>GY7{QXZe4o+1ob2>C1)qy(IRT26gtKAL>WmKug+%kJ}qHhmXtBRL}x z=?$3JT_uORw=SXA`(Qw29rGb*1Mh$eUR)1pL`p!E6SuvXHc$zx|7xE~^uZ&zQ=;V) zY=_cDi}l3kd?l~Jy(31qWB7|(ql|ir(A}K$L}Gdn#>k#k9p_mpu=`Xm9wKSwp6QHY z*A59KkLiv8mGU~hEbR354lXR{)D)KFT-0MQXR>XuBf;T8y0gbGh9;dYIiAO?gPw1J z!cK1}wYFd%X9-l|1AFsW{o_I&!Q{Sr;e|AkExV9JeM(Ss-G;XM|F5L8;A*SuwlG!* zQY2_`cPqu+U5Z1n;_mKViWj#4Ek%k4cPZ}f?(Xi~yx;u+8QJ5Ez1P`m&bgkm>kBpM zV@*NPzdxYyha~kb*Tb$dZmbu^UH;PBt!$oWx8lRm5DjW~Iz~Dkh`2g%)(M;S%-;># zm2{2B!0wv>g{mP0WcwHsSAx5vG~yuO3)i6Co&*oHTH1>vx}xm-o@!Ha(IvSuGeR)$ z-*1yl_~UQ2$v+pwFN_|Mh1uPc9d@sQU3|GqaQ@OYTMleL4-XfcJgg3gW~`Ws(h#$r7B3nP2;l?Rrr z;BmHUpVfu6X(#c!lya5M%V1}-`*H*ZN%IlP*y`S<{@()ze;6;;%;l&g!3M)UN8fo@ z_3GFVl)pCSq+Fyl0ph{G$ck}psAN2tawwq!`RpcTZCqgwGv-xTI^W^eWD%BH!o(Cx zCMH1zG_J{?-}`xecibZGy5kX+%WR85`q0abBOWi7nN{$Ho`d6IvEzN>UKF~%w=2-p z?{Oo7nJ&CMisz4^^Hf{d6&-KK-IJC2WquMoJ~#fX6PsGz(+9$DtRhh`KFrTOzpT=u zqX0!UVW&aZ@XKOU6QFQ~jR>)c;6Tch*B&6)FPm2Jkp7ne$W1Q#Tnpvp=)kZ&Gk2q@ z6L<0vq7#6Z#g5l+?U>u_vRuz*Q|?S$^xGVkniW!WO2a9P^iJvO%pIO%6% zlA?^qM&m1t;TY&Q)Uh2_mlEKJd~ZA!+^@zUMWuj=z#E4xxEICb;7oDv#HquQn$}AP z&h#R7Qrft@$ByuReGv1QD}}~U4*wE08&~9zxx47@y>NYyr67P15AkonPxpH-9vGI? zaj;RBaW#`Qx+M65gl9g00yVu_nc@fbCjV+ z9r_ZA;Hhfum0kyCix@x~+2PcO=lvXm+v(i5T4yP0nwXE>~_t*LaJvXdat71^LM$=Jd!{&l$=EwFy$7U|lwi6lZk zruz_vWp9Gj!KSQ(U*xcS_Fvt{746+tNL*d@fX#g10fb_Y_r>nXTk&^DEeO4_nnt8H zbo-Igu2qe63?sg!uyb1sbNIcln7U|{XX+Jd(l}?wy`l1SxyVIqRn>s?{Is?fTh~-Ln}FdAYP`B zyR@oux@yXZSsY^fdy4N_Q&GkzO&9ISur{vtg zR5w3};qHAu#$}yLoTnR_lRsr_czy|PPJ2)d1f;XVEB+G~PYNe6mu$Ctx?c`am&(j_-GYIVjqei7vo zS7hGe?JFZP-=jv3Ktlr7{wSi&SmO*LnG#2RFs$n|Qo*RH0c})u(l8tD&FFr>gJ950 z)HSp`e^Fw7xwlHhhdky=>yX?kqNOvL4SJpHB5MEtP1K9yg20tGn7zBiIl*+WX&7$& zy3uC2zVdvv9OC=(-60k5vE&yi>4CJZ^iu>2BYqe@6XNjRX7P zfuO2p=0J9%RxUc`=ZO=OUoCszXt*3=@>Y0QtPG<9giYD4{RFv?*3K?B56q6 z$PVHMNA^444FL`IU)i>)sc1m8|rH(WROAp2Fb@>W?L#m~hUv;dug>Td61TmC>55lnN)@3xJu+9`v z88`01{p~mVKRVPToHjxgN;K;E|3uR+SxBR~Hc1yH?)0yU#*^xIAn2IpW~bJuvq)UP zIH75Eufz)3uo@6rYW#Q#NqO{y)nOQ1@zsBf_cVDXVK%q{<`%Iu&04J@iy1c&UNmH60)%eoeeFNn6=sORj>+Q z6y4XYs^JC-d2G{4qxmH#4B;mM*~1X^?O=o!K^Kf-Oz-7>VoKx zh<2jq0Y?`pPf<6I_GBXJ*tB`x|Jn+|-$Y(@d|{{;JFOSt*N(xPykp~ZB2SZK@n_5T zU=HJ+f`*ebJgitf)VSNf`+aaYqtSOP9EBS(hJe=CTmq5{tBmIE-wCB$@ z^H)`8@q*veku?;n!(%U#AEJq2W8iwW9RgLx%d2!0QLFM(mAD{d)IoC~WQsn(bHth8 z@RLwyL1%B6^-?^|$=!0)r3lgZWeZORlkMQoNf_TEXpvg_jkVSlo;?C_Qc>2Pe=(h4 z9^QI7u6W)VeZCjj|2an|f5jG|GZCgvDdr|^K*B;*$B|n?(jzlPrs6Ee(VY^BMwE?U zd&0Xq)rSQg^2wZg0OkI`Zu%)1zn7pc#{uM)GseOWsYc=5n0;_AAGt5_4p1AE*r@sN zK-0yW4x)BQ^Z*MBNCoDFp6Ptgce|+T(k{YKxpx;`l4sW07#Mg%3SRs7FSnT7>tY~* zN~tpTntqJSfD0PZJx;ozzUa2%yYo<0 zZOWNBI;m$~sbwjmD8WVWHcKM=&U!J7bBPmVerS#P&;WX;SChWsk;JNV+&vxMp|Ac% zz15@Z#(nU*9qjqohVGg`qc~e`cV|&>C7g)k1zuWQPEC${I-T<^$Ek08mBjGUrv3~6 z#QH|FuoKV41FGnb8KCIm`eP)R&HqpV704%Qy!~{W+kQNdAo3~x%t?X8#iEVZnn}4U zE|=hI%A7_Be?g}dv>{~M#L@2c9DHOIsn}^!U&;sb8dM>ao*<;rsOgg`REq;R zn}{OJEKy@QJ>=u+R>G|Rkt+U;0@8b83&-TcG7;7Mz50%Cr$z8U>sG9C%xNRi-y!zZ zFgDSs$iS9cvWr&e`ME%eJJncSP@yP^*1SJb4z+-*9p$TPrzcgv9CO!Xa+t2>VopwR zzfs_;=aY}GZdX|e)HA_WdKi=I!kG?4cuR)#hSVt*Z7fQTRp5GjS;Zn5XZv!$Gs)p3 zQ~SbTJh!M9!~?0d7n$lqXR(c_SqJW?a=+1a24X7v-n+ilG#e*e@6d^Oi>>eQqH7zt z&+ebKpSOFSFygg5^ZNddu>cTLP~%%7eUf)GMt%gG2Nn4-1}h9!s$SXRyfA8ZD2qR$ zNn3`N`mHppR2W(yG#Y?p4=1*Jbnq3XjQQ-`w)6>As{bkf1Ojn;Z$^|Iv&Zl!W8@Nz zZs;Qih_ItR(E-``ulkZTM0Gzj=i``@{3w}<`9L~7WV&$8cQ8+IY2Xq(9&^ROV6-5g zK*3yC#RZJ87u5%BX@TvSB`ld0WSGUo`ygSGwqNOwg5Ob}eOQ?(7@jm|;G`|EgoaLF zp{eA+Oyz>J^z?L{xaf2J&wQpzFK1Mpw#cYguT;jm#RarV3n>L2nfC$h;ts#eyT*pz zn}3Yk`64sTy?rt+9CgIzZ_k1%e8)?hc7oaLaYa~X)OG+uOl5<>S2#>Q+aM%DARjzD zDpP>Q8|E#_|z%&Lh68vJLM=L-I$Gl zbW!aOimE)AdF&i&&I6ez`WszZiyd9FV8r~1niBNfulkSj>e8RFA9gf59UA%|=N!b1 zPmSkMSmOoxeyZ~*+Qsy1v^NmyT3YNTQbYh17IxS*2|Ao!SU;O>(ZP=bYu732Q-Z3$ zLP=4S-hy23&+#+}^0v}8O&^rN%VEKY1zxQluTQr;+NGL~pIUh_o7K{mlCG^tVFEsR z;a)g0`)`=sq4C_3gjHdau=rj30ldWW)3U_S9}G6sJMjV0L2S4GUzB)>Vtt(D!*Z4v zvo3go0+H7IV1I!7`o8Nqwz(VU;FQZz1JBfRUv|dNp~1J5?mAGbCvsphOlxORh2Pec zu*9_TE1*GMae>+d-GDL_CRq)qjj_MvRdk5WrZ(u^(n-O0y+-i2*p5*QtqH9C06#8M7% zh{dI{ryE#6=1>la$)={2c#oRebiTOVdN^dJs0!N=^^O5+=QIpVCLkTal0(4&6NRxv z9r{p&%T`$l_SmRvt4Mp;^A$svS&d_L?Z33cFF*J`te~_uN;!f(vG3M1bwkdVuz=W)k-0#KG|D-4)pZ$Dj@CTW47YhM)(e1nDE4-bXwtD$|@l2^kD=P zR&V>G^HqSF`Zm>(gAQ|p!r#wxKv{z4CB59 zjAe3fE3}HN!@d!Ey#oXG7X=aC=kr33L!m|_-Ah59q|V@-Kv;&$=*F-A^(YjEU^cj1 z-qGXTftG92R5tEPcge9Fq3G?8F})^D?xCUUE5iIf(~<=)l%1Z%t$e1pg0|DH*A&(y z%B1B-WZxj3F!T2peoz+7MH|d`ITXd?KL6*eX=a5`vr>7sbel1^#7O1?EXdnyh)#6# z2!1t+Fnq)mP05Yt-rL;)s+fl%A}r7;9>Y0MShV9qMyXWgN;JE>gNSzqlEs!-{^G) z&@D-E@ZBxgR=!F?t)!~c-R6g}lvU0qwC9_&u(M;W16?;%W1v2hyDb|$oBmd?dn$_Y z;(N9dBz|io77c3BcB97^VtARuAIHKt@((|IVp$jjYzX4=eJn~?j>c`kM1ajcJzbZx zs6q17U?j@v8yxBx?So@9%=X#9srrpT!AwLQXsYB0x6$R$y2#Bvo2Q!VS|60 zDbygu(NMReFJy>xRe|Cj;5vrm&SIW}e?tw!sp(aJx5(oy!A#fQju_T%;gmeOb}g$b zZA4-C*1B+q^g!8b6A?n=boT50Ts-fVd#Q0DsK8Bl^*`o7Noc(5gwa(_7j zY2M|+-##He-}^IzqnOe2)R%S+Xz zrKN%VDFm?~ekq#~6bcHO`ecCJ7IJXh)E~?Dc(_=~udr6Z`w<;0_pj`+(1BZ_g8`Mi zNkBiGvy1P?)0$*itS4t?YhzS7OoYvSt{Hv&T4@m8w)(cB(m46)Ze@fyYBXrWCGd=W z+R*wRoQ#ZTD7@&Ta|piRnKRkFU_3OG zx80E^X8l=+X`RPI2g`%^7WR;bNavhNl~eK@puZwRAl>W*jqBsH zVU&Q%kL;K0{r#TDve|gQ(%)2ASTmBNb`__BHl{Z7_jiO7)waA@eKF1~j|)f55!WAwc{H=S;dt+iYRXauR11fS2k`m}i?ZQvWJRZwOPPA#qtF7!N9 zM-s~{&G@A~yF_GM4t=aUbkIs3^?F7^W=F#Tt3X(UE!ktY&fQLlks6N* zbKT@pT+)?>tlQFgj*01rT7hQ$a#)7awlXJ8#3{FPJYiN7_Q9@Bl zT_gHmSu6&e7$aA;^XrpbhYh-p$sCiyN|J9NB8?Sg&zc&;bVP_9ZV4OLf#s>TH*`ZAvh;LX}Py*Sr?A5FWWnbjg?54o}X{{ z>&qHO{`E+UDWTD^<5>6&McgxC-3&VaY4cS;A{*QXvCksESoHJ~30DjLSUSJO`x(?J z!0s4APM#%~q)1J#&8V;x-4zv5>bV#H`7jl)t~l`nPF{aLo#5ML?rO97Z~{3X)wiT% zR%%R*^U5cvuZTogGF|C9-JG9PK<~uGfcZHF*q8e41Y&aHRN>Vm5Y%C?(cYQ?aqDz( zb){}r_5|O<_FFTv7X5bExtp1p$$N*RKzJ1rdUvnY@q584UnGtMTTljtXcrL9MCw(s zLlgF-Bn3F8*xMQGt){spM0;`HI7wx-o+BSABEe;7YF9=kq3H+Ay|d+3=2c(uh{AXZ72i`FG^ zu($F7`nd6;{ck5G{~&qzuJwK7>=0;zu?gc-kZ8q_jP3S%``#!v5WL_SoA2K$ z_$gj@4kMRV=0;0PDNEG3oJfb*?sGvHxn@%bU-o-OMvRm&@1$)k?BdAnWW5{t3 z^J7%CukYId6c83vkqbUSzvOyFJO*MQXBll!0)6#eyLSbc zU$+$#2{5;jXu);_plA8{Up%ZoUEA=9jRa?8?A0PAs7=jIUZ!-1 zcln-w3>hn$_H&H;xU+&H;40IUXG-$fnx&B@I2ky9`*+p`O6tQs9GwiyaI81w;cAz~ zMkJh184nFNhAYoZtYi*~fRf?recdtr?te#++7xvA*Zbi78E!P{kiNDx_p^lUxKs%a zNUi5x?Pc*O7Pbz~4bIcLHlp{IsMsuohc-?a)S#YMDjM}PX71|yF<|V zJX5*nFuD?5XC`1U4RuR&Kf}YURB^Z~|1&94pZ#*+$@h;&5leBG`CHETC>>d z!iJm7FzlZgjH7PewhPTB&YBx4m`5+z9`)fxCODpDsvR1eizQLp=k2Ss+4}qlV~jmf zn(4*-&I#K4^6D(GpHpqaOj`sh=iZ&SE>BQHRQvI+da<+(F%H^m@WBkzbShc_3b;fx zRk&V9?xmwXvdGtP3NdCnD~5I69zEo&&vfd`fD{`)#A(pt&p2J5h@+e#op`-0(BK=r z6q5s-h>JAiTuZt3!EMxU9~UNe&YPn9N+3D6YE)$pAcO!<mxq_Q|*vb;{%_AWVl zd_T*l&#L?$#`8S%BR=-`a<*_bYIMbBbM(~y#YB=$gU;F%b6ska&&gV4lKDSpR{7hn zvhdQV!lAUGKPe10Ag+SybP0laE@UX;mX!m+P^n>Bve{_B zKm06;t>q?!^U-J2f$st-%)bp~*lW#BKWKgjuPbQm7cw`OhgA-VncFBh&Y<(0?ccfo zPp6?HGCb$3XXN8`K}hH63Un)%^2uPZeL{d8)z=_c^s^-mu}-a3L`8RM*xU z4lec6>bukRD0#z_fYf$>EETjK5bFo=2NPFA2^P7yMEs1U&33V-4 zf2+XUnh(cRQ2l93e^u7%kKBGt)v1E-okd2YSZZH?Um8C#U8gUG` zV~sh6B-1ov9|k}BU-y;#p5d%l`^z+?PfYtq{RRLWl5*cJC#B0+F>P8%C49^Gv1P5}JEC-fMzmJ=Q+Jxbu>0 zUjG_dVW^G8t8tvh#Sq|!M}RNBLKpVXe^B>ZY9&H=V?0mdc39ye>-@voe7^mA5JYsf zTJerdE%C7qLiD9^LEw^b63e4}G+%+js2ZiHyAgq#o_;>;Lhm-iF5; z-UBY7RSjfd4eZ*tyP&XhL^cU}e<09r+A(ecVIO?U86{Qr5l?L<>BHPswU5KMyc;A`Ml%(aE>29n05 z!haMLD+*EwCPIcs&h4Ax+@$uI@-a@z<&Ox?0+^D#MfEbx+*t+C`7runyAC5{u%R1I z_sox9x?)czy?LfStZ;ki2ny(<3SM$nu1ha`3Ml52PVc>a-@9D2aXWc4!oEB9z@vCr zFyuH7!+cMge&Q*lSni&3qYKzr6hWV*UJmW z&L>XI(qQk6*^!REN%2QPW9;#?@y#z0(0#tLp6}n>CPu`4^RpF)G(`aJ;gL1fW5{N1 zntlC*k%6Y-+||zxp+IvwtSb+d7^@G9ghW`nU8koy6Q74Z2&`u>f3;|b8u2Px-4Qr$ z4lN|e!__kG=t~u?z|+v3k?{ra(yO}~;-qRGCl9~26ZX<=D3wtdw3((k($2ou=D$07T_ z_j$lE=l0pY^_bhZ{-6})nSSs98HJrx6;3F0)Wv`32ux{NoD1h0q{q{lq7uuzI#LVs z!R!QK-qRoq$3=`}2)4D8?u=KzHsDM4DG3XM8d)s~fL zWK{dhlmr<}a3S%{&&ulIlZyXQO^VubnoZQLYwqjGN~^MX85J7XZxSdX$~-GEWCX;! zw<(B9x1Yp5aK!S6x2{LpmI#Amm&<4$e5}@3Jjq{rS`Kl^MtfeNy2Y&CuSz$hM;WNvIBFKZv*xA7~OVUyW(< z6SBBj%IBYXAiuqKu;-zIdTz?Wzjj{m7>M#Kr~+UWO$nSJ zlS=@9T}1O09v zGU2>hc|jV+$K>1BQ{+r<4Q99K(S?03Lng|4dqu(H=|hioX1MU|tjQAzY>$zT4^; zm(sU6Tq*X8O=A{i;4#W>vXG(3zpsL~=U%)Lvv+2tyv(>|MZ5hU&ce;OgY(OuyofZquOUML&N zVOm~U$~XVDy%JOIm({tXvhb?eDq$k*nlazm4_BWNH18zhuY1fJoRgK!v$gBnKK-G4 z33}{3rYEPc+p6|XiLzfVJZnA?YRqLJVxvq_+(ddyR53tCNU=%D)H9mO3y*_1)s0K^ zZhN`jZ2gd3nE?#@o>AC9g_||0EN=hN`m+08)2cS6s$<{K{lJe837A_l@y$Awh^%yI z(yi(2g+;ogx%|cg-}UmcUK6gpev#0fpubkh>KTcpBL-4AeKcOrv(Oj(u+bj|Th<^0 zdK1UwhKdZiS{Zrmuf*q-)^Z81B@2`Cn*243D)y}hd5&=^DjnDTvqz=h3ybC*KJfp! zZT0?g%?Vgl!n~L;-(iZ6Cyf>Li8gx26g= z<{L!<)4_T<>cIqJ1dCeKBjC(i3_A7VPzmUk>s{iq6?Q&ZsQUGRiI69YYVvAV-7slV zsx^UK&&>ViJV!m1n_MBi4NG7&wnS8Cew)|WV(8AQDXZW(VcLf0{Q1vr?w@&J!r#`I z38{`Kb_J`SkOLDLvuO1%rfzO_LS0_rrjst|5X51Ru1s-6Q>5;fjPkTEwUkn0#U}mt zuaUpo+eMmhs)yU1*2l6t+@FKt*>v=n@9ZMS>@aHQH_T#Sj)p8%ti$Z>OP%w>i!!O) z?3N2bl~vChhETedjEW_GoOy&{Hf=Ns1p@y>G9yi`7QmQmRqM00`i>Q;8fdz{Ny~X($nU>tKs#9Cg*L1_zJ!IUPsx%co;G_LN_YQTf2gl?i9JR zak78fu*i#oN|w5KIpc4S3aIZMlZZ6qY5z_!ZDb4~eTq|rJ%9g6he*@b_QTFQvW zAK+9L9W74-Vv6<-52uTY*Y@{Faqj27^RxB$6$PPq_XL>@{mr!+XR`j1X$}80=+is= zQQ({+a?XumiOWAF&d|HC!wWsbi*Bj)iipb|qPCob6x1Y(+$L4LHds?j1vogvQjB#r z(|XDP1j2xIxSS$F|4>@VYnJ~--S%&C++mqP;;0rMWd~K5R zgyZhRa?9kfd758VE;MN;Z7jknDq&-eJdLj~b+Ay-k;?C9C9PEy5wb19#4gAzxVVl-S&*y6XqQX3;EL`n;z z4)_owdEny7Z%u#ycVSNUi`)ndvK%PI3)}a9{5?J|*D<`b8W*XtGM%sT6yfO(3PtZ* z--#SwPO2s+8~i=*&+zZlhL723(f+AOid%9MDG1uYAdW(f9JjWCZza)ngRIpaC^8{a zncotk5p!6TY4><{6h2s7@ihxHD{FkMm@QEpQ%qvREpEAmnD;Q`;#<9ti(1EG{(=in z1}bpRW1A>s$$#D7+;Xm+i{~xOOsaFB-o)9Ol=UD>1`1@X)L1xO?A1v~ylc_p#pfzN z{0|ijfk~+O4tX6J!sUy{6U;d#1+C8Cw*(&tn3%a-xr;ES<*sWoJAlaKnz_4bllkeA zUV9ltK!-u0yU5Z^>Nhm}hbpzxxC+<}#9@d=Od(eMrJpui3DeUv^NRiuE!Pj?U!4f} z1-TRexo4BNYT@L_e^UCXERDt!rHNBcoUo#+qa5)T{pep*WKdclIp=kPAyA-p0!I3B zqoW6WPEiaHCXFV!@mv4#KTbQdBC= zw0gmmrfu+T*e=(pdaFQGQiisi_-EIA{$3~dObcp|E(lbR-I_9Xv<@?!CFZ7EW)od7I-)m*joKDvAgwH# zI&{1(oHnu=Aj)!{`A1sab497JZ{G0 z81V9MyFa(X*XF3up@1I=pfKoxl^T~FyQ&I~p-{E5Xyy1~_(?`NG0_>ic}bKr?{pHA zar+|+!;|O!((Bo@1G;qnY*wlAFY(jQm-K)as!3(UaCl=SZDUK}s50%| z3?3Wn{*shr^dH?#tGn`q0Vn5Ow8~4V<-8~&FBOYKG&4zEl^=uyMN+70(m&wFX%|)H zQ`4B{XCpwDT9!g?PWMAD5=SfjGAxdf+17$YcpoSR{l0=_A%k{_PU`GSS8&aHJg`=> zc3&J&iw<8C?GW3lM|++^@1yAwECV}A%?_ss5HkRb51GYbpriTOY6`y9U0zOFQH5SlA`~6s<8|{t30UfY?%8 zQuS6(ek_YQ!EoL#^6x(r#;DOUf8!u$icMO`+m3mG<0`G-m*Ko1 zgOtH+F@i8OPq9|{^SWe*N;Qc}@s$*DNR5#RFUtcMNd-L9pP%V@9|10N&CS(&rX&4LmOIRo&=R%zlu}Z|E`>ONqH>~Eu{X!O0VG(+ z1s>K3)h1@A2&c-KV>;5y;y`RQgac7)76kDnajQW)P2+OSgI6pR@o@#-kA<+RGOEbQ zm{$6~%KXd49^?-b(f?Z0z?Dm~UJy8!#*`8Yf6W#`1Wy^xISUTg7pWcIIQLgeZ;2Dz z#rJxcs}--_`uL9*;2Q~Y@N@Ug%-|F z>@9>L{Bj{`WMpKydfm*{elvBJE#Ps}P}k599~;-lm?D1;#UZpr@4DF0rYU&UEion& zN-|7<#(eyU$t&QJOSXJ9Pma*!@}2TyL&-(;0KqswJ@TE%1JW?@Z6p*LQQHeQXll+1 zffNNl78B0Mb_J3>PnFG|`gbuy5sIgMnCO(+4j2DTS~}a8G-zhXq^VP5G1~L6u%N-8 z0Up@B{t_A*y8XF7Ud#ia55a59ABQ1XKx{U#Y^{MpPn z(NOfl+@4ZaVlYZ|u-YJ$6I&}wttN)qQ&d#=w4&C8&k!QJi4Y`e+fh?_-Z= 400, 'First argument must be a number (400+):', statusCode); + + error.isBoom = true; + error.isServer = numberCode >= 500; + + if (!error.hasOwnProperty('data')) { + error.data = null; + } + + error.output = { + statusCode: numberCode, + payload: {}, + headers: {} + }; + + error.reformat = internals.reformat; + error.reformat(); + + if (!message && + !error.message) { + + message = error.output.payload.error; + } + + if (message) { + error.message = (message + (error.message ? ': ' + error.message : '')); + } + + return error; +}; + + +internals.reformat = function () { + + this.output.payload.statusCode = this.output.statusCode; + this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown'; + + if (this.output.statusCode === 500) { + this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user + } + else if (this.message) { + this.output.payload.message = this.message; + } +}; + + +// 4xx Client Errors + +exports.badRequest = function (message, data) { + + return internals.create(400, message, data, exports.badRequest); +}; + + +exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[]) + + var err = internals.create(401, message, undefined, exports.unauthorized); + + if (!scheme) { + return err; + } + + var wwwAuthenticate = ''; + var i = 0; + var il = 0; + + if (typeof scheme === 'string') { + + // function (message, scheme, attributes) + + wwwAuthenticate = scheme; + + if (attributes || message) { + err.output.payload.attributes = {}; + } + + if (attributes) { + var names = Object.keys(attributes); + for (i = 0, il = names.length; i < il; ++i) { + var name = names[i]; + if (i) { + wwwAuthenticate += ','; + } + + var value = attributes[name]; + if (value === null || + value === undefined) { // Value can be zero + + value = ''; + } + wwwAuthenticate += ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"'; + err.output.payload.attributes[name] = value; + } + } + + if (message) { + if (attributes) { + wwwAuthenticate += ','; + } + wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"'; + err.output.payload.attributes.error = message; + } + else { + err.isMissing = true; + } + } + else { + + // function (message, wwwAuthenticate[]) + + var wwwArray = scheme; + for (i = 0, il = wwwArray.length; i < il; ++i) { + if (i) { + wwwAuthenticate += ', '; + } + + wwwAuthenticate += wwwArray[i]; + } + } + + err.output.headers['WWW-Authenticate'] = wwwAuthenticate; + + return err; +}; + + +exports.forbidden = function (message, data) { + + return internals.create(403, message, data, exports.forbidden); +}; + + +exports.notFound = function (message, data) { + + return internals.create(404, message, data, exports.notFound); +}; + + +exports.methodNotAllowed = function (message, data) { + + return internals.create(405, message, data, exports.methodNotAllowed); +}; + + +exports.notAcceptable = function (message, data) { + + return internals.create(406, message, data, exports.notAcceptable); +}; + + +exports.proxyAuthRequired = function (message, data) { + + return internals.create(407, message, data, exports.proxyAuthRequired); +}; + + +exports.clientTimeout = function (message, data) { + + return internals.create(408, message, data, exports.clientTimeout); +}; + + +exports.conflict = function (message, data) { + + return internals.create(409, message, data, exports.conflict); +}; + + +exports.resourceGone = function (message, data) { + + return internals.create(410, message, data, exports.resourceGone); +}; + + +exports.lengthRequired = function (message, data) { + + return internals.create(411, message, data, exports.lengthRequired); +}; + + +exports.preconditionFailed = function (message, data) { + + return internals.create(412, message, data, exports.preconditionFailed); +}; + + +exports.entityTooLarge = function (message, data) { + + return internals.create(413, message, data, exports.entityTooLarge); +}; + + +exports.uriTooLong = function (message, data) { + + return internals.create(414, message, data, exports.uriTooLong); +}; + + +exports.unsupportedMediaType = function (message, data) { + + return internals.create(415, message, data, exports.unsupportedMediaType); +}; + + +exports.rangeNotSatisfiable = function (message, data) { + + return internals.create(416, message, data, exports.rangeNotSatisfiable); +}; + + +exports.expectationFailed = function (message, data) { + + return internals.create(417, message, data, exports.expectationFailed); +}; + +exports.badData = function (message, data) { + + return internals.create(422, message, data, exports.badData); +}; + + +exports.preconditionRequired = function (message, data) { + + return internals.create(428, message, data, exports.preconditionRequired); +}; + + +exports.tooManyRequests = function (message, data) { + + return internals.create(429, message, data, exports.tooManyRequests); +}; + + +// 5xx Server Errors + +exports.internal = function (message, data, statusCode) { + + return internals.serverError(message, data, statusCode, exports.internal); +}; + +internals.serverError = function (message, data, statusCode, ctor) { + + var error; + if (data instanceof Error) { + error = exports.wrap(data, statusCode, message); + } else { + error = internals.create(statusCode || 500, message, undefined, ctor); + error.data = data; + } + + return error; +}; + + +exports.notImplemented = function (message, data) { + + return internals.serverError(message, data, 501, exports.notImplemented); +}; + + +exports.badGateway = function (message, data) { + + return internals.serverError(message, data, 502, exports.badGateway); +}; + + +exports.serverTimeout = function (message, data) { + + return internals.serverError(message, data, 503, exports.serverTimeout); +}; + + +exports.gatewayTimeout = function (message, data) { + + return internals.serverError(message, data, 504, exports.gatewayTimeout); +}; + + +exports.badImplementation = function (message, data) { + + var err = internals.serverError(message, data, 500, exports.badImplementation); + err.isDeveloperError = true; + return err; +}; diff --git a/node_modules/boom/package.json b/node_modules/boom/package.json new file mode 100644 index 000000000..d9d7d5216 --- /dev/null +++ b/node_modules/boom/package.json @@ -0,0 +1,89 @@ +{ + "_args": [ + [ + "boom@2.x.x", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\hawk" + ] + ], + "_from": "boom@>=2.0.0-0 <3.0.0-0", + "_id": "boom@2.10.1", + "_inCache": true, + "_location": "/boom", + "_nodeVersion": "0.10.40", + "_npmUser": { + "email": "arbretz@gmail.com", + "name": "arb" + }, + "_npmVersion": "2.11.1", + "_phantomChildren": {}, + "_requested": { + "name": "boom", + "raw": "boom@2.x.x", + "rawSpec": "2.x.x", + "scope": null, + "spec": ">=2.0.0-0 <3.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/cryptiles", + "/hawk" + ], + "_resolved": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz", + "_shasum": "39c8918ceff5799f83f9492a848f625add0c766f", + "_shrinkwrap": null, + "_spec": "boom@2.x.x", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\hawk", + "bugs": { + "url": "https://github.com/hapijs/boom/issues" + }, + "dependencies": { + "hoek": "2.x.x" + }, + "description": "HTTP-friendly error objects", + "devDependencies": { + "code": "1.x.x", + "lab": "7.x.x" + }, + "directories": {}, + "dist": { + "shasum": "39c8918ceff5799f83f9492a848f625add0c766f", + "tarball": "https://registry.npmjs.org/boom/-/boom-2.10.1.tgz" + }, + "engines": { + "node": ">=0.10.40" + }, + "gitHead": "ff1a662a86b39426cdd18f4441b112d307a34a6f", + "homepage": "https://github.com/hapijs/boom#readme", + "installable": true, + "keywords": [ + "error", + "http" + ], + "license": "BSD-3-Clause", + "main": "lib/index.js", + "maintainers": [ + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + }, + { + "name": "wyatt", + "email": "wpreul@gmail.com" + }, + { + "name": "arb", + "email": "arbretz@gmail.com" + } + ], + "name": "boom", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/hapijs/boom.git" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-cov-html": "lab -a code -r html -o coverage.html -L" + }, + "version": "2.10.1" +} diff --git a/node_modules/boom/test/index.js b/node_modules/boom/test/index.js new file mode 100644 index 000000000..79a59e9f4 --- /dev/null +++ b/node_modules/boom/test/index.js @@ -0,0 +1,654 @@ +// Load modules + +var Code = require('code'); +var Boom = require('../lib'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.describe; +var it = lab.it; +var expect = Code.expect; + + +it('returns the same object when already boom', function (done) { + + var error = Boom.badRequest(); + var wrapped = Boom.wrap(error); + expect(error).to.equal(wrapped); + done(); +}); + +it('returns an error with info when constructed using another error', function (done) { + + var error = new Error('ka-boom'); + error.xyz = 123; + var err = Boom.wrap(error); + expect(err.xyz).to.equal(123); + expect(err.message).to.equal('ka-boom'); + expect(err.output).to.deep.equal({ + statusCode: 500, + payload: { + statusCode: 500, + error: 'Internal Server Error', + message: 'An internal server error occurred' + }, + headers: {} + }); + expect(err.data).to.equal(null); + done(); +}); + +it('does not override data when constructed using another error', function (done) { + + var error = new Error('ka-boom'); + error.data = { useful: 'data' }; + var err = Boom.wrap(error); + expect(err.data).to.equal(error.data); + done(); +}); + +it('sets new message when none exists', function (done) { + + var error = new Error(); + var wrapped = Boom.wrap(error, 400, 'something bad'); + expect(wrapped.message).to.equal('something bad'); + done(); +}); + +it('throws when statusCode is not a number', function (done) { + + expect(function () { + + Boom.create('x'); + }).to.throw('First argument must be a number (400+): x'); + done(); +}); + +it('will cast a number-string to an integer', function (done) { + + var codes = [ + { input: '404', result: 404 }, + { input: '404.1', result: 404 }, + { input: 400, result: 400 }, + { input: 400.123, result: 400 }]; + for (var i = 0, il = codes.length; i < il; ++i) { + var code = codes[i]; + var err = Boom.create(code.input); + expect(err.output.statusCode).to.equal(code.result); + } + + done(); +}); + +it('throws when statusCode is not finite', function (done) { + + expect(function () { + + Boom.create(1 / 0); + }).to.throw('First argument must be a number (400+): null'); + done(); +}); + +it('sets error code to unknown', function (done) { + + var err = Boom.create(999); + expect(err.output.payload.error).to.equal('Unknown'); + done(); +}); + +describe('create()', function () { + + it('does not sets null message', function (done) { + + var error = Boom.unauthorized(null); + expect(error.output.payload.message).to.not.exist(); + expect(error.isServer).to.be.false(); + done(); + }); + + it('sets message and data', function (done) { + + var error = Boom.badRequest('Missing data', { type: 'user' }); + expect(error.data.type).to.equal('user'); + expect(error.output.payload.message).to.equal('Missing data'); + done(); + }); +}); + +describe('isBoom()', function () { + + it('returns true for Boom object', function (done) { + + expect(Boom.badRequest().isBoom).to.equal(true); + done(); + }); + + it('returns false for Error object', function (done) { + + expect((new Error()).isBoom).to.not.exist(); + done(); + }); +}); + +describe('badRequest()', function () { + + it('returns a 400 error statusCode', function (done) { + + var error = Boom.badRequest(); + + expect(error.output.statusCode).to.equal(400); + expect(error.isServer).to.be.false(); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.badRequest('my message').message).to.equal('my message'); + done(); + }); + + it('sets the message to HTTP status if none provided', function (done) { + + expect(Boom.badRequest().message).to.equal('Bad Request'); + done(); + }); +}); + +describe('unauthorized()', function () { + + it('returns a 401 error statusCode', function (done) { + + var err = Boom.unauthorized(); + expect(err.output.statusCode).to.equal(401); + expect(err.output.headers).to.deep.equal({}); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.unauthorized('my message').message).to.equal('my message'); + done(); + }); + + it('returns a WWW-Authenticate header when passed a scheme', function (done) { + + var err = Boom.unauthorized('boom', 'Test'); + expect(err.output.statusCode).to.equal(401); + expect(err.output.headers['WWW-Authenticate']).to.equal('Test error="boom"'); + done(); + }); + + it('returns a WWW-Authenticate header set to the schema array value', function (done) { + + var err = Boom.unauthorized(null, ['Test','one','two']); + expect(err.output.statusCode).to.equal(401); + expect(err.output.headers['WWW-Authenticate']).to.equal('Test, one, two'); + done(); + }); + + it('returns a WWW-Authenticate header when passed a scheme and attributes', function (done) { + + var err = Boom.unauthorized('boom', 'Test', { a: 1, b: 'something', c: null, d: 0 }); + expect(err.output.statusCode).to.equal(401); + expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"'); + expect(err.output.payload.attributes).to.deep.equal({ a: 1, b: 'something', c: '', d: 0, error: 'boom' }); + done(); + }); + + it('returns a WWW-Authenticate header when passed attributes, missing error', function (done) { + + var err = Boom.unauthorized(null, 'Test', { a: 1, b: 'something', c: null, d: 0 }); + expect(err.output.statusCode).to.equal(401); + expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0"'); + expect(err.isMissing).to.equal(true); + done(); + }); + + it('sets the isMissing flag when error message is empty', function (done) { + + var err = Boom.unauthorized('', 'Basic'); + expect(err.isMissing).to.equal(true); + done(); + }); + + it('does not set the isMissing flag when error message is not empty', function (done) { + + var err = Boom.unauthorized('message', 'Basic'); + expect(err.isMissing).to.equal(undefined); + done(); + }); + + it('sets a WWW-Authenticate when passed as an array', function (done) { + + var err = Boom.unauthorized('message', ['Basic', 'Example e="1"', 'Another x="3", y="4"']); + expect(err.output.headers['WWW-Authenticate']).to.equal('Basic, Example e="1", Another x="3", y="4"'); + done(); + }); +}); + + +describe('methodNotAllowed()', function () { + + it('returns a 405 error statusCode', function (done) { + + expect(Boom.methodNotAllowed().output.statusCode).to.equal(405); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.methodNotAllowed('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('notAcceptable()', function () { + + it('returns a 406 error statusCode', function (done) { + + expect(Boom.notAcceptable().output.statusCode).to.equal(406); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.notAcceptable('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('proxyAuthRequired()', function () { + + it('returns a 407 error statusCode', function (done) { + + expect(Boom.proxyAuthRequired().output.statusCode).to.equal(407); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.proxyAuthRequired('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('clientTimeout()', function () { + + it('returns a 408 error statusCode', function (done) { + + expect(Boom.clientTimeout().output.statusCode).to.equal(408); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.clientTimeout('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('conflict()', function () { + + it('returns a 409 error statusCode', function (done) { + + expect(Boom.conflict().output.statusCode).to.equal(409); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.conflict('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('resourceGone()', function () { + + it('returns a 410 error statusCode', function (done) { + + expect(Boom.resourceGone().output.statusCode).to.equal(410); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.resourceGone('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('lengthRequired()', function () { + + it('returns a 411 error statusCode', function (done) { + + expect(Boom.lengthRequired().output.statusCode).to.equal(411); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.lengthRequired('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('preconditionFailed()', function () { + + it('returns a 412 error statusCode', function (done) { + + expect(Boom.preconditionFailed().output.statusCode).to.equal(412); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.preconditionFailed('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('entityTooLarge()', function () { + + it('returns a 413 error statusCode', function (done) { + + expect(Boom.entityTooLarge().output.statusCode).to.equal(413); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.entityTooLarge('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('uriTooLong()', function () { + + it('returns a 414 error statusCode', function (done) { + + expect(Boom.uriTooLong().output.statusCode).to.equal(414); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.uriTooLong('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('unsupportedMediaType()', function () { + + it('returns a 415 error statusCode', function (done) { + + expect(Boom.unsupportedMediaType().output.statusCode).to.equal(415); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.unsupportedMediaType('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('rangeNotSatisfiable()', function () { + + it('returns a 416 error statusCode', function (done) { + + expect(Boom.rangeNotSatisfiable().output.statusCode).to.equal(416); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.rangeNotSatisfiable('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('expectationFailed()', function () { + + it('returns a 417 error statusCode', function (done) { + + expect(Boom.expectationFailed().output.statusCode).to.equal(417); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.expectationFailed('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('badData()', function () { + + it('returns a 422 error statusCode', function (done) { + + expect(Boom.badData().output.statusCode).to.equal(422); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.badData('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('preconditionRequired()', function () { + + it('returns a 428 error statusCode', function (done) { + + expect(Boom.preconditionRequired().output.statusCode).to.equal(428); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.preconditionRequired('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('tooManyRequests()', function () { + + it('returns a 429 error statusCode', function (done) { + + expect(Boom.tooManyRequests().output.statusCode).to.equal(429); + done(); + }); + + it('sets the message with the passed-in message', function (done) { + + expect(Boom.tooManyRequests('my message').message).to.equal('my message'); + done(); + }); +}); + +describe('serverTimeout()', function () { + + it('returns a 503 error statusCode', function (done) { + + expect(Boom.serverTimeout().output.statusCode).to.equal(503); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.serverTimeout('my message').message).to.equal('my message'); + done(); + }); +}); + +describe('forbidden()', function () { + + it('returns a 403 error statusCode', function (done) { + + expect(Boom.forbidden().output.statusCode).to.equal(403); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.forbidden('my message').message).to.equal('my message'); + done(); + }); +}); + +describe('notFound()', function () { + + it('returns a 404 error statusCode', function (done) { + + expect(Boom.notFound().output.statusCode).to.equal(404); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.notFound('my message').message).to.equal('my message'); + done(); + }); +}); + +describe('internal()', function () { + + it('returns a 500 error statusCode', function (done) { + + expect(Boom.internal().output.statusCode).to.equal(500); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + var err = Boom.internal('my message'); + expect(err.message).to.equal('my message'); + expect(err.isServer).to.true(); + expect(err.output.payload.message).to.equal('An internal server error occurred'); + done(); + }); + + it('passes data on the callback if its passed in', function (done) { + + expect(Boom.internal('my message', { my: 'data' }).data.my).to.equal('data'); + done(); + }); + + it('returns an error with composite message', function (done) { + + try { + JSON.parse('{'); + } + catch (err) { + var boom = Boom.internal('Someting bad', err); + expect(boom.message).to.equal('Someting bad: Unexpected end of input'); + expect(boom.isServer).to.be.true(); + done(); + } + }); +}); + +describe('notImplemented()', function () { + + it('returns a 501 error statusCode', function (done) { + + expect(Boom.notImplemented().output.statusCode).to.equal(501); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.notImplemented('my message').message).to.equal('my message'); + done(); + }); +}); + + +describe('badGateway()', function () { + + it('returns a 502 error statusCode', function (done) { + + expect(Boom.badGateway().output.statusCode).to.equal(502); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.badGateway('my message').message).to.equal('my message'); + done(); + }); +}); + +describe('gatewayTimeout()', function () { + + it('returns a 504 error statusCode', function (done) { + + expect(Boom.gatewayTimeout().output.statusCode).to.equal(504); + done(); + }); + + it('sets the message with the passed in message', function (done) { + + expect(Boom.gatewayTimeout('my message').message).to.equal('my message'); + done(); + }); +}); + +describe('badImplementation()', function () { + + it('returns a 500 error statusCode', function (done) { + + var err = Boom.badImplementation(); + expect(err.output.statusCode).to.equal(500); + expect(err.isDeveloperError).to.equal(true); + expect(err.isServer).to.be.true(); + done(); + }); +}); + +describe('stack trace', function () { + + it('should omit lib', function (done) { + + ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', + 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', + 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', + 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', + 'badData', 'preconditionRequired', 'tooManyRequests', + + // 500s + 'internal', 'notImplemented', 'badGateway', 'serverTimeout', 'gatewayTimeout', + 'badImplementation' + ].forEach(function (name) { + + var err = Boom[name](); + expect(err.stack).to.not.match(/\/lib\/index\.js/); + }); + + done(); + }); +}); diff --git a/node_modules/browserify-mime/.npmignore b/node_modules/browserify-mime/.npmignore new file mode 100644 index 000000000..e2385fa8b --- /dev/null +++ b/node_modules/browserify-mime/.npmignore @@ -0,0 +1,3 @@ +types +generate.js +main.js diff --git a/node_modules/browserify-mime/LICENSE b/node_modules/browserify-mime/LICENSE new file mode 100644 index 000000000..451fc4550 --- /dev/null +++ b/node_modules/browserify-mime/LICENSE @@ -0,0 +1,19 @@ +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/browserify-mime/README.md b/node_modules/browserify-mime/README.md new file mode 100644 index 000000000..b90552a3b --- /dev/null +++ b/node_modules/browserify-mime/README.md @@ -0,0 +1,63 @@ +# mime + +Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + + var mime = require('mime'); + + mime.lookup('/path/to/file.txt'); // => 'text/plain' + mime.lookup('file.txt'); // => 'text/plain' + mime.lookup('.TXT'); // => 'text/plain' + mime.lookup('htm'); // => 'text/html' + +### mime.extension(type) +Get the default extension for `type` + + mime.extension('text/html'); // => 'html' + mime.extension('application/octet-stream'); // => 'bin' + +### mime.charsets.lookup() + +Map mime-type to charset + + mime.charsets.lookup('text/plain'); // => 'UTF-8' + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). + +### mime.define() + +Add custom mime/extension mappings + + mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... + }); + + mime.lookup('x-sft'); // => 'text/x-some-format' + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + + mime.extension('text/x-some-format'); // => 'x-sf' + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + + mime.load('./my_project.types'); + +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/browserify-mime/browserify-mime.js b/node_modules/browserify-mime/browserify-mime.js new file mode 100644 index 000000000..d24bdbe03 --- /dev/null +++ b/node_modules/browserify-mime/browserify-mime.js @@ -0,0 +1,1813 @@ +//this file was generated +"use strict" +var mime = module.exports = { + lookup: function (path, fallback) { + var ext = path.replace(/.*[\.\/]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +} + , default_type: "application/octet-stream" + , types: { + "123": "application/vnd.lotus-1-2-3", + "ez": "application/andrew-inset", + "aw": "application/applixware", + "atom": "application/atom+xml", + "atomcat": "application/atomcat+xml", + "atomsvc": "application/atomsvc+xml", + "ccxml": "application/ccxml+xml", + "cdmia": "application/cdmi-capability", + "cdmic": "application/cdmi-container", + "cdmid": "application/cdmi-domain", + "cdmio": "application/cdmi-object", + "cdmiq": "application/cdmi-queue", + "cu": "application/cu-seeme", + "davmount": "application/davmount+xml", + "dbk": "application/docbook+xml", + "dssc": "application/dssc+der", + "xdssc": "application/dssc+xml", + "ecma": "application/ecmascript", + "emma": "application/emma+xml", + "epub": "application/epub+zip", + "exi": "application/exi", + "pfr": "application/font-tdpfr", + "gml": "application/gml+xml", + "gpx": "application/gpx+xml", + "gxf": "application/gxf", + "stk": "application/hyperstudio", + "ink": "application/inkml+xml", + "inkml": "application/inkml+xml", + "ipfix": "application/ipfix", + "jar": "application/java-archive", + "ser": "application/java-serialized-object", + "class": "application/java-vm", + "js": "application/javascript", + "json": "application/json", + "jsonml": "application/jsonml+json", + "lostxml": "application/lost+xml", + "hqx": "application/mac-binhex40", + "cpt": "application/mac-compactpro", + "mads": "application/mads+xml", + "mrc": "application/marc", + "mrcx": "application/marcxml+xml", + "ma": "application/mathematica", + "nb": "application/mathematica", + "mb": "application/mathematica", + "mathml": "application/mathml+xml", + "mbox": "application/mbox", + "mscml": "application/mediaservercontrol+xml", + "metalink": "application/metalink+xml", + "meta4": "application/metalink4+xml", + "mets": "application/mets+xml", + "mods": "application/mods+xml", + "m21": "application/mp21", + "mp21": "application/mp21", + "mp4s": "application/mp4", + "doc": "application/msword", + "dot": "application/msword", + "mxf": "application/mxf", + "bin": "application/octet-stream", + "dms": "application/octet-stream", + "lrf": "application/octet-stream", + "mar": "application/octet-stream", + "so": "application/octet-stream", + "dist": "application/octet-stream", + "distz": "application/octet-stream", + "pkg": "application/octet-stream", + "bpk": "application/octet-stream", + "dump": "application/octet-stream", + "elc": "application/octet-stream", + "deploy": "application/octet-stream", + "oda": "application/oda", + "opf": "application/oebps-package+xml", + "ogx": "application/ogg", + "omdoc": "application/omdoc+xml", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "onetmp": "application/onenote", + "onepkg": "application/onenote", + "oxps": "application/oxps", + "xer": "application/patch-ops-error+xml", + "pdf": "application/pdf", + "pgp": "application/pgp-encrypted", + "asc": "application/pgp-signature", + "sig": "application/pgp-signature", + "prf": "application/pics-rules", + "p10": "application/pkcs10", + "p7m": "application/pkcs7-mime", + "p7c": "application/pkcs7-mime", + "p7s": "application/pkcs7-signature", + "p8": "application/pkcs8", + "ac": "application/pkix-attr-cert", + "cer": "application/pkix-cert", + "crl": "application/pkix-crl", + "pkipath": "application/pkix-pkipath", + "pki": "application/pkixcmp", + "pls": "application/pls+xml", + "ai": "application/postscript", + "eps": "application/postscript", + "ps": "application/postscript", + "cww": "application/prs.cww", + "pskcxml": "application/pskc+xml", + "rdf": "application/rdf+xml", + "rif": "application/reginfo+xml", + "rnc": "application/relax-ng-compact-syntax", + "rl": "application/resource-lists+xml", + "rld": "application/resource-lists-diff+xml", + "rs": "application/rls-services+xml", + "gbr": "application/rpki-ghostbusters", + "mft": "application/rpki-manifest", + "roa": "application/rpki-roa", + "rsd": "application/rsd+xml", + "rss": "application/rss+xml", + "rtf": "application/rtf", + "sbml": "application/sbml+xml", + "scq": "application/scvp-cv-request", + "scs": "application/scvp-cv-response", + "spq": "application/scvp-vp-request", + "spp": "application/scvp-vp-response", + "sdp": "application/sdp", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "shf": "application/shf+xml", + "smi": "application/smil+xml", + "smil": "application/smil+xml", + "rq": "application/sparql-query", + "srx": "application/sparql-results+xml", + "gram": "application/srgs", + "grxml": "application/srgs+xml", + "sru": "application/sru+xml", + "ssdl": "application/ssdl+xml", + "ssml": "application/ssml+xml", + "tei": "application/tei+xml", + "teicorpus": "application/tei+xml", + "tfi": "application/thraud+xml", + "tsd": "application/timestamped-data", + "plb": "application/vnd.3gpp.pic-bw-large", + "psb": "application/vnd.3gpp.pic-bw-small", + "pvb": "application/vnd.3gpp.pic-bw-var", + "tcap": "application/vnd.3gpp2.tcap", + "pwn": "application/vnd.3m.post-it-notes", + "aso": "application/vnd.accpac.simply.aso", + "imp": "application/vnd.accpac.simply.imp", + "acu": "application/vnd.acucobol", + "atc": "application/vnd.acucorp", + "acutc": "application/vnd.acucorp", + "air": "application/vnd.adobe.air-application-installer-package+zip", + "fcdt": "application/vnd.adobe.formscentral.fcdt", + "fxp": "application/vnd.adobe.fxp", + "fxpl": "application/vnd.adobe.fxp", + "xdp": "application/vnd.adobe.xdp+xml", + "xfdf": "application/vnd.adobe.xfdf", + "ahead": "application/vnd.ahead.space", + "azf": "application/vnd.airzip.filesecure.azf", + "azs": "application/vnd.airzip.filesecure.azs", + "azw": "application/vnd.amazon.ebook", + "acc": "application/vnd.americandynamics.acc", + "ami": "application/vnd.amiga.ami", + "apk": "application/vnd.android.package-archive", + "cii": "application/vnd.anser-web-certificate-issue-initiation", + "fti": "application/vnd.anser-web-funds-transfer-initiation", + "atx": "application/vnd.antix.game-component", + "mpkg": "application/vnd.apple.installer+xml", + "m3u8": "application/vnd.apple.mpegurl", + "swi": "application/vnd.aristanetworks.swi", + "iota": "application/vnd.astraea-software.iota", + "aep": "application/vnd.audiograph", + "mpm": "application/vnd.blueice.multipass", + "bmi": "application/vnd.bmi", + "rep": "application/vnd.businessobjects", + "cdxml": "application/vnd.chemdraw+xml", + "mmd": "application/vnd.chipnuts.karaoke-mmd", + "cdy": "application/vnd.cinderella", + "cla": "application/vnd.claymore", + "rp9": "application/vnd.cloanto.rp9", + "c4g": "application/vnd.clonk.c4group", + "c4d": "application/vnd.clonk.c4group", + "c4f": "application/vnd.clonk.c4group", + "c4p": "application/vnd.clonk.c4group", + "c4u": "application/vnd.clonk.c4group", + "c11amc": "application/vnd.cluetrust.cartomobile-config", + "c11amz": "application/vnd.cluetrust.cartomobile-config-pkg", + "csp": "application/vnd.commonspace", + "cdbcmsg": "application/vnd.contact.cmsg", + "cmc": "application/vnd.cosmocaller", + "clkx": "application/vnd.crick.clicker", + "clkk": "application/vnd.crick.clicker.keyboard", + "clkp": "application/vnd.crick.clicker.palette", + "clkt": "application/vnd.crick.clicker.template", + "clkw": "application/vnd.crick.clicker.wordbank", + "wbs": "application/vnd.criticaltools.wbs+xml", + "pml": "application/vnd.ctc-posml", + "ppd": "application/vnd.cups-ppd", + "car": "application/vnd.curl.car", + "pcurl": "application/vnd.curl.pcurl", + "dart": "application/vnd.dart", + "rdz": "application/vnd.data-vision.rdz", + "uvf": "application/vnd.dece.data", + "uvvf": "application/vnd.dece.data", + "uvd": "application/vnd.dece.data", + "uvvd": "application/vnd.dece.data", + "uvt": "application/vnd.dece.ttml+xml", + "uvvt": "application/vnd.dece.ttml+xml", + "uvx": "application/vnd.dece.unspecified", + "uvvx": "application/vnd.dece.unspecified", + "uvz": "application/vnd.dece.zip", + "uvvz": "application/vnd.dece.zip", + "fe_launch": "application/vnd.denovo.fcselayout-link", + "dna": "application/vnd.dna", + "mlp": "application/vnd.dolby.mlp", + "dpg": "application/vnd.dpgraph", + "dfac": "application/vnd.dreamfactory", + "kpxx": "application/vnd.ds-keypoint", + "ait": "application/vnd.dvb.ait", + "svc": "application/vnd.dvb.service", + "geo": "application/vnd.dynageo", + "mag": "application/vnd.ecowin.chart", + "nml": "application/vnd.enliven", + "esf": "application/vnd.epson.esf", + "msf": "application/vnd.epson.msf", + "qam": "application/vnd.epson.quickanime", + "slt": "application/vnd.epson.salt", + "ssf": "application/vnd.epson.ssf", + "es3": "application/vnd.eszigno3+xml", + "et3": "application/vnd.eszigno3+xml", + "ez2": "application/vnd.ezpix-album", + "ez3": "application/vnd.ezpix-package", + "fdf": "application/vnd.fdf", + "mseed": "application/vnd.fdsn.mseed", + "seed": "application/vnd.fdsn.seed", + "dataless": "application/vnd.fdsn.seed", + "gph": "application/vnd.flographit", + "ftc": "application/vnd.fluxtime.clip", + "fm": "application/vnd.framemaker", + "frame": "application/vnd.framemaker", + "maker": "application/vnd.framemaker", + "book": "application/vnd.framemaker", + "fnc": "application/vnd.frogans.fnc", + "ltf": "application/vnd.frogans.ltf", + "fsc": "application/vnd.fsc.weblaunch", + "oas": "application/vnd.fujitsu.oasys", + "oa2": "application/vnd.fujitsu.oasys2", + "oa3": "application/vnd.fujitsu.oasys3", + "fg5": "application/vnd.fujitsu.oasysgp", + "bh2": "application/vnd.fujitsu.oasysprs", + "ddd": "application/vnd.fujixerox.ddd", + "xdw": "application/vnd.fujixerox.docuworks", + "xbd": "application/vnd.fujixerox.docuworks.binder", + "fzs": "application/vnd.fuzzysheet", + "txd": "application/vnd.genomatix.tuxedo", + "ggb": "application/vnd.geogebra.file", + "ggt": "application/vnd.geogebra.tool", + "gex": "application/vnd.geometry-explorer", + "gre": "application/vnd.geometry-explorer", + "gxt": "application/vnd.geonext", + "g2w": "application/vnd.geoplan", + "g3w": "application/vnd.geospace", + "gmx": "application/vnd.gmx", + "kml": "application/vnd.google-earth.kml+xml", + "kmz": "application/vnd.google-earth.kmz", + "gqf": "application/vnd.grafeq", + "gqs": "application/vnd.grafeq", + "gac": "application/vnd.groove-account", + "ghf": "application/vnd.groove-help", + "gim": "application/vnd.groove-identity-message", + "grv": "application/vnd.groove-injector", + "gtm": "application/vnd.groove-tool-message", + "tpl": "application/vnd.groove-tool-template", + "vcg": "application/vnd.groove-vcard", + "hal": "application/vnd.hal+xml", + "zmm": "application/vnd.handheld-entertainment+xml", + "hbci": "application/vnd.hbci", + "les": "application/vnd.hhe.lesson-player", + "hpgl": "application/vnd.hp-hpgl", + "hpid": "application/vnd.hp-hpid", + "hps": "application/vnd.hp-hps", + "jlt": "application/vnd.hp-jlyt", + "pcl": "application/vnd.hp-pcl", + "pclxl": "application/vnd.hp-pclxl", + "sfd-hdstx": "application/vnd.hydrostatix.sof-data", + "mpy": "application/vnd.ibm.minipay", + "afp": "application/vnd.ibm.modcap", + "listafp": "application/vnd.ibm.modcap", + "list3820": "application/vnd.ibm.modcap", + "irm": "application/vnd.ibm.rights-management", + "sc": "application/vnd.ibm.secure-container", + "icc": "application/vnd.iccprofile", + "icm": "application/vnd.iccprofile", + "igl": "application/vnd.igloader", + "ivp": "application/vnd.immervision-ivp", + "ivu": "application/vnd.immervision-ivu", + "igm": "application/vnd.insors.igm", + "xpw": "application/vnd.intercon.formnet", + "xpx": "application/vnd.intercon.formnet", + "i2g": "application/vnd.intergeo", + "qbo": "application/vnd.intu.qbo", + "qfx": "application/vnd.intu.qfx", + "rcprofile": "application/vnd.ipunplugged.rcprofile", + "irp": "application/vnd.irepository.package+xml", + "xpr": "application/vnd.is-xpr", + "fcs": "application/vnd.isac.fcs", + "jam": "application/vnd.jam", + "rms": "application/vnd.jcp.javame.midlet-rms", + "jisp": "application/vnd.jisp", + "joda": "application/vnd.joost.joda-archive", + "ktz": "application/vnd.kahootz", + "ktr": "application/vnd.kahootz", + "karbon": "application/vnd.kde.karbon", + "chrt": "application/vnd.kde.kchart", + "kfo": "application/vnd.kde.kformula", + "flw": "application/vnd.kde.kivio", + "kon": "application/vnd.kde.kontour", + "kpr": "application/vnd.kde.kpresenter", + "kpt": "application/vnd.kde.kpresenter", + "ksp": "application/vnd.kde.kspread", + "kwd": "application/vnd.kde.kword", + "kwt": "application/vnd.kde.kword", + "htke": "application/vnd.kenameaapp", + "kia": "application/vnd.kidspiration", + "kne": "application/vnd.kinar", + "knp": "application/vnd.kinar", + "skp": "application/vnd.koan", + "skd": "application/vnd.koan", + "skt": "application/vnd.koan", + "skm": "application/vnd.koan", + "sse": "application/vnd.kodak-descriptor", + "lasxml": "application/vnd.las.las+xml", + "lbd": "application/vnd.llamagraphics.life-balance.desktop", + "lbe": "application/vnd.llamagraphics.life-balance.exchange+xml", + "apr": "application/vnd.lotus-approach", + "pre": "application/vnd.lotus-freelance", + "nsf": "application/vnd.lotus-notes", + "org": "application/vnd.lotus-organizer", + "scm": "application/vnd.lotus-screencam", + "lwp": "application/vnd.lotus-wordpro", + "portpkg": "application/vnd.macports.portpkg", + "mcd": "application/vnd.mcd", + "mc1": "application/vnd.medcalcdata", + "cdkey": "application/vnd.mediastation.cdkey", + "mwf": "application/vnd.mfer", + "mfm": "application/vnd.mfmp", + "flo": "application/vnd.micrografx.flo", + "igx": "application/vnd.micrografx.igx", + "mif": "application/vnd.mif", + "daf": "application/vnd.mobius.daf", + "dis": "application/vnd.mobius.dis", + "mbk": "application/vnd.mobius.mbk", + "mqy": "application/vnd.mobius.mqy", + "msl": "application/vnd.mobius.msl", + "plc": "application/vnd.mobius.plc", + "txf": "application/vnd.mobius.txf", + "mpn": "application/vnd.mophun.application", + "mpc": "application/vnd.mophun.certificate", + "xul": "application/vnd.mozilla.xul+xml", + "cil": "application/vnd.ms-artgalry", + "cab": "application/vnd.ms-cab-compressed", + "xls": "application/vnd.ms-excel", + "xlm": "application/vnd.ms-excel", + "xla": "application/vnd.ms-excel", + "xlc": "application/vnd.ms-excel", + "xlt": "application/vnd.ms-excel", + "xlw": "application/vnd.ms-excel", + "xlam": "application/vnd.ms-excel.addin.macroenabled.12", + "xlsb": "application/vnd.ms-excel.sheet.binary.macroenabled.12", + "xlsm": "application/vnd.ms-excel.sheet.macroenabled.12", + "xltm": "application/vnd.ms-excel.template.macroenabled.12", + "eot": "application/vnd.ms-fontobject", + "chm": "application/vnd.ms-htmlhelp", + "ims": "application/vnd.ms-ims", + "lrm": "application/vnd.ms-lrm", + "thmx": "application/vnd.ms-officetheme", + "cat": "application/vnd.ms-pki.seccat", + "stl": "application/vnd.ms-pki.stl", + "ppt": "application/vnd.ms-powerpoint", + "pps": "application/vnd.ms-powerpoint", + "pot": "application/vnd.ms-powerpoint", + "ppam": "application/vnd.ms-powerpoint.addin.macroenabled.12", + "pptm": "application/vnd.ms-powerpoint.presentation.macroenabled.12", + "sldm": "application/vnd.ms-powerpoint.slide.macroenabled.12", + "ppsm": "application/vnd.ms-powerpoint.slideshow.macroenabled.12", + "potm": "application/vnd.ms-powerpoint.template.macroenabled.12", + "mpp": "application/vnd.ms-project", + "mpt": "application/vnd.ms-project", + "docm": "application/vnd.ms-word.document.macroenabled.12", + "dotm": "application/vnd.ms-word.template.macroenabled.12", + "wps": "application/vnd.ms-works", + "wks": "application/vnd.ms-works", + "wcm": "application/vnd.ms-works", + "wdb": "application/vnd.ms-works", + "wpl": "application/vnd.ms-wpl", + "xps": "application/vnd.ms-xpsdocument", + "mseq": "application/vnd.mseq", + "mus": "application/vnd.musician", + "msty": "application/vnd.muvee.style", + "taglet": "application/vnd.mynfc", + "nlu": "application/vnd.neurolanguage.nlu", + "ntf": "application/vnd.nitf", + "nitf": "application/vnd.nitf", + "nnd": "application/vnd.noblenet-directory", + "nns": "application/vnd.noblenet-sealer", + "nnw": "application/vnd.noblenet-web", + "ngdat": "application/vnd.nokia.n-gage.data", + "n-gage": "application/vnd.nokia.n-gage.symbian.install", + "rpst": "application/vnd.nokia.radio-preset", + "rpss": "application/vnd.nokia.radio-presets", + "edm": "application/vnd.novadigm.edm", + "edx": "application/vnd.novadigm.edx", + "ext": "application/vnd.novadigm.ext", + "odc": "application/vnd.oasis.opendocument.chart", + "otc": "application/vnd.oasis.opendocument.chart-template", + "odb": "application/vnd.oasis.opendocument.database", + "odf": "application/vnd.oasis.opendocument.formula", + "odft": "application/vnd.oasis.opendocument.formula-template", + "odg": "application/vnd.oasis.opendocument.graphics", + "otg": "application/vnd.oasis.opendocument.graphics-template", + "odi": "application/vnd.oasis.opendocument.image", + "oti": "application/vnd.oasis.opendocument.image-template", + "odp": "application/vnd.oasis.opendocument.presentation", + "otp": "application/vnd.oasis.opendocument.presentation-template", + "ods": "application/vnd.oasis.opendocument.spreadsheet", + "ots": "application/vnd.oasis.opendocument.spreadsheet-template", + "odt": "application/vnd.oasis.opendocument.text", + "odm": "application/vnd.oasis.opendocument.text-master", + "ott": "application/vnd.oasis.opendocument.text-template", + "oth": "application/vnd.oasis.opendocument.text-web", + "xo": "application/vnd.olpc-sugar", + "dd2": "application/vnd.oma.dd2+xml", + "oxt": "application/vnd.openofficeorg.extension", + "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", + "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", + "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", + "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + "mgp": "application/vnd.osgeo.mapguide.package", + "dp": "application/vnd.osgi.dp", + "esa": "application/vnd.osgi.subsystem", + "pdb": "application/vnd.palm", + "pqa": "application/vnd.palm", + "oprc": "application/vnd.palm", + "paw": "application/vnd.pawaafile", + "str": "application/vnd.pg.format", + "ei6": "application/vnd.pg.osasli", + "efif": "application/vnd.picsel", + "wg": "application/vnd.pmi.widget", + "plf": "application/vnd.pocketlearn", + "pbd": "application/vnd.powerbuilder6", + "box": "application/vnd.previewsystems.box", + "mgz": "application/vnd.proteus.magazine", + "qps": "application/vnd.publishare-delta-tree", + "ptid": "application/vnd.pvi.ptid1", + "qxd": "application/vnd.quark.quarkxpress", + "qxt": "application/vnd.quark.quarkxpress", + "qwd": "application/vnd.quark.quarkxpress", + "qwt": "application/vnd.quark.quarkxpress", + "qxl": "application/vnd.quark.quarkxpress", + "qxb": "application/vnd.quark.quarkxpress", + "bed": "application/vnd.realvnc.bed", + "mxl": "application/vnd.recordare.musicxml", + "musicxml": "application/vnd.recordare.musicxml+xml", + "cryptonote": "application/vnd.rig.cryptonote", + "cod": "application/vnd.rim.cod", + "rm": "application/vnd.rn-realmedia", + "rmvb": "application/vnd.rn-realmedia-vbr", + "link66": "application/vnd.route66.link66+xml", + "st": "application/vnd.sailingtracker.track", + "see": "application/vnd.seemail", + "sema": "application/vnd.sema", + "semd": "application/vnd.semd", + "semf": "application/vnd.semf", + "ifm": "application/vnd.shana.informed.formdata", + "itp": "application/vnd.shana.informed.formtemplate", + "iif": "application/vnd.shana.informed.interchange", + "ipk": "application/vnd.shana.informed.package", + "twd": "application/vnd.simtech-mindmapper", + "twds": "application/vnd.simtech-mindmapper", + "mmf": "application/vnd.smaf", + "teacher": "application/vnd.smart.teacher", + "sdkm": "application/vnd.solent.sdkm+xml", + "sdkd": "application/vnd.solent.sdkm+xml", + "dxp": "application/vnd.spotfire.dxp", + "sfs": "application/vnd.spotfire.sfs", + "sdc": "application/vnd.stardivision.calc", + "sda": "application/vnd.stardivision.draw", + "sdd": "application/vnd.stardivision.impress", + "smf": "application/vnd.stardivision.math", + "sdw": "application/vnd.stardivision.writer", + "vor": "application/vnd.stardivision.writer", + "sgl": "application/vnd.stardivision.writer-global", + "smzip": "application/vnd.stepmania.package", + "sm": "application/vnd.stepmania.stepchart", + "sxc": "application/vnd.sun.xml.calc", + "stc": "application/vnd.sun.xml.calc.template", + "sxd": "application/vnd.sun.xml.draw", + "std": "application/vnd.sun.xml.draw.template", + "sxi": "application/vnd.sun.xml.impress", + "sti": "application/vnd.sun.xml.impress.template", + "sxm": "application/vnd.sun.xml.math", + "sxw": "application/vnd.sun.xml.writer", + "sxg": "application/vnd.sun.xml.writer.global", + "stw": "application/vnd.sun.xml.writer.template", + "sus": "application/vnd.sus-calendar", + "susp": "application/vnd.sus-calendar", + "svd": "application/vnd.svd", + "sis": "application/vnd.symbian.install", + "sisx": "application/vnd.symbian.install", + "xsm": "application/vnd.syncml+xml", + "bdm": "application/vnd.syncml.dm+wbxml", + "xdm": "application/vnd.syncml.dm+xml", + "tao": "application/vnd.tao.intent-module-archive", + "pcap": "application/vnd.tcpdump.pcap", + "cap": "application/vnd.tcpdump.pcap", + "dmp": "application/vnd.tcpdump.pcap", + "tmo": "application/vnd.tmobile-livetv", + "tpt": "application/vnd.trid.tpt", + "mxs": "application/vnd.triscape.mxs", + "tra": "application/vnd.trueapp", + "ufd": "application/vnd.ufdl", + "ufdl": "application/vnd.ufdl", + "utz": "application/vnd.uiq.theme", + "umj": "application/vnd.umajin", + "unityweb": "application/vnd.unity", + "uoml": "application/vnd.uoml+xml", + "vcx": "application/vnd.vcx", + "vsd": "application/vnd.visio", + "vst": "application/vnd.visio", + "vss": "application/vnd.visio", + "vsw": "application/vnd.visio", + "vis": "application/vnd.visionary", + "vsf": "application/vnd.vsf", + "wbxml": "application/vnd.wap.wbxml", + "wmlc": "application/vnd.wap.wmlc", + "wmlsc": "application/vnd.wap.wmlscriptc", + "wtb": "application/vnd.webturbo", + "nbp": "application/vnd.wolfram.player", + "wpd": "application/vnd.wordperfect", + "wqd": "application/vnd.wqd", + "stf": "application/vnd.wt.stf", + "xar": "application/vnd.xara", + "xfdl": "application/vnd.xfdl", + "hvd": "application/vnd.yamaha.hv-dic", + "hvs": "application/vnd.yamaha.hv-script", + "hvp": "application/vnd.yamaha.hv-voice", + "osf": "application/vnd.yamaha.openscoreformat", + "osfpvg": "application/vnd.yamaha.openscoreformat.osfpvg+xml", + "saf": "application/vnd.yamaha.smaf-audio", + "spf": "application/vnd.yamaha.smaf-phrase", + "cmp": "application/vnd.yellowriver-custom-menu", + "zir": "application/vnd.zul", + "zirz": "application/vnd.zul", + "zaz": "application/vnd.zzazz.deck+xml", + "vxml": "application/voicexml+xml", + "wgt": "application/widget", + "hlp": "application/winhlp", + "wsdl": "application/wsdl+xml", + "wspolicy": "application/wspolicy+xml", + "7z": "application/x-7z-compressed", + "abw": "application/x-abiword", + "ace": "application/x-ace-compressed", + "dmg": "application/x-apple-diskimage", + "aab": "application/x-authorware-bin", + "x32": "application/x-authorware-bin", + "u32": "application/x-authorware-bin", + "vox": "application/x-authorware-bin", + "aam": "application/x-authorware-map", + "aas": "application/x-authorware-seg", + "bcpio": "application/x-bcpio", + "torrent": "application/x-bittorrent", + "blb": "application/x-blorb", + "blorb": "application/x-blorb", + "bz": "application/x-bzip", + "bz2": "application/x-bzip2", + "boz": "application/x-bzip2", + "cbr": "application/x-cbr", + "cba": "application/x-cbr", + "cbt": "application/x-cbr", + "cbz": "application/x-cbr", + "cb7": "application/x-cbr", + "vcd": "application/x-cdlink", + "cfs": "application/x-cfs-compressed", + "chat": "application/x-chat", + "pgn": "application/x-chess-pgn", + "nsc": "application/x-conference", + "cpio": "application/x-cpio", + "csh": "application/x-csh", + "deb": "application/x-debian-package", + "udeb": "application/x-debian-package", + "dgc": "application/x-dgc-compressed", + "dir": "application/x-director", + "dcr": "application/x-director", + "dxr": "application/x-director", + "cst": "application/x-director", + "cct": "application/x-director", + "cxt": "application/x-director", + "w3d": "application/x-director", + "fgd": "application/x-director", + "swa": "application/x-director", + "wad": "application/x-doom", + "ncx": "application/x-dtbncx+xml", + "dtb": "application/x-dtbook+xml", + "res": "application/x-dtbresource+xml", + "dvi": "application/x-dvi", + "evy": "application/x-envoy", + "eva": "application/x-eva", + "bdf": "application/x-font-bdf", + "gsf": "application/x-font-ghostscript", + "psf": "application/x-font-linux-psf", + "otf": "application/x-font-otf", + "pcf": "application/x-font-pcf", + "snf": "application/x-font-snf", + "ttf": "application/x-font-ttf", + "ttc": "application/x-font-ttf", + "pfa": "application/x-font-type1", + "pfb": "application/x-font-type1", + "pfm": "application/x-font-type1", + "afm": "application/x-font-type1", + "woff": "application/x-font-woff", + "arc": "application/x-freearc", + "spl": "application/x-futuresplash", + "gca": "application/x-gca-compressed", + "ulx": "application/x-glulx", + "gnumeric": "application/x-gnumeric", + "gramps": "application/x-gramps-xml", + "gtar": "application/x-gtar", + "hdf": "application/x-hdf", + "install": "application/x-install-instructions", + "iso": "application/x-iso9660-image", + "jnlp": "application/x-java-jnlp-file", + "latex": "application/x-latex", + "lzh": "application/x-lzh-compressed", + "lha": "application/x-lzh-compressed", + "mie": "application/x-mie", + "prc": "application/x-mobipocket-ebook", + "mobi": "application/x-mobipocket-ebook", + "application": "application/x-ms-application", + "lnk": "application/x-ms-shortcut", + "wmd": "application/x-ms-wmd", + "wmz": "application/x-msmetafile", + "xbap": "application/x-ms-xbap", + "mdb": "application/x-msaccess", + "obd": "application/x-msbinder", + "crd": "application/x-mscardfile", + "clp": "application/x-msclip", + "exe": "application/x-msdownload", + "dll": "application/x-msdownload", + "com": "application/x-msdownload", + "bat": "application/x-msdownload", + "msi": "application/x-msdownload", + "mvb": "application/x-msmediaview", + "m13": "application/x-msmediaview", + "m14": "application/x-msmediaview", + "wmf": "application/x-msmetafile", + "emf": "application/x-msmetafile", + "emz": "application/x-msmetafile", + "mny": "application/x-msmoney", + "pub": "application/x-mspublisher", + "scd": "application/x-msschedule", + "trm": "application/x-msterminal", + "wri": "application/x-mswrite", + "nc": "application/x-netcdf", + "cdf": "application/x-netcdf", + "nzb": "application/x-nzb", + "p12": "application/x-pkcs12", + "pfx": "application/x-pkcs12", + "p7b": "application/x-pkcs7-certificates", + "spc": "application/x-pkcs7-certificates", + "p7r": "application/x-pkcs7-certreqresp", + "rar": "application/x-rar-compressed", + "ris": "application/x-research-info-systems", + "sh": "application/x-sh", + "shar": "application/x-shar", + "swf": "application/x-shockwave-flash", + "xap": "application/x-silverlight-app", + "sql": "application/x-sql", + "sit": "application/x-stuffit", + "sitx": "application/x-stuffitx", + "srt": "application/x-subrip", + "sv4cpio": "application/x-sv4cpio", + "sv4crc": "application/x-sv4crc", + "t3": "application/x-t3vm-image", + "gam": "application/x-tads", + "tar": "application/x-tar", + "tcl": "application/x-tcl", + "tex": "application/x-tex", + "tfm": "application/x-tex-tfm", + "texinfo": "application/x-texinfo", + "texi": "application/x-texinfo", + "obj": "application/x-tgif", + "ustar": "application/x-ustar", + "src": "application/x-wais-source", + "der": "application/x-x509-ca-cert", + "crt": "application/x-x509-ca-cert", + "fig": "application/x-xfig", + "xlf": "application/x-xliff+xml", + "xpi": "application/x-xpinstall", + "xz": "application/x-xz", + "z1": "application/x-zmachine", + "z2": "application/x-zmachine", + "z3": "application/x-zmachine", + "z4": "application/x-zmachine", + "z5": "application/x-zmachine", + "z6": "application/x-zmachine", + "z7": "application/x-zmachine", + "z8": "application/x-zmachine", + "xaml": "application/xaml+xml", + "xdf": "application/xcap-diff+xml", + "xenc": "application/xenc+xml", + "xhtml": "application/xhtml+xml", + "xht": "application/xhtml+xml", + "xml": "application/xml", + "xsl": "application/xml", + "dtd": "application/xml-dtd", + "xop": "application/xop+xml", + "xpl": "application/xproc+xml", + "xslt": "application/xslt+xml", + "xspf": "application/xspf+xml", + "mxml": "application/xv+xml", + "xhvml": "application/xv+xml", + "xvml": "application/xv+xml", + "xvm": "application/xv+xml", + "yang": "application/yang", + "yin": "application/yin+xml", + "zip": "application/zip", + "adp": "audio/adpcm", + "au": "audio/basic", + "snd": "audio/basic", + "mid": "audio/midi", + "midi": "audio/midi", + "kar": "audio/midi", + "rmi": "audio/midi", + "mp4a": "audio/mp4", + "mpga": "audio/mpeg", + "mp2": "audio/mpeg", + "mp2a": "audio/mpeg", + "mp3": "audio/mpeg", + "m2a": "audio/mpeg", + "m3a": "audio/mpeg", + "oga": "audio/ogg", + "ogg": "audio/ogg", + "spx": "audio/ogg", + "s3m": "audio/s3m", + "sil": "audio/silk", + "uva": "audio/vnd.dece.audio", + "uvva": "audio/vnd.dece.audio", + "eol": "audio/vnd.digital-winds", + "dra": "audio/vnd.dra", + "dts": "audio/vnd.dts", + "dtshd": "audio/vnd.dts.hd", + "lvp": "audio/vnd.lucent.voice", + "pya": "audio/vnd.ms-playready.media.pya", + "ecelp4800": "audio/vnd.nuera.ecelp4800", + "ecelp7470": "audio/vnd.nuera.ecelp7470", + "ecelp9600": "audio/vnd.nuera.ecelp9600", + "rip": "audio/vnd.rip", + "weba": "audio/webm", + "aac": "audio/x-aac", + "aif": "audio/x-aiff", + "aiff": "audio/x-aiff", + "aifc": "audio/x-aiff", + "caf": "audio/x-caf", + "flac": "audio/x-flac", + "mka": "audio/x-matroska", + "m3u": "audio/x-mpegurl", + "wax": "audio/x-ms-wax", + "wma": "audio/x-ms-wma", + "ram": "audio/x-pn-realaudio", + "ra": "audio/x-pn-realaudio", + "rmp": "audio/x-pn-realaudio-plugin", + "wav": "audio/x-wav", + "xm": "audio/xm", + "cdx": "chemical/x-cdx", + "cif": "chemical/x-cif", + "cmdf": "chemical/x-cmdf", + "cml": "chemical/x-cml", + "csml": "chemical/x-csml", + "xyz": "chemical/x-xyz", + "bmp": "image/bmp", + "cgm": "image/cgm", + "g3": "image/g3fax", + "gif": "image/gif", + "ief": "image/ief", + "jpeg": "image/jpeg", + "jpg": "image/jpeg", + "jpe": "image/jpeg", + "ktx": "image/ktx", + "png": "image/png", + "btif": "image/prs.btif", + "sgi": "image/sgi", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "tiff": "image/tiff", + "tif": "image/tiff", + "psd": "image/vnd.adobe.photoshop", + "uvi": "image/vnd.dece.graphic", + "uvvi": "image/vnd.dece.graphic", + "uvg": "image/vnd.dece.graphic", + "uvvg": "image/vnd.dece.graphic", + "sub": "text/vnd.dvb.subtitle", + "djvu": "image/vnd.djvu", + "djv": "image/vnd.djvu", + "dwg": "image/vnd.dwg", + "dxf": "image/vnd.dxf", + "fbs": "image/vnd.fastbidsheet", + "fpx": "image/vnd.fpx", + "fst": "image/vnd.fst", + "mmr": "image/vnd.fujixerox.edmics-mmr", + "rlc": "image/vnd.fujixerox.edmics-rlc", + "mdi": "image/vnd.ms-modi", + "wdp": "image/vnd.ms-photo", + "npx": "image/vnd.net-fpx", + "wbmp": "image/vnd.wap.wbmp", + "xif": "image/vnd.xiff", + "webp": "image/webp", + "3ds": "image/x-3ds", + "ras": "image/x-cmu-raster", + "cmx": "image/x-cmx", + "fh": "image/x-freehand", + "fhc": "image/x-freehand", + "fh4": "image/x-freehand", + "fh5": "image/x-freehand", + "fh7": "image/x-freehand", + "ico": "image/x-icon", + "sid": "image/x-mrsid-image", + "pcx": "image/x-pcx", + "pic": "image/x-pict", + "pct": "image/x-pict", + "pnm": "image/x-portable-anymap", + "pbm": "image/x-portable-bitmap", + "pgm": "image/x-portable-graymap", + "ppm": "image/x-portable-pixmap", + "rgb": "image/x-rgb", + "tga": "image/x-tga", + "xbm": "image/x-xbitmap", + "xpm": "image/x-xpixmap", + "xwd": "image/x-xwindowdump", + "eml": "message/rfc822", + "mime": "message/rfc822", + "igs": "model/iges", + "iges": "model/iges", + "msh": "model/mesh", + "mesh": "model/mesh", + "silo": "model/mesh", + "dae": "model/vnd.collada+xml", + "dwf": "model/vnd.dwf", + "gdl": "model/vnd.gdl", + "gtw": "model/vnd.gtw", + "mts": "model/vnd.mts", + "vtu": "model/vnd.vtu", + "wrl": "model/vrml", + "vrml": "model/vrml", + "x3db": "model/x3d+binary", + "x3dbz": "model/x3d+binary", + "x3dv": "model/x3d+vrml", + "x3dvz": "model/x3d+vrml", + "x3d": "model/x3d+xml", + "x3dz": "model/x3d+xml", + "appcache": "text/cache-manifest", + "ics": "text/calendar", + "ifb": "text/calendar", + "css": "text/css", + "csv": "text/csv", + "html": "text/html", + "htm": "text/html", + "n3": "text/n3", + "txt": "text/plain", + "text": "text/plain", + "conf": "text/plain", + "def": "text/plain", + "list": "text/plain", + "log": "text/plain", + "in": "text/plain", + "dsc": "text/prs.lines.tag", + "rtx": "text/richtext", + "sgml": "text/sgml", + "sgm": "text/sgml", + "tsv": "text/tab-separated-values", + "t": "text/troff", + "tr": "text/troff", + "roff": "text/troff", + "man": "text/troff", + "me": "text/troff", + "ms": "text/troff", + "ttl": "text/turtle", + "uri": "text/uri-list", + "uris": "text/uri-list", + "urls": "text/uri-list", + "vcard": "text/vcard", + "curl": "text/vnd.curl", + "dcurl": "text/vnd.curl.dcurl", + "scurl": "text/vnd.curl.scurl", + "mcurl": "text/vnd.curl.mcurl", + "fly": "text/vnd.fly", + "flx": "text/vnd.fmi.flexstor", + "gv": "text/vnd.graphviz", + "3dml": "text/vnd.in3d.3dml", + "spot": "text/vnd.in3d.spot", + "jad": "text/vnd.sun.j2me.app-descriptor", + "wml": "text/vnd.wap.wml", + "wmls": "text/vnd.wap.wmlscript", + "s": "text/x-asm", + "asm": "text/x-asm", + "c": "text/x-c", + "cc": "text/x-c", + "cxx": "text/x-c", + "cpp": "text/x-c", + "h": "text/x-c", + "hh": "text/x-c", + "dic": "text/x-c", + "f": "text/x-fortran", + "for": "text/x-fortran", + "f77": "text/x-fortran", + "f90": "text/x-fortran", + "java": "text/x-java-source", + "opml": "text/x-opml", + "p": "text/x-pascal", + "pas": "text/x-pascal", + "nfo": "text/x-nfo", + "etx": "text/x-setext", + "sfv": "text/x-sfv", + "uu": "text/x-uuencode", + "vcs": "text/x-vcalendar", + "vcf": "text/x-vcard", + "3gp": "video/3gpp", + "3g2": "video/3gpp2", + "h261": "video/h261", + "h263": "video/h263", + "h264": "video/h264", + "jpgv": "video/jpeg", + "jpm": "video/jpm", + "jpgm": "video/jpm", + "mj2": "video/mj2", + "mjp2": "video/mj2", + "mp4": "video/mp4", + "mp4v": "video/mp4", + "mpg4": "video/mp4", + "mpeg": "video/mpeg", + "mpg": "video/mpeg", + "mpe": "video/mpeg", + "m1v": "video/mpeg", + "m2v": "video/mpeg", + "ogv": "video/ogg", + "qt": "video/quicktime", + "mov": "video/quicktime", + "uvh": "video/vnd.dece.hd", + "uvvh": "video/vnd.dece.hd", + "uvm": "video/vnd.dece.mobile", + "uvvm": "video/vnd.dece.mobile", + "uvp": "video/vnd.dece.pd", + "uvvp": "video/vnd.dece.pd", + "uvs": "video/vnd.dece.sd", + "uvvs": "video/vnd.dece.sd", + "uvv": "video/vnd.dece.video", + "uvvv": "video/vnd.dece.video", + "dvb": "video/vnd.dvb.file", + "fvt": "video/vnd.fvt", + "mxu": "video/vnd.mpegurl", + "m4u": "video/vnd.mpegurl", + "pyv": "video/vnd.ms-playready.media.pyv", + "uvu": "video/vnd.uvvu.mp4", + "uvvu": "video/vnd.uvvu.mp4", + "viv": "video/vnd.vivo", + "webm": "video/webm", + "f4v": "video/x-f4v", + "fli": "video/x-fli", + "flv": "video/x-flv", + "m4v": "video/x-m4v", + "mkv": "video/x-matroska", + "mk3d": "video/x-matroska", + "mks": "video/x-matroska", + "mng": "video/x-mng", + "asf": "video/x-ms-asf", + "asx": "video/x-ms-asf", + "vob": "video/x-ms-vob", + "wm": "video/x-ms-wm", + "wmv": "video/x-ms-wmv", + "wmx": "video/x-ms-wmx", + "wvx": "video/x-ms-wvx", + "avi": "video/x-msvideo", + "movie": "video/x-sgi-movie", + "smv": "video/x-smv", + "ice": "x-conference/x-cooltalk", + "vtt": "text/vtt", + "crx": "application/x-chrome-extension", + "htc": "text/x-component", + "manifest": "text/cache-manifest", + "buffer": "application/octet-stream", + "m4p": "application/mp4", + "m4a": "audio/mp4", + "ts": "video/MP2T", + "event-stream": "text/event-stream", + "webapp": "application/x-web-app-manifest+json", + "lua": "text/x-lua", + "luac": "application/x-lua-bytecode", + "markdown": "text/x-markdown", + "md": "text/x-markdown", + "mkd": "text/x-markdown" +} + , extensions: { + "application/andrew-inset": "ez", + "application/applixware": "aw", + "application/atom+xml": "atom", + "application/atomcat+xml": "atomcat", + "application/atomsvc+xml": "atomsvc", + "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/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/gml+xml": "gml", + "application/gpx+xml": "gpx", + "application/gxf": "gxf", + "application/hyperstudio": "stk", + "application/inkml+xml": "ink", + "application/ipfix": "ipfix", + "application/java-archive": "jar", + "application/java-serialized-object": "ser", + "application/java-vm": "class", + "application/javascript": "js", + "application/json": "json", + "application/jsonml+json": "jsonml", + "application/lost+xml": "lostxml", + "application/mac-binhex40": "hqx", + "application/mac-compactpro": "cpt", + "application/mads+xml": "mads", + "application/marc": "mrc", + "application/marcxml+xml": "mrcx", + "application/mathematica": "ma", + "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", + "application/mp4": "mp4s", + "application/msword": "doc", + "application/mxf": "mxf", + "application/octet-stream": "bin", + "application/oda": "oda", + "application/oebps-package+xml": "opf", + "application/ogg": "ogx", + "application/omdoc+xml": "omdoc", + "application/onenote": "onetoc", + "application/oxps": "oxps", + "application/patch-ops-error+xml": "xer", + "application/pdf": "pdf", + "application/pgp-encrypted": "pgp", + "application/pgp-signature": "asc", + "application/pics-rules": "prf", + "application/pkcs10": "p10", + "application/pkcs7-mime": "p7m", + "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", + "application/prs.cww": "cww", + "application/pskc+xml": "pskcxml", + "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", + "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", + "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", + "application/vnd.adobe.air-application-installer-package+zip": "air", + "application/vnd.adobe.formscentral.fcdt": "fcdt", + "application/vnd.adobe.fxp": "fxp", + "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.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", + "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", + "application/vnd.dece.ttml+xml": "uvt", + "application/vnd.dece.unspecified": "uvx", + "application/vnd.dece.zip": "uvz", + "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", + "application/vnd.ezpix-album": "ez2", + "application/vnd.ezpix-package": "ez3", + "application/vnd.fdf": "fdf", + "application/vnd.fdsn.mseed": "mseed", + "application/vnd.fdsn.seed": "seed", + "application/vnd.flographit": "gph", + "application/vnd.fluxtime.clip": "ftc", + "application/vnd.framemaker": "fm", + "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", + "application/vnd.geonext": "gxt", + "application/vnd.geoplan": "g2w", + "application/vnd.geospace": "g3w", + "application/vnd.gmx": "gmx", + "application/vnd.google-earth.kml+xml": "kml", + "application/vnd.google-earth.kmz": "kmz", + "application/vnd.grafeq": "gqf", + "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", + "application/vnd.ibm.rights-management": "irm", + "application/vnd.ibm.secure-container": "sc", + "application/vnd.iccprofile": "icc", + "application/vnd.igloader": "igl", + "application/vnd.immervision-ivp": "ivp", + "application/vnd.immervision-ivu": "ivu", + "application/vnd.insors.igm": "igm", + "application/vnd.intercon.formnet": "xpw", + "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", + "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", + "application/vnd.kde.kspread": "ksp", + "application/vnd.kde.kword": "kwd", + "application/vnd.kenameaapp": "htke", + "application/vnd.kidspiration": "kia", + "application/vnd.kinar": "kne", + "application/vnd.koan": "skp", + "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", + "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-pki.seccat": "cat", + "application/vnd.ms-pki.stl": "stl", + "application/vnd.ms-powerpoint": "ppt", + "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", + "application/vnd.ms-word.document.macroenabled.12": "docm", + "application/vnd.ms-word.template.macroenabled.12": "dotm", + "application/vnd.ms-works": "wps", + "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", + "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", + "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", + "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", + "application/vnd.smaf": "mmf", + "application/vnd.smart.teacher": "teacher", + "application/vnd.solent.sdkm+xml": "sdkm", + "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", + "application/vnd.stardivision.writer-global": "sgl", + "application/vnd.stepmania.package": "smzip", + "application/vnd.stepmania.stepchart": "sm", + "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", + "application/vnd.svd": "svd", + "application/vnd.symbian.install": "sis", + "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", + "application/vnd.tmobile-livetv": "tmo", + "application/vnd.trid.tpt": "tpt", + "application/vnd.triscape.mxs": "mxs", + "application/vnd.trueapp": "tra", + "application/vnd.ufdl": "ufd", + "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", + "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", + "application/vnd.zzazz.deck+xml": "zaz", + "application/voicexml+xml": "vxml", + "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": "dmg", + "application/x-authorware-bin": "aab", + "application/x-authorware-map": "aam", + "application/x-authorware-seg": "aas", + "application/x-bcpio": "bcpio", + "application/x-bittorrent": "torrent", + "application/x-blorb": "blb", + "application/x-bzip": "bz", + "application/x-bzip2": "bz2", + "application/x-cbr": "cbr", + "application/x-cdlink": "vcd", + "application/x-cfs-compressed": "cfs", + "application/x-chat": "chat", + "application/x-chess-pgn": "pgn", + "application/x-conference": "nsc", + "application/x-cpio": "cpio", + "application/x-csh": "csh", + "application/x-debian-package": "deb", + "application/x-dgc-compressed": "dgc", + "application/x-director": "dir", + "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-otf": "otf", + "application/x-font-pcf": "pcf", + "application/x-font-snf": "snf", + "application/x-font-ttf": "ttf", + "application/x-font-type1": "pfa", + "application/x-font-woff": "woff", + "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-install-instructions": "install", + "application/x-iso9660-image": "iso", + "application/x-java-jnlp-file": "jnlp", + "application/x-latex": "latex", + "application/x-lzh-compressed": "lzh", + "application/x-mie": "mie", + "application/x-mobipocket-ebook": "prc", + "application/x-ms-application": "application", + "application/x-ms-shortcut": "lnk", + "application/x-ms-wmd": "wmd", + "application/x-ms-wmz": "wmz", + "application/x-ms-xbap": "xbap", + "application/x-msaccess": "mdb", + "application/x-msbinder": "obd", + "application/x-mscardfile": "crd", + "application/x-msclip": "clp", + "application/x-msdownload": "exe", + "application/x-msmediaview": "mvb", + "application/x-msmetafile": "wmf", + "application/x-msmoney": "mny", + "application/x-mspublisher": "pub", + "application/x-msschedule": "scd", + "application/x-msterminal": "trm", + "application/x-mswrite": "wri", + "application/x-netcdf": "nc", + "application/x-nzb": "nzb", + "application/x-pkcs12": "p12", + "application/x-pkcs7-certificates": "p7b", + "application/x-pkcs7-certreqresp": "p7r", + "application/x-rar-compressed": "rar", + "application/x-research-info-systems": "ris", + "application/x-sh": "sh", + "application/x-shar": "shar", + "application/x-shockwave-flash": "swf", + "application/x-silverlight-app": "xap", + "application/x-sql": "sql", + "application/x-stuffit": "sit", + "application/x-stuffitx": "sitx", + "application/x-subrip": "srt", + "application/x-sv4cpio": "sv4cpio", + "application/x-sv4crc": "sv4crc", + "application/x-t3vm-image": "t3", + "application/x-tads": "gam", + "application/x-tar": "tar", + "application/x-tcl": "tcl", + "application/x-tex": "tex", + "application/x-tex-tfm": "tfm", + "application/x-texinfo": "texinfo", + "application/x-tgif": "obj", + "application/x-ustar": "ustar", + "application/x-wais-source": "src", + "application/x-x509-ca-cert": "der", + "application/x-xfig": "fig", + "application/x-xliff+xml": "xlf", + "application/x-xpinstall": "xpi", + "application/x-xz": "xz", + "application/x-zmachine": "z1", + "application/xaml+xml": "xaml", + "application/xcap-diff+xml": "xdf", + "application/xenc+xml": "xenc", + "application/xhtml+xml": "xhtml", + "application/xml": "xml", + "application/xml-dtd": "dtd", + "application/xop+xml": "xop", + "application/xproc+xml": "xpl", + "application/xslt+xml": "xslt", + "application/xspf+xml": "xspf", + "application/xv+xml": "mxml", + "application/yang": "yang", + "application/yin+xml": "yin", + "application/zip": "zip", + "audio/adpcm": "adp", + "audio/basic": "au", + "audio/midi": "mid", + "audio/mp4": "mp4a", + "audio/mpeg": "mpga", + "audio/ogg": "oga", + "audio/s3m": "s3m", + "audio/silk": "sil", + "audio/vnd.dece.audio": "uva", + "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/webm": "weba", + "audio/x-aac": "aac", + "audio/x-aiff": "aif", + "audio/x-caf": "caf", + "audio/x-flac": "flac", + "audio/x-matroska": "mka", + "audio/x-mpegurl": "m3u", + "audio/x-ms-wax": "wax", + "audio/x-ms-wma": "wma", + "audio/x-pn-realaudio": "ram", + "audio/x-pn-realaudio-plugin": "rmp", + "audio/x-wav": "wav", + "audio/xm": "xm", + "chemical/x-cdx": "cdx", + "chemical/x-cif": "cif", + "chemical/x-cmdf": "cmdf", + "chemical/x-cml": "cml", + "chemical/x-csml": "csml", + "chemical/x-xyz": "xyz", + "image/bmp": "bmp", + "image/cgm": "cgm", + "image/g3fax": "g3", + "image/gif": "gif", + "image/ief": "ief", + "image/jpeg": "jpeg", + "image/ktx": "ktx", + "image/png": "png", + "image/prs.btif": "btif", + "image/sgi": "sgi", + "image/svg+xml": "svg", + "image/tiff": "tiff", + "image/vnd.adobe.photoshop": "psd", + "image/vnd.dece.graphic": "uvi", + "image/vnd.dvb.subtitle": "sub", + "image/vnd.djvu": "djvu", + "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", + "image/x-icon": "ico", + "image/x-mrsid-image": "sid", + "image/x-pcx": "pcx", + "image/x-pict": "pic", + "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", + "model/iges": "igs", + "model/mesh": "msh", + "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", + "model/x3d+binary": "x3db", + "model/x3d+vrml": "x3dv", + "model/x3d+xml": "x3d", + "text/cache-manifest": "appcache", + "text/calendar": "ics", + "text/css": "css", + "text/csv": "csv", + "text/html": "html", + "text/n3": "n3", + "text/plain": "txt", + "text/prs.lines.tag": "dsc", + "text/richtext": "rtx", + "text/sgml": "sgml", + "text/tab-separated-values": "tsv", + "text/troff": "t", + "text/turtle": "ttl", + "text/uri-list": "uri", + "text/vcard": "vcard", + "text/vnd.curl": "curl", + "text/vnd.curl.dcurl": "dcurl", + "text/vnd.curl.scurl": "scurl", + "text/vnd.curl.mcurl": "mcurl", + "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/x-asm": "s", + "text/x-c": "c", + "text/x-fortran": "f", + "text/x-java-source": "java", + "text/x-opml": "opml", + "text/x-pascal": "p", + "text/x-nfo": "nfo", + "text/x-setext": "etx", + "text/x-sfv": "sfv", + "text/x-uuencode": "uu", + "text/x-vcalendar": "vcs", + "text/x-vcard": "vcf", + "video/3gpp": "3gp", + "video/3gpp2": "3g2", + "video/h261": "h261", + "video/h263": "h263", + "video/h264": "h264", + "video/jpeg": "jpgv", + "video/jpm": "jpm", + "video/mj2": "mj2", + "video/mp4": "mp4", + "video/mpeg": "mpeg", + "video/ogg": "ogv", + "video/quicktime": "qt", + "video/vnd.dece.hd": "uvh", + "video/vnd.dece.mobile": "uvm", + "video/vnd.dece.pd": "uvp", + "video/vnd.dece.sd": "uvs", + "video/vnd.dece.video": "uvv", + "video/vnd.dvb.file": "dvb", + "video/vnd.fvt": "fvt", + "video/vnd.mpegurl": "mxu", + "video/vnd.ms-playready.media.pyv": "pyv", + "video/vnd.uvvu.mp4": "uvu", + "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", + "video/x-mng": "mng", + "video/x-ms-asf": "asf", + "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", + "text/vtt": "vtt", + "application/x-chrome-extension": "crx", + "text/x-component": "htc", + "video/MP2T": "ts", + "text/event-stream": "event-stream", + "application/x-web-app-manifest+json": "webapp", + "text/x-lua": "lua", + "application/x-lua-bytecode": "luac", + "text/x-markdown": "markdown" +} + , extension: function (mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +} + , define: function (map) { + for (var type in map) { + var exts = map[type]; + + for (var i = 0; i < exts.length; i++) { + if (false && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +} + , charsets: {lookup: function (mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + }} +} +mime.types.constructor = undefined +mime.extensions.constructor = undefined \ No newline at end of file diff --git a/node_modules/browserify-mime/mime.js b/node_modules/browserify-mime/mime.js new file mode 100644 index 000000000..8a7eb093f --- /dev/null +++ b/node_modules/browserify-mime/mime.js @@ -0,0 +1,114 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts]) { + console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/.*[\.\/]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Load local copy of +// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +mime.load(path.join(__dirname, 'types/mime.types')); + +// Load additional types from node.js community +mime.load(path.join(__dirname, 'types/node.types')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/browserify-mime/package.json b/node_modules/browserify-mime/package.json new file mode 100644 index 000000000..b598f77c8 --- /dev/null +++ b/node_modules/browserify-mime/package.json @@ -0,0 +1,76 @@ +{ + "_args": [ + [ + "browserify-mime@~1.2.9", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage" + ] + ], + "_from": "browserify-mime@>=1.2.9-0 <1.3.0-0", + "_id": "browserify-mime@1.2.9", + "_inCache": true, + "_location": "/browserify-mime", + "_npmUser": { + "email": "coverslide@gmail.com", + "name": "coverslide" + }, + "_npmVersion": "1.2.0", + "_phantomChildren": {}, + "_requested": { + "name": "browserify-mime", + "raw": "browserify-mime@~1.2.9", + "rawSpec": "~1.2.9", + "scope": null, + "spec": ">=1.2.9-0 <1.3.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage" + ], + "_resolved": "https://registry.npmjs.org/browserify-mime/-/browserify-mime-1.2.9.tgz", + "_shasum": "aeb1af28de6c0d7a6a2ce40adb68ff18422af31f", + "_shrinkwrap": null, + "_spec": "browserify-mime@~1.2.9", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage", + "author": { + "email": "robert@broofa.com", + "name": "Robert Kieffer", + "url": "http://github.com/broofa" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "dependencies": {}, + "description": "A comprehensive library for mime-type mapping (with browserify support)", + "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "aeb1af28de6c0d7a6a2ce40adb68ff18422af31f", + "tarball": "https://registry.npmjs.org/browserify-mime/-/browserify-mime-1.2.9.tgz" + }, + "installable": true, + "keywords": [ + "browserify", + "mime", + "util" + ], + "main": "browserify-mime.js", + "maintainers": [ + { + "name": "coverslide", + "email": "coverslide@gmail.com" + } + ], + "name": "browserify-mime", + "optionalDependencies": {}, + "readme": "# mime\n\nComprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n var mime = require('mime');\n\n mime.lookup('/path/to/file.txt'); // => 'text/plain'\n mime.lookup('file.txt'); // => 'text/plain'\n mime.lookup('.TXT'); // => 'text/plain'\n mime.lookup('htm'); // => 'text/html'\n\n### mime.extension(type)\nGet the default extension for `type`\n\n mime.extension('text/html'); // => 'html'\n mime.extension('application/octet-stream'); // => 'bin'\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n mime.charsets.lookup('text/plain'); // => 'UTF-8'\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nThe following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n mime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n });\n\n mime.lookup('x-sft'); // => 'text/x-some-format'\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n mime.extension('text/x-some-format'); // => 'x-sf'\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n mime.load('./my_project.types');\n\nThe .types file format is simple - See the `types` dir for examples.\n", + "readmeFilename": "README.md", + "repository": { + "type": "git", + "url": "https://github.com/broofa/node-mime" + }, + "version": "1.2.9" +} diff --git a/node_modules/browserify-mime/test.js b/node_modules/browserify-mime/test.js new file mode 100644 index 000000000..1932ce74f --- /dev/null +++ b/node_modules/browserify-mime/test.js @@ -0,0 +1,62 @@ +/** + * Usage: node test.js + */ + +var mime = require('./browserify-mime'); +var assert = require('assert'); + +function eq(a, b) { + console.log('Test: ' + a + ' === ' + b); + assert.strictEqual.apply(null, arguments); +} + +console.log(Object.keys(mime.extensions).length + ' types'); +console.log(Object.keys(mime.types).length + ' extensions\n'); + +// +// Test mime lookups +// + +eq('text/plain', mime.lookup('text.txt')); +eq('text/plain', mime.lookup('.text.txt')); +eq('text/plain', mime.lookup('.txt')); +eq('text/plain', mime.lookup('txt')); +eq('application/octet-stream', mime.lookup('text.nope')); +eq('fallback', mime.lookup('text.fallback', 'fallback')); +eq('application/octet-stream', mime.lookup('constructor')); +eq('text/plain', mime.lookup('TEXT.TXT')); +eq('text/event-stream', mime.lookup('text/event-stream')); +eq('application/x-web-app-manifest+json', mime.lookup('text.webapp')); + +// +// Test extensions +// + +eq('txt', mime.extension(mime.types.text)); +eq('html', mime.extension(mime.types.htm)); +eq('bin', mime.extension('application/octet-stream')); +eq('bin', mime.extension('application/octet-stream ')); +eq('html', mime.extension(' text/html; charset=UTF-8')); +eq('html', mime.extension('text/html; charset=UTF-8 ')); +eq('html', mime.extension('text/html; charset=UTF-8')); +eq('html', mime.extension('text/html ; charset=UTF-8')); +eq('html', mime.extension('text/html;charset=UTF-8')); +eq('html', mime.extension('text/Html;charset=UTF-8')); +eq(undefined, mime.extension('constructor')); + +// +// Test node types +// + +eq('application/octet-stream', mime.lookup('file.buffer')); +eq('audio/mp4', mime.lookup('file.m4a')); + +// +// Test charsets +// + +eq('UTF-8', mime.charsets.lookup('text/plain')); +eq(undefined, mime.charsets.lookup(mime.types.js)); +eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nOK'); diff --git a/node_modules/caseless/LICENSE b/node_modules/caseless/LICENSE new file mode 100644 index 000000000..61789f4a4 --- /dev/null +++ b/node_modules/caseless/LICENSE @@ -0,0 +1,28 @@ +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: +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +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 +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 \ No newline at end of file diff --git a/node_modules/caseless/README.md b/node_modules/caseless/README.md new file mode 100644 index 000000000..e5077a216 --- /dev/null +++ b/node_modules/caseless/README.md @@ -0,0 +1,45 @@ +## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing. + +This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set. + +## Usage + +```javascript +var headers = {} + , c = caseless(headers) + ; +c.set('a-Header', 'asdf') +c.get('a-header') === 'asdf' +``` + +## has(key) + +Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with. + +```javascript +c.has('a-header') === 'a-Header' +``` + +## set(key, value[, clobber=true]) + +Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header. + +```javascript +c.set('a-Header', 'fdas') +c.set('a-HEADER', 'more', false) +c.get('a-header') === 'fdsa,more' +``` + +## swap(key) + +Swaps the casing of a header with the new one that is passed in. + +```javascript +var headers = {} + , c = caseless(headers) + ; +c.set('a-Header', 'fdas') +c.swap('a-HEADER') +c.has('a-header') === 'a-HEADER' +headers === {'a-HEADER': 'fdas'} +``` diff --git a/node_modules/caseless/index.js b/node_modules/caseless/index.js new file mode 100644 index 000000000..b194734ee --- /dev/null +++ b/node_modules/caseless/index.js @@ -0,0 +1,67 @@ +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) + } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) + + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i=0.12.0-0 <0.13.0-0", + "_id": "caseless@0.12.0", + "_inCache": true, + "_location": "/caseless", + "_nodeVersion": "6.9.2", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/caseless-0.12.0.tgz_1485466648253_0.3714302028529346" + }, + "_npmUser": { + "email": "mikeal.rogers@gmail.com", + "name": "mikeal" + }, + "_npmVersion": "3.10.9", + "_phantomChildren": {}, + "_requested": { + "name": "caseless", + "raw": "caseless@~0.12.0", + "rawSpec": "~0.12.0", + "scope": null, + "spec": ">=0.12.0-0 <0.13.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage/request", + "/request" + ], + "_resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "_shasum": "1b681c21ff84033c826543090689420d187151dc", + "_shrinkwrap": null, + "_spec": "caseless@~0.12.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request", + "author": { + "email": "mikeal.rogers@gmail.com", + "name": "Mikeal Rogers" + }, + "bugs": { + "url": "https://github.com/mikeal/caseless/issues" + }, + "dependencies": {}, + "description": "Caseless object set/get/has, very useful when working with HTTP headers.", + "devDependencies": { + "tape": "^2.10.2" + }, + "directories": {}, + "dist": { + "shasum": "1b681c21ff84033c826543090689420d187151dc", + "tarball": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz" + }, + "gitHead": "af91df7878a8b53cf3dc2e9a086dc57ba8301649", + "homepage": "https://github.com/mikeal/caseless#readme", + "installable": true, + "keywords": [ + "caseless", + "headers", + "http" + ], + "license": "Apache-2.0", + "main": "index.js", + "maintainers": [ + { + "name": "mikeal", + "email": "mikeal.rogers@gmail.com" + }, + { + "name": "nylen", + "email": "jnylen@gmail.com" + }, + { + "name": "simov", + "email": "simeonvelichkov@gmail.com" + } + ], + "name": "caseless", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/mikeal/caseless.git" + }, + "scripts": { + "test": "node test.js" + }, + "test": "node test.js", + "version": "0.12.0" +} diff --git a/node_modules/caseless/test.js b/node_modules/caseless/test.js new file mode 100644 index 000000000..f55196cc0 --- /dev/null +++ b/node_modules/caseless/test.js @@ -0,0 +1,67 @@ +var tape = require('tape') + , caseless = require('./') + ; + +tape('set get has', function (t) { + var headers = {} + , c = caseless(headers) + ; + t.plan(17) + c.set('a-Header', 'asdf') + t.equal(c.get('a-header'), 'asdf') + t.equal(c.has('a-header'), 'a-Header') + t.ok(!c.has('nothing')) + // old bug where we used the wrong regex + t.ok(!c.has('a-hea')) + c.set('a-header', 'fdsa') + t.equal(c.get('a-header'), 'fdsa') + t.equal(c.get('a-Header'), 'fdsa') + c.set('a-HEADER', 'more', false) + t.equal(c.get('a-header'), 'fdsa,more') + + t.deepEqual(headers, {'a-Header': 'fdsa,more'}) + c.swap('a-HEADER') + t.deepEqual(headers, {'a-HEADER': 'fdsa,more'}) + + c.set('deleteme', 'foobar') + t.ok(c.has('deleteme')) + t.ok(c.del('deleteme')) + t.notOk(c.has('deleteme')) + t.notOk(c.has('idonotexist')) + t.ok(c.del('idonotexist')) + + c.set('tva', 'test1') + c.set('tva-header', 'test2') + t.equal(c.has('tva'), 'tva') + t.notOk(c.has('header')) + + t.equal(c.get('tva'), 'test1') + +}) + +tape('swap', function (t) { + var headers = {} + , c = caseless(headers) + ; + t.plan(4) + // No Header to Swap. + t.throws(function () { + c.swap('content-type') + }) + // Set Header. + c.set('content-type', 'application/json') + // Swap Header With Itself. + c.swap('content-type') + // Does Not Delete Itself. + t.ok(c.has('content-type')) + // Swap Header With a Different Header. + c.swap('Content-Type') + // Still Has Header. + t.ok(c.has('Content-Type')) + // Delete Header. + c.del('Content-Type') + // No Header to Swap. + t.throws(function () { + c.swap('content-type') + }) +}) diff --git a/node_modules/co/History.md b/node_modules/co/History.md new file mode 100644 index 000000000..68fbb154d --- /dev/null +++ b/node_modules/co/History.md @@ -0,0 +1,172 @@ +4.6.0 / 2015-07-09 +================== + + * support passing the rest of the arguments to co into the generator + + ```js + function *gen(...args) { } + co(gen, ...args); + ``` + +4.5.0 / 2015-03-17 +================== + + * support regular functions (that return promises) + +4.4.0 / 2015-02-14 +================== + + * refactor `isGeneratorFunction` + * expose generator function from `co.wrap()` + * drop support for node < 0.12 + +4.3.0 / 2015-02-05 +================== + + * check for generator functions in a ES5-transpiler-friendly way + +4.2.0 / 2015-01-20 +================== + + * support comparing generator functions with ES6 transpilers + +4.1.0 / 2014-12-26 +================== + + * fix memory leak #180 + +4.0.2 / 2014-12-18 +================== + + * always return a global promise implementation + +4.0.1 / 2014-11-30 +================== + + * friendlier ES6 module exports + +4.0.0 / 2014-11-15 +================== + + * co now returns a promise and uses promises underneath + * `co.wrap()` for wrapping generator functions + +3.1.0 / 2014-06-30 +================== + + * remove `setImmediate()` shim for node 0.8. semi-backwards breaking. + Users are expected to shim themselves. Also returns CommonJS browser support. + * added key order preservation for objects. thanks @greim + * replace `q` with `bluebird` in benchmarks and tests + +3.0.6 / 2014-05-03 +================== + + * add `setImmediate()` fallback to `process.nextTick` + * remove duplicate code in toThunk + * update thunkify + +3.0.5 / 2014-03-17 +================== + + * fix object/array test failure which tries to enumerate dates. Closes #98 + * fix final callback error propagation. Closes #92 + +3.0.4 / 2014-02-17 +================== + + * fix toThunk object check regression. Closes #89 + +3.0.3 / 2014-02-08 +================== + + * refactor: arrayToThunk @AutoSponge #88 + +3.0.2 / 2014-01-01 +================== + + * fixed: nil arguments replaced with error fn + +3.0.1 / 2013-12-19 +================== + + * fixed: callback passed as an argument to generators + +3.0.0 / 2013-12-19 +================== + + * fixed: callback passed as an argument to generators + * change: `co(function *(){})` now returns a reusable thunk + * change: `this` must now be passed through the returned thunk, ex. `co(function *(){}).call(this)` + * fix "generator already finished" errors + +2.3.0 / 2013-11-12 +================== + + * add `yield object` support + +2.2.0 / 2013-11-05 +================== + + * change: make the `isGenerator()` function more generic + +2.1.0 / 2013-10-21 +================== + + * add passing of arguments into the generator. closes #33. + +2.0.0 / 2013-10-14 +================== + + * remove callback in favour of thunk-only co(). Closes #30 [breaking change] + * remove `co.wrap()` [breaking change] + +1.5.2 / 2013-09-02 +================== + + * fix: preserve receiver with co.wrap() + +1.5.1 / 2013-08-11 +================== + + * remove setImmediate() usage - ~110% perf increase. Closes #14 + +0.5.0 / 2013-08-10 +================== + + * add receiver propagation support + * examples: update streams.js example to use `http.get()` and streams2 API + +1.4.1 / 2013-07-01 +================== + + * fix gen.next(val) for latest v8. Closes #8 + +1.4.0 / 2013-06-21 +================== + + * add promise support to joins + * add `yield generatorFunction` support + * add `yield generator` support + * add nested join support + +1.3.0 / 2013-06-10 +================== + + * add passing of arguments + +1.2.1 / 2013-06-08 +================== + + * fix join() of zero thunks + +1.2.0 / 2013-06-08 +================== + + * add array yielding support. great suggestion by @domenic + +1.1.0 / 2013-06-06 +================== + + * add promise support + * change nextTick to setImmediate diff --git a/node_modules/co/LICENSE b/node_modules/co/LICENSE new file mode 100644 index 000000000..92faba5db --- /dev/null +++ b/node_modules/co/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/co/Readme.md b/node_modules/co/Readme.md new file mode 100644 index 000000000..c1d4882a1 --- /dev/null +++ b/node_modules/co/Readme.md @@ -0,0 +1,212 @@ +# co + +[![Gitter][gitter-image]][gitter-url] +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![Downloads][downloads-image]][downloads-url] + + Generator based control flow goodness for nodejs and the browser, + using promises, letting you write non-blocking code in a nice-ish way. + +## Co v4 + + `co@4.0.0` has been released, which now relies on promises. + It is a stepping stone towards [ES7 async/await](https://github.com/lukehoban/ecmascript-asyncawait). + The primary API change is how `co()` is invoked. + Before, `co` returned a "thunk", which you then called with a callback and optional arguments. + Now, `co()` returns a promise. + +```js +co(function* () { + var result = yield Promise.resolve(true); + return result; +}).then(function (value) { + console.log(value); +}, function (err) { + console.error(err.stack); +}); +``` + + If you want to convert a `co`-generator-function into a regular function that returns a promise, + you now use `co.wrap(fn*)`. + +```js +var fn = co.wrap(function* (val) { + return yield Promise.resolve(val); +}); + +fn(true).then(function (val) { + +}); +``` + +## Platform Compatibility + + `co@4+` requires a `Promise` implementation. + For versions of node `< 0.11` and for many older browsers, + you should/must include your own `Promise` polyfill. + + When using node 0.11.x or greater, you must use the `--harmony-generators` + flag or just `--harmony` to get access to generators. + + When using node 0.10.x and lower or browsers without generator support, + you must use [gnode](https://github.com/TooTallNate/gnode) and/or [regenerator](http://facebook.github.io/regenerator/). + + io.js is supported out of the box, you can use `co` without flags or polyfills. + +## Installation + +``` +$ npm install co +``` + +## Associated libraries + +Any library that returns promises work well with `co`. + +- [mz](https://github.com/normalize/mz) - wrap all of node's code libraries as promises. + +View the [wiki](https://github.com/visionmedia/co/wiki) for more libraries. + +## Examples + +```js +var co = require('co'); + +co(function *(){ + // yield any promise + var result = yield Promise.resolve(true); +}).catch(onerror); + +co(function *(){ + // resolve multiple promises in parallel + var a = Promise.resolve(1); + var b = Promise.resolve(2); + var c = Promise.resolve(3); + var res = yield [a, b, c]; + console.log(res); + // => [1, 2, 3] +}).catch(onerror); + +// errors can be try/catched +co(function *(){ + try { + yield Promise.reject(new Error('boom')); + } catch (err) { + console.error(err.message); // "boom" + } +}).catch(onerror); + +function onerror(err) { + // log any uncaught errors + // co will not throw any errors you do not handle!!! + // HANDLE ALL YOUR ERRORS!!! + console.error(err.stack); +} +``` + +## Yieldables + + The `yieldable` objects currently supported are: + + - promises + - thunks (functions) + - array (parallel execution) + - objects (parallel execution) + - generators (delegation) + - generator functions (delegation) + +Nested `yieldable` objects are supported, meaning you can nest +promises within objects within arrays, and so on! + +### Promises + +[Read more on promises!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) + +### Thunks + +Thunks are functions that only have a single argument, a callback. +Thunk support only remains for backwards compatibility and may +be removed in future versions of `co`. + +### Arrays + +`yield`ing an array will resolve all the `yieldables` in parallel. + +```js +co(function* () { + var res = yield [ + Promise.resolve(1), + Promise.resolve(2), + Promise.resolve(3), + ]; + console.log(res); // => [1, 2, 3] +}).catch(onerror); +``` + +### Objects + +Just like arrays, objects resolve all `yieldable`s in parallel. + +```js +co(function* () { + var res = yield { + 1: Promise.resolve(1), + 2: Promise.resolve(2), + }; + console.log(res); // => { 1: 1, 2: 2 } +}).catch(onerror); +``` + +### Generators and Generator Functions + +Any generator or generator function you can pass into `co` +can be yielded as well. This should generally be avoided +as we should be moving towards spec-compliant `Promise`s instead. + +## API + +### co(fn*).then( val => ) + +Returns a promise that resolves a generator, generator function, +or any function that returns a generator. + +```js +co(function* () { + return yield Promise.resolve(true); +}).then(function (val) { + console.log(val); +}, function (err) { + console.error(err.stack); +}); +``` + +### var fn = co.wrap(fn*) + +Convert a generator into a regular function that returns a `Promise`. + +```js +var fn = co.wrap(function* (val) { + return yield Promise.resolve(val); +}); + +fn(true).then(function (val) { + +}); +``` + +## License + + MIT + +[npm-image]: https://img.shields.io/npm/v/co.svg?style=flat-square +[npm-url]: https://npmjs.org/package/co +[travis-image]: https://img.shields.io/travis/tj/co.svg?style=flat-square +[travis-url]: https://travis-ci.org/tj/co +[coveralls-image]: https://img.shields.io/coveralls/tj/co.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/tj/co +[downloads-image]: http://img.shields.io/npm/dm/co.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/co +[gitter-image]: https://badges.gitter.im/Join%20Chat.svg +[gitter-url]: https://gitter.im/tj/co?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge diff --git a/node_modules/co/index.js b/node_modules/co/index.js new file mode 100644 index 000000000..87ba8ba8b --- /dev/null +++ b/node_modules/co/index.js @@ -0,0 +1,237 @@ + +/** + * slice() reference. + */ + +var slice = Array.prototype.slice; + +/** + * Expose `co`. + */ + +module.exports = co['default'] = co.co = co; + +/** + * Wrap the given generator `fn` into a + * function that returns a promise. + * This is a separate function so that + * every `co()` call doesn't create a new, + * unnecessary closure. + * + * @param {GeneratorFunction} fn + * @return {Function} + * @api public + */ + +co.wrap = function (fn) { + createPromise.__generatorFunction__ = fn; + return createPromise; + function createPromise() { + return co.call(this, fn.apply(this, arguments)); + } +}; + +/** + * Execute the generator function or a generator + * and return a promise. + * + * @param {Function} fn + * @return {Promise} + * @api public + */ + +function co(gen) { + var ctx = this; + var args = slice.call(arguments, 1) + + // we wrap everything in a promise to avoid promise chaining, + // which leads to memory leak errors. + // see https://github.com/tj/co/issues/180 + return new Promise(function(resolve, reject) { + if (typeof gen === 'function') gen = gen.apply(ctx, args); + if (!gen || typeof gen.next !== 'function') return resolve(gen); + + onFulfilled(); + + /** + * @param {Mixed} res + * @return {Promise} + * @api private + */ + + function onFulfilled(res) { + var ret; + try { + ret = gen.next(res); + } catch (e) { + return reject(e); + } + next(ret); + } + + /** + * @param {Error} err + * @return {Promise} + * @api private + */ + + function onRejected(err) { + var ret; + try { + ret = gen.throw(err); + } catch (e) { + return reject(e); + } + next(ret); + } + + /** + * Get the next value in the generator, + * return a promise. + * + * @param {Object} ret + * @return {Promise} + * @api private + */ + + function next(ret) { + if (ret.done) return resolve(ret.value); + var value = toPromise.call(ctx, ret.value); + if (value && isPromise(value)) return value.then(onFulfilled, onRejected); + return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, ' + + 'but the following object was passed: "' + String(ret.value) + '"')); + } + }); +} + +/** + * Convert a `yield`ed value into a promise. + * + * @param {Mixed} obj + * @return {Promise} + * @api private + */ + +function toPromise(obj) { + if (!obj) return obj; + if (isPromise(obj)) return obj; + if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj); + if ('function' == typeof obj) return thunkToPromise.call(this, obj); + if (Array.isArray(obj)) return arrayToPromise.call(this, obj); + if (isObject(obj)) return objectToPromise.call(this, obj); + return obj; +} + +/** + * Convert a thunk to a promise. + * + * @param {Function} + * @return {Promise} + * @api private + */ + +function thunkToPromise(fn) { + var ctx = this; + return new Promise(function (resolve, reject) { + fn.call(ctx, function (err, res) { + if (err) return reject(err); + if (arguments.length > 2) res = slice.call(arguments, 1); + resolve(res); + }); + }); +} + +/** + * Convert an array of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Array} obj + * @return {Promise} + * @api private + */ + +function arrayToPromise(obj) { + return Promise.all(obj.map(toPromise, this)); +} + +/** + * Convert an object of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Object} obj + * @return {Promise} + * @api private + */ + +function objectToPromise(obj){ + var results = new obj.constructor(); + var keys = Object.keys(obj); + var promises = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var promise = toPromise.call(this, obj[key]); + if (promise && isPromise(promise)) defer(promise, key); + else results[key] = obj[key]; + } + return Promise.all(promises).then(function () { + return results; + }); + + function defer(promise, key) { + // predefine the key in the result + results[key] = undefined; + promises.push(promise.then(function (res) { + results[key] = res; + })); + } +} + +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isPromise(obj) { + return 'function' == typeof obj.then; +} + +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGenerator(obj) { + return 'function' == typeof obj.next && 'function' == typeof obj.throw; +} + +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ +function isGeneratorFunction(obj) { + var constructor = obj.constructor; + if (!constructor) return false; + if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; + return isGenerator(constructor.prototype); +} + +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ + +function isObject(val) { + return Object == val.constructor; +} diff --git a/node_modules/co/package.json b/node_modules/co/package.json new file mode 100644 index 000000000..b8e97f5db --- /dev/null +++ b/node_modules/co/package.json @@ -0,0 +1,98 @@ +{ + "_args": [ + [ + "co@^4.6.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\ajv" + ] + ], + "_from": "co@>=4.6.0-0 <5.0.0-0", + "_id": "co@4.6.0", + "_inCache": true, + "_location": "/co", + "_nodeVersion": "2.3.3", + "_npmUser": { + "email": "jonathanrichardong@gmail.com", + "name": "jongleberry" + }, + "_npmVersion": "2.11.3", + "_phantomChildren": {}, + "_requested": { + "name": "co", + "raw": "co@^4.6.0", + "rawSpec": "^4.6.0", + "scope": null, + "spec": ">=4.6.0-0 <5.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/ajv", + "/request/ajv" + ], + "_resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "_shasum": "6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184", + "_shrinkwrap": null, + "_spec": "co@^4.6.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\ajv", + "bugs": { + "url": "https://github.com/tj/co/issues" + }, + "dependencies": {}, + "description": "generator async control flow goodness", + "devDependencies": { + "browserify": "^10.0.0", + "istanbul-harmony": "0", + "mocha": "^2.0.0", + "mz": "^1.0.2" + }, + "directories": {}, + "dist": { + "shasum": "6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184", + "tarball": "https://registry.npmjs.org/co/-/co-4.6.0.tgz" + }, + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + }, + "files": [ + "index.js" + ], + "gitHead": "b54d18f8f472ad1314800e786993c4169a5ff9f8", + "homepage": "https://github.com/tj/co#readme", + "installable": true, + "keywords": [ + "async", + "coro", + "coroutine", + "flow", + "generator" + ], + "license": "MIT", + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + { + "name": "jonathanong", + "email": "jonathanrichardong@gmail.com" + }, + { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + } + ], + "name": "co", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/tj/co.git" + }, + "scripts": { + "browserify": "browserify index.js -o ./co-browser.js -s co", + "prepublish": "npm run browserify", + "test": "mocha --harmony", + "test-cov": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter dot", + "test-travis": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- --reporter dot" + }, + "version": "4.6.0" +} diff --git a/node_modules/combined-stream/License b/node_modules/combined-stream/License new file mode 100644 index 000000000..4804b7ab4 --- /dev/null +++ b/node_modules/combined-stream/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Debuggable Limited + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/combined-stream/Readme.md b/node_modules/combined-stream/Readme.md new file mode 100644 index 000000000..3a9e025fb --- /dev/null +++ b/node_modules/combined-stream/Readme.md @@ -0,0 +1,138 @@ +# combined-stream + +A stream that emits multiple other streams one after another. + +**NB** Currently `combined-stream` works with streams vesrion 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatability with `combined-stream`. + +- [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module. + +- [multistream](https://www.npmjs.com/package/multistream): A stream that emits multiple other streams one after another. + +## Installation + +``` bash +npm install combined-stream +``` + +## Usage + +Here is a simple example that shows how you can use combined-stream to combine +two files into one: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +While the example above works great, it will pause all source streams until +they are needed. If you don't want that to happen, you can set `pauseStreams` +to `false`: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create({pauseStreams: false}); +combinedStream.append(fs.createReadStream('file1.txt')); +combinedStream.append(fs.createReadStream('file2.txt')); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +However, what if you don't have all the source streams yet, or you don't want +to allocate the resources (file descriptors, memory, etc.) for them right away? +Well, in that case you can simply provide a callback that supplies the stream +by calling a `next()` function: + +``` javascript +var CombinedStream = require('combined-stream'); +var fs = require('fs'); + +var combinedStream = CombinedStream.create(); +combinedStream.append(function(next) { + next(fs.createReadStream('file1.txt')); +}); +combinedStream.append(function(next) { + next(fs.createReadStream('file2.txt')); +}); + +combinedStream.pipe(fs.createWriteStream('combined.txt')); +``` + +## API + +### CombinedStream.create([options]) + +Returns a new combined stream object. Available options are: + +* `maxDataSize` +* `pauseStreams` + +The effect of those options is described below. + +### combinedStream.pauseStreams = `true` + +Whether to apply back pressure to the underlaying streams. If set to `false`, +the underlaying streams will never be paused. If set to `true`, the +underlaying streams will be paused right after being appended, as well as when +`delayedStream.pipe()` wants to throttle. + +### combinedStream.maxDataSize = `2 * 1024 * 1024` + +The maximum amount of bytes (or characters) to buffer for all source streams. +If this value is exceeded, `combinedStream` emits an `'error'` event. + +### combinedStream.dataSize = `0` + +The amount of bytes (or characters) currently buffered by `combinedStream`. + +### combinedStream.append(stream) + +Appends the given `stream` to the combinedStream object. If `pauseStreams` is +set to `true, this stream will also be paused right away. + +`streams` can also be a function that takes one parameter called `next`. `next` +is a function that must be invoked in order to provide the `next` stream, see +example above. + +Regardless of how the `stream` is appended, combined-stream always attaches an +`'error'` listener to it, so you don't have to do that manually. + +Special case: `stream` can also be a String or Buffer. + +### combinedStream.write(data) + +You should not call this, `combinedStream` takes care of piping the appended +streams into itself for you. + +### combinedStream.resume() + +Causes `combinedStream` to start drain the streams it manages. The function is +idempotent, and also emits a `'resume'` event each time which usually goes to +the stream that is currently being drained. + +### combinedStream.pause(); + +If `combinedStream.pauseStreams` is set to `false`, this does nothing. +Otherwise a `'pause'` event is emitted, this goes to the stream that is +currently being drained, so you can use it to apply back pressure. + +### combinedStream.end(); + +Sets `combinedStream.writable` to false, emits an `'end'` event, and removes +all streams from the queue. + +### combinedStream.destroy(); + +Same as `combinedStream.end()`, except it emits a `'close'` event instead of +`'end'`. + +## License + +combined-stream is licensed under the MIT license. diff --git a/node_modules/combined-stream/lib/combined_stream.js b/node_modules/combined-stream/lib/combined_stream.js new file mode 100644 index 000000000..6b5c21b6b --- /dev/null +++ b/node_modules/combined-stream/lib/combined_stream.js @@ -0,0 +1,188 @@ +var util = require('util'); +var Stream = require('stream').Stream; +var DelayedStream = require('delayed-stream'); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; +} +util.inherits(CombinedStream, Stream); + +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } + + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } + + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } + } + + this._streams.push(stream); + return this; +}; + +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; + +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; + } + + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } + + this._pipeNext(stream); + }.bind(this)); +}; + +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } + + var value = stream; + this.write(value); + this._getNext(); +}; + +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; + +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; + +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; + +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } + + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; + +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; + +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; + +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; + +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } + + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; + +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } + + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; + +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; diff --git a/node_modules/combined-stream/package.json b/node_modules/combined-stream/package.json new file mode 100644 index 000000000..bfdf8aa04 --- /dev/null +++ b/node_modules/combined-stream/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "combined-stream@~1.0.5", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request" + ] + ], + "_from": "combined-stream@>=1.0.5-0 <1.1.0-0", + "_id": "combined-stream@1.0.5", + "_inCache": true, + "_location": "/combined-stream", + "_nodeVersion": "0.12.4", + "_npmUser": { + "email": "iam@alexindigo.com", + "name": "alexindigo" + }, + "_npmVersion": "2.10.1", + "_phantomChildren": {}, + "_requested": { + "name": "combined-stream", + "raw": "combined-stream@~1.0.5", + "rawSpec": "~1.0.5", + "scope": null, + "spec": ">=1.0.5-0 <1.1.0-0", + "type": "range" + }, + "_requiredBy": [ + "/azure-storage/request", + "/form-data", + "/request", + "/request/form-data" + ], + "_resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz", + "_shasum": "938370a57b4a51dea2c77c15d5c5fdf895164009", + "_shrinkwrap": null, + "_spec": "combined-stream@~1.0.5", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\azure-storage\\node_modules\\request", + "author": { + "email": "felix@debuggable.com", + "name": "Felix Geisendörfer", + "url": "http://debuggable.com/" + }, + "bugs": { + "url": "https://github.com/felixge/node-combined-stream/issues" + }, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "description": "A stream that emits multiple other streams one after another.", + "devDependencies": { + "far": "~0.0.7" + }, + "directories": {}, + "dist": { + "shasum": "938370a57b4a51dea2c77c15d5c5fdf895164009", + "tarball": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.5.tgz" + }, + "engines": { + "node": ">= 0.8" + }, + "gitHead": "cfc7b815d090a109bcedb5bb0f6713148d55a6b7", + "homepage": "https://github.com/felixge/node-combined-stream", + "installable": true, + "license": "MIT", + "main": "./lib/combined_stream", + "maintainers": [ + { + "name": "felixge", + "email": "felix@debuggable.com" + }, + { + "name": "celer", + "email": "dtyree77@gmail.com" + }, + { + "name": "alexindigo", + "email": "iam@alexindigo.com" + }, + { + "name": "apechimp", + "email": "apeherder@gmail.com" + } + ], + "name": "combined-stream", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-combined-stream.git" + }, + "scripts": { + "test": "node test/run.js" + }, + "version": "1.0.5" +} diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE new file mode 100644 index 000000000..d8d7f9437 --- /dev/null +++ b/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md new file mode 100644 index 000000000..5a76b4149 --- /dev/null +++ b/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch new file mode 100644 index 000000000..a06d5c05f --- /dev/null +++ b/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/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js new file mode 100644 index 000000000..ff4c851c0 --- /dev/null +++ b/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json new file mode 100644 index 000000000..9ed0a5bd0 --- /dev/null +++ b/node_modules/core-util-is/package.json @@ -0,0 +1,86 @@ +{ + "_args": [ + [ + "core-util-is@~1.0.0", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\readable-stream" + ] + ], + "_from": "core-util-is@>=1.0.0-0 <1.1.0-0", + "_id": "core-util-is@1.0.2", + "_inCache": true, + "_location": "/core-util-is", + "_nodeVersion": "4.0.0", + "_npmUser": { + "email": "i@izs.me", + "name": "isaacs" + }, + "_npmVersion": "3.3.2", + "_phantomChildren": {}, + "_requested": { + "name": "core-util-is", + "raw": "core-util-is@~1.0.0", + "rawSpec": "~1.0.0", + "scope": null, + "spec": ">=1.0.0-0 <1.1.0-0", + "type": "range" + }, + "_requiredBy": [ + "/readable-stream", + "/verror" + ], + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_shrinkwrap": null, + "_spec": "core-util-is@~1.0.0", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\readable-stream", + "author": { + "email": "i@izs.me", + "name": "Isaac Z. Schlueter", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "dependencies": {}, + "description": "The `util.is*` functions introduced in Node v0.12.", + "devDependencies": { + "tap": "^2.3.0" + }, + "directories": {}, + "dist": { + "shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "tarball": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" + }, + "gitHead": "a177da234df5638b363ddc15fa324619a38577c8", + "homepage": "https://github.com/isaacs/core-util-is#readme", + "installable": true, + "keywords": [ + "isArray", + "isBuffer", + "isNumber", + "isRegExp", + "isString", + "isThat", + "isThis", + "polyfill", + "util" + ], + "license": "MIT", + "main": "lib/util.js", + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "name": "core-util-is", + "optionalDependencies": {}, + "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 new file mode 100644 index 000000000..1a490c65a --- /dev/null +++ b/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/node_modules/cryptiles/.npmignore b/node_modules/cryptiles/.npmignore new file mode 100644 index 000000000..77ba16cb0 --- /dev/null +++ b/node_modules/cryptiles/.npmignore @@ -0,0 +1,18 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov + diff --git a/node_modules/cryptiles/.travis.yml b/node_modules/cryptiles/.travis.yml new file mode 100644 index 000000000..dd1b24f13 --- /dev/null +++ b/node_modules/cryptiles/.travis.yml @@ -0,0 +1,8 @@ +language: node_js + +node_js: + - 0.10 + - 4.0 + +sudo: false + diff --git a/node_modules/cryptiles/LICENSE b/node_modules/cryptiles/LICENSE new file mode 100644 index 000000000..cda44736a --- /dev/null +++ b/node_modules/cryptiles/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014, Eran Hammer and other contributors. +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. + * The names of any contributors may not 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 HOLDERS AND 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. + + * * * + +The complete list of contributors can be found at: https://github.com/hueniverse/cryptiles/graphs/contributors diff --git a/node_modules/cryptiles/README.md b/node_modules/cryptiles/README.md new file mode 100644 index 000000000..400830501 --- /dev/null +++ b/node_modules/cryptiles/README.md @@ -0,0 +1,16 @@ +cryptiles +========= + +General purpose crypto utilities + +[![Build Status](https://secure.travis-ci.org/hapijs/cryptiles.png)](http://travis-ci.org/hapijs/cryptiles) + +Lead Maintainer - [C J Silverio](https://github.com/ceejbot) + +## Methods + +### `randomString( size)` +Returns a cryptographically strong pseudo-random data string. Takes a size argument for the length of the string. + +### `fixedTimeComparison( a, b)` +Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match). Returns `true` if the strings match, `false` if they differ. diff --git a/node_modules/cryptiles/lib/index.js b/node_modules/cryptiles/lib/index.js new file mode 100644 index 000000000..f385870ee --- /dev/null +++ b/node_modules/cryptiles/lib/index.js @@ -0,0 +1,68 @@ +// Load modules + +var Crypto = require('crypto'); +var Boom = require('boom'); + + +// Declare internals + +var internals = {}; + + +// Generate a cryptographically strong pseudo-random data + +exports.randomString = function (size) { + + var buffer = exports.randomBits((size + 1) * 6); + if (buffer instanceof Error) { + return buffer; + } + + var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); + return string.slice(0, size); +}; + + +exports.randomBits = function (bits) { + + if (!bits || + bits < 0) { + + return Boom.internal('Invalid random bits count'); + } + + var bytes = Math.ceil(bits / 8); + try { + return Crypto.randomBytes(bytes); + } + catch (err) { + return Boom.internal('Failed generating random bits: ' + err.message); + } +}; + + +// Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match) + +exports.fixedTimeComparison = function (a, b) { + + if (typeof a !== 'string' || + typeof b !== 'string') { + + return false; + } + + var mismatch = (a.length === b.length ? 0 : 1); + if (mismatch) { + b = a; + } + + for (var i = 0, il = a.length; i < il; ++i) { + var ac = a.charCodeAt(i); + var bc = b.charCodeAt(i); + mismatch |= (ac ^ bc); + } + + return (mismatch === 0); +}; + + diff --git a/node_modules/cryptiles/package.json b/node_modules/cryptiles/package.json new file mode 100644 index 000000000..ea1f6155d --- /dev/null +++ b/node_modules/cryptiles/package.json @@ -0,0 +1,85 @@ +{ + "_args": [ + [ + "cryptiles@2.x.x", + "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\hawk" + ] + ], + "_from": "cryptiles@>=2.0.0-0 <3.0.0-0", + "_id": "cryptiles@2.0.5", + "_inCache": true, + "_location": "/cryptiles", + "_nodeVersion": "4.0.0", + "_npmUser": { + "email": "eran@hammer.io", + "name": "hueniverse" + }, + "_npmVersion": "2.14.2", + "_phantomChildren": {}, + "_requested": { + "name": "cryptiles", + "raw": "cryptiles@2.x.x", + "rawSpec": "2.x.x", + "scope": null, + "spec": ">=2.0.0-0 <3.0.0-0", + "type": "range" + }, + "_requiredBy": [ + "/hawk" + ], + "_resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-2.0.5.tgz", + "_shasum": "3bdfecdc608147c1c67202fa291e7dca59eaa3b8", + "_shrinkwrap": null, + "_spec": "cryptiles@2.x.x", + "_where": "c:\\users\\luis\\source\\repos\\AACharly\\node_modules\\hawk", + "bugs": { + "url": "https://github.com/hapijs/cryptiles/issues" + }, + "dependencies": { + "boom": "2.x.x" + }, + "description": "General purpose crypto utilities", + "devDependencies": { + "code": "1.x.x", + "lab": "5.x.x" + }, + "directories": {}, + "dist": { + "shasum": "3bdfecdc608147c1c67202fa291e7dca59eaa3b8", + "tarball": "https://registry.npmjs.org/cryptiles/-/cryptiles-2.0.5.tgz" + }, + "engines": { + "node": ">=0.10.40" + }, + "gitHead": "9bc5a852f01cd51e615814e1cb255fe2df810649", + "homepage": "https://github.com/hapijs/cryptiles#readme", + "installable": true, + "keywords": [ + "cryptography", + "security", + "utilites" + ], + "license": "BSD-3-Clause", + "main": "lib/index.js", + "maintainers": [ + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + }, + { + "name": "ceejbot", + "email": "ceejceej@gmail.com" + } + ], + "name": "cryptiles", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/hapijs/cryptiles.git" + }, + "scripts": { + "test": "lab -a code -t 100 -L", + "test-cov-html": "lab -a code -r html -o coverage.html" + }, + "version": "2.0.5" +} diff --git a/node_modules/cryptiles/test/index.js b/node_modules/cryptiles/test/index.js new file mode 100644 index 000000000..170393f9b --- /dev/null +++ b/node_modules/cryptiles/test/index.js @@ -0,0 +1,102 @@ +// Load modules + +var Code = require('code'); +var Cryptiles = require('..'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.describe; +var it = lab.it; +var expect = Code.expect; + + +describe('randomString()', function () { + + it('should generate the right length string', function (done) { + + for (var i = 1; i <= 1000; ++i) { + expect(Cryptiles.randomString(i).length).to.equal(i); + } + + done(); + }); + + it('returns an error on invalid bits size', function (done) { + + expect(Cryptiles.randomString(99999999999999999999).message).to.match(/Failed generating random bits/); + done(); + }); +}); + +describe('randomBits()', function () { + + it('returns an error on invalid input', function (done) { + + expect(Cryptiles.randomBits(0).message).to.equal('Invalid random bits count'); + done(); + }); +}); + +describe('fixedTimeComparison()', function () { + + var a = Cryptiles.randomString(50000); + var b = Cryptiles.randomString(150000); + + it('should take the same amount of time comparing different string sizes', function (done) { + + var now = Date.now(); + Cryptiles.fixedTimeComparison(b, a); + var t1 = Date.now() - now; + + now = Date.now(); + Cryptiles.fixedTimeComparison(b, b); + var t2 = Date.now() - now; + + expect(t2 - t1).to.be.within(-20, 20); + done(); + }); + + it('should return true for equal strings', function (done) { + + expect(Cryptiles.fixedTimeComparison(a, a)).to.equal(true); + done(); + }); + + it('should return false for different strings (size, a < b)', function (done) { + + expect(Cryptiles.fixedTimeComparison(a, a + 'x')).to.equal(false); + done(); + }); + + it('should return false for different strings (size, a > b)', function (done) { + + expect(Cryptiles.fixedTimeComparison(a + 'x', a)).to.equal(false); + done(); + }); + + it('should return false for different strings (size, a = b)', function (done) { + + expect(Cryptiles.fixedTimeComparison(a + 'x', a + 'y')).to.equal(false); + done(); + }); + + it('should return false when not a string', function (done) { + + expect(Cryptiles.fixedTimeComparison('x', null)).to.equal(false); + done(); + }); + + it('should return false when not a string (left)', function (done) { + + expect(Cryptiles.fixedTimeComparison(null, 'x')).to.equal(false); + done(); + }); +}); diff --git a/node_modules/dashdash/CHANGES.md b/node_modules/dashdash/CHANGES.md new file mode 100644 index 000000000..d7c8f4ebe --- /dev/null +++ b/node_modules/dashdash/CHANGES.md @@ -0,0 +1,364 @@ +# node-dashdash changelog + +## not yet released + +(nothing yet) + +## 1.14.1 + +- [issue #30] Change the output used by dashdash's Bash completion support to + indicate "there are no completions for this argument" to cope with different + sorting rules on different Bash/platforms. For example: + + $ triton -v -p test2 package get # before + ##-no -tritonpackage- completions-## + + $ triton -v -p test2 package get # after + ##-no-completion- -results-## + +## 1.14.0 + +- New `synopsisFromOpt(