diff --git a/.vs/AACarol/v15/.suo b/.vs/AACarol/v15/.suo deleted file mode 100644 index 6ad044f7b..000000000 Binary files a/.vs/AACarol/v15/.suo and /dev/null differ diff --git a/.vs/AAOlivia-Indicator-Bot/v15/.suo b/.vs/AAOlivia-Indicator-Bot/v15/.suo deleted file mode 100644 index dfbd3a89b..000000000 Binary files a/.vs/AAOlivia-Indicator-Bot/v15/.suo and /dev/null differ diff --git a/.vs/AAOlivia-Indicator.Bot/v15/.suo b/.vs/AAOlivia-Indicator.Bot/v15/.suo deleted file mode 100644 index c6a9bba69..000000000 Binary files a/.vs/AAOlivia-Indicator.Bot/v15/.suo and /dev/null differ diff --git a/.vs/AAOlivia/v15/.suo b/.vs/AAOlivia/v15/.suo deleted file mode 100644 index 632047349..000000000 Binary files a/.vs/AAOlivia/v15/.suo and /dev/null differ diff --git a/bin/Microsoft.NodejsTools.WebRole.dll b/bin/Microsoft.NodejsTools.WebRole.dll deleted file mode 100644 index 03b93f4a1..000000000 Binary files a/bin/Microsoft.NodejsTools.WebRole.dll and /dev/null differ diff --git a/node_modules/.bin/sshpk-conv b/node_modules/.bin/sshpk-conv deleted file mode 100644 index ecb743209..000000000 --- a/node_modules/.bin/sshpk-conv +++ /dev/null @@ -1,15 +0,0 @@ -#!/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 deleted file mode 100644 index dde70b020..000000000 --- a/node_modules/.bin/sshpk-conv.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@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 deleted file mode 100644 index 5a6a17ca2..000000000 --- a/node_modules/.bin/sshpk-sign +++ /dev/null @@ -1,15 +0,0 @@ -#!/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 deleted file mode 100644 index 45025ec15..000000000 --- a/node_modules/.bin/sshpk-sign.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@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 deleted file mode 100644 index 80e3a6b3d..000000000 --- a/node_modules/.bin/sshpk-verify +++ /dev/null @@ -1,15 +0,0 @@ -#!/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 deleted file mode 100644 index 1b5fc0c17..000000000 --- a/node_modules/.bin/sshpk-verify.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@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 deleted file mode 100644 index f3bfcf46b..000000000 --- a/node_modules/.bin/uuid +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - "$basedir/node" "$basedir/../uuid/bin/uuid" "$@" - ret=$? -else - node "$basedir/../uuid/bin/uuid" "$@" - ret=$? -fi -exit $ret diff --git a/node_modules/.bin/uuid.cmd b/node_modules/.bin/uuid.cmd deleted file mode 100644 index da52d68ad..000000000 --- a/node_modules/.bin/uuid.cmd +++ /dev/null @@ -1,7 +0,0 @@ -@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/ajv/.tonic_example.js b/node_modules/ajv/.tonic_example.js deleted file mode 100644 index aa11812d8..000000000 --- a/node_modules/ajv/.tonic_example.js +++ /dev/null @@ -1,20 +0,0 @@ -var Ajv = require('ajv'); -var ajv = new 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 deleted file mode 100644 index 810539685..000000000 --- a/node_modules/ajv/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index fdf6144a2..000000000 --- a/node_modules/ajv/README.md +++ /dev/null @@ -1,1327 +0,0 @@ -Ajv logo - -# Ajv: Another JSON Schema Validator - -The fastest JSON Schema validator for Node.js and browser with draft 6 support. - - -[![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@beta](https://img.shields.io/npm/v/ajv/beta.svg)](https://github.com/epoberezkin/ajv/tree/beta) -[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) -[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master) -[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/) -[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) - - -__Please note__: Ajv [version 6](https://github.com/epoberezkin/ajv/tree/beta) with [JSON Schema draft-07](http://json-schema.org/work-in-progress) support is released. Use `npm install ajv@beta` to install. - - -## Using version 5 - -[JSON Schema draft-06](https://trac.tools.ietf.org/html/draft-wright-json-schema-validation-01) is published. - -[Ajv version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0) that supports draft-06 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas). - -__Please note__: To use Ajv with draft-04 schemas you need to explicitly add meta-schema to the validator instance: - -```javascript -ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); -``` - - -## 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) - - [Combining schemas with $ref](#ref) - - [$data reference](#data-reference) - - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - - [Defining custom keywords](#defining-custom-keywords) - - [Asynchronous schema compilation](#asynchronous-schema-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) - - -Performance 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 6](http://json-schema.org/) and draft 4 standards: - - 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 Node.js 0.10-8.x -- [asynchronous loading](#asynchronous-schema-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) -- draft-6 keywords `const`, `contains` and `propertyNames` -- draft-6 boolean schemas (`true`/`false` as a schema to always pass/fail). -- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON-schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package -- [$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 -``` - -or to install [version 6](https://github.com/epoberezkin/ajv/tree/beta): - -``` -npm install ajv@beta -``` - - -## Getting started - -Try it in the Node.js 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 -// ... -var valid = ajv.addSchema(schema, 'mySchema') - .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 serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function 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 a 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; it 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)) -- migrate schemas to draft-06 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) -- 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, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains) -- [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames) -- [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const) -- [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf - -With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension 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-proposed) - conditional validation with a sequence of if/then clauses -- [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - 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-proposed) - 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. -- _url_: [URL record](https://url.spec.whatwg.org/#concept-url). -- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) -- _email_: email address. -- _hostname_: host name according 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 changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details. - -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). - - -## Combining schemas with $ref - -You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. - -Example: - -```javascript -var schema = { - "$id": "http://example.com/schemas/schema.json", - "type": "object", - "properties": { - "foo": { "$ref": "defs.json#/definitions/int" }, - "bar": { "$ref": "defs.json#/definitions/str" } - } -}; - -var defsSchema = { - "$id": "http://example.com/schemas/defs.json", - "definitions": { - "int": { "type": "integer" }, - "str": { "type": "string" } - } -}; -``` - -Now to compile your schema you can either pass all schemas to Ajv instance: - -```javascript -var ajv = new Ajv({schemas: [schema, defsSchema]}); -var validate = ajv.getSchema('http://example.com/schemas/schema.json'); -``` - -or use `addSchema` method: - -```javascript -var ajv = new Ajv; -var validate = ajv.addSchema(defsSchema) - .compile(schema); -``` - -See [Options](#options) and [addSchema](#api) method. - -__Please note__: -- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). -- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). -- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. -- The actual location of the schema file in the file system is not used. -- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. -- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. -- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). - - -## $data reference - -With `$data` option you can use values from the validated data as the values for the schema keywords. See [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: const, 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 ajv = new Ajv({$data: true}); - -var schema = { - "properties": { - "smaller": { - "type": "number", - "maximum": { "$data": "1/larger" } - }, - "larger": { "type": "number" } - } -}; - -var validData = { - smaller: 5, - larger: 7 -}; - -ajv.validate(schema, validData); // true -``` - -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 `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. - - -## $merge and $patch keywords - -With 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 schema compilation - -During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). - -Example: - -```javascript -var ajv = new Ajv({ loadSchema: loadSchema }); - -ajv.compileAsync(schema).then(function (validate) { - var valid = validate(data); - // ... -}); - -function loadSchema(uri) { - return request.json(uri).then(function (res) { - if (res.statusCode >= 400) - throw new Error('Loading error: ' + res.statusCode); - return res.body; - }); -} -``` - -__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. - - -## Asynchronous validation - -Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation - -You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (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 with `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 [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent) or with [regenerator](https://github.com/facebook/regenerator) or to [generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) that can be optionally transpiled 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 synchronous 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). - -Async functions are currently supported in Chrome 55, Firefox 52, Node.js 7 (with --harmony-async-await) and MS Edge 13 (with flag). - -Generator functions are currently supported in Chrome, Firefox and Node.js. - -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 with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. - - -Example: - -```javascript -/** - * Default mode is non-transpiled generator function wrapped with `co`. - * Using package ajv-async (https://github.com/epoberezkin/ajv-async) - * you can auto-detect the best async mode. - * In this case, without "async" and "transpile" options - * (or with option {async: true}) - * Ajv will choose the first supported/installed option in this order: - * 1. native async function - * 2. native generator function wrapped with co - * 3. es7 async functions transpiled with nodent - * 4. es7 async functions transpiled with regenerator - */ - -var setupAsync = require('ajv-async'); -var ajv = setupAsync(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 (data) { - console.log('Data is valid', data); // { userId: 1, postId: 19 } -}) -.catch(function (err) { - if (!(err instanceof Ajv.ValidationError)) throw err; - // data is invalid - console.log('Validation errors:', err.errors); -}); -``` - -### Using transpilers with asynchronous 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 setupAsync = require('ajv-async'); -var ajv = new Ajv({ /* async: 'es7', */ transpile: 'nodent' }); -setupAsync(ajv); -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 setupAsync = require('ajv-async'); -var ajv = new Ajv({ /* async: 'es7', */ transpile: 'regenerator' }); -setupAsync(ajv); -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', processCode: 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| -|---|:-:|:-:|:-:| -|es7 async
(native)|-|0.75|-| -|generators
(native)|-|1.0|-| -|es7.nodent|1.35|1.1|215Kb| -|es7.regenerator|1.0|2.7|1109Kb| -|regenerator|1.0|3.2|1109Kb| - -\* Relative performance in Node.js 7.x — 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 Node.js and the latest Chrome -- much better performance than native generators in other browsers -- works in IE 9 (regenerator does not) - - -## 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 `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. - - -##### .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 [, Boolean meta] [, Function callback]) -> Promise - -Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - -- missing schema can't be loaded (`loadSchema` returns a Promise that rejects). -- a schema containing a missing reference is loaded, but the reference cannot be resolved. -- schema (or some loaded/referenced schema) is invalid. - -The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. - -You can asynchronously compile meta-schema by passing `true` as the second parameter. - -See example in [Asynchronous compilation](#asynchronous-schema-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]) -> Ajv - -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. - -__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. -This allows you to do nice things like the following. - -```javascript -var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); -``` - -##### .addMetaSchema(Array<Object>|Object schema [, String key]) -> Ajv - -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 6 meta schema (http://json-schema.org/draft-06/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`. - - -##### .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 6 meta-schema (option `meta` should not be false). - -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). The returned validating function has `schema` property with the reference to the original schema. - - -##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -> Ajv - -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) -> Ajv - -Add custom format to validate strings or numbers. 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` (defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package). 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`. -- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/epoberezkin/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. - -Custom formats can be also added via `formats` option. - - -##### .addKeyword(String keyword, Object definition) -> Ajv - -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) -> Ajv - -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: - $data: false, - allErrors: false, - verbose: false, - jsonPointers: false, - uniqueItems: true, - unicode: true, - format: 'fast', - formats: {}, - unknownFormats: true, - schemas: {}, - logger: undefined, - // referenced schema options: - schemaId: undefined // recommended '$id' - missingRefs: true, - extendRefs: 'ignore', // recommended 'fail' - loadSchema: undefined, // function(uri: string): Promise {} - // options to modify validated data: - removeAdditional: false, - useDefaults: false, - coerceTypes: false, - // asynchronous validation options: - async: 'co*', - transpile: undefined, // requires ajv-async package - // advanced options: - meta: true, - validateSchema: true, - addUsedSchema: true, - inlineRefs: true, - passContext: false, - loopRequired: Infinity, - ownProperties: false, - multipleOfPrecision: false, - errorDataPath: 'object', - messages: true, - sourceCode: false, - processCode: undefined, // function (str: string): string {} - cache: new Cache, - serialize: undefined -} -``` - -##### Validation and reporting options - -- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). -- _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` property 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` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$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 another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON-schema specification. -- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. -- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values: - - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - - `false` - logging is disabled. - - -##### Referenced schema options - -- _schemaId_: this option defines which keywords are used as schema URI. Option value: - - `"$id"` (recommended) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06), ignore `id` keyword (if it is present a warning will be logged). - - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - - `undefined` (default) - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. -- _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: - - `"ignore"` (default) - 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"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). -- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-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*"` (default) - compile to generator function ("co*" - wrapped with `co.wrap`). If generators are not supported and you don't provide `processCode` option (or `transpile` option if you use [ajv-async](https://github.com/epoberezkin/ajv-async) package), the exception will be thrown when async schema is compiled. - - `"es7"` - compile to es7 async function. Unless your platform supports them you need to provide `processCode` or `transpile` option. According to [compatibility table](http://kangax.github.io/compat-table/es7/)) async functions are supported by: - - Firefox 52, - - Chrome 55, - - Node.js 7 (with `--harmony-async-await`), - - MS Edge 13 (with flag). - - `undefined`/`true` - auto-detect async mode. It requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. If `transpile` option is not passed, ajv-async will choose the first of supported/installed async/transpile modes in this order: - - "es7" (native async functions), - - "co*" (native generators 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. -- _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It 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. If you are passing a function, you can simply pass it to `processCode` option without using ajv-async. - - -##### Advanced options - -- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). 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` (or `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`. -- _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)). -- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). -- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass `require('js-beautify').js_beautify`. - - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/epoberezkin/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. -- _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()`. -- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. - - -## 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 when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. - - -### 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). - -__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. - - -### 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). -- `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 dependencies). -- `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). -- `propertyNames` - property `propertyName` (an invalid property name). -- `patternRequired` (in ajv-keywords) - 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-async](https://github.com/epoberezkin/ajv-async) - configure async validation mode -- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface -- [ajv-errors](https://github.com/epoberezkin/ajv-errors) - custom error messages -- [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages -- [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - instrument generated validation code to measure test coverage of your schemas -- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - custom validation keywords (if/then/else, select, typeof, etc.) -- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - keywords $merge and $patch -- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions - - -## 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.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.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 deleted file mode 100644 index ee5623cb1..000000000 --- a/node_modules/ajv/dist/ajv.bundle.js +++ /dev/null @@ -1,7345 +0,0 @@ -(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%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; -// For the source: https://gist.github.com/dperini/729294 -// For test cases: https://mathiasbynens.be/demo/url-regex -// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. -// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; -var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; -var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$|^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; - - -module.exports = formats; - -function formats(mode) { - mode = mode == 'full' ? 'full' : 'fast'; - return util.copy(formats[mode]); -} - - -formats.fast = { - // date: http://tools.ietf.org/html/rfc3339#section-5.6 - date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, - // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 - time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i, - 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i, - // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js - uri: /^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i, - 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i, - 'uri-template': URITEMPLATE, - url: URL, - // email (sources from jsen validator): - // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 - // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, - hostname: HOSTNAME, - // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses - ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, - regex: regex, - // uuid: http://tools.ietf.org/html/rfc4122 - uuid: UUID, - // JSON-pointer: https://tools.ietf.org/html/rfc6901 - // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A - 'json-pointer': JSON_POINTER, - // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 - 'relative-json-pointer': RELATIVE_JSON_POINTER -}; - - -formats.full = { - date: date, - time: time, - 'date-time': date_time, - uri: uri, - 'uri-reference': URIREF, - 'uri-template': URITEMPLATE, - url: URL, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: hostname, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, - regex: regex, - uuid: UUID, - 'json-pointer': JSON_POINTER, - 'relative-json-pointer': RELATIVE_JSON_POINTER -}; - - -function date(str) { - // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 - var matches = str.match(DATE); - if (!matches) return false; - - var month = +matches[1]; - var day = +matches[2]; - return month >= 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); -} - - -var Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch(e) { - return false; - } -} - -},{"./util":12}],7:[function(require,module,exports){ -'use strict'; - -var resolve = require('./resolve') - , util = require('./util') - , errorClasses = require('./error_classes') - , stableStringify = require('fast-json-stable-stringify'); - -var validateGenerator = require('../dotjs/validate'); - -/** - * Functions below are used inside compiled validations function - */ - -var co = require('co'); -var ucs2length = util.ucs2length; -var equal = require('fast-deep-equal'); - -// this error is thrown by async schemas to return validation errors via exception -var ValidationError = errorClasses.Validation; - -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 = []; - - 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 (opts.sourceCode) cv.source = v.source; - } - 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; - - var sourceCode = validateGenerator({ - isTop: true, - schema: _schema, - isRoot: isRoot, - baseId: baseId, - root: _root, - schemaPath: '', - errSchemaPath: '#', - errorPath: '""', - MissingRefError: errorClasses.MissingRef, - RULES: RULES, - validate: validateGenerator, - util: util, - resolve: resolve, - resolveRef: resolveRef, - usePattern: usePattern, - useDefault: useDefault, - useCustomRule: useCustomRule, - opts: opts, - formats: formats, - logger: self.logger, - self: self - }); - - sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) - + vars(defaults, defaultCode) + vars(customRules, customRuleCode) - + sourceCode; - - if (opts.processCode) sourceCode = opts.processCode(sourceCode); - // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); - var validate; - try { - var makeValidate = new Function( - 'self', - 'RULES', - 'formats', - 'root', - 'refVal', - 'defaults', - 'customRules', - 'co', - 'equal', - 'ucs2length', - 'ValidationError', - sourceCode - ); - - validate = makeValidate( - self, - RULES, - formats, - root, - refVal, - defaults, - customRules, - co, - equal, - ucs2length, - ValidationError - ); - - refVal[0] = validate; - } catch(e) { - self.logger.error('Error compiling schema, function code:', sourceCode); - 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 (opts.sourceCode === true) { - validate.source = { - code: sourceCode, - 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 === undefined) { - var localSchema = localRefs && localRefs[ref]; - if (localSchema) { - v = resolve.inlineRef(localSchema, opts.inlineRefs) - ? localSchema - : compile.call(self, localSchema, root, localRefs, baseId); - } - } - - if (v === undefined) { - removeLocalRef(ref); - } else { - 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 removeLocalRef(ref) { - delete refs[ref]; - } - - function replaceLocalRef(ref, v) { - var refId = refs[ref]; - refVal[refId] = v; - } - - function resolvedRef(refVal, code) { - return typeof refVal == 'object' || typeof refVal == 'boolean' - ? { 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') self.logger.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; - if (!validate) return; - } - - if (validate === undefined) - throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); - - 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; -}; - -},{}],12:[function(require,module,exports){ -'use strict'; - - -module.exports = { - copy: copy, - checkDataType: checkDataType, - checkDataTypes: checkDataTypes, - coerceToTypes: coerceToTypes, - toHash: toHash, - getProperty: getProperty, - escapeQuotes: escapeQuotes, - equal: require('fast-deep-equal'), - ucs2length: require('./ucs2length'), - varOccurences: varOccurences, - varReplace: varReplace, - cleanUpCode: cleanUpCode, - finalCleanUpCode: finalCleanUpCode, - schemaHasRules: schemaHasRules, - schemaHasRulesExcept: schemaHasRulesExcept, - toQuotedString: toQuotedString, - getPathExpr: getPathExpr, - getPath: getPath, - getData: getData, - unescapeFragment: unescapeFragment, - unescapeJsonPointer: unescapeJsonPointer, - 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 ? '>' : '<', - $errorKeyword = undefined; - if ($isDataExcl) { - var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), - $exclusive = 'exclusive' + $lvl, - $exclType = 'exclType' + $lvl, - $exclIsNumber = 'exclIsNumber' + $lvl, - $opExpr = 'op' + $lvl, - $opStr = '\' + ' + $opExpr + ' + \''; - out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; - $schemaValueExcl = 'schemaExcl' + $lvl; - out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; - 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 += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; - } else { - var $exclIsNumber = typeof $schemaExcl == 'number', - $opStr = $op; - if ($exclIsNumber && $isData) { - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; - } else { - if ($exclIsNumber && $schema === undefined) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $schemaValue = $schemaExcl; - $notOp += '='; - } else { - if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); - if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; - $notOp += '='; - } else { - $exclusive = false; - $opStr += '='; - } - } - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; - } - } - $errorKeyword = $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 += '' + ($schemaValue) + '\''; - } - } - 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; -} - -},{}],14:[function(require,module,exports){ -'use strict'; -module.exports = function generate__limitItems(it, $keyword, $ruleType) { - 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.$data && $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; -} - -},{}],15:[function(require,module,exports){ -'use strict'; -module.exports = function generate__limitLength(it, $keyword, $ruleType) { - 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.$data && $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; -} - -},{}],16:[function(require,module,exports){ -'use strict'; -module.exports = function generate__limitProperties(it, $keyword, $ruleType) { - 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.$data && $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; -} - -},{}],17:[function(require,module,exports){ -'use strict'; -module.exports = function generate_allOf(it, $keyword, $ruleType) { - 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; -} - -},{}],18:[function(require,module,exports){ -'use strict'; -module.exports = function generate_anyOf(it, $keyword, $ruleType) { - 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++; '; - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - out += ' } 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; -} - -},{}],19:[function(require,module,exports){ -'use strict'; -module.exports = function generate_const(it, $keyword, $ruleType) { - 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.$data && $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: \'' + ('const') + '\' , 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 += ' }'; - if ($breakOnError) { - out += ' else { '; - } - return out; -} - -},{}],20:[function(require,module,exports){ -'use strict'; -module.exports = function generate_contains(it, $keyword, $ruleType) { - 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 $idx = 'i' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $currentBaseId = it.baseId, - $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all); - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if ($nonEmptySchema) { - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' var ' + ($nextValid) + ' = false; 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) + ' '; - } - out += ' if (' + ($nextValid) + ') break; } '; - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; - } else { - out += ' if (' + ($data) + '.length == 0) {'; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should contain a valid item\' '; - } - 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 ($nonEmptySchema) { - out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - } - if (it.opts.allErrors) { - out += ' } '; - } - out = it.util.cleanUpCode(out); - return out; -} - -},{}],21:[function(require,module,exports){ -'use strict'; -module.exports = function generate_custom(it, $keyword, $ruleType) { - 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.$data && $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, - $closingBraces = ''; - 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); - if (!$ruleValidate) return; - $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 ($isData && $rDef.$data) { - $closingBraces += '}'; - out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; - if ($validateSchema) { - $closingBraces += '}'; - 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); - var $closingBraces = ''; - $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 += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; - } - out += '' + ($closingBraces); - 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) + '= 0) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } else { - throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); - } - } - var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; - var $formatType = $isObject && $format.type || 'string'; - if ($isObject) { - var $async = $format.async === true; - $format = $format.validate; - } - if ($formatType != $ruleType) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - if ($async) { - if (!it.async) throw new Error('async format in sync schema'); - var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; - out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { '; - } else { - out += ' if (! '; - var $formatRef = 'formats' + it.util.getProperty($schema); - if ($isObject) $formatRef += '.validate'; - if (typeof $format == 'function') { - out += ' ' + ($formatRef) + '(' + ($data) + ') '; - } else { - out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; - } - out += ') { '; - } - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match format "'; - 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; -} - -},{}],25:[function(require,module,exports){ -'use strict'; -module.exports = function generate_items(it, $keyword, $ruleType) { - 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 $idx = 'i' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $currentBaseId = it.baseId; - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if (Array.isArray($schema)) { - var $additionalItems = it.schema.additionalItems; - if ($additionalItems === false) { - out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + '/additionalItems'; - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; - } - 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++; '; - } - out += ' } '; - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - 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)) { - out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($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 += ' ' + ($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, $ruleType) { - 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.$data && $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 += '' + ($schemaValue) + '\''; - } - } - 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, $ruleType) { - 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, $ruleType) { - 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 err = '; /* 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 += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - 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, $ruleType) { - 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.$data && $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_properties(it, $keyword, $ruleType) { - 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, - $idx = 'idx' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $dataProperties = 'dataProperties' + $lvl; - 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.patternGroups) { - var $pgProperties = it.schema.patternGroups || {}, - $pgPropertyKeys = Object.keys($pgProperties); - } - out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; - if ($ownProperties) { - out += ' var ' + ($dataProperties) + ' = undefined;'; - } - if ($checkAdditional) { - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; - } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - 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.patternGroups && $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 '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { ' + ($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 '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { ' + ($nextValid) + ' = true; } else { '; - } else { - out += ' if (' + ($useData) + ' !== undefined '; - if ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ' ) { '; - } - } - out += ' ' + ($code) + ' } '; - } - } - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if ($pPropertyKeys.length) { - 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); - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; - } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - 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.patternGroups && $pgPropertyKeys.length) { - 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; '; - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; - } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - 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; -} - -},{}],31:[function(require,module,exports){ -'use strict'; -module.exports = function generate_propertyNames(it, $keyword, $ruleType) { - 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); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - if (it.util.schemaHasRules($schema, it.RULES.all)) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - var $key = 'key' + $lvl, - $idx = 'idx' + $lvl, - $i = 'i' + $lvl, - $invalidName = '\' + ' + $key + ' + \'', - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $dataProperties = 'dataProperties' + $lvl, - $ownProperties = it.opts.ownProperties, - $currentBaseId = it.baseId; - out += ' var ' + ($errs) + ' = errors; '; - if ($ownProperties) { - out += ' var ' + ($dataProperties) + ' = undefined; '; - } - if ($ownProperties) { - out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; - } else { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - } - out += ' var startErrs' + ($lvl) + ' = errors; '; - var $passData = $key; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - 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) + ' '; - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '= it.opts.loopRequired, - $ownProperties = it.opts.ownProperties; - 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 ($ownProperties) { - out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; - } - out += '; 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 $propertyKey, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - $propertyKey = arr2[$i += 1]; - if ($i) { - out += ' || '; - } - var $prop = it.util.getProperty($propertyKey), - $useData = $data + $prop; - out += ' ( ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $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 '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; - } - out += ') { 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 $propertyKey, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $prop = it.util.getProperty($propertyKey), - $missingProperty = it.util.escapeQuotes($propertyKey), - $useData = $data + $prop; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - out += ' if ( ' + ($useData) + ' === undefined '; - if ($ownProperties) { - out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; - } - out += ') { 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_uniqueItems(it, $keyword, $ruleType) { - 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.$data && $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; -} - -},{}],35:[function(require,module,exports){ -'use strict'; -module.exports = function generate_validate(it, $keyword, $ruleType) { - var out = ''; - var $async = it.schema.$async === true, - $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), - $id = it.self._getId(it.schema); - if (it.isTop) { - if ($async) { - it.async = true; - var $es7 = it.opts.async == 'es7'; - it.yieldAwait = $es7 ? 'await' : 'yield'; - } - out += ' var validate = '; - if ($async) { - if ($es7) { - out += ' (async function '; - } else { - if (it.opts.async != '*') { - out += 'co.wrap'; - } - out += '(function* '; - } - } else { - out += ' (function '; - } - out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; - if ($id && (it.opts.sourceCode || it.opts.processCode)) { - out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; - } - } - if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { - var $keyword = 'false schema'; - 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; - if (it.schema === false) { - if (it.isTop) { - $breakOnError = true; - } else { - out += ' var ' + ($valid) + ' = false; '; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'boolean schema is false\' '; - } - 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++; '; - } - } else { - if (it.isTop) { - if ($async) { - out += ' return data; '; - } else { - out += ' validate.errors = null; return true; '; - } - } else { - out += ' var ' + ($valid) + ' = true; '; - } - } - if (it.isTop) { - out += ' }); return validate; '; - } - return out; - } - if (it.isTop) { - var $top = it.isTop, - $lvl = it.level = 0, - $dataLvl = it.dataLevel = 0, - $data = 'data'; - it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); - it.baseId = it.baseId || it.rootId; - delete it.isTop; - it.dataPathArr = [undefined]; - out += ' 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 ($id) it.baseId = it.resolve.url(it.baseId, $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 $errorKeyword; - var $typeSchema = it.schema.type, - $typeIsArray = Array.isArray($typeSchema); - if ($typeIsArray && $typeSchema.length == 1) { - $typeSchema = $typeSchema[0]; - $typeIsArray = false; - } - if (it.schema.$ref && $refKeywords) { - if (it.opts.extendRefs == 'fail') { - throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); - } else if (it.opts.extendRefs !== true) { - $refKeywords = false; - it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); - } - } - if ($typeSchema) { - if (it.opts.coerceTypes) { - var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); - } - var $rulesGroup = it.RULES.types[$typeSchema]; - if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type'; - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type', - $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; - out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; - if ($coerceToTypes) { - 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: \'' + ($errorKeyword || '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) + '; } '; - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '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 (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 { - if (it.opts.v5 && it.schema.patternGroups) { - it.logger.warn('keyword "patternGroups" is deprecated and disabled. Use option patternGroups: true to enable.'); - } - 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)) { - var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); - if ($code) { - out += ' ' + ($code) + ' '; - if ($breakOnError) { - $closingBraces1 += '}'; - } - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces1) + ' '; - $closingBraces1 = ''; - } - if ($rulesGroup.type) { - out += ' } '; - if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { - 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: \'' + ($errorKeyword || '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 ($breakOnError) { - out += ' ' + ($closingBraces2) + ' '; - } - if ($top) { - if ($async) { - out += ' if (errors === 0) return data; '; - 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) { - out = it.util.finalCleanUpCode(out, $async); - } - - function $shouldUseGroup($rulesGroup) { - var rules = $rulesGroup.rules; - for (var i = 0; i < rules.length; i++) - if ($shouldUseRule(rules[i])) return true; - } - - function $shouldUseRule($rule) { - return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); - } - - function $ruleImplementsSomeKeyword($rule) { - var impl = $rule.implements; - for (var i = 0; i < impl.length; i++) - if (it.schema[impl[i]] !== undefined) return true; - } - return out; -} - -},{}],36:[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`. - * @return {Ajv} this for method chaining - */ -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; -} - -},{}],41:[function(require,module,exports){ -'use strict'; - -module.exports = function equal(a, b) { - if (a === b) return true; - - var arrA = Array.isArray(a) - , arrB = Array.isArray(b) - , i; - - if (arrA && arrB) { - if (a.length != b.length) return false; - for (i = 0; i < a.length; i++) - if (!equal(a[i], b[i])) return false; - return true; - } - - if (arrA != arrB) return false; - - if (a && b && typeof a === 'object' && typeof b === 'object') { - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) return false; - - var dateA = a instanceof Date - , dateB = b instanceof Date; - if (dateA && dateB) return a.getTime() == b.getTime(); - if (dateA != dateB) return false; - - var regexpA = a instanceof RegExp - , regexpB = b instanceof RegExp; - if (regexpA && regexpB) return a.toString() == b.toString(); - if (regexpA != regexpB) return false; - - for (i = 0; i < keys.length; i++) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - - for (i = 0; i < keys.length; i++) - if(!equal(a[keys[i]], b[keys[i]])) return false; - - return true; - } - - return false; -}; - -},{}],42:[function(require,module,exports){ -'use strict'; - -module.exports = function (data, opts) { - if (!opts) opts = {}; - if (typeof opts === 'function') opts = { cmp: opts }; - var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; - - 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 (node) { - if (node && node.toJSON && typeof node.toJSON === 'function') { - node = node.toJSON(); - } - - if (node === undefined) return; - if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; - if (typeof node !== 'object') return JSON.stringify(node); - - var i, out; - if (Array.isArray(node)) { - out = '['; - for (i = 0; i < node.length; i++) { - if (i) out += ','; - out += stringify(node[i]) || 'null'; - } - return out + ']'; - } - - if (node === null) return 'null'; - - if (seen.indexOf(node) !== -1) { - if (cycles) return JSON.stringify('__cycle__'); - throw new TypeError('Converting circular structure to JSON'); - } - - var seenIndex = seen.push(node) - 1; - var keys = Object.keys(node).sort(cmp && cmp(node)); - out = ''; - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = stringify(node[key]); - - if (!value) continue; - if (out) out += ','; - out += JSON.stringify(key) + ':' + value; - } - seen.splice(seenIndex, 1); - return '{' + out + '}'; - })(data); -}; - -},{}],43:[function(require,module,exports){ -'use strict'; - -var traverse = module.exports = function (schema, opts, cb) { - if (typeof opts == 'function') { - cb = opts; - opts = {}; - } - _traverse(opts, cb, schema, '', schema); -}; - - -traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true -}; - -traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; - -traverse.propsKeywords = { - definitions: true, - properties: true, - patternProperties: true, - dependencies: true -}; - -traverse.skipKeywords = { - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; - - -function _traverse(opts, cb, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == 'object' && !Array.isArray(schema)) { - cb(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i=0; i= 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 : {}) -},{}],45:[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]'; -}; - -},{}],46:[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; -}; - -},{}],47:[function(require,module,exports){ -'use strict'; - -exports.decode = exports.parse = require('./decode'); -exports.encode = exports.stringify = require('./encode'); - -},{"./decode":45,"./encode":46}],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 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":49,"punycode":44,"querystring":47}],49:[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('fast-json-stable-stringify') - , formats = require('./compile/formats') - , rules = require('./compile/rules') - , $dataMetaSchema = require('./$data') - , patternGroups = require('./patternGroups') - , util = require('./compile/util') - , co = require('co'); - -module.exports = Ajv; - -Ajv.prototype.validate = validate; -Ajv.prototype.compile = compile; -Ajv.prototype.addSchema = addSchema; -Ajv.prototype.addMetaSchema = addMetaSchema; -Ajv.prototype.validateSchema = validateSchema; -Ajv.prototype.getSchema = getSchema; -Ajv.prototype.removeSchema = removeSchema; -Ajv.prototype.addFormat = addFormat; -Ajv.prototype.errorsText = errorsText; - -Ajv.prototype._addSchema = _addSchema; -Ajv.prototype._compile = _compile; - -Ajv.prototype.compileAsync = require('./compile/async'); -var customKeyword = require('./keyword'); -Ajv.prototype.addKeyword = customKeyword.add; -Ajv.prototype.getKeyword = customKeyword.get; -Ajv.prototype.removeKeyword = customKeyword.remove; - -var errorClasses = require('./compile/error_classes'); -Ajv.ValidationError = errorClasses.Validation; -Ajv.MissingRefError = errorClasses.MissingRef; -Ajv.$dataMetaSchema = $dataMetaSchema; - -var META_SCHEMA_ID = 'http://json-schema.org/draft-06/schema'; - -var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ]; -var META_SUPPORT_DATA = ['/properties']; - -/** - * 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); - opts = this._opts = util.copy(opts) || {}; - setLogger(this); - this._schemas = {}; - this._refs = {}; - this._fragments = {}; - this._formats = formats(opts.format); - var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference']; - this._schemaUriFormatFunc = function (str) { return schemaUriFormat.test(str); }; - - this._cache = opts.cache || new Cache; - this._loadingSchemas = {}; - this._compilations = []; - this.RULES = rules(); - this._getId = chooseGetId(opts); - - opts.loopRequired = opts.loopRequired || Infinity; - if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; - if (opts.serialize === undefined) opts.serialize = stableStringify; - this._metaOpts = getMetaSchemaOptions(this); - - if (opts.formats) addInitialFormats(this); - addDraft6MetaSchema(this); - if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); - addInitialSchemas(this); - if (opts.patternGroups) patternGroups(this); -} - - - -/** - * Validate data using schema - * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. - * @this Ajv - * @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 = this.getSchema(schemaKeyRef); - if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); - } else { - var schemaObj = this._addSchema(schemaKeyRef); - v = schemaObj.validate || this._compile(schemaObj); - } - - var valid = v(data); - if (v.$async === true) - return this._opts.async == '*' ? co(valid) : valid; - this.errors = v.errors; - return valid; -} - - -/** - * Create validating function for passed schema. - * @this Ajv - * @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 = this._addSchema(schema, undefined, _meta); - return schemaObj.validate || this._compile(schemaObj); -} - - -/** - * Adds schema to the instance. - * @this Ajv - * @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. - * @return {Ajv} this for method chaining - */ -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 || this.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<=h[t]}function o(e,r){var t=e.match(u);if(!t)return!1;return t[1]<=23&&t[2]<=59&&t[3]<=59&&(!r||t[5])}function i(e){if(E.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}var n=e("./util"),l=/^\d\d\d\d-(\d\d)-(\d\d)$/,h=[0,31,29,31,30,31,30,31,31,30,31,30,31],u=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i,c=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,d=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,f=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,p=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,m=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,v=/^(?:\/(?:[^~/]|~0|~1)*)*$|^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,y=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;r.exports=a,a.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,uri:/^(?:[a-z][a-z0-9+-.]*)(?::|\/)\/?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i,"uri-template":f,url:p,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:c,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:i,uuid:m,"json-pointer":v,"relative-json-pointer":y},a.full={date:s,time:o,"date-time":function(e){var r=e.split(g);return 2==r.length&&s(r[0])&&o(r[1],!0)},uri:function(e){return P.test(e)&&d.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":f,url:p,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:function(e){return e.length<=255&&c.test(e)},ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:i,uuid:m,"json-pointer":v,"relative-json-pointer":y};var g=/t|\s/i,P=/\/|:/,E=/[^\\]\\Z/},{"./util":12}],7:[function(e,r,t){"use strict";function a(e,r,t,P){function E(){var e=C.validate,r=e.apply(null,arguments);return E.errors=e.errors,r}function w(e,t,s,f){var P=!t||t&&t.schema==e;if(t.schema!=r.schema)return a.call($,e,t,s,f);var E=!0===e.$async,w=p({isTop:!0,schema:e,isRoot:P,baseId:f,root:t,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:d.MissingRef,RULES:U,validate:p,util:c,resolve:u,resolveRef:b,usePattern:_,useDefault:x,useCustomRule:F,opts:R,formats:Q,logger:$.logger,self:$});w=h(O,n)+h(I,o)+h(k,i)+h(L,l)+w,R.processCode&&(w=R.processCode(w));var S;try{S=new Function("self","RULES","formats","root","refVal","defaults","customRules","co","equal","ucs2length","ValidationError",w)($,U,Q,r,O,k,L,m,y,v,g),O[0]=S}catch(e){throw $.logger.error("Error compiling schema, function code:",w),e}return S.schema=e,S.errors=null,S.refs=D,S.refVal=O,S.root=P?S:t,E&&(S.$async=!0),!0===R.sourceCode&&(S.source={code:w,patterns:I,defaults:k}),S}function b(e,s,o){s=u.url(e,s);var i,n,l=D[s];if(void 0!==l)return i=O[l],n="refVal["+l+"]",j(i,n);if(!o&&r.refs){var h=r.refs[s];if(void 0!==h)return i=r.refVal[h],n=S(s,i),j(i,n)}n=S(s);var c=u.call($,w,r,s);if(void 0===c){var d=t&&t[s];d&&(c=u.inlineRef(d,R.inlineRefs)?d:a.call($,d,r,t,e))}if(void 0!==c)return function(e,r){O[D[e]]=r}(s,c),j(c,n);!function(e){delete D[e]}(s)}function S(e,r){var t=O.length;return O[t]=r,D[e]=t,"refVal"+t}function j(e,r){return"object"==typeof e||"boolean"==typeof e?{code:r,schema:e,inline:!0}:{code:r,$async:e&&e.$async}}function _(e){var r=A[e];return void 0===r&&(r=A[e]=I.length,I[r]=e),"pattern"+r}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return c.toQuotedString(e);case"object":if(null===e)return"null";var r=f(e),t=q[r];return void 0===t&&(t=q[r]=k.length,k[t]=e),"default"+t}}function F(e,r,t,a){var s=e.definition.validateSchema;if(s&&!1!==$._opts.validateSchema){if(!s(r)){var o="keyword schema is invalid: "+$.errorsText(s.errors);if("log"!=$._opts.validateSchema)throw new Error(o);$.logger.error(o)}}var i,n=e.definition.compile,l=e.definition.inline,h=e.definition.macro;if(n)i=n.call($,r,t,a);else if(h)i=h.call($,r,t,a),!1!==R.validateSchema&&$.validateSchema(i,!0);else if(l)i=l.call($,a,e.keyword,r,t);else if(!(i=e.definition.validate))return;if(void 0===i)throw new Error('custom keyword "'+e.keyword+'"failed to compile');var u=L.length;return L[u]=i,{code:"customRule"+u,validate:i}}var $=this,R=this._opts,O=[void 0],D={},I=[],A={},k=[],q={},L=[],z=function(e,r,t){var a=s.call(this,e,r,t);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:e,root:r,baseId:t},{index:a,compiling:!1})}.call(this,e,r=r||{schema:e,refVal:O,refs:D},P),C=this._compilations[z.index];if(z.compiling)return C.callValidate=E;var Q=this._formats,U=this.RULES;try{var V=w(e,r,t,P);C.validate=V;var N=C.callValidate;return N&&(N.schema=V.schema,N.errors=null,N.refs=V.refs,N.refVal=V.refVal,N.root=V.root,N.$async=V.$async,R.sourceCode&&(N.source=V.source)),V}finally{(function(e,r,t){var a=s.call(this,e,r,t);a>=0&&this._compilations.splice(a,1)}).call(this,e,r,P)}}function s(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(i="data"+(r-a||""),!s)return i}for(var l=i,h=s.split("/"),c=0;c",y=f?">":"<",g=void 0;if(e.opts.$data&&m&&m.$data){var P=e.util.getData(m.$data,i,e.dataPathArr),E="exclusive"+o,w="exclType"+o,b="exclIsNumber"+o,S="' + "+(j="op"+o)+" + '";s+=" var schemaExcl"+o+" = "+P+"; ",s+=" var "+E+"; var "+w+" = typeof "+(P="schemaExcl"+o)+"; if ("+w+" != 'boolean' && "+w+" != 'undefined' && "+w+" != 'number') { ";g=p;(_=_||[]).push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(g||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , 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: "+c+" "),s+=" } "):s+=" {} ";x=s;s=_.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } else if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+w+" == 'number' ? ( ("+E+" = "+a+" === undefined || "+P+" "+v+"= "+a+") ? "+c+" "+y+"= "+P+" : "+c+" "+y+" "+a+" ) : ( ("+E+" = "+P+" === true) ? "+c+" "+y+"= "+a+" : "+c+" "+y+" "+a+" ) || "+c+" !== "+c+") { var op"+o+" = "+E+" ? '"+v+"' : '"+v+"=';"}else{S=v;if((b="number"==typeof m)&&d){j="'"+S+"'";s+=" if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" ( "+a+" === undefined || "+m+" "+v+"= "+a+" ? "+c+" "+y+"= "+m+" : "+c+" "+y+" "+a+" ) || "+c+" !== "+c+") { "}else{b&&void 0===n?(E=!0,g=p,h=e.errSchemaPath+"/"+p,a=m,y+="="):(b&&(a=Math[f?"min":"max"](m,n)),m===(!b||a)?(E=!0,g=p,h=e.errSchemaPath+"/"+p,y+="="):(E=!1,S+="="));var j="'"+S+"'";s+=" if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+c+" "+y+" "+a+" || "+c+" !== "+c+") { "}}g=g||r;var _=_||[];_.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(g||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { comparison: "+j+", limit: "+a+", exclusive: "+E+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be "+S+" ",s+=d?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var x=s;return s=_.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+=" } ",u&&(s+=" else { "),s}},{}],14:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;s+="if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" "+c+".length "+("maxItems"==r?">":"<")+" "+a+") { ";var f=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxItems"==r?"more":"less",s+=" than ",s+=d?"' + "+a+" + '":""+n,s+=" items' "),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&u?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+="} ",u&&(s+=" else { "),s}},{}],15:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;s+="if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=!1===e.opts.unicode?" "+c+".length ":" ucs2length("+c+") ",s+=" "+("maxLength"==r?">":"<")+" "+a+") { ";var f=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT be ",s+="maxLength"==r?"longer":"shorter",s+=" than ",s+=d?"' + "+a+" + '":""+n,s+=" characters' "),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&u?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+="} ",u&&(s+=" else { "),s}},{}],16:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n;s+="if ( ",d&&(s+=" ("+a+" !== undefined && typeof "+a+" != 'number') || "),s+=" Object.keys("+c+").length "+("maxProperties"==r?">":"<")+" "+a+") { ";var f=r,p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: '"+(f||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { limit: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have ",s+="maxProperties"==r?"more":"less",s+=" than ",s+=d?"' + "+a+" + '":""+n,s+=" properties' "),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;return s=p.pop(),s+=!e.compositeRule&&u?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+="} ",u&&(s+=" else { "),s}},{}],17:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,n=!e.opts.allErrors,l=e.util.copy(e),h="";l.level++;var u="valid"+l.level,c=l.baseId,d=!0,f=s;if(f)for(var p,m=-1,v=f.length-1;m=0)return h&&(a+=" if (true) { "),a;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var v="object"==typeof m&&!(m instanceof RegExp)&&m.validate,y=v&&m.type||"string";if(v){var g=!0===m.async;m=m.validate}if(y!=t)return h&&(a+=" if (true) { "),a;if(g){if(!e.async)throw new Error("async format in sync schema");P="formats"+e.util.getProperty(i)+".validate";a+=" if (!("+e.yieldAwait+" "+P+"("+u+"))) { "}else{a+=" if (! ";var P="formats"+e.util.getProperty(i);v&&(P+=".validate"),a+="function"==typeof m?" "+P+"("+u+") ":" "+P+".test("+u+") ",a+=") { "}}var E=E||[];E.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { format: ",a+=d?""+c:""+e.util.toQuotedString(i),a+=" } ",!1!==e.opts.messages&&(a+=" , message: 'should match format \"",a+=d?"' + "+c+" + '":""+e.util.escapeQuotes(i),a+="\"' "),e.opts.verbose&&(a+=" , schema: ",a+=d?"validate.schema"+n:""+e.util.toQuotedString(i),a+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var w=a;return a=E.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+w+"]); ":" validate.errors = ["+w+"]; return false; ":" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",h&&(a+=" else { "),a}},{}],25:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="valid"+s,d="errs__"+s,f=e.util.copy(e),p="";f.level++;var m="valid"+f.level,v="i"+s,y=f.dataLevel=e.dataLevel+1,g="data"+y,P=e.baseId;if(a+="var "+d+" = errors;var "+c+";",Array.isArray(i)){var E=e.schema.additionalItems;if(!1===E){a+=" "+c+" = "+u+".length <= "+i.length+"; ";var w=l;l=e.errSchemaPath+"/additionalItems",a+=" if (!"+c+") { ";var b=b||[];b.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+i.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var S=a;a=b.pop(),a+=!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++; ",a+=" } ",l=w,h&&(p+="}",a+=" else { ")}var j=i;if(j)for(var _,x=-1,F=j.length-1;x "+x+") { ";$=u+"["+x+"]";f.schema=_,f.schemaPath=n+"["+x+"]",f.errSchemaPath=l+"/"+x,f.errorPath=e.util.getPathExpr(e.errorPath,x,e.opts.jsonPointers,!0),f.dataPathArr[y]=x;R=e.validate(f);f.baseId=P,e.util.varOccurences(R,g)<2?a+=" "+e.util.varReplace(R,g,$)+" ":a+=" var "+g+" = "+$+"; "+R+" ",a+=" } ",h&&(a+=" if ("+m+") { ",p+="}")}if("object"==typeof E&&e.util.schemaHasRules(E,e.RULES.all)){f.schema=E,f.schemaPath=e.schemaPath+".additionalItems",f.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+m+" = true; if ("+u+".length > "+i.length+") { for (var "+v+" = "+i.length+"; "+v+" < "+u+".length; "+v+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);$=u+"["+v+"]";f.dataPathArr[y]=v;R=e.validate(f);f.baseId=P,e.util.varOccurences(R,g)<2?a+=" "+e.util.varReplace(R,g,$)+" ":a+=" var "+g+" = "+$+"; "+R+" ",h&&(a+=" if (!"+m+") break; "),a+=" } } ",h&&(a+=" if ("+m+") { ",p+="}")}}else if(e.util.schemaHasRules(i,e.RULES.all)){f.schema=i,f.schemaPath=n,f.errSchemaPath=l,a+=" for (var "+v+" = 0; "+v+" < "+u+".length; "+v+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers,!0);var $=u+"["+v+"]";f.dataPathArr[y]=v;var R=e.validate(f);f.baseId=P,e.util.varOccurences(R,g)<2?a+=" "+e.util.varReplace(R,g,$)+" ":a+=" var "+g+" = "+$+"; "+R+" ",h&&(a+=" if (!"+m+") break; "),a+=" }"}return h&&(a+=" "+p+" if ("+d+" == errors) {"),a=e.util.cleanUpCode(a)}},{}],26:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,c="data"+(i||""),d=e.opts.$data&&n&&n.$data;d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ",a="schema"+o):a=n,s+="var division"+o+";if (",d&&(s+=" "+a+" !== undefined && ( typeof "+a+" != 'number' || "),s+=" (division"+o+" = "+c+" / "+a+", ",s+=e.opts.multipleOfPrecision?" Math.abs(Math.round(division"+o+") - division"+o+") > 1e-"+e.opts.multipleOfPrecision+" ":" division"+o+" !== parseInt(division"+o+") ",s+=" ) ",d&&(s+=" ) "),s+=" ) { ";var f=f||[];f.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { multipleOf: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should be multiple of ",s+=d?"' + "+a:a+"'"),e.opts.verbose&&(s+=" , schema: ",s+=d?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var p=s;return s=f.pop(),s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",s+="} ",u&&(s+=" else { "),s}},{}],27:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="errs__"+s,d=e.util.copy(e);d.level++;var f="valid"+d.level;if(e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=n,d.errSchemaPath=l,a+=" var "+c+" = errors; ";var p=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var m;d.opts.allErrors&&(m=d.opts.allErrors,d.opts.allErrors=!1),a+=" "+e.validate(d)+" ",d.createErrors=!0,m&&(d.opts.allErrors=m),e.compositeRule=d.compositeRule=p,a+=" if ("+f+") { ";var v=v||[];v.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var y=a;a=v.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+y+"]); ":" validate.errors = ["+y+"]; return false; ":" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { errors = "+c+"; if (vErrors !== null) { if ("+c+") vErrors.length = "+c+"; else vErrors = null; } ",e.opts.allErrors&&(a+=" } ")}else a+=" var err = ",!1!==e.createErrors?(a+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should NOT be valid' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",h&&(a+=" if (false) { ");return a}},{}],28:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="valid"+s,d="errs__"+s,f=e.util.copy(e),p="";f.level++;var m="valid"+f.level;a+="var "+d+" = errors;var prevValid"+s+" = false;var "+c+" = false;";var v=f.baseId,y=e.compositeRule;e.compositeRule=f.compositeRule=!0;var g=i;if(g)for(var P,E=-1,w=g.length-1;E5)a+=" || validate.schema"+n+"["+v+"] ";else{var L=w;if(L)for(var z=-1,C=L.length-1;z= "+me+"; ",l=e.errSchemaPath+"/patternGroups/minimum",a+=" if (!"+c+") { ";(Ee=Ee||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'patternGroups' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { reason: '"+ge+"', limit: "+ye+", pattern: '"+e.util.escapeQuotes(he)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have "+Pe+" than "+ye+' properties matching pattern "'+e.util.escapeQuotes(he)+"\"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";we=a;a=Ee.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+we+"]); ":" validate.errors = ["+we+"]; return false; ":" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } ",void 0!==ve&&(a+=" else ")}if(void 0!==ve){var ye=ve,ge="maximum",Pe="more";a+=" "+c+" = pgPropCount"+s+" <= "+ve+"; ",l=e.errSchemaPath+"/patternGroups/maximum",a+=" if (!"+c+") { ";var Ee=Ee||[];Ee.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'patternGroups' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { reason: '"+ge+"', limit: "+ye+", pattern: '"+e.util.escapeQuotes(he)+"' } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have "+Pe+" than "+ye+' properties matching pattern "'+e.util.escapeQuotes(he)+"\"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var we=a;a=Ee.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+we+"]); ":" validate.errors = ["+we+"]; return false; ":" var err = "+we+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } "}l=te,h&&(a+=" if ("+c+") { ",p+="}")}}}}return h&&(a+=" "+p+" if ("+d+" == errors) {"),a=e.util.cleanUpCode(a)}},{}],31:[function(e,r,t){"use strict";r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,h=!e.opts.allErrors,u="data"+(o||""),c="errs__"+s,d=e.util.copy(e);d.level++;var f="valid"+d.level;if(e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=n,d.errSchemaPath=l;var p="key"+s,m="idx"+s,v="i"+s,y="' + "+p+" + '",g="data"+(d.dataLevel=e.dataLevel+1),P="dataProperties"+s,E=e.opts.ownProperties,w=e.baseId;a+=" var "+c+" = errors; ",E&&(a+=" var "+P+" = undefined; "),a+=E?" "+P+" = "+P+" || Object.keys("+u+"); for (var "+m+"=0; "+m+"<"+P+".length; "+m+"++) { var "+p+" = "+P+"["+m+"]; ":" for (var "+p+" in "+u+") { ",a+=" var startErrs"+s+" = errors; ";var b=p,S=e.compositeRule;e.compositeRule=d.compositeRule=!0;var j=e.validate(d);d.baseId=w,e.util.varOccurences(j,g)<2?a+=" "+e.util.varReplace(j,g,b)+" ":a+=" var "+g+" = "+b+"; "+j+" ",e.compositeRule=d.compositeRule=S,a+=" if (!"+f+") { for (var "+v+"=startErrs"+s+"; "+v+"=e.opts.loopRequired,b=e.opts.ownProperties;if(h)if(a+=" var missing"+s+"; ",w){d||(a+=" var "+f+" = validate.schema"+n+"; ");R="' + "+($="schema"+s+"["+(j="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),a+=" var "+c+" = true; ",d&&(a+=" if (schema"+s+" === undefined) "+c+" = true; else if (!Array.isArray(schema"+s+")) "+c+" = false; else {"),a+=" for (var "+j+" = 0; "+j+" < "+f+".length; "+j+"++) { "+c+" = "+u+"["+f+"["+j+"]] !== undefined ",b&&(a+=" && Object.prototype.hasOwnProperty.call("+u+", "+f+"["+j+"]) "),a+="; if (!"+c+") break; } ",d&&(a+=" } "),a+=" if (!"+c+") { ";(x=x||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";F=a;a=x.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+F+"]); ":" validate.errors = ["+F+"]; return false; ":" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else{a+=" if ( ";var S=p;if(S)for(var j=-1,_=S.length-1;j<_;){D=S[j+=1],j&&(a+=" || ");a+=" ( ( "+(q=u+(k=e.util.getProperty(D)))+" === undefined ",b&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", '"+e.util.escapeQuotes(D)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?D:k)+") ) "}a+=") { ";R="' + "+($="missing"+s)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,$,!0):E+" + "+$);var x=x||[];x.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ";var F=a;a=x.pop(),a+=!e.compositeRule&&h?e.async?" throw new ValidationError(["+F+"]); ":" validate.errors = ["+F+"]; return false; ":" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",a+=" } else { "}else if(w){d||(a+=" var "+f+" = validate.schema"+n+"; ");var $="schema"+s+"["+(j="i"+s)+"]",R="' + "+$+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,$,e.opts.jsonPointers)),d&&(a+=" if ("+f+" && !Array.isArray("+f+")) { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+f+" !== undefined) { "),a+=" for (var "+j+" = 0; "+j+" < "+f+".length; "+j+"++) { if ("+u+"["+f+"["+j+"]] === undefined ",b&&(a+=" || ! Object.prototype.hasOwnProperty.call("+u+", "+f+"["+j+"]) "),a+=") { var err = ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+R+"' } ",!1!==e.opts.messages&&(a+=" , message: '",a+=e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+R+"\\'",a+="' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",a+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(a+=" } ")}else{var O=p;if(O)for(var D,I=-1,A=O.length-1;I 1) { var i = "+c+".length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal("+c+"[i], "+c+"[j])) { "+d+" = false; break outer; } } } } ",f&&(s+=" } "),s+=" if (!"+d+") { ";var p=p||[];p.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s+=" , schema: ",s+=f?"validate.schema"+l:""+n,s+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),s+=" } "):s+=" {} ";var m=s;s=p.pop(),s+=!e.compositeRule&&u?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+=" } ",u&&(s+=" else { ")}else u&&(s+=" if (true) { ");return s}},{}],35:[function(e,r,t){"use strict";r.exports=function(e,r,t){function a(e){for(var r=e.rules,t=0;t2&&(r=n.call(arguments,1)),t(r)})})}.call(this,e):Array.isArray(e)?function(e){return Promise.all(e.map(s,this))}.call(this,e):function(e){return Object==e.constructor}(e)?function(e){for(var r=new e.constructor,t=Object.keys(e),a=[],i=0;i1&&(a=t[0]+"@",e=t[1]);return a+o((e=e.replace(O,".")).split("."),r).join(".")}function n(e){for(var r,t,a=[],s=0,o=e.length;s=55296&&r<=56319&&s65535&&(r+=k((e-=65536)>>>10&1023|55296),e=56320|1023&e),r+=k(e)}).join("")}function h(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:E}function u(e,r){return e+22+75*(e<26)-((0!=r)<<5)}function c(e,r,t){var a=0;for(e=t?A(e/j):e>>1,e+=A(e/r);e>I*b>>1;a+=E)e=A(e/I);return A(a+(I+1)*e/(e+S))}function d(e){var r,t,a,o,i,n,u,d,f,p,m=[],v=e.length,y=0,g=x,S=_;for((t=e.lastIndexOf(F))<0&&(t=0),a=0;a=128&&s("not-basic"),m.push(e.charCodeAt(a));for(o=t>0?t+1:0;o=v&&s("invalid-input"),((d=h(e.charCodeAt(o++)))>=E||d>A((P-y)/n))&&s("overflow"),y+=d*n,f=u<=S?w:u>=S+b?b:u-S,!(dA(P/(p=E-f))&&s("overflow"),n*=p;S=c(y-i,r=m.length+1,0==i),A(y/r)>P-g&&s("overflow"),g+=A(y/r),y%=r,m.splice(y++,0,g)}return l(m)}function f(e){var r,t,a,o,i,l,h,d,f,p,m,v,y,g,S,j=[];for(v=(e=n(e)).length,r=x,t=0,i=_,l=0;l=r&&mA((P-t)/(y=a+1))&&s("overflow"),t+=(h-r)*y,r=h,l=0;lP&&s("overflow"),m==r){for(d=t,f=E;p=f<=i?w:f>=i+b?b:f-i,!(d= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=E-w,A=Math.floor,k=String.fromCharCode;if(y={version:"1.4.1",ucs2:{decode:n,encode:l},decode:d,encode:f,toASCII:function(e){return i(e,function(e){return R.test(e)?"xn--"+f(e):e})},toUnicode:function(e){return i(e,function(e){return $.test(e)?d(e.slice(4).toLowerCase()):e})}},p&&m)if(r.exports==p)m.exports=y;else for(g in y)y.hasOwnProperty(g)&&(p[g]=y[g]);else a.punycode=y}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],45:[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;var n=/\+/g;e=e.split(r);var l=1e3;o&&"number"==typeof o.maxKeys&&(l=o.maxKeys);var h=e.length;l>0&&h>l&&(h=l);for(var u=0;u=0?(c=m.substr(0,v),d=m.substr(v+1)):(c=m,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),a(i,f)?s(i[f])?i[f].push(p):i[f]=[i[f],p]:i[f]=p}return i};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],46:[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"]),c=["'"].concat(u),d=["%","/","?",";","#"].concat(c),f=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},P=e("querystring");a.prototype.parse=function(e,r,t){if(!i.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(p)){var L=O.slice(0,_),z=O.slice(_+1),C=I.match(m);C&&(L.push(C[1]),z.unshift(C[2])),z.length&&(u="/"+z.join(".")+u),this.hostname=L.join(".");break}}}this.hostname=this.hostname.length>255?"":this.hostname.toLowerCase(),R||(this.hostname=o.toASCII(this.hostname));T=this.port?":"+this.port:"";this.host=(this.hostname||"")+T,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==u[0]&&(u="/"+u))}if(!v[b])for(var _=0,D=c.length;_0)&&t.host.split("@"))&&(t.auth=$.shift(),t.host=t.hostname=$.shift())}return t.search=e.search,t.query=e.query,i.isNull(t.pathname)&&i.isNull(t.search)||(t.path=(t.pathname?t.pathname:"")+(t.search?t.search:"")),t.href=t.format(),t}if(!E.length)return t.pathname=null,t.path=t.search?"/"+t.search:null,t.href=t.format(),t;for(var S=E.slice(-1)[0],j=(t.host||e.host||E.length>1)&&("."===S||".."===S)||""===S,_=0,x=E.length;x>=0;x--)"."===(S=E[x])?E.splice(x,1):".."===S?(E.splice(x,1),_++):_&&(E.splice(x,1),_--);if(!v&&!P)for(;_--;_)E.unshift("..");!v||""===E[0]||E[0]&&"/"===E[0].charAt(0)||E.unshift(""),j&&"/"!==E.join("/").substr(-1)&&E.push("");var F=""===E[0]||E[0]&&"/"===E[0].charAt(0);if(b){t.hostname=t.host=F?"":E.length?E.shift():"";var $=!!(t.host&&t.host.indexOf("@")>0)&&t.host.split("@");$&&(t.auth=$.shift(),t.host=t.hostname=$.shift())}return(v=v||t.host&&E.length)&&!F&&E.unshift(""),E.length?t.pathname=E.join("/"):(t.pathname=null,t.path=null),i.isNull(t.pathname)&&i.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=l.exec(e);r&&(":"!==(r=r[0])&&(this.port=r.substr(1)),e=e.substr(0,e.length-r.length)),e&&(this.hostname=e)}},{"./util":49,punycode:44,querystring:47}],49:[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(r){if(!(this instanceof a))return new a(r);r=this._opts=E.copy(r)||{},function(e){var r=e._opts.logger;if(!1===r)e.logger={log:u,warn:u,error:u};else{if(void 0===r&&(r=console),!("object"==typeof r&&r.log&&r.warn&&r.error))throw new Error("logger must implement log, warn and error methods");e.logger=r}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=v(r.format);var t=this._schemaUriFormat=this._formats["uri-reference"];this._schemaUriFormatFunc=function(e){return t.test(e)},this._cache=r.cache||new f,this._loadingSchemas={},this._compilations=[],this.RULES=y(),this._getId=function(e){switch(e.schemaId){case"$id":return n;case"id":return i;default:return l}}(r),r.loopRequired=r.loopRequired||1/0,"property"==r.errorDataPath&&(r._errorDataPathProperty=!0),void 0===r.serialize&&(r.serialize=m),this._metaOpts=function(e){for(var r=E.copy(e._opts),t=0;t<_.length;t++)delete r[_[t]];return r}(this),r.formats&&function(e){for(var r in e._opts.formats){e.addFormat(r,e._opts.formats[r])}}(this),function(r){var t;r._opts.$data&&(t=e("./refs/$data.json"),r.addMetaSchema(t,t.$id,!0));if(!1===r._opts.meta)return;var a=e("./refs/json-schema-draft-06.json");r._opts.$data&&(a=g(a,x));r.addMetaSchema(a,j,!0),r._refs["http://json-schema.org/schema"]=j}(this),"object"==typeof r.meta&&this.addMetaSchema(r.meta),function(e){var r=e._opts.schemas;if(!r)return;if(Array.isArray(r))e.addSchema(r);else for(var t in r)e.addSchema(r[t],t)}(this),r.patternGroups&&P(this)}function s(e,r){return r=d.normalizeId(r),e._schemas[r]||e._refs[r]||e._fragments[r]}function o(e,r,t){for(var a in r){var s=r[a];s.meta||t&&!t.test(a)||(e._cache.del(s.cacheKey),delete r[a])}}function i(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function n(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function l(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function h(e,r){if(e._schemas[r]||e._refs[r])throw new Error('schema with key or id "'+r+'" already exists')}function u(){}var c=e("./compile"),d=e("./compile/resolve"),f=e("./cache"),p=e("./compile/schema_obj"),m=e("fast-json-stable-stringify"),v=e("./compile/formats"),y=e("./compile/rules"),g=e("./$data"),P=e("./patternGroups"),E=e("./compile/util"),w=e("co");r.exports=a,a.prototype.validate=function(e,r){var t;if("string"==typeof e){if(!(t=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var a=this._addSchema(e);t=a.validate||this._compile(a)}var s=t(r);return!0===t.$async?"*"==this._opts.async?w(s):s:(this.errors=t.errors,s)},a.prototype.compile=function(e,r){var t=this._addSchema(e,void 0,r);return t.validate||this._compile(t)},a.prototype.addSchema=function(e,r,t,a){if(!Array.isArray(e)){var s=this._getId(e);if(void 0!==s&&"string"!=typeof s)throw new Error("schema id must be string");return r=d.normalizeId(r||s),h(this,r),this._schemas[r]=this._addSchema(e,t,a,!0),this}for(var o=0;o=t}function i(e,t,n){var r=t.input.slice(t.start);return n&&(r=r.replace(l,"$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}var o={},a=/^async[\t ]+(return|throw)/,u=/^async[\t ]+function/,c=/^\s*[():;]/,l=/([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g,p=/\s*(get|set)\s*\(/;t.exports=function(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(u,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(u,this,!0)){var c=this.inAsyncFunction;try{return this.inAsyncFunction=!0,this.next(),(l=this.parseStatement(n,r)).async=!0,l.start=s,l.loc&&(l.loc.start=o),l.range&&(l.range[0]=s),l}finally{this.inAsyncFunction=c}}else if("object"==typeof t&&t.asyncExits&&i(a,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 a,u=this.start,l=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 a=this.parseExprSubscripts(),h.operator="await",h.argument=a,h=this.finishNodeAt(h,"AwaitExpression",a.end,a.loc&&a.loc.end),n(h),h;if(this.input.slice(p.end).match(c))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,(a=s(this,u-4).parseExprSubscripts()).end<=u))return a=s(this,u).parseExprSubscripts(),h.operator="await",h.argument=a,h=this.finishNodeAt(h,"AwaitExpression",a.end,a.loc&&a.loc.end),this.pos=a.end,this.end=a.end,this.endLoc=a.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:o}}};if("SequenceExpression"===(a=s(this,this.start,m,!0).parseExpression()).type&&(a=a.expressions[0]),"CallExpression"===a.type&&(a=a.callee),"FunctionExpression"===a.type||"FunctionDeclaration"===a.type||"ArrowFunctionExpression"===a.type)return"SequenceExpression"===(a=s(this,this.start,m).parseExpression()).type&&(a=a.expressions[0]),"CallExpression"===a.type&&(a=a.callee),a.async=!0,a.start=u,a.loc&&(a.loc.start=l),a.range&&(a.range[0]=u),this.pos=a.end,this.end=a.end,this.endLoc=a.endLoc,this.next(),n(a),a}catch(e){if(e!==o)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){t.key&&t.key.name;var i=e.apply(this,arguments);return"Identifier"!==i.type||"async"!==i.name||r(this,i.end)||this.input.slice(i.end).match(c)||(p.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"),"Identifier"===(i=e.apply(this,arguments)).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}})}},{}],3:[function(e,t,n){function r(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}var i=/^async[\t ]+(return|throw)/,s=/^\s*[):;]/,o=/([^\n])\/\*(\*(?!\/)|[^\n*])*\*\/([^\n])/g;t.exports=function(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,a=this.startLoc;if("name"===this.type.label&&t.asyncExits&&function(e,t,n){var r=t.input.slice(t.start);return n&&(r=r.replace(o,"$1 $3")),e.test(r)}(i,this)){this.next();var u=this.parseStatement(n,r);return u.async=!0,u.start=s,u.loc&&(u.loc.start=a),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(i){var s,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((s=r(this,o-4,c).parseExprSubscripts()).end<=o)return s=r(this,o,c).parseExprSubscripts(),u.argument=s,u=this.finishNodeAt(u,"AwaitExpression",s.end,s.loc&&s.loc.end),this.pos=s.end,this.end=s.end,this.endLoc=s.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 r=t.key&&t.key.name,i=e.apply(this,arguments);return"get"===this.value&&(t.__maybeStaticAsyncGetter=!0),n[this.value]?i:("Identifier"!==i.type||"async"!==i.name&&"async"!==r||function(e,t){return e.lineStart>=t}(this,i.end)||this.input.slice(i.end).match(s)?delete t.__maybeStaticAsyncGetter:"set"===t.kind||"set"===i.name?this.raise(i.start,"'set (value)' cannot be be async"):(this.__isAsyncProp=!0,"Identifier"===(i=e.apply(this,arguments)).type&&"set"===i.name&&this.raise(i.start,"'set (value)' cannot be be async")),i)}}),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}})}},{}],4:[function(e,t,n){!function(e,r){"object"==typeof n&&void 0!==t?r(n):"function"==typeof define&&define.amd?define(["exports"],r):r(e.acorn=e.acorn||{})}(this,function(e){"use strict";function t(e,t){for(var n=65536,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&&x.test(String.fromCharCode(e)):!1!==n&&t(e,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&&w.test(String.fromCharCode(e)):!1!==n&&(t(e,E)||t(e,S)))))}function i(e,t){return new k(e,{beforeExpr:!0,binop:t})}function s(e,t){return void 0===t&&(t={}),t.keyword=e,_[e]=new k(e,t)}function o(e){return 10===e||13===e||8232===e||8233===e}function a(e,t){return $.call(e,t)}function u(e,t){for(var n=1,r=0;;){T.lastIndex=r;var i=T.exec(e);if(!(i&&i.index=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),R(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}return R(t.onComment)&&(t.onComment=function(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 j(this,o,a)),e.ranges&&(u.range=[i,s]),t.push(u)}}(t,t.onComment)),t}function l(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}function p(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=-1}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)))}var y={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"},m="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",g={5:m,6:m+" const class extends export import super"},v="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",b="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",x=new RegExp("["+v+"]"),w=new RegExp("["+v+b+"]");v=b=null;var E=[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],S=[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],k=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},A={beforeExpr:!0},C={startsExpr:!0},_={},L={num:new k("num",C),regexp:new k("regexp",C),string:new k("string",C),name:new k("name",C),eof:new k("eof"),bracketL:new k("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new k("]"),braceL:new k("{",{beforeExpr:!0,startsExpr:!0}),braceR:new k("}"),parenL:new k("(",{beforeExpr:!0,startsExpr:!0}),parenR:new k(")"),comma:new k(",",A),semi:new k(";",A),colon:new k(":",A),dot:new k("."),question:new k("?",A),arrow:new k("=>",A),template:new k("template"),invalidTemplate:new k("invalidTemplate"),ellipsis:new k("...",A),backQuote:new k("`",C),dollarBraceL:new k("${",{beforeExpr:!0,startsExpr:!0}),eq:new k("=",{beforeExpr:!0,isAssign:!0}),assign:new k("_=",{beforeExpr:!0,isAssign:!0}),incDec:new k("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new k("!/~",{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 k("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:i("%",10),star:i("*",10),slash:i("/",10),starstar:new k("**",{beforeExpr:!0}),_break:s("break"),_case:s("case",A),_catch:s("catch"),_continue:s("continue"),_debugger:s("debugger"),_default:s("default",A),_do:s("do",{isLoop:!0,beforeExpr:!0}),_else:s("else",A),_finally:s("finally"),_for:s("for",{isLoop:!0}),_function:s("function",C),_if:s("if"),_return:s("return",A),_switch:s("switch"),_throw:s("throw",A),_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",C),_super:s("super",C),_class:s("class",C),_extends:s("extends",A),_export:s("export"),_import:s("import"),_null:s("null",C),_true:s("true",C),_false:s("false",C),_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})},O=/\r\n?|\n|\u2028|\u2029/,T=new RegExp(O.source,"g"),N=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,P=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,F=Object.prototype,$=F.hasOwnProperty,B=F.toString,R=Array.isArray||function(e){return"[object Array]"===B.call(e)},I=function(e,t){this.line=e,this.column=t};I.prototype.offset=function(e){return new I(this.line,this.column+e)};var j=function(e,t,n){this.start=t,this.end=n,null!==e.sourceFile&&(this.source=e.sourceFile)},D={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:{}},M={},q=function(e,t,n){this.options=e=c(e),this.sourceFile=e.sourceFile,this.keywords=l(g[e.ecmaVersion>=6?6:5]);var r="";if(!e.allowReserved){for(var i=e.ecmaVersion;!(r=y[i]);i--);"module"==e.sourceType&&(r+=" await")}this.reservedWords=l(r);var s=(r?r+" ":"")+y.strict;this.reservedWordsStrict=l(s),this.reservedWordsStrictBind=l(s+" "+y.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(O).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=L.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()};q.prototype.isKeyword=function(e){return this.keywords.test(e)},q.prototype.isReservedWord=function(e){return this.reservedWords.test(e)},q.prototype.extend=function(e,t){this[e]=t(this[e])},q.prototype.loadPlugins=function(e){for(var t in e){var n=M[t];if(!n)throw new Error("Plugin '"+t+"' not found");n(this,e[t])}},q.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)};var V=q.prototype,U=/^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;V.strictDirective=function(e){for(;;){P.lastIndex=e,e+=P.exec(this.input)[0].length;var t=U.exec(this.input.slice(e));if(!t)return!1;if("use strict"==(t[1]||t[2]))return!0;e+=t[0].length}},V.eat=function(e){return this.type===e&&(this.next(),!0)},V.isContextual=function(e){return this.type===L.name&&this.value===e},V.eatContextual=function(e){return this.value===e&&this.eat(L.name)},V.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},V.canInsertSemicolon=function(){return this.type===L.eof||this.type===L.braceR||O.test(this.input.slice(this.lastTokEnd,this.start))},V.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},V.semicolon=function(){this.eat(L.semi)||this.insertSemicolon()||this.unexpected()},V.afterTrailingComma=function(e,t){if(this.type==e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},V.expect=function(e){this.eat(e)||this.unexpected()},V.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")},V.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")}},V.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")},V.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos=6&&(e.sourceType=this.options.sourceType),this.finishNode(e,"Program")};var W={kind:"loop"},G={kind:"switch"};z.isLet=function(){if(this.type!==L.name||this.options.ecmaVersion<6||"let"!=this.value)return!1;P.lastIndex=this.pos;var e=P.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},z.isAsyncFunction=function(){if(this.type!==L.name||this.options.ecmaVersion<8||"async"!=this.value)return!1;P.lastIndex=this.pos;var e=P.exec(this.input),t=this.pos+e[0].length;return!(O.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)))},z.parseStatement=function(e,t,n){var r,i=this.type,s=this.startNode();switch(this.isLet()&&(i=L._var,r="let"),i){case L._break:case L._continue:return this.parseBreakContinueStatement(s,i.keyword);case L._debugger:return this.parseDebuggerStatement(s);case L._do:return this.parseDoStatement(s);case L._for:return this.parseForStatement(s);case L._function:return!e&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(s,!1);case L._class:return e||this.unexpected(),this.parseClass(s,!0);case L._if:return this.parseIfStatement(s);case L._return:return this.parseReturnStatement(s);case L._switch:return this.parseSwitchStatement(s);case L._throw:return this.parseThrowStatement(s);case L._try:return this.parseTryStatement(s);case L._const:case L._var:return r=r||this.value,e||"var"==r||this.unexpected(),this.parseVarStatement(s,r);case L._while:return this.parseWhileStatement(s);case L._with:return this.parseWithStatement(s);case L.braceL:return this.parseBlock();case L.semi:return this.parseEmptyStatement(s);case L._export:case L._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===L._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===L.name&&"Identifier"===a.type&&this.eat(L.colon)?this.parseLabeledStatement(s,o,a):this.parseExpressionStatement(s,a)}},z.parseBreakContinueStatement=function(e,t){var n="break"==t;this.next(),this.eat(L.semi)||this.insertSemicolon()?e.label=null:this.type!==L.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(L.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},z.parseForStatement=function(e){if(this.next(),this.labels.push(W),this.enterLexicalScope(),this.expect(L.parenL),this.type===L.semi)return this.parseFor(e,null);var t=this.isLet();if(this.type===L._var||this.type===L._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===L._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 p,s=this.parseExpression(!0,i);return this.type===L._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))},z.parseFunctionStatement=function(e,t){return this.next(),this.parseFunction(e,!0,!1,t)},z.isFunction=function(){return this.type===L._function||this.isAsyncFunction()},z.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(!this.strict&&this.isFunction()),e.alternate=this.eat(L._else)?this.parseStatement(!this.strict&&this.isFunction()):null,this.finishNode(e,"IfStatement")},z.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(L.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},z.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(L.braceL),this.labels.push(G),this.enterLexicalScope();for(var t,n=!1;this.type!=L.braceR;)if(this.type===L._case||this.type===L._default){var r=this.type===L._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),n=!0,t.test=null),this.expect(L.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(!0));return this.exitLexicalScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},z.parseThrowStatement=function(e){return this.next(),O.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 J=[];z.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===L._catch){var t=this.startNode();this.next(),this.expect(L.parenL),t.param=this.parseBindingAtom(),this.enterLexicalScope(),this.checkLVal(t.param,"let"),this.expect(L.parenR),t.body=this.parseBlock(!1),this.exitLexicalScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(L._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},z.parseVarStatement=function(e,t){return this.next(),this.parseVar(e,!1,t),this.semicolon(),this.finishNode(e,"VariableDeclaration")},z.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(W),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"WhileStatement")},z.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")},z.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},z.parseLabeledStatement=function(e,t,n){for(var r=0,i=this.labels;r=0;o--){var a=this.labels[o];if(a.statementStart!=e.start)break;a.statementStart=this.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")},z.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},z.parseBlock=function(e){void 0===e&&(e=!0);var t=this.startNode();for(t.body=[],this.expect(L.braceL),e&&this.enterLexicalScope();!this.eat(L.braceR);){var n=this.parseStatement(!0);t.body.push(n)}return e&&this.exitLexicalScope(),this.finishNode(t,"BlockStatement")},z.parseFor=function(e,t){return e.init=t,this.expect(L.semi),e.test=this.type===L.semi?null:this.parseExpression(),this.expect(L.semi),e.update=this.type===L.parenR?null:this.parseExpression(),this.expect(L.parenR),this.exitLexicalScope(),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,"ForStatement")},z.parseForIn=function(e,t){var n=this.type===L._in?"ForInStatement":"ForOfStatement";return this.next(),e.left=t,e.right=this.parseExpression(),this.expect(L.parenR),this.exitLexicalScope(),e.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(e,n)},z.parseVar=function(e,t,n){for(e.declarations=[],e.kind=n;;){var r=this.startNode();if(this.parseVarId(r,n),this.eat(L.eq)?r.init=this.parseMaybeAssign(t):"const"!==n||this.type===L._in||this.options.ecmaVersion>=6&&this.isContextual("of")?"Identifier"==r.id.type||t&&(this.type===L._in||this.isContextual("of"))?r.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(r,"VariableDeclarator")),!this.eat(L.comma))break}return e},z.parseVarId=function(e,t){e.id=this.parseBindingAtom(t),this.checkLVal(e.id,t,!1)},z.parseFunction=function(e,t,n,r){this.initFunction(e),this.options.ecmaVersion>=6&&!r&&(e.generator=this.eat(L.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&&(e.id="nullableID"===t&&this.type!=L.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==L.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")},z.parseFunctionParams=function(e){this.expect(L.parenL),e.params=this.parseBindingList(L.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},z.parseClass=function(e,t){this.next(),this.parseClassId(e,t),this.parseClassSuper(e);var n=this.startNode(),r=!1;for(n.body=[],this.expect(L.braceL);!this.eat(L.braceR);)if(!this.eat(L.semi)){var i=this.startNode(),s=this.eat(L.star),o=!1,a=this.type===L.name&&"static"===this.value;this.parsePropertyName(i),i.static=a&&this.type!==L.parenL,i.static&&(s&&this.unexpected(),s=this.eat(L.star),this.parsePropertyName(i)),this.options.ecmaVersion>=8&&!s&&!i.computed&&"Identifier"===i.key.type&&"async"===i.key.name&&this.type!==L.parenL&&!this.canInsertSemicolon()&&(o=!0,this.parsePropertyName(i)),i.kind="method";var u=!1;if(!i.computed){var c=i.key;s||o||"Identifier"!==c.type||this.type===L.parenL||"get"!==c.name&&"set"!==c.name||(u=!0,i.kind=c.name,c=this.parsePropertyName(i)),!i.static&&("Identifier"===c.type&&"constructor"===c.name||"Literal"===c.type&&"constructor"===c.value)&&(r&&this.raise(c.start,"Duplicate constructor in the same class"),u&&this.raise(c.start,"Constructor can't have get/set modifier"),s&&this.raise(c.start,"Constructor can't be a generator"),o&&this.raise(c.start,"Constructor can't be an async method"),i.kind="constructor",r=!0)}if(this.parseClassMethod(n,i,s,o),u){var l="get"===i.kind?0:1;if(i.value.params.length!==l){var p=i.value.start;"get"===i.kind?this.raiseRecoverable(p,"getter should have no params"):this.raiseRecoverable(p,"setter should have exactly one param")}else"set"===i.kind&&"RestElement"===i.value.params[0].type&&this.raiseRecoverable(i.value.params[0].start,"Setter cannot use rest params")}}return e.body=this.finishNode(n,"ClassBody"),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},z.parseClassMethod=function(e,t,n,r){t.value=this.parseMethod(n,r),e.body.push(this.finishNode(t,"MethodDefinition"))},z.parseClassId=function(e,t){e.id=this.type===L.name?this.parseIdent():!0===t?this.unexpected():null},z.parseClassSuper=function(e){e.superClass=this.eat(L._extends)?this.parseExprSubscripts():null},z.parseExport=function(e,t){if(this.next(),this.eat(L.star))return this.expectContextual("from"),e.source=this.type===L.string?this.parseExprAtom():this.unexpected(),this.semicolon(),this.finishNode(e,"ExportAllDeclaration");if(this.eat(L._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===L._function||(n=this.isAsyncFunction())){var r=this.startNode();this.next(),n&&this.next(),e.declaration=this.parseFunction(r,"nullableID",!1,n)}else if(this.type===L._class){var i=this.startNode();e.declaration=this.parseClass(i,"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===L.string?this.parseExprAtom():this.unexpected();else{for(var s=0,o=e.specifiers;s=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 n=0,r=e.properties;n=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)"__proto__"===n&&"init"===i&&(t.proto&&this.raiseRecoverable(r.start,"Redefinition of __proto__ property"),t.proto=!0);else{var s=t[n="$"+n];if(s){("init"===i?this.strict&&s.init||s.get||s.set:s.init||s[i])&&this.raiseRecoverable(r.start,"Redefinition of property")}else s=t[n]={init:!1,get:!1,set:!1};s[i]=!0}}},Y.parseExpression=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeAssign(e,t);if(this.type===L.comma){var s=this.startNodeAt(n,r);for(s.expressions=[i];this.eat(L.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(s,"SequenceExpression")}return i},Y.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 p,r=!0);var o=this.start,a=this.startLoc;this.type!=L.parenL&&this.type!=L.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||p.call(t);var c=this.startNodeAt(o,a);return c.operator=this.value,c.left=this.type===L.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},Y.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(L.question)){var s=this.startNodeAt(n,r);return s.test=i,s.consequent=this.parseMaybeAssign(),this.expect(L.colon),s.alternate=this.parseMaybeAssign(e),this.finishNode(s,"ConditionalExpression")}return i},Y.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)},Y.parseExprOp=function(e,t,n,r,i){var s=this.type.binop;if(null!=s&&(!i||this.type!==L._in)&&s>r){var o=this.type===L.logicalOR||this.type===L.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},Y.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")},Y.parseMaybeUnary=function(e,t){var n,r=this.start,i=this.startLoc;if(this.inAsync&&this.isContextual("await"))n=this.parseAwait(),t=!0;else if(this.type.prefix){var s=this.startNode(),o=this.type===L.incDec;s.operator=this.value,s.prefix=!0,this.next(),s.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(e,!0),o?this.checkLVal(s.argument):this.strict&&"delete"===s.operator&&"Identifier"===s.argument.type?this.raiseRecoverable(s.start,"Deleting local variable in strict mode"):t=!0,n=this.finishNode(s,o?"UpdateExpression":"UnaryExpression")}else{if(n=this.parseExprSubscripts(e),this.checkExpressionErrors(e))return n;for(;this.type.postfix&&!this.canInsertSemicolon();){var a=this.startNodeAt(r,i);a.operator=this.value,a.prefix=!1,a.argument=n,this.checkLVal(n),this.next(),n=this.finishNode(a,"UpdateExpression")}}return!t&&this.eat(L.starstar)?this.buildBinary(r,i,n,this.parseMaybeUnary(null,!1),"**",!1):n},Y.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},Y.parseSubscripts=function(e,t,n,r){for(var i=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd==e.end&&!this.canInsertSemicolon(),s=void 0;;)if((s=this.eat(L.bracketL))||this.eat(L.dot)){var o=this.startNodeAt(t,n);o.object=e,o.property=s?this.parseExpression():this.parseIdent(!0),o.computed=!!s,s&&this.expect(L.bracketR),e=this.finishNode(o,"MemberExpression")}else if(!r&&this.eat(L.parenL)){var a=new p,u=this.yieldPos,c=this.awaitPos;this.yieldPos=0,this.awaitPos=0;var l=this.parseExprList(L.parenR,this.options.ecmaVersion>=8,!1,a);if(i&&!this.canInsertSemicolon()&&this.eat(L.arrow))return this.checkPatternErrors(a,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=c,this.parseArrowExpression(this.startNodeAt(t,n),l,!0);this.checkExpressionErrors(a,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=c||this.awaitPos;var h=this.startNodeAt(t,n);h.callee=e,h.arguments=l,e=this.finishNode(h,"CallExpression")}else{if(this.type!==L.backQuote)return e;var f=this.startNodeAt(t,n);f.tag=e,f.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(f,"TaggedTemplateExpression")}},Y.parseExprAtom=function(e){var t,n=this.potentialArrowAt==this.start;switch(this.type){case L._super:return this.inFunction||this.raise(this.start,"'super' outside of function or class"),t=this.startNode(),this.next(),this.type!==L.dot&&this.type!==L.bracketL&&this.type!==L.parenL&&this.unexpected(),this.finishNode(t,"Super");case L._this:return t=this.startNode(),this.next(),this.finishNode(t,"ThisExpression");case L.name:var r=this.start,i=this.startLoc,s=this.parseIdent(this.type!==L.name);if(this.options.ecmaVersion>=8&&"async"===s.name&&!this.canInsertSemicolon()&&this.eat(L._function))return this.parseFunction(this.startNodeAt(r,i),!1,!1,!0);if(n&&!this.canInsertSemicolon()){if(this.eat(L.arrow))return this.parseArrowExpression(this.startNodeAt(r,i),[s],!1);if(this.options.ecmaVersion>=8&&"async"===s.name&&this.type===L.name)return s=this.parseIdent(),!this.canInsertSemicolon()&&this.eat(L.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(r,i),[s],!0)}return s;case L.regexp:var o=this.value;return t=this.parseLiteral(o.value),t.regex={pattern:o.pattern,flags:o.flags},t;case L.num:case L.string:return this.parseLiteral(this.value);case L._null:case L._true:case L._false:return t=this.startNode(),t.value=this.type===L._null?null:this.type===L._true,t.raw=this.type.keyword,this.next(),this.finishNode(t,"Literal");case L.parenL:var a=this.start,u=this.parseParenAndDistinguishExpression(n);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(u)&&(e.parenthesizedAssign=a),e.parenthesizedBind<0&&(e.parenthesizedBind=a)),u;case L.bracketL:return t=this.startNode(),this.next(),t.elements=this.parseExprList(L.bracketR,!0,!0,e),this.finishNode(t,"ArrayExpression");case L.braceL:return this.parseObj(!1,e);case L._function:return t=this.startNode(),this.next(),this.parseFunction(t,!1);case L._class:return this.parseClass(this.startNode(),!1);case L._new:return this.parseNew();case L.backQuote:return this.parseTemplate();default:this.unexpected()}},Y.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")},Y.parseParenExpression=function(){this.expect(L.parenL);var e=this.parseExpression();return this.expect(L.parenR),e},Y.parseParenAndDistinguishExpression=function(e){var t,n=this.start,r=this.startLoc,i=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var s,o,a=this.start,u=this.startLoc,c=[],l=!0,h=!1,f=new p,d=this.yieldPos,y=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==L.parenR;){if(l?l=!1:this.expect(L.comma),i&&this.afterTrailingComma(L.parenR,!0)){h=!0;break}if(this.type===L.ellipsis){s=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===L.comma&&this.raise(this.start,"Comma is not permitted after the rest element");break}this.type!==L.parenL||o||(o=this.start),c.push(this.parseMaybeAssign(!1,f,this.parseParenItem))}var m=this.start,g=this.startLoc;if(this.expect(L.parenR),e&&!this.canInsertSemicolon()&&this.eat(L.arrow))return this.checkPatternErrors(f,!1),this.checkYieldAwaitInDefaultParams(),o&&this.unexpected(o),this.yieldPos=d,this.awaitPos=y,this.parseParenArrowList(n,r,c);c.length&&!h||this.unexpected(this.lastTokStart),s&&this.unexpected(s),this.checkExpressionErrors(f,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=y||this.awaitPos,c.length>1?((t=this.startNodeAt(a,u)).expressions=c,this.finishNodeAt(t,"SequenceExpression",m,g)):t=c[0]}else t=this.parseParenExpression();if(this.options.preserveParens){var v=this.startNodeAt(n,r);return v.expression=t,this.finishNode(v,"ParenthesizedExpression")}return t},Y.parseParenItem=function(e){return e},Y.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var Z=[];Y.parseNew=function(){var e=this.startNode(),t=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(L.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(L.parenL)?e.arguments=this.parseExprList(L.parenR,this.options.ecmaVersion>=8,!1):e.arguments=Z,this.finishNode(e,"NewExpression")},Y.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===L.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),n.value={raw:this.value,cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),n.tail=this.type===L.backQuote,this.finishNode(n,"TemplateElement")},Y.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var n=this.startNode();this.next(),n.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(n.quasis=[r];!r.tail;)this.expect(L.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(L.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(n,"TemplateLiteral")},Y.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===L.name||this.type===L.num||this.type===L.string||this.type===L.bracketL||this.type.keyword)&&!O.test(this.input.slice(this.lastTokEnd,this.start))},Y.parseObj=function(e,t){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(L.braceR);){if(r)r=!1;else if(this.expect(L.comma),this.afterTrailingComma(L.braceR))break;var s=this.parseProperty(e,t);this.checkPropClash(s,i),n.properties.push(s)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")},Y.parseProperty=function(e,t){var n,r,i,s,o=this.startNode();return this.options.ecmaVersion>=6&&(o.method=!1,o.shorthand=!1,(e||t)&&(i=this.start,s=this.startLoc),e||(n=this.eat(L.star))),this.parsePropertyName(o),!e&&this.options.ecmaVersion>=8&&!n&&this.isAsyncProp(o)?(r=!0,this.parsePropertyName(o,t)):r=!1,this.parsePropertyValue(o,e,n,r,i,s,t),this.finishNode(o,"Property")},Y.parsePropertyValue=function(e,t,n,r,i,s,o){if((n||r)&&this.type===L.colon&&this.unexpected(),this.eat(L.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===L.parenL)t&&this.unexpected(),e.kind="init",e.method=!0,e.value=this.parseMethod(n,r);else if(t||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type==L.comma||this.type==L.braceR)this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?(this.checkUnreserved(e.key),e.kind="init",t?e.value=this.parseMaybeDefault(i,s,e.key):this.type===L.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();else{(n||r)&&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")}},Y.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(L.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(L.bracketR),e.key;e.computed=!1}return e.key=this.type===L.num||this.type===L.string?this.parseExprAtom():this.parseIdent(!0)},Y.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=!1,e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},Y.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(L.parenL),n.params=this.parseBindingList(L.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")},Y.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")},Y.parseFunctionBody=function(e,t){var n=t&&this.type!==L.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.adaptDirectivePrologue(e.body.body),this.labels=o}this.exitFunctionScope(),this.strict&&e.id&&this.checkLVal(e.id,"none"),this.strict=r},Y.isSimpleParamList=function(e){for(var t=0,n=e;t0;)t[n]=arguments[n+1];for(var r=0,i=t;r=1;e--){var t=this.context[e];if("function"===t.token)return t.generator}return!1},ie.updateContext=function(e){var t,n=this.type;n.keyword&&e==L.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},L.parenR.updateContext=L.braceR.updateContext=function(){if(1!=this.context.length){var e=this.context.pop();e===re.b_stat&&"function"===this.curContext().token&&(e=this.context.pop()),this.exprAllowed=!e.isExpr}else this.exprAllowed=!0},L.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?re.b_stat:re.b_expr),this.exprAllowed=!0},L.dollarBraceL.updateContext=function(){this.context.push(re.b_tmpl),this.exprAllowed=!0},L.parenL.updateContext=function(e){var t=e===L._if||e===L._for||e===L._with||e===L._while;this.context.push(t?re.p_stat:re.p_expr),this.exprAllowed=!0},L.incDec.updateContext=function(){},L._function.updateContext=L._class.updateContext=function(e){e.beforeExpr&&e!==L.semi&&e!==L._else&&(e!==L.colon&&e!==L.braceL||this.curContext()!==re.b_stat)?this.context.push(re.f_expr):this.context.push(re.f_stat),this.exprAllowed=!1},L.backQuote.updateContext=function(){this.curContext()===re.q_tmpl?this.context.pop():this.context.push(re.q_tmpl),this.exprAllowed=!1},L.star.updateContext=function(e){if(e==L._function){var t=this.context.length-1;this.context[t]===re.f_expr?this.context[t]=re.f_expr_gen:this.context[t]=re.f_gen}this.exprAllowed=!0},L.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 se=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new j(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},oe=q.prototype,ae="object"==typeof Packages&&"[object JavaPackage]"==Object.prototype.toString.call(Packages);oe.next=function(){this.options.onToken&&this.options.onToken(new se(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},oe.getToken=function(){return this.next(),new se(this)},"undefined"!=typeof Symbol&&(oe[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===L.eof,value:t}}}}),oe.curContext=function(){return this.context[this.context.length-1]},oe.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(L.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},oe.readToken=function(e){return n(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},oe.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=57344)return e;return(e<<10)+this.input.charCodeAt(this.pos+1)-56613888},oe.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(-1===n&&this.raise(this.pos-2,"Unterminated comment"),this.pos=n+2,this.options.locations){T.lastIndex=t;for(var r;(r=T.exec(this.input))&&r.index8&&e<14||e>=5760&&N.test(String.fromCharCode(e))))break e;++this.pos}}},oe.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)},oe.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(L.ellipsis)):(++this.pos,this.finishToken(L.dot))},oe.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(L.assign,2):this.finishOp(L.slash,1)},oe.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=42===e?L.star:L.modulo;return this.options.ecmaVersion>=7&&42==e&&42===t&&(++n,r=L.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(L.assign,n+1):this.finishOp(r,n)},oe.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.finishOp(124===e?L.logicalOR:L.logicalAND,2):61===t?this.finishOp(L.assign,2):this.finishOp(124===e?L.bitwiseOR:L.bitwiseAND,1)},oe.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(L.assign,2):this.finishOp(L.bitwiseXOR,1)},oe.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!=t||this.inModule||62!=this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!O.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(L.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(L.assign,2):this.finishOp(L.plusMin,1)},oe.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(L.assign,n+1):this.finishOp(L.bitShift,n)):33!=t||60!=e||this.inModule||45!=this.input.charCodeAt(this.pos+2)||45!=this.input.charCodeAt(this.pos+3)?(61===t&&(n=2),this.finishOp(L.relational,n)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},oe.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(L.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(L.arrow)):this.finishOp(61===e?L.eq:L.prefix,1)},oe.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(L.parenL);case 41:return++this.pos,this.finishToken(L.parenR);case 59:return++this.pos,this.finishToken(L.semi);case 44:return++this.pos,this.finishToken(L.comma);case 91:return++this.pos,this.finishToken(L.bracketL);case 93:return++this.pos,this.finishToken(L.bracketR);case 123:return++this.pos,this.finishToken(L.braceL);case 125:return++this.pos,this.finishToken(L.braceR);case 58:return++this.pos,this.finishToken(L.colon);case 63:return++this.pos,this.finishToken(L.question);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(L.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(L.prefix,1)}this.raise(this.pos,"Unexpected character '"+d(e)+"'")},oe.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)};var ue=!!f("￿","u");oe.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(O.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&&(ue?u="u":(a=(a=a.replace(/\\u\{([0-9a-fA-F]+)\}/g,function(e,t,i){return(t=Number("0x"+t))>1114111&&n.raise(r+i+3,"Code point out of bounds"),"x"})).replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x"),u=u.replace("u","")))}var l=null;return ae||(f(a,u,r,this),l=f(s,o)),this.finishToken(L.regexp,{pattern:s,flags:o,value:l})},oe.readInt=function(e,t){for(var n=this.pos,r=0,i=0,s=null==t?1/0:t;i=97?o-97+10:o>=65?o-65+10:o>=48&&o<=57?o-48:1/0)>=e)break;++this.pos,r=r*e+a}return this.pos===n||null!=t&&this.pos-n!==t?null:r},oe.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(L.num,t)},oe.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||(43!==(s=this.input.charCodeAt(++this.pos))&&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?this.strict?this.raise(t,"Invalid number"):o=/[89]/.test(a)?parseInt(a,10):parseInt(a,8):o=parseInt(a,10),this.finishToken(L.num,o)},oe.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},oe.readString=function(e){for(var t="",n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var r=this.input.charCodeAt(this.pos);if(r===e)break;92===r?(t+=this.input.slice(n,this.pos),t+=this.readEscapedChar(!1),n=this.pos):(o(r)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(L.string,t)};var ce={};oe.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==ce)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},oe.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw ce;this.raise(e,t)},oe.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var n=this.input.charCodeAt(this.pos);if(96===n||36===n&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==L.template&&this.type!==L.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(L.template,e)):36===n?(this.pos+=2,this.finishToken(L.dollarBraceL)):(++this.pos,this.finishToken(L.backQuote));if(92===n)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(o(n)){switch(e+=this.input.slice(t,this.pos),++this.pos,n){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},oe.readInvalidTemplateToken=function(){for(;this.pos=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.invalidStringToken(this.pos-2,"Octal literal in strict mode"),this.pos+=n.length-1,String.fromCharCode(r)}return String.fromCharCode(t)}},oe.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return null===n&&this.invalidStringToken(t,"Bad character escape sequence"),n},oe.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,s=this.options.ecmaVersion>=6;this.pos=s)&&a[c](t,n,e),(null==r||t.start==r)&&(null==s||t.end==s)&&o(c,t))throw new i(t,n)}(n,u)}catch(e){if(e instanceof i)return e;throw e}},e.findNodeAround=function(n,r,s,o,a){s=t(s),o||(o=e.base);try{!function e(t,n,a){var u=a||t.type;if(!(t.start>r||t.end=r&&s(u,t))throw new i(t,n);o[u](t,n,e)}}(n,a)}catch(e){if(e instanceof i)return e;throw e}},e.findNodeBefore=function(n,r,s,o,a){s=t(s),o||(o=e.base);var u;return function e(t,n,a){if(!(t.start>r)){var c=a||t.type;t.end<=r&&(!u||u.node.end0)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 o[e>>18&63]+o[e>>12&63]+o[e>>6&63]+o[63&e]}function s(e,t,n){for(var r,s=[],o=t;o0?c-4:c;var l=0;for(t=0;t>16&255,o[l++]=i>>8&255,o[l++]=255&i;return 2===s?(i=a[e.charCodeAt(t)]<<2|a[e.charCodeAt(t+1)]>>4,o[l++]=255&i):1===s&&(i=a[e.charCodeAt(t)]<<10|a[e.charCodeAt(t+1)]<<4|a[e.charCodeAt(t+2)]>>2,o[l++]=i>>8&255,o[l++]=255&i),o},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i="",a=[],u=0,c=n-r;uc?c:u+16383));return 1===r?(t=e[n-1],i+=o[t>>2],i+=o[t<<4&63],i+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],i+=o[t>>10],i+=o[t>>4&63],i+=o[t<<2&63],i+="="),a.push(i),a.join("")};for(var o=[],a=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,p=c.length;lB)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 a(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 T(e)?function(e,t,n){if(t<0||e.byteLength=B)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+B.toString(16)+" bytes");return 0|e}function l(e,t){if(i.isBuffer(e))return e.length;if(N(e)||T(e))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 _(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(e).length;default:if(r)return _(e).length;t=(""+t).toLowerCase(),r=!0}}function p(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 function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||n>r)&&(n=r);for(var i="",s=t;s2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,P(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:d(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):d(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function d(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;o>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function w(e,t,n){n=Math.min(e.length,n);for(var r=[],i=t;i239?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:128==(192&(u=e[i+1]))&&(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 function(e){var t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);var n="",r=0;for(;rn)throw new RangeError("Trying to access beyond buffer length")}function S(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 k(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 A(e,t,n,r,i){return t=+t,n>>>=0,i||k(e,0,n,4),$.write(e,t,n,r,23,4),n+4}function C(e,t,n,r,i){return t=+t,n>>>=0,i||k(e,0,n,8),$.write(e,t,n,r,52,8),n+8}function _(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 L(e){return F.toByteArray(function(e){if((e=e.trim().replace(I,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function O(e,t,n,r){for(var i=0;i=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function T(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function N(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function P(e){return e!=e}var F=e("base64-js"),$=e("ieee754");n.Buffer=i,n.SlowBuffer=function(e){return+e!=e&&(e=0),i.alloc(+e)},n.INSPECT_MAX_BYTES=50;var B=2147483647;n.kMaxLength=B,(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}}())||"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 function(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)}(e,t,n)},i.allocUnsafe=function(e){return a(e)},i.allocUnsafeSlow=function(e){return a(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 y(this,e,t,n);case"utf8":case"utf-8":return m(this,e,t,n);case"ascii":return g(this,e,t,n);case"latin1":case"binary":return v(this,e,t,n);case"base64":return b(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(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 R=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(e,t,this.length);for(var r=this[e],i=1,s=0;++s>>=0,t>>>=0,n||E(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(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(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(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(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(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(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||E(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(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(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(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(e,4,this.length),$.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),$.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),$.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(e,8,this.length),$.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){S(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){S(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||S(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||S(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||S(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||S(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||S(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);S(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);S(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||S(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||S(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||S(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||S(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||S(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 A(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return A(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return C(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return C(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))*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}},{}],10:[function(e,t,n){(function(n){function r(){}function i(e){this.covers={},this._ident=i.prototype.version+"_"+Math.random(),this.setOptions(e||{})}var s=e("./lib/parser"),o=e("./lib/arboriculture"),a=e("./lib/output");i.prototype.smCache={},i.prototype.setOptions=function(e){return this.log=!1===e.log?r:e.log||this.log,this.options=function(e){var t={};return e.forEach(function(e){if(e&&"object"==typeof e)for(var n in e)t[n]=e[n]}),t}([this.options,e]),delete this.options.log,this},i.prototype.version=e("./package.json").version,i.prototype.isThenable=function(e){return e&&e instanceof Object&&"function"==typeof e.then},i.prototype.compile=function(e,t,n,s){"object"==typeof n&&void 0===s&&(s=n),s=s||{};for(var o in i.initialCodeGenOpts)o in s||(s[o]=i.initialCodeGenOpts[o]);var a=this.parse(e,t,null,s);return this.asynchronize(a,null,s,this.log||r),this.prettyPrint(a,s),a},i.prototype.parse=function(e,t,n,r){"object"==typeof n&&void 0===r&&(r=n);var i={origCode:e.toString(),filename:t};try{return i.ast=s.parse(i.origCode,r&&r.parser),r.babelTree&&s.treeWalker(i.ast,function(e,t,n){"Literal"===e.type?n[0].replace(o.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 a=i.origCode.substr(e.pos-e.loc.column);a=a.split("\n")[0],e.message+=" "+t+" (nodent)\n"+a+"\n"+a.replace(/[\S ]/g,"-").substring(0,e.loc.column)+"^",e.stack=""}throw e}},i.prototype.asynchronize=o.asynchronize,i.prototype.printNode=o.printNode,i.prototype.prettyPrint=function(t,r){var i=t.filename?t.filename.split("/"):["anonymous"],s=i.pop(),o=a(t.ast,r&&r.sourcemap?{map:{startLine:r.mapStartLine||0,file:s+"(original)",sourceMapRoot:i.join("/"),sourceContent:t.origCode}}:null,t.origCode);if(r&&r.sourcemap)try{var u="",c=o.map.toJSON();if(c){var l=e("source-map").SourceMapConsumer;t.sourcemap=c,this.smCache[t.filename]={map:c,smc:new l(c)},u="\n\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+function(e){return(e instanceof n?e:new n(e.toString(),"binary")).toString("base64")}(JSON.stringify(c))+"\n"}t.code=o.code+u}catch(e){t.code=o}else t.code=o;return t},i.prototype.getDefaultCompileOptions=void 0,Object.defineProperty(i.prototype,"Promise",{get:function(){return initOpts.log("Warning: nodent.Promise is deprecated. Use nodent.Thenable instead"),Thenable},enumerable:!1,configurable:!1}),i.initialCodeGenOpts={noRuntime:!1,lazyThenables:!1,es6target:!1,noUseDirective:!1,wrapAwait:null,mapStartLine:0,sourcemap:!0,engine:!1,parser:{sourceType:"script"},$return:"$return",$error:"$error",$arguments:"$args",$asyncspawn:"$asyncspawn",$asyncbind:"$asyncbind",generatedSymbolPrefix:"$",$makeThenable:"$makeThenable"},t.exports=i}).call(this,e("buffer").Buffer)},{"./lib/arboriculture":11,"./lib/output":12,"./lib/parser":13,"./package.json":25,buffer:8,"source-map":24}],11:[function(e,t,n){"use strict";function r(e){if(!e)return"";if(Array.isArray(e))return e.map(r).join("|\n");try{return m(e)}catch(t){return t.message+": "+(e&&e.type)}}function i(e){if(Array.isArray(e))return e.map(function(e){return i(e)});var t={};return Object.keys(e).forEach(function(n){t[n]=e[n]}),t}function s(e,t){e!==t&&(e.__proto__=Object.getPrototypeOf(t),Object.keys(e).forEach(function(t){t in g||delete e[t]}),Object.keys(t).forEach(function(n){n in e||(e[n]=t[n])}))}function o(){}function a(e){return e?(b.node=e,b):{}}function u(e,t,n){if(!e)return null;if(t&&"object"==typeof t){var r=Object.keys(t);return u(e,function(e){return r.every(function(n){return e[n]==t[n]})})}var i,s={};if(Array.isArray(e)){for(var o=0;o0){if(!o)return t(e);delete e.async}return void(!o&&i?t():(e.type="ReturnStatement",e.$mapped=!0,e.argument={type:"CallExpression",callee:k(s,[n]).$error,arguments:[e.argument]}))}return"TryStatement"===e.type?(i++,t(e),void i--):a(e).isFunction?(r++,t(e),void r--):void t(e)}if(r>0){if(!a(e).isAsync)return t(e);delete e.async}return e.$mapped=!0,void(a(e.argument).isUnaryExpression&&"void"===e.argument.operator?e.argument=e.argument.argument:e.argument={type:"CallExpression",callee:k(s,[n]).$return,arguments:e.argument?[e.argument]:[]})},t)}function P(e,t){return Array.isArray(e)?e.map(function(e){return P(e,t)}):(y.treeWalker(e,function(e,t,n){if(t(),"ConditionalExpression"===e.type&&(c(e.alternate)||c(e.consequent))){h(E("condOp"));s(e,_(y.part("if ($0) return $1 ; return $2",[e.test,e.consequent,e.alternate]).body))}},t),e)}function F(e,t){return Array.isArray(e)?e.map(function(e){return F(e,t)}):(y.treeWalker(e,function(e,t,n){if(t(),"LogicalExpression"===e.type&&c(e.right)){var r,i=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"}s(e,_(y.part(r,[i,e.left,e.right]).body))}},t),e)}function $(e,t,n){if("SwitchCase"!==e.type&&a(e).isBlockStatement)for(var r=0;r { $$setMapped: while (q) { if (q.then) "+(1===i?" 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===i?" 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:w,exit:P,idIter:E,idContinuation:A,idStep:S}).expr:y.part("(Function.$0.trampoline(this,$1,$2,$3,$5)($4))",[pe.asyncbind,A,S,P,E,b(1===i)]).expr,o.push({type:"ReturnStatement",argument:N}),o.push({$label:e.$label,type:"FunctionDeclaration",id:E,params:[],body:{type:"BlockStatement",body:d}}),f&&o.push({type:"FunctionDeclaration",id:S,params:[],body:{type:"BlockStatement",body:[f,L]}}),!l||"VariableDeclaration"!==l.type||"let"!==l.kind&&"const"!==l.kind?(o.push(v),t[0].replace(o.map(r))):("const"===l.kind&&(l.kind="let"),t[0].replace([{type:"BlockStatement",body:o.map(r)},r(v)]))}}function G(e){if(!a(e).isFunction)throw new Error("Cannot examine non-Function node types for async exits");return u(e.body,function(e){return"Identifier"===e.type&&(e.name===n.$return||e.name===n.$error)||I(e)&&a(e).isAsync},function(e){return!(a(e).isFunction&&(e.$wasAsync||a(e).isAsync))})}function J(t){return y.treeWalker(t,function(t,r,i){var s=x(t);if(r(),s&&a(s).isAsync){if("set"==t.kind){var o=new SyntaxError(v(s)+"method 'async set' cannot be invoked",e.filename,t.start);throw o.pos=t.start,o.loc=t.loc.start,o}s.async=!1;var u=w(s);G(s)||0!==s.body.body.length&&"ReturnStatement"===s.body.body[s.body.body.length-1].type||s.body.body.push({type:"ReturnStatement"});var c=m(S({type:"FunctionExpression",params:[pe.return,pe.error],body:J(N(s.body,i)),$wasAsync:!0},n),n.promises||n.generators||n.engine?null:b(!n.lazyThenables||0));n.promises?s.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"NewExpression",callee:h("Promise"),arguments:[c]}}]}:s.body={type:"BlockStatement",body:[{type:"ReturnStatement",argument:c}]},u&&D(s.body.body,[he])}})}function H(e){return y.treeWalker(e,function(e,t,r){if(t(),a(e).isAsync&&a(e).isFunction){var i;(i=x(r[0].parent))&&a(i).isAsync&&"get"===r[0].parent.kind&&X(r[0].parent.key),delete e.async;var s=w(e),o=S({type:"FunctionExpression",params:[pe.return,pe.error],$wasAsync:!0},n),u=[{self:o}].concat(r);return a(e.body).isBlockStatement?(G(e)||0!==e.body.body.length&&"ReturnStatement"===e.body.body[e.body.body.length-1].type||e.body.body.push({type:"ReturnStatement"}),o.body={type:"BlockStatement",body:e.body.body.map(function(e){return N(e,u)})}):(o.body={type:"BlockStatement",body:[N({type:"ReturnStatement",argument:e.body},u)]},e.expression=!1),o=m(o,n.promises||n.generators||n.engine?null:b(!n.lazyThenables||0)),n.promises&&(o={type:"NewExpression",callee:h("Promise"),arguments:[o]}),o={type:"BlockStatement",body:[{type:"ReturnStatement",loc:e.loc,argument:o}]},s&&D(o.body,[he]),void(e.body=o)}}),e}function Y(e){if(Array.isArray(e))return e.map(Y);var t=0;return y.treeWalker(e,function(e,n,r){if("ThrowStatement"!==e.type&&"ReturnStatement"!==e.type||e.$mapped){if(a(e).isFunction)return t++,n(e),void t--}else if(t>0&&a(e).isAsync)return delete e.async,e.argument={type:"CallExpression",callee:"ThrowStatement"===e.type?pe.error:pe.return,arguments:e.argument?[e.argument]:[]},void(e.type="ReturnStatement");n(e)})}function Z(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:pe.return,error:pe.error,asyncspawn:pe.asyncspawn,body:Y(e).concat(t?[{type:"ReturnStatement",argument:pe.return}]:[])}).body[0]}function X(e){e.$asyncgetwarninig||(e.$asyncgetwarninig=!0,d(v(e)+"'async get "+r(e)+"(){...}' is non-standard. See https://github.com/MatAtBread/nodent#differences-from-the-es7-specification"))}function Q(e,t){function r(e,t){y.treeWalker(e,function(n,r,i){n!==e&&a(n).isFunction||(a(n).isAwait?t?(n.$hidden=!0,r()):(delete n.operator,n.delegate=!1,n.type="YieldExpression",r()):r())})}function o(e){var t=n.promises;n.promises=!0,A(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,i){n();var l,p,h;if(a(e).isAsync&&a(e).isFunction){var f;(f=x(i[0].parent))&&a(f).isAsync&&"get"===i[0].parent.kind&&X(i[0].parent.key),(p=G(e))?(c(p,e.body),o(e)):t?"get"!==i[0].parent.kind&&r(e,!0):(delete(l=e).async,h=w(l),r(l,!1),(l=u(l)).body=Z(l.body.body,p),h&&D(l.body.body,[he]),l.id&&"ExpressionStatement"===i[0].parent.type?(l.type="FunctionDeclaration",i[1].replace(l)):i[0].replace(l))}else(l=x(e))&&a(l).isAsync&&((p=G(l))?(c(p,l),o(e)):t&&"get"!==e.kind||(t?o(e):(e.async=!1,h=w(l),r(l,!1),s(l,u(l)),l.body=Z(l.body.body,p)),h&&D(l.body.body,[he])))});var l=i(n);return n.engine=!1,n.generators=!1,ie(e),ne(e),j(e,l.engine),F(e),P(e),q(e,[M,W,B,R,$]),V(e,"warn"),n.engine=l.engine,n.generators=l.generators,e}function K(e,t,n){var r=[];return y.treeWalker(e,function(i,s,o){if(i===e)return s();t(i,o)?r.push([].concat(o)):n||a(i).isScope||s()}),r}function ee(e,t){var n=[],r={};if((e=e.filter(function(e){return"ExportNamedDeclaration"!==e[0].parent.type})).length){var s={};e.forEach(function(e){function t(e){e in s?r[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:r}}function te(e){if(!e)return[];if(Array.isArray(e))return e.reduce(function(e,t){return e.concat(te(t.id))},[]);switch(e.type){case"Identifier":return[e.name];case"AssignmentPattern":return te(e.left);case"ArrayPattern":return e.elements.reduce(function(e,t){return e.concat(te(t))},[]);case"ObjectPattern":return e.properties.reduce(function(e,t){return e.concat(te(t))},[]);case"ObjectProperty":case"Property":return te(e.value);case"RestElement":case"RestProperty":return te(e.argument)}}function ne(e){function t(e){return u(e,function(e){return"AssignmentExpression"===e.type})}function n(e){return function(t,n){if("VariableDeclaration"===t.type&&(t.kind=t.kind||"var")&&e.indexOf(t.kind)>=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 o(e,t){return!("FunctionDeclaration"!==e.type||!e.id)&&(a(e).isAsync||!e.$continuation)}var l={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,r){function o(e){h.length&&(e.argument={type:"SequenceExpression",expressions:h.map(function(e){var t=i(e);return s(e,e.left),t}).concat(e.argument)},h=[])}var u;if(n(),e.type in l&&!e.$hoisted){var p=l[e.type](e),h=[];for(u=0;u0;u--)if(e.declarations[u]&&e.declarations[u].init&&c(e.declarations[u].init)){var f={type:"VariableDeclaration",kind:e.kind,declarations:e.declarations.splice(u)},d=r[0];if(!("index"in d))throw new Error("VariableDeclaration not in a block");d.parent[d.field].splice(d.index+1,0,f)}}),function(e){function t(e){d(v(e)+"Possible assignment to 'const "+r(e)+"'")}function n(e){switch(e.type){case"Identifier":"const"===i[e.name]&&t(e);break;case"ArrayPattern":e.elements.forEach(function(e){"const"===i[e.name]&&t(e)});break;case"ObjectPattern":e.properties.forEach(function(e){"const"===i[e.key.name]&&t(e)})}}var i={};y.treeWalker(e,function(e,t,r){var s=a(e).isBlockStatement;if(s){i=Object.create(i);for(var o=0;o=0&&"ReturnStatement"===r[1].self.type){var s=e.$thisCallName,o=i(ce[s].def.body.body);ce[s].$inlined=!0,a(r[1].self).isJump||o.push({type:"ReturnStatement"}),r[1].replace(o)}});var n=Object.keys(ce).map(function(e){return ce[e].$inlined&&ce[e].def});y.treeWalker(e,function(e,t,r){t(),n.indexOf(e)>=0&&r[0].remove()})}if(!("Program"===e.type&&"module"===e.sourceType||u(e,function(e){return a(e).isES6},!0))){var r=oe(e);!function(e){y.treeWalker(e,function(e,t,n){if("Program"===e.type||"FunctionDeclaration"===e.type||"FunctionExpression"===e.type){var i=r;if(r=r||oe(e)){t();var s="Program"===e.type?e:e.body,o=K(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();r=i}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 ce={},le=1,pe={};Object.keys(n).filter(function(e){return"$"===e[0]}).forEach(function(e){pe[e.slice(1)]=h(n[e])});var he=y.part("var $0 = arguments",[pe.arguments]).body[0];return n.engine?(e.ast=re(e.ast,!0),e.ast=Q(e.ast,n.engine),e.ast=se(e.ast),ue(e.ast)):n.generators?(e.ast=re(e.ast),e.ast=Q(e.ast),e.ast=se(e.ast),ue(e.ast)):(e.ast=re(e.ast),A(e.ast)),n.babelTree&&y.treeWalker(e.ast,function(e,t,n){t(),"Literal"===e.type&&s(e,b(e.value))}),e}var y=e("./parser"),m=e("./output"),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:r,babelLiteralNode:p,asynchronize:function(e,t,n,r){try{return d(e,0,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}}}},{"./output":12,"./parser":13}],12:[function(e,t,n){"use strict";function r(e){if("NewExpression"===e.type&&e.arguments&&e.arguments.length)return 19;var t=h[e.type]||h[e.type+e.operator]||h[e.type+e.operator+(e.prefix?"prefix":"")];return void 0!==t?t:20}var i,s,o,a,u,c,l=e("source-map").SourceMapGenerator;if("".repeat)c=function(e,t){return t&&e?e.repeat(t):""};else{var p={};c=function(e,t){if(!t||!e)return"";var n=""+e+t;if(!p[n]){for(var r=[];t--;)r.push(e);p[n]=r.join("")}return p[n]}}var h={ExpressionStatement:-1,Identifier:21,Literal:21,BooleanLiteral:21,RegExpLiteral:21,NumericLiteral:21,StringLiteral:21,NullLiteral:21,ThisExpression:21,SuperExpression:21,ObjectExpression:21,ClassExpression:21,MemberExpression:19,CallExpression:18,NewExpression:18,ArrayExpression:17.5,FunctionExpression:17.5,FunctionDeclaration:17.5,ArrowFunctionExpression:17.5,"UpdateExpression++":17,"UpdateExpression--":17,"UpdateExpression++prefix":16,"UpdateExpression--prefix":16,UnaryExpression:16,AwaitExpression:16,"BinaryExpression**":15,"BinaryExpression*":15,"BinaryExpression/":15,"BinaryExpression%":15,"BinaryExpression+":14,"BinaryExpression-":14,"BinaryExpression<<":13,"BinaryExpression>>":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},f={type:"comma-separated-list"},d={out:function(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))},expr:function(e,t,n,i){2===i||r(n)0)for(var r=n.length,i=0;i0){this.out(e[0],t,e[0].type);for(var r=1,i=e.length;r0){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 s=0;s0)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:s=function(e,t){t.write(e,"..."),this.out(e.argument,t,e.argument.type)},SpreadElement:s,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,f,s),((i+=1)=r)break;t.lineLength()>t.wrapColumn&&t.write(null,t.lineEnd,c(t.indent,t.indentLevel+1))}t.write(null,"]")},ArrayPattern:a,ObjectExpression:function(e,t){var n,r=c(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,c(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,f,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:o=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:o,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.expr(t,e,e.callee,"CallExpression"===e.callee.type||"ObjectExpression"===e.callee.type?2:0),this.argumentList(e,t)},CallExpression:function(e,t){this.expr(t,e,e.callee,"ObjectExpression"===e.callee.type?2:0),this.argumentList(e,t)},MemberExpression:function(e,t){!("ObjectExpression"===e.object.type||e.object.type.match(/Literal$/)&&e.object.raw&&e.object.raw.match(/^[0-9]/))&&("ArrayExpression"===e.object.type||"CallExpression"===e.object.type||"NewExpression"===e.object.type||r(e)<=r(e.object))?this.out(e.object,t,e.object.type):(t.write(null,"("),this.out(e.object,t,e.object.type),t.write(null,")")),e.computed?(t.write(e,"["),this.out(e.property,t,e.property.type),t.write(null,"]")):(t.write(e,"."),this.out(e.property,t,e.property.type))},Identifier:function(e,t){t.write(e,e.name)},Literal:function(e,t){t.write(e,e.raw)},NullLiteral:function(e,t){t.write(e,"null")},BooleanLiteral:function(e,t){t.write(e,JSON.stringify(e.value))},StringLiteral:function(e,t){t.write(e,JSON.stringify(e.value))},RegExpLiteral:function(e,t){t.write(e,e.extra.raw||"/"+e.pattern+"/"+e.flags)},NumericLiteral:function(e,t){t.write(e,JSON.stringify(e.value))}};t.exports=function(e,t,n){var r="",i=[],s=(t=t||{}).map&&new l(t.map);s&&t.map.sourceContent&&s.setSourceContent(t.map.file,t.map.sourceContent);var o="",a=[],u=[],p={inForInit:0,lineLength:function(){return r.length},sourceAt:function(e,t){return n?n.substring(e,t):"/* Omitted Non-standard node */"},write:function(e){o=arguments[arguments.length-1];for(var n=1;n=0&&r({self:i,parent:e,field:u[c],index:!0}):l instanceof Object&&i===l&&r({self:i,parent:e,field:u[c]})}})},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(o.version)<4)&&(c||(parseInt(o.version)<4&&console.warn("Nodent: Warning - noNodentExtensions option requires acorn >=v4.x. Extensions installed."),e("acorn-es7-plugin")(o),c=!0),s.plugins=s.plugins||{},s.plugins.asyncawait={asyncExits:!0,awaitAnywhere:!0}),n)for(var a in n)"noNodentExtensions"!==a&&(s[a]=n[a]);var u=o.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}var o=e("acorn"),a=e("acorn/dist/walk").make({AwaitExpression:function(e,t,n){n(e.argument,t,"Expression")},SwitchStatement:function(e,t,n){n(e.discriminant,t,"Expression");for(var r=0;r=0)return t}else{var n=i.toSetString(e);if(s.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')},r.prototype.at=function(e){if(e>=0&&e>>=5)>0&&(t|=32),n+=r.encode(t)}while(i>0);return n},n.decode=function(e,t,n){var i,s,o=e.length,a=0,u=0;do{if(t>=o)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(s=r.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));i=!!(32&s),a+=(s&=31)<>1;return 1==(1&e)?-t:t}(a),n.rest=t}},{"./base64":16}],16:[function(e,t,n){var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");n.encode=function(e){if(0<=e&&e0?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}},{}],18:[function(e,t,n){function r(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=e("./util");r.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},r.prototype.add=function(e){!function(e,t){var n=e.generatedLine,r=t.generatedLine,s=e.generatedColumn,o=t.generatedColumn;return r>n||r==n&&o>=s||i.compareByGeneratedPositionsInflated(e,t)<=0}(this._last,e)?(this._sorted=!1,this._array.push(e)):(this._last=e,this._array.push(e))},r.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=r},{"./util":23}],19:[function(e,t,n){function r(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function i(e,t,n,s){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)).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};var n={source:t=this._sources.indexOf(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)).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":14,"./base64-vlq":15,"./mapping-list":18,"./util":23}],22:[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[a]=!0,null!=r&&this.add(r)}var i=e("./source-map-generator").SourceMapGenerator,s=e("./util"),o=/(\r?\n)/,a="$$$isSourceNode$$$";r.fromStringWithSourceMap=function(e,t,n){function i(e,t){if(null===e||void 0===e.source)a.add(t);else{var i=n?s.join(n,e.source):e.source;a.add(new r(e.originalLine,e.originalColumn,i,t,e.name))}}var a=new r,u=e.split(o),c=0,l=function(){function e(){return c=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},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])?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=a?"/":"."),s?(s.path=t,i(s)):t}function o(e){return e}function a(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 u(e,t){return e===t?0:e>t?1:-1}n.getArg=function(e,t,n){if(t in e)return e[t];if(3===arguments.length)return n;throw new Error('"'+t+'" is a required argument.')};var c=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,l=/^data:.+\,.+$/;n.urlParse=r,n.urlGenerate=i,n.normalize=s,n.join=function(e,t){""===e&&(e="."),""===t&&(t=".");var n=r(t),o=r(e);if(o&&(e=o.path||"/"),n&&!n.scheme)return o&&(n.scheme=o.scheme),i(n);if(n||t.match(l))return t;if(o&&!o.host&&!o.path)return o.host=t,i(o);var a="/"===t.charAt(0)?t:s(e.replace(/\/+$/,"")+"/"+t);return o?(o.path=a,i(o)):a},n.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(c)},n.relative=function(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)).match(/^([^\/]+:\/)?\/*$/))return t;++n}return Array(n+1).join("../")+t.substr(e.length+1)};var p=!("__proto__"in Object.create(null));n.toSetString=p?o:function(e){return a(e)?"$"+e:e},n.fromSetString=p?o:function(e){return a(e)?e.slice(1):e},n.compareByOriginalPositions=function(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:0!=(r=e.generatedLine-t.generatedLine)?r:e.name-t.name},n.compareByGeneratedPositionsDeflated=function(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:0!=(r=e.originalColumn-t.originalColumn)?r:e.name-t.name},n.compareByGeneratedPositionsInflated=function(e,t){var n=e.generatedLine-t.generatedLine;return 0!==n?n:0!=(n=e.generatedColumn-t.generatedColumn)?n:0!==(n=u(e.source,t.source))?n:0!=(n=e.originalLine-t.originalLine)?n:0!=(n=e.originalColumn-t.originalColumn)?n:u(e.name,t.name)}},{}],24:[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":20,"./lib/source-map-generator":21,"./lib/source-node":22}],25:[function(e,t,n){t.exports={_args:[[{raw:"nodent-compiler@>=3.1.3",scope:null,escapedName:"nodent-compiler",name:"nodent-compiler",rawSpec:">=3.1.3",spec:">=3.1.3",type:"range"},"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/nodent"]],_from:"nodent-compiler@>=3.1.3",_id:"nodent-compiler@3.1.3",_inCache:!0,_location:"/nodent-compiler",_nodeVersion:"8.4.0",_npmOperationalInternal:{host:"s3://npm-registry-packages",tmp:"tmp/nodent-compiler-3.1.3.tgz_1504874988276_0.6329000329133123"},_npmUser:{name:"matatbread",email:"npm@mailed.me.uk"},_npmVersion:"5.3.0",_phantomChildren:{},_requested:{raw:"nodent-compiler@>=3.1.3",scope:null,escapedName:"nodent-compiler",name:"nodent-compiler",rawSpec:">=3.1.3",spec:">=3.1.3",type:"range"},_requiredBy:["/nodent"],_resolved:"https://registry.npmjs.org/nodent-compiler/-/nodent-compiler-3.1.3.tgz",_shasum:"6f0f1f8098db251ec773742bb4f33cd0266434b2",_shrinkwrap:null,_spec:"nodent-compiler@>=3.1.3",_where:"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/nodent",author:{name:"Mat At Bread",email:"nodent@mailed.me.uk"},bugs:{url:"https://github.com/MatAtBread/nodent/issues"},dependencies:{acorn:">=2.5.2","acorn-es7-plugin":">=1.1.6","source-map":"^0.5.6"},description:"NoDent - Asynchronous Javascript language extensions",devDependencies:{},directories:{},dist:{integrity:"sha512-pcUC9gIgXXI3mbGjESZfVZO4Vgarw63xYZFRdkqxCDnygvvpiAwzwvvJ7rWqskp72Nk3cxWZY/rYxUIkPT14lw==",shasum:"6f0f1f8098db251ec773742bb4f33cd0266434b2",tarball:"https://registry.npmjs.org/nodent-compiler/-/nodent-compiler-3.1.3.tgz"},engines:"node >= 0.10.0",gitHead:"d72c5767ca302884c3215e6267d4910239add177",homepage:"https://github.com/MatAtBread/nodent-compiler#readme",keywords:["Javascript","ES7","async","await","language","extensions","Node","callback","generator","Promise","asynchronous"],license:"BSD-2-Clause",main:"compiler.js",maintainers:[{name:"matatbread",email:"npm@mailed.me.uk"}],name:"nodent-compiler",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+https://github.com/MatAtBread/nodent-compiler.git"},scripts:{test:"node tests/basic.js # Please install 'nodent' and test the compiler fully from there."},version:"3.1.3"}},{}],26:[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)).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":27,"./zousan":28}],27:[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(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 s(e){this._resolver=e,this.then=i}return n.prototype={resolve:r,reject:r,then:function(e,t){this.resolve=e,this.reject=t}},s.resolve=function(e){return s.isThenable(e)?e:{then:function(t){return t(e)}}},s.isThenable=e,s}},{}],28:[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;u=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("/"))||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= 8.8",https:!0,_http_server:">= 0.11",_linklist:"< 8",module:!0,net:!0,os:!0,path:!0,perf_hooks:">= 8.5",process:">= 1",punycode:!0,querystring:!0,readline:!0,repl:!0,stream:!0,string_decoder:!0,sys:!0,timers:!0,tls:!0,tty:!0,url:!0,util:!0,v8:">= 1",vm:!0,zlib:!0}},{}],37:[function(e,t,n){(function(n){function r(e){if(!0===e)return!0;for(var t=e.split(" "),n=t[0],r=t[1].split("."),s=0;s<3;++s){var o=Number(i[s]||0),a=Number(r[s]||0);if(o!==a)return"<"===n?o="===n&&o>=a}return!1}var i=n.versions&&n.versions.node&&n.versions.node.split(".")||[],s=e("./core.json"),o={};for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(o[a]=r(s[a]));t.exports=o}).call(this,e("_process"))},{"./core.json":36,_process:32}],38:[function(e,t,n){var r=e("path"),i=e("fs"),s=r.parse||e("path-parse");t.exports=function(e,t){var n=t&&t.moduleDirectory?[].concat(t.moduleDirectory):["node_modules"],o=r.resolve(e);if(t&&!1===t.preserveSymlinks)try{o=i.realpathSync(o)}catch(e){if("ENOENT"!==e.code)throw e}var a="/";/^([A-Za-z]:)/.test(o)?a="":/^\\\\/.test(o)&&(a="\\\\");for(var u=[o],c=s(o);c.dir!==u[u.length-1];)u.push(c.dir),c=s(c.dir);var l=u.reduce(function(e,t){return e.concat(n.map(function(e){return r.join(a,t,e)}))},[]);return t&&t.paths?l.concat(t.paths):l}},{fs:7,path:30,"path-parse":31}],39:[function(e,t,n){var r=e("./core"),i=e("fs"),s=e("path"),o=e("./caller.js"),a=e("./node-modules-paths.js");t.exports=function(e,t){function n(e){if(l(e))return e;for(var t=0;t"))}return Object.keys(hostOptions).forEach(function(k){"host"===parseOpts[k]&&(parseOpts[k]=function(){try{return eval(hostOptions[k]),!0}catch(e){return!1}}())}),parseOpts.promises||parseOpts.es7||parseOpts.generators||parseOpts.engine?((parseOpts.promises||parseOpts.es7)&&parseOpts.generators&&(log("No valid 'use nodent' directive, assumed -es7 mode"),parseOpts=optionSets.es7),(parseOpts.generators||parseOpts.engine)&&(parseOpts.promises=!0),parseOpts.promises&&(parseOpts.es7=!0),parseOpts):null}function stripBOM(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),"#!"===e.substring(0,2)&&(e="//"+e),e}function compileNodentedFile(e,t){return t=t||e.log,function(n,r,i){var s=stripBOM(fs.readFileSync(r,"utf8")),o=e.parse(s,r,i);i=i||parseCompilerOptions(o.ast,t,r),e.asynchronize(o,void 0,i,t),e.prettyPrint(o,i),n._compile(o.code,o.filename)}}function asyncify(e){return e=e||Thenable,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 generateRequestHandler(e,t,n){var r={},i=this;t||(t=/\.njs$/),n?n.compiler||(n.compiler={}):n={compiler:{}};var s=copyObj([NodentCompiler.initialCodeGenOpts,n.compiler]);return function(o,a,u){function c(e){a.statusCode=500,a.write(e.toString()),a.end()}if(r[o.url])return a.setHeader("Content-Type",r[o.url].contentType),n.setHeaders&&n.setHeaders(a),a.write(r[o.url].output),void a.end();if(!(o.url.match(t)||n.htmlScriptRegex&&o.url.match(n.htmlScriptRegex)))return u&&u();var l=e+o.url;if(n.extensions&&!fs.existsSync(l))for(var p=0;p=0?this.covers[n]=require(e):this.covers[n]=require(__dirname+"/covers/"+e)),this.covers[n](this,t)}function prepareMappedStackTrace(e,t){return e+t.map(function(e){var t=e.getFileName();if(t&&NodentCompiler.prototype.smCache[t]){var n=NodentCompiler.prototype.smCache[t].smc.originalPositionFor({line:e.getLineNumber(),column:e.getColumnNumber()});if(n&&n.line){var r=e.toString();return"\n at "+r.substring(0,r.length-1)+" => …"+n.source+":"+n.line+":"+n.column+(e.getFunctionName()?")":"")}}return"\n at "+e}).join("")}function setGlobalEnvironment(e){var t={};t[defaultCodeGenOpts.$asyncbind]={value:$asyncbind,writable:!0,enumerable:!1,configurable:!0},t[defaultCodeGenOpts.$asyncspawn]={value:$asyncspawn,writable:!0,enumerable:!1,configurable:!0};try{Object.defineProperties(Function.prototype,t)}catch(t){e.log("Function prototypes already assigned: ",t.messsage)}defaultCodeGenOpts[defaultCodeGenOpts.$error]in global||(global[defaultCodeGenOpts[defaultCodeGenOpts.$error]]=globalErrorHandler),e.augmentObject&&Object.defineProperties(Object.prototype,{asyncify:{value:function(e,t,n){return asyncify(e)(this,t,n)},writable:!0,configurable:!0},isThenable:{value:function(){return Thenable.isThenable(this)},writable:!0,configurable:!0}}),Object[defaultCodeGenOpts.$makeThenable]=Thenable.resolve}function initialize(e){function t(n,r){if(!r.match(/nodent\/nodent\.js$/)){if(r.match(/node_modules\/nodent\/.*\.js$/))return stdJSLoader(n,r);for(var o=0;ot[n])return 1}return 0}(u.version,NodentCompiler.prototype.version)<0&&(u.originalNodentLoader=n.exports,n.exports=function(){var t=require.extensions[".js"],n=u.originalNodentLoader.apply(this,arguments);return u.jsCompiler=require.extensions[".js"],require.extensions[".js"]=t,setGlobalEnvironment(e),n},Object.keys(u.originalNodentLoader).forEach(function(e){n.exports[e]=u.originalNodentLoader[e]}),i.push(u),i=i.sort(function(e,t){return t.path.length-e.path.length})))}function n(t){if(Array.isArray(t))return t.forEach(n);if(require.extensions[t]){Object.keys(e).filter(function(t){return compiler[t]!=e[t]}).length&&e.log("File extension "+t+" already configured for async/await compilation.")}require.extensions[t]=compileNodentedFile(compiler,e.log)}if(e){for(var r in e)if("use"!==r&&!config.hasOwnProperty(r))throw new Error("NoDent: unknown option: "+r+"="+JSON.stringify(e[r]))}else e={};compiler?compiler.setOptions(e):(Object.keys(config).forEach(function(t){t in e||(e[t]=config[t])}),compiler=new NodentCompiler(e)),e.dontMapStackTraces||(Error.prepareStackTrace=prepareMappedStackTrace),setGlobalEnvironment(e);var i=[];if(!e.dontInstallRequireHook){if(!stdJSLoader){stdJSLoader=require.extensions[".js"];var s=compileNodentedFile(compiler,e.log);require.extensions[".js"]=t}e.extension&&n(e.extension)}return e.use&&(Array.isArray(e.use)?(e.log("Warning: nodent({use:[...]}) is deprecated. Use nodent.require(module,options)\n"+(new Error).stack.split("\n")[2]),e.use.length&&e.use.forEach(function(e){compiler[e]=compiler.require(e)})):(e.log("Warning: nodent({use:{...}}) is deprecated. Use nodent.require(module,options)\n"+(new Error).stack.split("\n")[2]),Object.keys(e.use).forEach(function(t){compiler[t]=compiler.require(t,e.use[t])}))),compiler}function runFromCLI(){function e(e,n){try{var s,o;if(r.fromast){if(e=JSON.parse(e),s={origCode:"",filename:t,ast:e},!(o=parseCompilerOptions(e,i.log))){var a=r.use?'"use nodent-'+r.use+'";':'"use nodent";';o=parseCompilerOptions(a,i.log),console.warn("/* "+t+": No 'use nodent*' directive, assumed "+a+" */")}}else(o=parseCompilerOptions(r.use?'"use nodent-'+r.use+'";':e,i.log))||(o=parseCompilerOptions('"use nodent";',i.log),r.dest||console.warn("/* "+t+": 'use nodent*' directive missing/ignored, assumed 'use nodent;' */")),s=i.parse(e,t,o);if(r.parseast||r.pretty||i.asynchronize(s,void 0,o,i.log),i.prettyPrint(s,o),r.out||r.pretty||r.dest){if(r.dest&&!n)throw new Error("Can't write unknown file to "+r.dest);var u="";r.runtime&&(u+="Function.prototype.$asyncbind = "+Function.prototype.$asyncbind.toString()+";\n",u+="global.$error = global.$error || "+global.$error.toString()+";\n"),u+=s.code,n&&r.dest?(fs.writeFileSync(r.dest+n,u),console.log("Compiled",r.dest+n)):console.log(u)}(r.minast||r.parseast)&&console.log(JSON.stringify(s.ast,function(e,t){return"$"===e[0]||e.match(/^(start|end|loc)$/)?void 0:t},2,null)),r.ast&&console.log(JSON.stringify(s.ast,function(e,t){return"$"===e[0]?void 0:t},0)),r.exec&&new Function(s.code)()}catch(e){console.error(e)}}var t,n=require("path"),r=(process.env.NODENT_OPTS&&JSON.parse(process.env.NODENT_OPTS),function(e){for(var t=[],n=e||2;n0",engine:"(async ()=>0)",noRuntime:"Promise"};NodentCompiler.prototype.Thenable=Thenable,NodentCompiler.prototype.EagerThenable=$asyncbind.EagerThenableFactory,NodentCompiler.prototype.asyncify=asyncify,NodentCompiler.prototype.require=requireCover,NodentCompiler.prototype.generateRequestHandler=generateRequestHandler,NodentCompiler.prototype.$asyncspawn=$asyncspawn,NodentCompiler.prototype.$asyncbind=$asyncbind,NodentCompiler.prototype.parseCompilerOptions=parseCompilerOptions,$asyncbind.call($asyncbind);var compiler;initialize.setDefaultCompileOptions=function(e,t){return e&&Object.keys(e).forEach(function(t){if(!(t in defaultCodeGenOpts))throw new Error("NoDent: unknown compiler option: "+t);defaultCodeGenOpts[t]=e[t]}),t&&Object.keys(t).forEach(function(e){if(!(e in t))throw new Error("NoDent: unknown configuration option: "+e);config[e]=t[e]}),initialize},initialize.setCompileOptions=function(e,t){return optionSet[e]=optionSet[e]||copyObj([defaultCodeGenOpts]),t&&Object.keys(t).forEach(function(n){if(!(n in defaultCodeGenOpts))throw new Error("NoDent: unknown compiler option: "+n);optionSet[e][n]=t[n]}),initialize},initialize.asyncify=asyncify,initialize.Thenable=$asyncbind.Thenable,initialize.EagerThenable=$asyncbind.EagerThenableFactory,module.exports=initialize,require.main===module&&process.argv.length>=3&&runFromCLI()}).call(this,require("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},"/node_modules/nodent")},{"./htmlScriptParser":29,_process:32,fs:7,"nodent-compiler":10,"nodent-runtime":26,path:30,resolve:33}]},{},[]); \ No newline at end of file diff --git a/node_modules/ajv/dist/regenerator.min.js b/node_modules/ajv/dist/regenerator.min.js deleted file mode 100644 index 0b05fb9cf..000000000 --- a/node_modules/ajv/dist/regenerator.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/* regenerator 0.10.0: Source transformer enabling ECMAScript 6 generator functions (yield) in JavaScript-of-today (ES5) */ -require=function e(t,r,n){function i(a,o){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!o&&u)return u(a,!0);if(s)return s(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=r[a]={exports:{}};t[a][0].call(c.exports,function(e){var r=t[a][1][e];return i(r||e)},c,c.exports,e,t,r,n)}return r[a].exports}for(var s="function"==typeof require&&require,a=0;a=0;o--)if(u[o]!==l[o])return!1;for(o=u.length-1;o>=0;o--)if(a=u[o],!h(e[a],t[a],r,n))return!1;return!0}(e,t,r,o))}return r?e===t:e==t}function f(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function d(e,t,r){h(e,t,!0)&&c(e,t,r,"notDeepStrictEqual",d)}function m(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 y(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=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&c(i,r,"Missing expected exception"+n);var s="string"==typeof n,a=!e&&g.isError(i),o=!e&&i&&!r;if((a&&s&&m(i,r)||o)&&c(i,r,"Got unwanted exception"+n),e&&i&&r&&!m(i,r)||!e&&i)throw i}var g=e("util/"),b=Object.prototype.hasOwnProperty,v=Array.prototype.slice,x="foo"===function(){}.name,E=t.exports=p,A=/\s*function\s+([^\(\s]*)\s*/;E.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=function(e){return u(l(e.actual),128)+" "+e.operator+" "+u(l(e.expected),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||c;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}}},g.inherits(E.AssertionError,Error),E.fail=c,E.ok=p,E.equal=function(e,t,r){e!=t&&c(e,t,r,"==",E.equal)},E.notEqual=function(e,t,r){e==t&&c(e,t,r,"!=",E.notEqual)},E.deepEqual=function(e,t,r){h(e,t,!1)||c(e,t,r,"deepEqual",E.deepEqual)},E.deepStrictEqual=function(e,t,r){h(e,t,!0)||c(e,t,r,"deepStrictEqual",E.deepStrictEqual)},E.notDeepEqual=function(e,t,r){h(e,t,!1)&&c(e,t,r,"notDeepEqual",E.notDeepEqual)},E.notDeepStrictEqual=d,E.strictEqual=function(e,t,r){e!==t&&c(e,t,r,"===",E.strictEqual)},E.notStrictEqual=function(e,t,r){e===t&&c(e,t,r,"!==",E.notStrictEqual)},E.throws=function(e,t,r){y(!0,e,t,r)},E.doesNotThrow=function(e,t,r){y(!1,e,t,r)},E.ifError=function(e){if(e)throw e};var D=Object.keys||function(e){var t=[];for(var r in e)b.call(e,r)&&t.push(r);return t}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":613}],2:[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":18,"../lib/types":19,"./es7":7}],3:[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":18,"../lib/types":19,"./babel":2,"./flow":9}],4:[function(e,t,r){t.exports=function(t){var r=t.use(e("../lib/types")).Type,n=r.def,i=r.or,s=t.use(e("../lib/shared")),a=s.defaults,o=s.geq;n("Printable").field("loc",i(n("SourceLocation"),null),a.null,!0),n("Node").bases("Printable").field("type",String).field("comments",i([n("Comment")],null),a.null,!0),n("SourceLocation").build("start","end","source").field("start",n("Position")).field("end",n("Position")).field("source",i(String,null),a.null),n("Position").build("line","column").field("line",o(1)).field("column",o(0)),n("File").bases("Node").build("program","name").field("program",n("Program")).field("name",i(String,null),a.null),n("Program").bases("Node").build("body").field("body",[n("Statement")]),n("Function").bases("Node").field("id",i(n("Identifier"),null),a.null).field("params",[n("Pattern")]).field("body",n("BlockStatement")),n("Statement").bases("Node"),n("EmptyStatement").bases("Statement").build(),n("BlockStatement").bases("Statement").build("body").field("body",[n("Statement")]),n("ExpressionStatement").bases("Statement").build("expression").field("expression",n("Expression")),n("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",n("Expression")).field("consequent",n("Statement")).field("alternate",i(n("Statement"),null),a.null),n("LabeledStatement").bases("Statement").build("label","body").field("label",n("Identifier")).field("body",n("Statement")),n("BreakStatement").bases("Statement").build("label").field("label",i(n("Identifier"),null),a.null),n("ContinueStatement").bases("Statement").build("label").field("label",i(n("Identifier"),null),a.null),n("WithStatement").bases("Statement").build("object","body").field("object",n("Expression")).field("body",n("Statement")),n("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",n("Expression")).field("cases",[n("SwitchCase")]).field("lexical",Boolean,a.false),n("ReturnStatement").bases("Statement").build("argument").field("argument",i(n("Expression"),null)),n("ThrowStatement").bases("Statement").build("argument").field("argument",n("Expression")),n("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",n("BlockStatement")).field("handler",i(n("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[n("CatchClause")],function(){return this.handler?[this.handler]:[]},!0).field("guardedHandlers",[n("CatchClause")],a.emptyArray).field("finalizer",i(n("BlockStatement"),null),a.null),n("CatchClause").bases("Node").build("param","guard","body").field("param",n("Pattern")).field("guard",i(n("Expression"),null),a.null).field("body",n("BlockStatement")),n("WhileStatement").bases("Statement").build("test","body").field("test",n("Expression")).field("body",n("Statement")),n("DoWhileStatement").bases("Statement").build("body","test").field("body",n("Statement")).field("test",n("Expression")),n("ForStatement").bases("Statement").build("init","test","update","body").field("init",i(n("VariableDeclaration"),n("Expression"),null)).field("test",i(n("Expression"),null)).field("update",i(n("Expression"),null)).field("body",n("Statement")),n("ForInStatement").bases("Statement").build("left","right","body").field("left",i(n("VariableDeclaration"),n("Expression"))).field("right",n("Expression")).field("body",n("Statement")),n("DebuggerStatement").bases("Statement").build(),n("Declaration").bases("Statement"),n("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",n("Identifier")),n("FunctionExpression").bases("Function","Expression").build("id","params","body"),n("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",i("var","let","const")).field("declarations",[n("VariableDeclarator")]),n("VariableDeclarator").bases("Node").build("id","init").field("id",n("Pattern")).field("init",i(n("Expression"),null)),n("Expression").bases("Node","Pattern"),n("ThisExpression").bases("Expression").build(),n("ArrayExpression").bases("Expression").build("elements").field("elements",[i(n("Expression"),null)]),n("ObjectExpression").bases("Expression").build("properties").field("properties",[n("Property")]),n("Property").bases("Node").build("kind","key","value").field("kind",i("init","get","set")).field("key",i(n("Literal"),n("Identifier"))).field("value",n("Expression")),n("SequenceExpression").bases("Expression").build("expressions").field("expressions",[n("Expression")]);var u=i("-","+","!","~","typeof","void","delete");n("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",u).field("argument",n("Expression")).field("prefix",Boolean,a.true);var l=i("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");n("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",l).field("left",n("Expression")).field("right",n("Expression"));var c=i("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");n("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",c).field("left",n("Pattern")).field("right",n("Expression"));var p=i("++","--");n("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",p).field("argument",n("Expression")).field("prefix",Boolean);var h=i("||","&&");n("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",h).field("left",n("Expression")).field("right",n("Expression")),n("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",n("Expression")).field("consequent",n("Expression")).field("alternate",n("Expression")),n("NewExpression").bases("Expression").build("callee","arguments").field("callee",n("Expression")).field("arguments",[n("Expression")]),n("CallExpression").bases("Expression").build("callee","arguments").field("callee",n("Expression")).field("arguments",[n("Expression")]),n("MemberExpression").bases("Expression").build("object","property","computed").field("object",n("Expression")).field("property",i(n("Identifier"),n("Expression"))).field("computed",Boolean,function(){var e=this.property.type;return"Literal"===e||"MemberExpression"===e||"BinaryExpression"===e}),n("Pattern").bases("Node"),n("SwitchCase").bases("Node").build("test","consequent").field("test",i(n("Expression"),null)).field("consequent",[n("Statement")]),n("Identifier").bases("Node","Expression","Pattern").build("name").field("name",String),n("Literal").bases("Node","Expression").build("value").field("value",i(String,Boolean,null,Number,RegExp)).field("regex",i({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}),n("Comment").bases("Printable").field("value",String).field("leading",Boolean,a.true).field("trailing",Boolean,a.false)}},{"../lib/shared":18,"../lib/types":19}],5:[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":19,"./core":4}],6:[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":18,"../lib/types":19,"./core":4}],7:[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":18,"../lib/types":19,"./es6":6}],8:[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":18,"../lib/types":19,"./es7":7}],9:[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":18,"../lib/types":19,"./es7":7}],10:[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":18,"../lib/types":19,"./es7":7}],11:[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":18,"../lib/types":19,"./core":4}],12:[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":13,"./lib/node-path":14,"./lib/path":16,"./lib/path-visitor":15,"./lib/types":19}],13:[function(e,t,r){t.exports=function(t){function r(e,t,r){return u.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||(u.check(e)?function(e,t,r){u.assert(e);var n=e.length;if(!u.check(t)||t.length!==n)return r&&r.push("length"),!1;for(var s=0;su)return!0;if(s===u&&"right"===this.name){if(r.right!==t)throw new Error("Nodes must be equal");return!0}default:return!1}case"SequenceExpression":switch(r.type){case"ForStatement":return!1;case"ExpressionStatement":return"expression"!==this.name;default:return!0}case"YieldExpression":switch(r.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"===r.type&&l.check(t.value)&&"object"===this.name&&r.object===t;case"AssignmentExpression":case"ConditionalExpression":switch(r.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return!0;case"CallExpression":return"callee"===this.name&&r.callee===t;case"ConditionalExpression":return"test"===this.name&&r.test===t;case"MemberExpression":return"object"===this.name&&r.object===t;default:return!1}default:if("NewExpression"===r.type&&"callee"===this.name&&r.callee===t)return i(t)}return!(!0===e||this.canBeFirstInStatement()||!this.firstInStatement())};var d={};return[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,t){e.forEach(function(e){d[e]=t})}),f.canBeFirstInStatement=function(){var e=this.node;return!o.FunctionExpression.check(e)&&!o.ObjectExpression.check(e)},f.firstInStatement=function(){return function(e){for(var t,r;e.parent;e=e.parent){if(t=e.node,r=e.parent.node,o.BlockStatement.check(r)&&"body"===e.parent.name&&0===e.name){if(r.body[0]!==t)throw new Error("Nodes must be equal");return!0}if(o.ExpressionStatement.check(r)&&"expression"===e.name){if(r.expression!==t)throw new Error("Nodes must be equal");return!0}if(o.SequenceExpression.check(r)&&"expressions"===e.parent.name&&0===e.name){if(r.expressions[0]!==t)throw new Error("Nodes must be equal")}else if(o.CallExpression.check(r)&&"callee"===e.name){if(r.callee!==t)throw new Error("Nodes must be equal")}else if(o.MemberExpression.check(r)&&"object"===e.name){if(r.object!==t)throw new Error("Nodes must be equal")}else if(o.ConditionalExpression.check(r)&&"test"===e.name){if(r.test!==t)throw new Error("Nodes must be equal")}else if(n(r)&&"left"===e.name){if(r.left!==t)throw new Error("Nodes must be equal")}else{if(!o.UnaryExpression.check(r)||r.prefix||"argument"!==e.name)return!1;if(r.argument!==t)throw new Error("Nodes must be equal")}}return!0}(this)},r}},{"./path":16,"./scope":17,"./types":19}],15:[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=function(e){r=Object.create(null);for(var t in e)/^visit[A-Z]/.test(t)&&(r[t.slice("visit".length)]=!0);for(var r,n=a.computeSupertypeLookupTable(r),i=Object.create(null),s=(r=Object.keys(n)).length,o=0;o=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("")}(this),l.check(i)){for(var u=i.length,c=o(this.parentPath,a-1,this.name+1),p=[this.name,1],h=0;h=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":19}],19:[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 C.check(e)?"{"+Object.keys(e).map(function(t){return t+": "+e[t]}).join(", ")+"}":D.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 x[r]=i,t&&"function"==typeof t.constructor&&(b.push(t.constructor),v.push(i)),i}function n(t,r){if(t instanceof e)return t;if(t instanceof c)return t.type;if(D.check(t))return e.fromArray(t);if(C.check(t))return e.fromObject(t);if(A.check(t)){var n=b.indexOf(t);return n>=0?v[n]:new e(t,r)}return new e(function(e){return e===t},_.check(r)?function(){return t+""}:r)}function s(e,t,r,i){if(!(this instanceof s))throw new Error("Field constructor cannot be invoked without 'new'");E.assert(e);var a={name:{value:e},type:{value:t=n(t)},hidden:{value:!!i}};A.check(r)&&(a.defaultFn={value:r}),Object.defineProperties(this,a)}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)).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,t){return Object.keys(t).forEach(function(r){e[r]=t[r]}),e}var y={},g=e.prototype;y.Type=e,g.assert=function(e,r){if(!this.check(e,r)){var n=t(e);throw new Error(n+" does not match type "+this)}return!0},g.toString=function(){var e=this.name;return E.check(e)?e:A.check(e)?e.call(this)+"":e+" type"};var b=[],v=[],x={};y.builtInTypes=x;var E=r("truthy","string"),A=r(function(){},"function"),D=r([],"array"),C=r({},"object"),S=(r(/./,"RegExp"),r(new Date,"Date"),r(3,"number")),_=(r(!0,"boolean"),r(null,"null"),r(void 0,"undefined"));e.or=function(){for(var t=[],r=arguments.length,i=0;i=0&&function(e){var t=h(e);if(!T[t]){var r=T[p(e)];r&&(T[t]=function(){return T.expressionStatement(r.apply(T,arguments))})}}(e.typeName)}},y.finalize=function(){Object.keys(k).forEach(function(e){k[e].finalize()})},y}},{}],20:[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":2,"./def/babel6":3,"./def/core":4,"./def/e4x":5,"./def/es6":6,"./def/es7":7,"./def/esprima":8,"./def/flow":9,"./def/jsx":10,"./def/mozilla":11,"./fork":12}],21:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t){return t.replace(a.default,function(){for(var t=arguments.length,r=Array(t),n=0;n3&&void 0!==arguments[3]?arguments[3]:{};r=Math.max(r,0);var s=n.highlightCode&&u.default.supportsColor||n.forceColor,a=u.default;n.forceColor&&(a=new u.default.constructor({enabled:!0}));var o=function(e,t){return s?e(t):t},c=function(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}}(a);s&&(e=i(c,e));var p=n.linesAbove||2,h=n.linesBelow||3,f=e.split(l),d=Math.max(t-(p+1),0),m=Math.min(f.length,t+h);t||r||(d=0,m=f.length);var y=String(m).length,g=f.slice(d,m).map(function(e,n){var i=d+1+n,s=" "+(" "+i).slice(-y)+" | ";if(i===t){var a="";if(r){var u=e.slice(0,r-1).replace(/[^\t]/g," ");a=["\n ",o(c.gutter,s.replace(/\d/g," ")),u,o(c.marker,"^")].join("")}return[o(c.marker,">"),o(c.gutter,s),e,a].join("")}return" "+o(c.gutter,s)+e}).join("\n");return s?a.reset(g):g};var s=e("js-tokens"),a=n(s),o=n(e("esutils")),u=n(e("chalk")),l=/\r\n|[\n\r\u2028\u2029]/,c=/^[a-z][\w-]*$/i,p=/^[()\[\]{}]$/;t.exports=r.default},{chalk:24,esutils:28,"js-tokens":322}],22:[function(e,t,r){"use strict";t.exports=function(){return/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g}},{}],23:[function(e,t,r){"use strict";Object.defineProperty(t,"exports",{enumerable:!0,get:function(){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}})},{}],24:[function(e,t,r){(function(r){"use strict";function n(e){this.enabled=e&&void 0!==e.enabled?e.enabled:l}function i(e){var t=function(){return function(){var e=arguments,t=e.length,r=0!==t&&String(arguments[0]);if(t>1)for(var n=1;n=97&&o<=122||o>=65&&o<=90||36===o||95===o;for(a=new Array(128),o=0;o<128;++o)a[o]=o>=97&&o<=122||o>=65&&o<=90||o>=48&&o<=57||36===o||95===o;t.exports={isDecimalDigit:function(e){return 48<=e&&e<=57},isHexDigit:function(e){return 48<=e&&e<=57||97<=e&&e<=102||65<=e&&e<=70},isOctalDigit:function(e){return e>=48&&e<=55},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&i.indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStartES5:function(t){return t<128?s[t]:n.NonAsciiIdentifierStart.test(e(t))},isIdentifierPartES5:function(t){return t<128?a[t]:n.NonAsciiIdentifierPart.test(e(t))},isIdentifierStartES6:function(t){return t<128?s[t]:r.NonAsciiIdentifierStart.test(e(t))},isIdentifierPartES6:function(t){return t<128?a[t]:r.NonAsciiIdentifierPart.test(e(t))}}}()},{}],27:[function(e,t,r){!function(){"use strict";function r(e,t){return!(!t&&"yield"===e)&&n(e,t)}function n(e,t){if(t&&function(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return!0;default:return!1}}(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 i(e,t){return"null"===e||"true"===e||"false"===e||r(e,t)}function s(e,t){return"null"===e||"true"===e||"false"===e||n(e,t)}function a(e){var t,r,n;if(0===e.length)return!1;if(n=e.charCodeAt(0),!l.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=o(n,i)}if(!s(n))return!1;s=l.isIdentifierPartES6}return!0}var l=e("./code");t.exports={isKeywordES5:r,isKeywordES6:n,isReservedWordES5:i,isReservedWordES6:s,isRestrictedWord:function(e){return"eval"===e||"arguments"===e},isIdentifierNameES5:a,isIdentifierNameES6:u,isIdentifierES5:function(e,t){return a(e)&&!i(e,t)},isIdentifierES6:function(e,t){return u(e)&&!s(e,t)}}}()},{"./code":26}],28:[function(e,t,r){!function(){"use strict";r.ast=e("./ast"),r.code=e("./code"),r.keyword=e("./keyword")}()},{"./ast":25,"./code":26,"./keyword":27}],29:[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":22}],30:[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||t1&&void 0!==arguments[1]?arguments[1]:{};return t.filename=e,x(h.default.readFileSync(e,"utf8"),t)};var h=i(e("fs")),f=n(e("../util")),d=n(e("babel-messages")),m=n(e("babel-types")),y=i(e("babel-traverse")),g=i(e("../transformation/file/options/option-manager")),b=i(e("../transformation/pipeline"));r.util=f,r.messages=d,r.types=m,r.traverse=y.default,r.OptionManager=g.default,r.Pipeline=b.default;var v=new b.default,x=(r.analyse=v.analyse.bind(v),r.transform=v.transform.bind(v));r.transformFromAst=v.transformFromAst.bind(v)},{"../../package":73,"../helpers/resolve-plugin":38,"../helpers/resolve-preset":39,"../tools/build-external-helpers":42,"../transformation/file":43,"../transformation/file/options/config":47,"../transformation/file/options/option-manager":49,"../transformation/pipeline":54,"../util":57,"babel-messages":110,"babel-template":139,"babel-traverse":143,"babel-types":178,fs:191}],33:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e){return["babel-plugin-"+e,e]},t.exports=r.default},{}],34:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(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},t.exports=r.default},{}],35:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.default=function(e,t){if(e&&t)return(0,s.default)(e,t,function(e,t){if(t&&Array.isArray(e)){for(var r=t.slice(0),n=e,s=Array.isArray(n),a=0,n=s?n:(0,i.default)(n);;){var o;if(s){if(a>=n.length)break;o=n[a++]}else{if((a=n.next()).done)break;o=a.value}var u=o;r.indexOf(u)<0&&r.push(u)}return r}})};var s=n(e("lodash/mergeWith"));t.exports=r.default},{"babel-runtime/core-js/get-iterator":120,"lodash/mergeWith":527}],36:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t,r){if(e){if("Program"===e.type)return n.file(e,t||[],r||[]);if("File"===e.type)return e}throw new Error("Not a valid ast?")};var n=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}(e("babel-types"));t.exports=r.default},{"babel-types":178}],37:[function(e,t,r){"use strict";r.__esModule=!0,r.default=function(e,t){return e.reduce(function(e,r){return e||(0,n.default)(r,t)},null)};var n=function(e){return e&&e.__esModule?e:{default:e}}(e("./resolve"));t.exports=r.default},{"./resolve":40}],38:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();return(0,s.default)((0,a.default)(e),t)};var s=i(e("./resolve-from-possible-names")),a=i(e("./get-possible-plugin-names"));t.exports=r.default}).call(this,e("_process"))},{"./get-possible-plugin-names":33,"./resolve-from-possible-names":37,_process:550}],39:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();return(0,s.default)((0,a.default)(e),t)};var s=i(e("./resolve-from-possible-names")),a=i(e("./get-possible-preset-names"));t.exports=r.default}).call(this,e("_process"))},{"./get-possible-preset-names":34,"./resolve-from-possible-names":37,_process:550}],40:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var s=i(e("babel-runtime/helpers/typeof"));r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:n.cwd();if("object"===(void 0===a.default?"undefined":(0,s.default)(a.default)))return null;var r=u[t];if(!r){r=new a.default;var i=o.default.join(t,".babelrc");r.id=i,r.filename=i,r.paths=a.default._nodeModulePaths(t),u[t]=r}try{return a.default._resolveFilename(e,r)}catch(e){return null}};var a=i(e("module")),o=i(e("path")),u={};t.exports=r.default}).call(this,e("_process"))},{_process:550,"babel-runtime/helpers/typeof":138,module:191,path:546}],41:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/map")),s=n(e("babel-runtime/helpers/classCallCheck")),a=n(e("babel-runtime/helpers/possibleConstructorReturn")),o=n(e("babel-runtime/helpers/inherits")),u=function(e){function t(){(0,s.default)(this,t);var r=(0,a.default)(this,e.call(this));return r.dynamicData={},r}return(0,o.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}(i.default);r.default=u,t.exports=r.default},{"babel-runtime/core-js/map":122,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137}],42:[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=h.functionExpression(null,[h.identifier("global")],h.blockStatement(r)),i=h.program([h.expressionStatement(h.callExpression(n,[u.get("selfGlobal")]))]);return r.push(h.variableDeclaration("var",[h.variableDeclarator(e,h.assignmentExpression("=",h.memberExpression(h.identifier("global"),e),h.objectExpression([])))])),t(r),i}function a(e,t){var r=[];return r.push(h.variableDeclaration("var",[h.variableDeclarator(e,h.identifier("global"))])),t(r),h.program([f({FACTORY_PARAMETERS:h.identifier("global"),BROWSER_ARGUMENTS:h.assignmentExpression("=",h.memberExpression(h.identifier("root"),e),h.objectExpression([])),COMMON_ARGUMENTS:h.identifier("exports"),AMD_ARGUMENTS:h.arrayExpression([h.stringLiteral("exports")]),FACTORY_BODY:r,UMD_ROOT:h.identifier("this")})])}function o(e,t){var r=[];return r.push(h.variableDeclaration("var",[h.variableDeclarator(e,h.objectExpression([]))])),t(r),r.push(h.expressionStatement(e)),h.program(r)}r.__esModule=!0,r.default=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"global",r=h.identifier("babelHelpers"),n=void 0,i={global:s,umd:a,var:o}[t];if(!i)throw new Error(c.get("unsupportedOutputType",t));return n=i(r,function(t){return function(e,t,r){u.list.forEach(function(n){if(!(r&&r.indexOf(n)<0)){var i=h.identifier(n);e.push(h.expressionStatement(h.assignmentExpression("=",h.memberExpression(t,i),u.get(n))))}})}(t,r,e)}),(0,l.default)(n).code};var u=i(e("babel-helpers")),l=n(e("babel-generator")),c=i(e("babel-messages")),p=n(e("babel-template")),h=i(e("babel-types")),f=(0,p.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":85,"babel-helpers":109,"babel-messages":110,"babel-template":139,"babel-types":178}],43:[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=i(e("babel-runtime/core-js/get-iterator")),a=i(e("babel-runtime/core-js/object/create")),o=i(e("babel-runtime/core-js/object/assign")),u=i(e("babel-runtime/helpers/classCallCheck")),l=i(e("babel-runtime/helpers/possibleConstructorReturn")),c=i(e("babel-runtime/helpers/inherits")),p=i(e("babel-helpers")),h=n(e("./metadata")),f=i(e("convert-source-map")),d=i(e("./options/option-manager")),m=i(e("../plugin-pass")),y=e("babel-traverse"),g=i(y),b=i(e("source-map")),v=i(e("babel-generator")),x=i(e("babel-code-frame")),E=i(e("lodash/defaults")),A=i(e("./logger")),D=i(e("../../store")),C=e("babylon"),S=n(e("../../util")),_=i(e("path")),w=n(e("babel-types")),k=i(e("../../helpers/resolve")),F=i(e("../internal-plugins/block-hoist")),T=i(e("../internal-plugins/shadow-functions")),P=/^#!.*/,B=[[F.default],[T.default]],O={enter:function(e,t){var r=e.node.loc;r&&(t.loc=r,e.stop())}},j=function(r){function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];(0,u.default)(this,n);var i=(0,l.default)(this,r.call(this));return i.pipeline=t,i.log=new A.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,o.default)((0,a.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 y.Hub(i),i}return(0,c.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,s.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var a=i;if(w.isModuleDeclaration(a)){e=!0;break}}e&&this.path.traverse(h,this)},n.prototype.initOptions=function(e){(e=new d.default(this.log,this.pipeline).init(e)).inputSourceMap&&(e.sourceMaps=!0),e.moduleId&&(e.moduleIds=!0),e.basename=_.default.basename(e.filename,_.default.extname(e.filename)),e.ignore=S.arrayify(e.ignore,S.regexify),e.only&&(e.only=S.arrayify(e.only,S.regexify)),(0,E.default)(e,{moduleRoot:e.sourceRoot}),(0,E.default)(e,{sourceRoot:e.moduleRoot}),(0,E.default)(e,{filenameRelative:e.filename});var t=_.default.basename(e.filenameRelative);return(0,E.default)(e,{sourceFileName:t,sourceMapTarget:t}),e},n.prototype.buildPluginsForOptions=function(e){if(Array.isArray(e.plugins)){for(var t=[],r=[],n=e.plugins.concat(B),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()).done)break;o=a.value}var u=o,l=u[0],c=u[1];t.push(l.visitor),r.push(new m.default(this,l,c)),l.manipulateOptions&&l.manipulateOptions(e,this.parserOpts,this)}this.pluginVisitors.push(t),this.pluginPasses.push(r)}},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(w.importNamespaceSpecifier(i)):"default"===t?s.push(w.importDefaultSpecifier(i)):s.push(w.importSpecifier(i,w.identifier(t)));var a=w.importDeclaration(s,w.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 w.memberExpression(n,w.identifier(e));var s=(0,p.default)(e),a=this.declarations[e]=this.scope.generateUidIdentifier(e);return w.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=w.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,g.default)(e,O,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 b.default.SourceMapConsumer(t),n=new b.default.SourceMapConsumer(e),i=new b.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=C.parse,i=this.opts.parserOpts;if(i&&(i=(0,o.default)({},this.parserOpts,i)).parser){if("string"==typeof i.parser){var s=_.default.dirname(this.opts.filename)||t.cwd(),a=(0,k.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,C.parse)(e,i)}}}this.log.debug("Parse start");var u=n(r,i||this.parserOpts);return this.log.debug("Parse stop"),u},n.prototype._addAst=function(e){this.path=y.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;a=r[i++]}else{if((i=r.next()).done)break;a=i.value}var o=a,u=o.plugin[e];u&&u.call(o,this)}},n.prototype.parseInputSourceMap=function(e){var t=this.opts;if(!1!==t.inputSourceMap){var r=f.default.fromSource(e);r&&(t.inputSourceMap=r.toObject(),e=f.default.removeComments(e))}return e},n.prototype.parseShebang=function(){var e=P.exec(this.code);e&&(this.shebang=e[0],this.code=this.code.replace(P,""))},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=v.default;if(r.generatorOpts.generator&&"string"==typeof(s=r.generatorOpts.generator)){var a=_.default.dirname(this.opts.filename)||t.cwd(),u=(0,k.default)(s,a);if(!u)throw new Error("Couldn't find generator "+s+' with "print" method relative to directory '+a);s=e(u).print}this.log.debug("Generation start");var l=s(n,r.generatorOpts?(0,o.default)(r,r.generatorOpts):r,this.code);return i.code=l.code,i.map=l.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"+f.default.fromObject(i.map).toComment()),"inline"===r.sourceMaps&&(i.map=null),this.makeResult(i)},n}(D.default);r.default=j,r.File=j}).call(this,e("_process"))},{"../../helpers/resolve":40,"../../store":41,"../../util":57,"../internal-plugins/block-hoist":52,"../internal-plugins/shadow-functions":53,"../plugin-pass":55,"./logger":44,"./metadata":45,"./options/option-manager":49,_process:550,"babel-code-frame":21,"babel-generator":85,"babel-helpers":109,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/object/assign":124,"babel-runtime/core-js/object/create":125,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137,"babel-traverse":143,"babel-types":178,babylon:186,"convert-source-map":58,"lodash/defaults":495,path:546,"source-map":72}],44:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=n(e("debug/node")),a=(0,s.default)("babel:verbose"),o=(0,s.default)("babel"),u=[],l=function(){function e(t,r){(0,i.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),u.indexOf(e)>=0||(u.push(e),console.error(e)))},e.prototype.verbose=function(e){a.enabled&&a(this._buildMessage(e))},e.prototype.debug=function(e){o.enabled&&o(this._buildMessage(e))},e.prototype.deopt=function(e,t){this.debug(t)},e}();r.default=l,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134,"debug/node":59}],45:[function(e,t,r){"use strict";r.__esModule=!0,r.ImportDeclaration=r.ModuleDeclaration=void 0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.ExportDeclaration=function(e,t){var r=e.node,s=r.source?r.source.value:null,a=t.metadata.modules.exports,o=e.get("declaration");if(o.isStatement()){var u=o.getBindingIdentifiers();for(var l in u)a.exported.push(l),a.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,n.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}var d=f,m=d.exported.name;a.exported.push(m),i.isExportDefaultSpecifier(d)&&a.specifiers.push({kind:"external",local:m,exported:m,source:s}),i.isExportNamespaceSpecifier(d)&&a.specifiers.push({kind:"external-namespace",exported:m,source:s});var y=d.local;y&&(s&&a.specifiers.push({kind:"external",local:y.name,exported:m,source:s}),s||a.specifiers.push({kind:"local",local:y.name,exported:m}))}e.isExportAllDeclaration()&&a.specifiers.push({kind:"external-all",source:s})},r.Scope=function(e){e.skip()};var 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}(e("babel-types"));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,i=[],s=[];t.metadata.modules.imports.push({source:r.source.value,imported:s,specifiers:i});for(var a=e.get("specifiers"),o=Array.isArray(a),u=0,a=o?a:(0,n.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var c=l,p=c.node.local.name;if(c.isImportDefaultSpecifier()&&(s.push("default"),i.push({kind:"named",imported:"default",local:p})),c.isImportSpecifier()){var h=c.node.imported.name;s.push(h),i.push({kind:"named",imported:h,local:p})}c.isImportNamespaceSpecifier()&&(s.push("*"),i.push({kind:"namespace",local:p}))}}}},{"babel-runtime/core-js/get-iterator":120,"babel-types":178}],46:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}function s(e){var t=f[e];return null==t?f[e]=h.default.existsSync(e):t}r.__esModule=!0;var a=i(e("babel-runtime/core-js/object/assign")),o=i(e("babel-runtime/helpers/classCallCheck"));r.default=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],r=e.filename,n=new m(t);return!1!==e.babelrc&&n.findConfigs(r),n.mergeConfig({options:e,alias:"base",dirname:r&&p.default.dirname(r)}),n.configs};var u=i(e("../../../helpers/resolve")),l=i(e("json5")),c=i(e("path-is-absolute")),p=i(e("path")),h=i(e("fs")),f={},d={},m=function(){function e(t){(0,o.default)(this,e),this.resolvedConfigs=[],this.configs=[],this.log=t}return e.prototype.findConfigs=function(e){if(e){(0,c.default)(e)||(e=p.default.join(n.cwd(),e));for(var t=!1,r=!1;e!==(e=p.default.dirname(e));){if(!t){var i=p.default.join(e,".babelrc");s(i)&&(this.addConfig(i),t=!0);var a=p.default.join(e,"package.json");!t&&s(a)&&(t=this.addConfig(a,"babel",JSON))}if(!r){var o=p.default.join(e,".babelignore");s(o)&&(this.addIgnoreConfig(o),r=!0)}if(r&&t)return}}},e.prototype.addIgnoreConfig=function(e){var t=h.default.readFileSync(e,"utf8").split("\n");(t=t.map(function(e){return e.replace(/#(.*?)$/,"").trim()}).filter(function(e){return!!e})).length&&this.mergeConfig({options:{ignore:t},alias:e,dirname:p.default.dirname(e)})},e.prototype.addConfig=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:l.default;if(this.resolvedConfigs.indexOf(e)>=0)return!1;this.resolvedConfigs.push(e);var n=h.default.readFileSync(e,"utf8"),i=void 0;try{i=d[n]=d[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:p.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,a.default)({},t),s=s||n.cwd(),i=i||r,t.extends){var o=(0,u.default)(t.extends,s);o?this.addConfig(o):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 l=void 0,c=n.env.BABEL_ENV||n.env.NODE_ENV||"development";t.env&&(l=t.env[c],delete t.env),this.mergeConfig({options:l,alias:r+".env."+c,dirname:s})},e}();t.exports=r.default}).call(this,e("_process"))},{"../../../helpers/resolve":40,_process:550,"babel-runtime/core-js/object/assign":124,"babel-runtime/helpers/classCallCheck":134,fs:191,json5:324,path:546,"path-is-absolute":547}],47:[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}}},{}],48:[function(e,t,r){"use strict";r.__esModule=!0,r.config=void 0,r.normaliseOptions=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e){var r=e[t];if(null!=r){var s=i.default[t];if(s&&s.alias&&(s=i.default[s.alias]),s){var a=n[s.type];a&&(r=a(r)),e[t]=r}}}return e};var n=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}(e("./parsers")),i=function(e){return e&&e.__esModule?e:{default:e}}(e("./config"));r.config=i.default},{"./config":47,"./parsers":50}],49:[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=s(e("babel-runtime/helpers/objectWithoutProperties")),o=s(e("babel-runtime/core-js/json/stringify")),u=s(e("babel-runtime/core-js/object/assign")),l=s(e("babel-runtime/core-js/get-iterator")),c=s(e("babel-runtime/helpers/typeof")),p=s(e("babel-runtime/helpers/classCallCheck")),h=i(e("../../../api/node")),f=s(e("../../plugin")),d=i(e("babel-messages")),m=e("./index"),y=s(e("../../../helpers/resolve-plugin")),g=s(e("../../../helpers/resolve-preset")),b=s(e("lodash/cloneDeepWith")),v=s(e("lodash/clone")),x=s(e("../../../helpers/merge")),E=s(e("./config")),A=s(e("./removed")),D=s(e("./build-config-chain")),C=s(e("path")),S=function(){function t(e){(0,p.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,l.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var p=u;if(p.container===e)return p.plugin}var m=void 0;if("object"===(void 0===(m="function"==typeof e?e(h):e)?"undefined":(0,c.default)(m))){var y=new f.default(m,i);return t.memoisedPlugins.push({container:e,plugin:y}),y}throw new TypeError(d.get("pluginNotObject",r,n,void 0===m?"undefined":(0,c.default)(m))+r+n)},t.createBareOptions=function(){var e={};for(var t in E.default){var r=E.default[t];e[t]=(0,v.default)(r.default)}return e},t.normalisePlugin=function(e,r,n,i){if(!((e=e.__esModule?e.default:e)instanceof f.default)){if("function"!=typeof e&&"object"!==(void 0===e?"undefined":(0,c.default)(e)))throw new TypeError(d.get("pluginNotFunction",r,n,void 0===e?"undefined":(0,c.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,y.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,l=e.dirname;if(a=a||"foreign",i){("object"!==(void 0===i?"undefined":(0,c.default)(i))||Array.isArray(i))&&this.log.error("Invalid options type for "+a,TypeError);var p=(0,b.default)(i,function(e){if(e instanceof f.default)return e});l=l||n.cwd(),o=o||a;for(var h in p){if(!E.default[h]&&this.log)if(A.default[h])this.log.error("Using removed Babel 5 option: "+a+"."+h+" - "+A.default[h].message,ReferenceError);else{var d="Unknown option: "+a+"."+h+". Check out http://babeljs.io/docs/usage/options/ for more information about options.";this.log.error(d+"\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,m.normaliseOptions)(p),p.plugins&&(p.plugins=t.normalisePlugins(o,l,p.plugins)),p.presets&&(p.passPerPreset?p.presets=this.resolvePresets(p.presets,l,function(e,t){r.mergeOptions({options:e,extending:e,alias:t,loc:t,dirname:l})}):(this.mergePresets(p.presets,l),delete p.presets)),i===s?(0,u.default)(s,p):(0,x.default)(s||this.options,p)}},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:C.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,o.default)(t.slice(2))+" passed to preset.");var s=t;t=s[0],i=s[1]}var u=void 0;try{if("string"==typeof t){if(!(u=(0,g.default)(t,r)))throw new Error("Couldn't find preset "+(0,o.default)(t)+" relative to directory "+(0,o.default)(r));t=e(u)}if("object"===(void 0===t?"undefined":(0,c.default)(t))&&t.__esModule)if(t.default)t=t.default;else{var l=t;l.__esModule;t=(0,a.default)(l,["__esModule"])}if("object"===(void 0===t?"undefined":(0,c.default)(t))&&t.buildPreset&&(t=t.buildPreset),"function"!=typeof t&&void 0!==i)throw new Error("Options "+(0,o.default)(i)+" passed to "+(u||"a preset")+" which does not accept options.");if("function"==typeof t&&(t=t(h,i,{dirname:r})),"object"!==(void 0===t?"undefined":(0,c.default)(t)))throw new Error("Unsupported preset format: "+t+".");n&&n(t,u)}catch(e){throw u&&(e.message+=" (While processing preset: "+(0,o.default)(u)+")"),e}return t})},t.prototype.normaliseOptions=function(){var e=this.options;for(var t in E.default){var r=E.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,D.default)(e,this.log),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()).done)break;i=n.value}var s=i;this.mergeOptions(s)}return this.normaliseOptions(e),this.options},t}();r.default=S,S.memoisedPlugins=[],t.exports=r.default}).call(this,e("_process"))},{"../../../api/node":32,"../../../helpers/merge":35,"../../../helpers/resolve-plugin":38,"../../../helpers/resolve-preset":39,"../../plugin":56,"./build-config-chain":46,"./config":47,"./index":48,"./removed":51,_process:550,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/core-js/object/assign":124,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/objectWithoutProperties":136,"babel-runtime/helpers/typeof":138,"lodash/clone":491,"lodash/cloneDeepWith":493,path:546}],50:[function(e,t,r){"use strict";r.__esModule=!0,r.filename=void 0,r.boolean=function(e){return!!e},r.booleanString=function(e){return i.booleanify(e)},r.list=function(e){return i.list(e)};var n=function(e){return e&&e.__esModule?e:{default:e}}(e("slash")),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}(e("../../../util"));r.filename=n.default},{"../../../util":57,slash:603}],51:[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"}}},{}],52:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("../plugin")),s=n(e("lodash/sortBy"));r.default=new i.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 o.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 o.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 a.default({visitor:r}))),this.transform(e,t).metadata},e.prototype.transformFromAst=function(e,t,r){e=(0,s.default)(e);var n=new o.default(r,this);return n.wrap(t,function(){return n.addCode(t),n.addAst(e),n.transform()})},e}();r.default=u,t.exports=r.default},{"../helpers/normalize-ast":36,"./file":43,"./plugin":56,"babel-runtime/helpers/classCallCheck":134}],55:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=n(e("babel-runtime/helpers/possibleConstructorReturn")),a=n(e("babel-runtime/helpers/inherits")),o=n(e("../store")),u=(n(e("./file")),function(e){function t(r,n){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};(0,i.default)(this,t);var o=(0,s.default)(this,e.call(this));return o.plugin=n,o.key=n.key,o.file=r,o.opts=a,o}return(0,a.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}(o.default));r.default=u,t.exports=r.default},{"../store":41,"./file":43,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137}],56:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator")),s=n(e("babel-runtime/helpers/classCallCheck")),a=n(e("babel-runtime/helpers/possibleConstructorReturn")),o=n(e("babel-runtime/helpers/inherits")),u=n(e("./file/options/option-manager")),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}(e("babel-messages")),c=n(e("../store")),p=n(e("babel-traverse")),h=n(e("lodash/assign")),f=n(e("lodash/clone")),d=["enter","exit"],m=function(e){function t(r,n){(0,s.default)(this,t);var i=(0,a.default)(this,e.call(this));return i.initialized=!1,i.raw=(0,h.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,f.default)(i.take("visitor"))||{}),i}return(0,o.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),s=0;s=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}if(l){var c=l.apply(this,n);null!=c&&(e=c)}}return e}},t.prototype.maybeInherit=function(e){var t=this.take("inherits");t&&(t=u.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=p.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(l.get("pluginInvalidProperty",e,t,r))}},t.prototype.normaliseVisitor=function(e){for(var t=d,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}if(e[s])throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.")}return p.default.explode(e),e},t}(c.default);r.default=m,t.exports=r.default},{"../store":41,"./file/options/option-manager":49,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137,"babel-traverse":143,"lodash/assign":488,"lodash/clone":491}],57:[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=m.default.extname(e);return(0,f.default)(r,n)}function s(e){return e?Array.isArray(e)?e:"string"==typeof e?e.split(","):[e]:[]}function a(e,t){return e?"boolean"==typeof e?a([e],t):"string"==typeof e?a(s(e),t):Array.isArray(e)?(t&&(e=e.map(t)),e):[e]:[]}function o(e,t){return"function"==typeof e?e(t):e.test(t)}r.__esModule=!0,r.inspect=r.inherits=void 0;var u=n(e("babel-runtime/core-js/get-iterator")),l=e("util");Object.defineProperty(r,"inherits",{enumerable:!0,get:function(){return l.inherits}}),Object.defineProperty(r,"inspect",{enumerable:!0,get:function(){return l.inspect}}),r.canCompile=i,r.list=s,r.regexify=function(e){if(!e)return new RegExp(/.^/);if(Array.isArray(e)&&(e=new RegExp(e.map(c.default).join("|"),"i")),"string"==typeof e){e=(0,y.default)(e),((0,p.default)(e,"./")||(0,p.default)(e,"*/"))&&(e=e.slice(2)),(0,p.default)(e,"**/")&&(e=e.slice(3));var t=h.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")},r.arrayify=a,r.booleanify=function(e){return"true"===e||1==e||!("false"===e||0==e||!e)&&e},r.shouldIgnore=function(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,u.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}if(o(a,e))return!1}return!0}if(t.length)for(var l=t,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()).done)break;h=p.value}if(o(h,e))return!0}return!1};var c=n(e("lodash/escapeRegExp")),p=n(e("lodash/startsWith")),h=n(e("minimatch")),f=n(e("lodash/includes")),d=n(e("lodash/isRegExp")),m=n(e("path")),y=n(e("slash"));i.EXTENSIONS=[".js",".jsx",".es6",".es"]},{"babel-runtime/core-js/get-iterator":120,"lodash/escapeRegExp":497,"lodash/includes":507,"lodash/isRegExp":519,"lodash/startsWith":532,minimatch:542,path:546,slash:603,util:613}],58:[function(e,t,r){(function(t){"use strict";function n(e,n){(n=n||{}).isFileComment&&(e=function(e,t){var n=r.mapFileCommentRegex.exec(e),a=n[1]||n[2],o=s.resolve(t,a);try{return i.readFileSync(o,"utf8")}catch(e){throw new Error("An error occurred while trying to read the map file at "+o+"\n"+e)}}(e,n.commentFileDir)),n.hasComment&&(e=function(e){return e.split(",").pop()}(e)),n.isEncoded&&(e=function(e){return new t(e,"base64").toString()}(e)),(n.isJSON||n.isEncoded)&&(e=JSON.parse(e)),this.sourcemap=e}var i=e("fs"),s=e("path");Object.defineProperty(r,"commentRegex",{get:function(){return/^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/gm}}),Object.defineProperty(r,"mapFileCommentRegex",{get:function(){return/(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/gm}}),n.prototype.toJSON=function(e){return JSON.stringify(this.sourcemap,null,e)},n.prototype.toBase64=function(){var e=this.toJSON();return new t(e).toString("base64")},n.prototype.toComment=function(e){var t="sourceMappingURL=data:application/json;charset=utf-8;base64,"+this.toBase64();return e&&e.multiline?"/*# "+t+" */":"//# "+t},n.prototype.toObject=function(){return JSON.parse(this.toJSON())},n.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)},n.prototype.setProperty=function(e,t){return this.sourcemap[e]=t,this},n.prototype.getProperty=function(e){return this.sourcemap[e]},r.fromObject=function(e){return new n(e)},r.fromJSON=function(e){return new n(e,{isJSON:!0})},r.fromBase64=function(e){return new n(e,{isEncoded:!0})},r.fromComment=function(e){return e=e.replace(/^\/\*/g,"//").replace(/\*\/$/g,""),new n(e,{isEncoded:!0,hasComment:!0})},r.fromMapFileComment=function(e,t){return new n(e,{commentFileDir:t,isFileComment:!0,isJSON:!0})},r.fromSource=function(e){var t=e.match(r.commentRegex);return t?r.fromComment(t.pop()):null},r.fromMapFileSource=function(e,t){var n=e.match(r.mapFileCommentRegex);return n?r.fromMapFileComment(n.pop(),t):null},r.removeComments=function(e){return e.replace(r.commentRegex,"")},r.removeMapFileComments=function(e){return e.replace(r.mapFileCommentRegex,"")},r.generateMapFileComment=function(e,t){var r="sourceMappingURL="+e;return t&&t.multiline?"/*# "+r+" */":"//# "+r}}).call(this,e("buffer").Buffer)},{buffer:192,fs:191,path:546}],59:[function(e,t,r){t.exports=e("./src/node")},{"./src/node":61}],60:[function(e,t,r){function n(e){function t(){if(t.enabled){var e=t,n=+new Date,s=n-(i||n);e.diff=s,e.prev=i,e.curr=n,i=n;for(var a=new Array(arguments.length),o=0;o=0)return t}else{var r=i.toSetString(e);if(s.call(this._set,r))return this._set[r]}throw new Error('"'+e+'" is not in the set.')},n.prototype.at=function(e){if(e>=0&&e>>=5)>0&&(t|=32),r+=n.encode(t)}while(i>0);return r},r.decode=function(e,t,r){var i,s,a=e.length,o=0,u=0;do{if(t>=a)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(s=n.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));i=!!(32&s),o+=(s&=31)<>1;return 1==(1&e)?-t:t}(o),r.rest=t}},{"./base64":64}],64:[function(e,t,r){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");r.encode=function(e){if(0<=e&&e0?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}},{}],66:[function(e,t,r){function n(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=e("./util");n.prototype.unsortedForEach=function(e,t){this._array.forEach(e,t)},n.prototype.add=function(e){!function(e,t){var r=e.generatedLine,n=t.generatedLine,s=e.generatedColumn,a=t.generatedColumn;return n>r||n==r&&a>=s||i.compareByGeneratedPositionsInflated(e,t)<=0}(this._last,e)?(this._sorted=!1,this._array.push(e)):(this._last=e,this._array.push(e))},n.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},r.MappingList=n},{"./util":71}],67:[function(e,t,r){function n(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function i(e,t,r,s){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)).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};var r={source:t=this._sources.indexOf(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)).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":62,"./base64-vlq":63,"./mapping-list":66,"./util":71}],70:[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[o]=!0,null!=n&&this.add(n)}var i=e("./source-map-generator").SourceMapGenerator,s=e("./util"),a=/(\r?\n)/,o="$$$isSourceNode$$$";n.fromStringWithSourceMap=function(e,t,r){function i(e,t){if(null===e||void 0===e.source)o.add(t);else{var i=r?s.join(r,e.source):e.source;o.add(new n(e.originalLine,e.originalColumn,i,t,e.name))}}var o=new n,u=e.split(a),l=0,c=function(){function e(){return l=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},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])?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=o?"/":"."),s?(s.path=t,i(s)):t}function a(e){return e}function o(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 u(e,t){return e===t?0:e>t?1:-1}r.getArg=function(e,t,r){if(t in e)return e[t];if(3===arguments.length)return r;throw new Error('"'+t+'" is a required argument.')};var l=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,c=/^data:.+\,.+$/;r.urlParse=n,r.urlGenerate=i,r.normalize=s,r.join=function(e,t){""===e&&(e="."),""===t&&(t=".");var r=n(t),a=n(e);if(a&&(e=a.path||"/"),r&&!r.scheme)return a&&(r.scheme=a.scheme),i(r);if(r||t.match(c))return t;if(a&&!a.host&&!a.path)return a.host=t,i(a);var o="/"===t.charAt(0)?t:s(e.replace(/\/+$/,"")+"/"+t);return a?(a.path=o,i(a)):o},r.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(l)},r.relative=function(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)).match(/^([^\/]+:\/)?\/*$/))return t;++r}return Array(r+1).join("../")+t.substr(e.length+1)};var p=!("__proto__"in Object.create(null));r.toSetString=p?a:function(e){return o(e)?"$"+e:e},r.fromSetString=p?a:function(e){return o(e)?e.slice(1):e},r.compareByOriginalPositions=function(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:0!=(n=e.generatedLine-t.generatedLine)?n:e.name-t.name},r.compareByGeneratedPositionsDeflated=function(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:0!=(n=e.originalColumn-t.originalColumn)?n:e.name-t.name},r.compareByGeneratedPositionsInflated=function(e,t){var r=e.generatedLine-t.generatedLine;return 0!==r?r:0!=(r=e.generatedColumn-t.generatedColumn)?r:0!==(r=u(e.source,t.source))?r:0!=(r=e.originalLine-t.originalLine)?r:0!=(r=e.originalColumn-t.originalColumn)?r:u(e.name,t.name)}},{}],72:[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":68,"./lib/source-map-generator":69,"./lib/source-node":70}],73:[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/Documents/JSON/ajv/node_modules/regenerator"]],_from:"babel-core@>=6.18.2 <7.0.0",_id:"babel-core@6.26.0",_inCache:!0,_location:"/babel-core",_nodeVersion:"6.9.0",_npmOperationalInternal:{host:"s3://npm-registry-packages",tmp:"tmp/babel-core-6.26.0.tgz_1502898861183_0.43529116874560714"},_npmUser:{name:"hzoo",email:"hi@henryzoo.com"},_npmVersion:"4.6.1",_phantomChildren:{ms:"2.0.0"},_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.26.0.tgz",_shasum:"af32f78b31a6fcef119c87b0fd8d9753f03a0bb8",_shrinkwrap:null,_spec:"babel-core@^6.18.2",_where:"/Users/evgenypoberezkin/Documents/JSON/ajv/node_modules/regenerator",author:{name:"Sebastian McKenzie",email:"sebmck@gmail.com"},dependencies:{"babel-code-frame":"^6.26.0","babel-generator":"^6.26.0","babel-helpers":"^6.24.1","babel-messages":"^6.23.0","babel-register":"^6.26.0","babel-runtime":"^6.26.0","babel-template":"^6.26.0","babel-traverse":"^6.26.0","babel-types":"^6.26.0",babylon:"^6.18.0","convert-source-map":"^1.5.0",debug:"^2.6.8",json5:"^0.5.1",lodash:"^4.17.4",minimatch:"^3.0.4","path-is-absolute":"^1.0.1",private:"^0.1.7",slash:"^1.0.0","source-map":"^0.5.6"},description:"Babel compiler core.",devDependencies:{"babel-helper-fixtures":"^6.26.0","babel-helper-transform-fixture-test-runner":"^6.26.0","babel-polyfill":"^6.26.0"},directories:{},dist:{shasum:"af32f78b31a6fcef119c87b0fd8d9753f03a0bb8",tarball:"https://registry.npmjs.org/babel-core/-/babel-core-6.26.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:"thejameskyle",email:"me@thejameskyle.com"},{name:"sebmck",email:"sebmck@gmail.com"},{name:"danez",email:"daniel@tschinder.de"},{name:"hzoo",email:"hi@henryzoo.com"},{name:"loganfsmyth",email:"loganfsmyth@gmail.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.26.0"}},{}],74:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=n(e("trim-right")),a=/^[ \t]+$/,o=function(){function e(t){(0,i.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,s.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&&a.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")}function a(){this.space(),this.token("|"),this.space()}r.__esModule=!0,r.TypeParameterDeclaration=r.StringLiteralTypeAnnotation=r.NumericLiteralTypeAnnotation=r.GenericTypeAnnotation=r.ClassImplements=void 0,r.AnyTypeAnnotation=function(){this.word("any")},r.ArrayTypeAnnotation=function(e){this.print(e.elementType,e),this.token("["),this.token("]")},r.BooleanTypeAnnotation=function(){this.word("boolean")},r.BooleanLiteralTypeAnnotation=function(e){this.word(e.value?"true":"false")},r.NullLiteralTypeAnnotation=function(){this.word("null")},r.DeclareClass=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.word("class"),this.space(),this._interfaceish(e)},r.DeclareFunction=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.word("function"),this.space(),this.print(e.id,e),this.print(e.id.typeAnnotation.typeAnnotation,e),this.semicolon()},r.DeclareInterface=function(e){this.word("declare"),this.space(),this.InterfaceDeclaration(e)},r.DeclareModule=function(e){this.word("declare"),this.space(),this.word("module"),this.space(),this.print(e.id,e),this.space(),this.print(e.body,e)},r.DeclareModuleExports=function(e){this.word("declare"),this.space(),this.word("module"),this.token("."),this.word("exports"),this.print(e.typeAnnotation,e)},r.DeclareTypeAlias=function(e){this.word("declare"),this.space(),this.TypeAlias(e)},r.DeclareOpaqueType=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.OpaqueType(e)},r.DeclareVariable=function(e,t){u.isDeclareExportDeclaration(t)||(this.word("declare"),this.space()),this.word("var"),this.space(),this.print(e.id,e),this.print(e.id.typeAnnotation,e),this.semicolon()},r.DeclareExportDeclaration=function(e){this.word("declare"),this.space(),this.word("export"),this.space(),e.default&&(this.word("default"),this.space()),function(e){if(e.declaration){var t=e.declaration;this.print(t,e),u.isStatement(t)||this.semicolon()}else this.token("{"),e.specifiers.length&&(this.space(),this.printList(e.specifiers,e),this.space()),this.token("}"),e.source&&(this.space(),this.word("from"),this.space(),this.print(e.source,e)),this.semicolon()}.apply(this,arguments)},r.ExistentialTypeParam=function(){this.token("*")},r.FunctionTypeAnnotation=function(e,t){this.print(e.typeParameters,e),this.token("("),this.printList(e.params,e),e.rest&&(e.params.length&&(this.token(","),this.space()),this.token("..."),this.print(e.rest,e)),this.token(")"),"ObjectTypeCallProperty"===t.type||"DeclareFunction"===t.type?this.token(":"):(this.space(),this.token("=>")),this.space(),this.print(e.returnType,e)},r.FunctionTypeParam=function(e){this.print(e.name,e),e.optional&&this.token("?"),this.token(":"),this.space(),this.print(e.typeAnnotation,e)},r.InterfaceExtends=n,r._interfaceish=function(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)},r._variance=function(e){"plus"===e.variance?this.token("+"):"minus"===e.variance&&this.token("-")},r.InterfaceDeclaration=function(e){this.word("interface"),this.space(),this._interfaceish(e)},r.IntersectionTypeAnnotation=function(e){this.printJoin(e.types,e,{separator:i})},r.MixedTypeAnnotation=function(){this.word("mixed")},r.EmptyTypeAnnotation=function(){this.word("empty")},r.NullableTypeAnnotation=function(e){this.token("?"),this.print(e.typeAnnotation,e)};var o=e("./types");Object.defineProperty(r,"NumericLiteralTypeAnnotation",{enumerable:!0,get:function(){return o.NumericLiteral}}),Object.defineProperty(r,"StringLiteralTypeAnnotation",{enumerable:!0,get:function(){return o.StringLiteral}}),r.NumberTypeAnnotation=function(){this.word("number")},r.StringTypeAnnotation=function(){this.word("string")},r.ThisTypeAnnotation=function(){this.word("this")},r.TupleTypeAnnotation=function(e){this.token("["),this.printList(e.types,e),this.token("]")},r.TypeofTypeAnnotation=function(e){this.word("typeof"),this.space(),this.print(e.argument,e)},r.TypeAlias=function(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()},r.OpaqueType=function(e){this.word("opaque"),this.space(),this.word("type"),this.space(),this.print(e.id,e),this.print(e.typeParameters,e),e.supertype&&(this.token(":"),this.space(),this.print(e.supertype,e)),e.impltype&&(this.space(),this.token("="),this.space(),this.print(e.impltype,e)),this.semicolon()},r.TypeAnnotation=function(e){this.token(":"),this.space(),e.optional&&this.token("?"),this.print(e.typeAnnotation,e)},r.TypeParameter=function(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))},r.TypeParameterInstantiation=s,r.ObjectTypeAnnotation=function(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("}")},r.ObjectTypeCallProperty=function(e){e.static&&(this.word("static"),this.space()),this.print(e.value,e)},r.ObjectTypeIndexer=function(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)},r.ObjectTypeProperty=function(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)},r.ObjectTypeSpreadProperty=function(e){this.token("..."),this.print(e.argument,e)},r.QualifiedTypeIdentifier=function(e){this.print(e.qualification,e),this.token("."),this.print(e.id,e)},r.UnionTypeAnnotation=function(e){this.printJoin(e.types,e,{separator:a})},r.TypeCastExpression=function(e){this.token("("),this.print(e.expression,e),this.print(e.typeAnnotation,e),this.token(")")},r.VoidTypeAnnotation=function(){this.word("void")};var 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}(e("babel-types"));r.ClassImplements=n,r.GenericTypeAnnotation=n,r.TypeParameterDeclaration=s},{"./types":84,"babel-types":178}],79:[function(e,t,r){"use strict";function n(){this.space()}r.__esModule=!0;var i=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.JSXAttribute=function(e){this.print(e.name,e),e.value&&(this.token("="),this.print(e.value,e))},r.JSXIdentifier=function(e){this.word(e.name)},r.JSXNamespacedName=function(e){this.print(e.namespace,e),this.token(":"),this.print(e.name,e)},r.JSXMemberExpression=function(e){this.print(e.object,e),this.token("."),this.print(e.property,e)},r.JSXSpreadAttribute=function(e){this.token("{"),this.token("..."),this.print(e.argument,e),this.token("}")},r.JSXExpressionContainer=function(e){this.token("{"),this.print(e.expression,e),this.token("}")},r.JSXSpreadChild=function(e){this.token("{"),this.token("..."),this.print(e.expression,e),this.token("}")},r.JSXText=function(e){this.token(e.value)},r.JSXElement=function(e){var t=e.openingElement;if(this.print(t,e),!t.selfClosing){this.indent();for(var r=e.children,n=Array.isArray(r),s=0,r=n?r:(0,i.default)(r);;){var a;if(n){if(s>=r.length)break;a=r[s++]}else{if((s=r.next()).done)break;a=s.value}var o=a;this.print(o,e)}this.dedent(),this.print(e.closingElement,e)}},r.JSXOpeningElement=function(e){this.token("<"),this.print(e.name,e),e.attributes.length>0&&(this.space(),this.printJoin(e.attributes,e,{separator:n})),e.selfClosing?(this.space(),this.token("/>")):this.token(">")},r.JSXClosingElement=function(e){this.token("")},r.JSXEmptyExpression=function(){}},{"babel-runtime/core-js/get-iterator":120}],80:[function(e,t,r){"use strict";function n(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)}r.__esModule=!0,r.FunctionDeclaration=void 0,r._params=function(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)},r._method=function(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)},r.FunctionExpression=n,r.ArrowFunctionExpression=function(e){e.async&&(this.word("async"),this.space());var t=e.params[0];1===e.params.length&&i.isIdentifier(t)&&!function(e,t){return e.typeParameters||e.returnType||t.typeAnnotation||t.optional||t.trailingComments}(e,t)?this.print(t,e):this._params(e),this.space(),this.token("=>"),this.space(),this.print(e.body,e)};var 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}(e("babel-types"));r.FunctionDeclaration=n},{"babel-types":178}],81:[function(e,t,r){"use strict";function n(e){if(e.declaration){var t=e.declaration;this.print(t,e),i.isStatement(t)||this.semicolon()}else{"type"===e.exportKind&&(this.word("type"),this.space());for(var r=e.specifiers.slice(0),n=!1;;){var s=r[0];if(!i.isExportDefaultSpecifier(s)&&!i.isExportNamespaceSpecifier(s))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()}}r.__esModule=!0,r.ImportSpecifier=function(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))},r.ImportDefaultSpecifier=function(e){this.print(e.local,e)},r.ExportDefaultSpecifier=function(e){this.print(e.exported,e)},r.ExportSpecifier=function(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))},r.ExportNamespaceSpecifier=function(e){this.token("*"),this.space(),this.word("as"),this.space(),this.print(e.exported,e)},r.ExportAllDeclaration=function(e){this.word("export"),this.space(),this.token("*"),this.space(),this.word("from"),this.space(),this.print(e.source,e),this.semicolon()},r.ExportNamedDeclaration=function(){this.word("export"),this.space(),n.apply(this,arguments)},r.ExportDefaultDeclaration=function(){this.word("export"),this.space(),this.word("default"),this.space(),n.apply(this,arguments)},r.ImportDeclaration=function(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(!i.isImportDefaultSpecifier(r)&&!i.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()},r.ImportNamespaceSpecifier=function(e){this.token("*"),this.space(),this.word("as"),this.space(),this.print(e.local,e)};var 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}(e("babel-types"))},{"babel-types":178}],82:[function(e,t,r){"use strict";function n(e){return a.isStatement(e.body)?n(e.body):e}function i(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()}}r.__esModule=!0,r.ThrowStatement=r.BreakStatement=r.ReturnStatement=r.ContinueStatement=r.ForAwaitStatement=r.ForOfStatement=r.ForInStatement=void 0;var s=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.WithStatement=function(e){this.word("with"),this.space(),this.token("("),this.print(e.object,e),this.token(")"),this.printBlock(e)},r.IfStatement=function(e){this.word("if"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.space();var t=e.alternate&&a.isIfStatement(n(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))},r.ForStatement=function(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)},r.WhileStatement=function(e){this.word("while"),this.space(),this.token("("),this.print(e.test,e),this.token(")"),this.printBlock(e)},r.DoWhileStatement=function(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()},r.LabeledStatement=function(e){this.print(e.label,e),this.token(":"),this.space(),this.print(e.body,e)},r.TryStatement=function(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))},r.CatchClause=function(e){this.word("catch"),this.space(),this.token("("),this.print(e.param,e),this.token(")"),this.space(),this.print(e.body,e)},r.SwitchStatement=function(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("}")},r.SwitchCase=function(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}))},r.DebuggerStatement=function(){this.word("debugger"),this.semicolon()},r.VariableDeclaration=function(e,t){this.word(e.kind),this.space();var r=!1;if(!a.isFor(t))for(var n=e.declarations,i=Array.isArray(n),o=0,n=i?n:(0,s.default)(n);;){var u;if(i){if(o>=n.length)break;u=n[o++]}else{if((o=n.next()).done)break;u=o.value}u.init&&(r=!0)}var l=void 0;r&&(l="const"===e.kind?function(){if(this.token(","),this.newline(),this.endsWith("\n"))for(var e=0;e<6;e++)this.space(!0)}:function(){if(this.token(","),this.newline(),this.endsWith("\n"))for(var e=0;e<4;e++)this.space(!0)}),this.printList(e.declarations,e,{separator:l}),(!a.isFor(t)||t.left!==e&&t.init!==e)&&this.semicolon()},r.VariableDeclarator=function(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))};var 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}(e("babel-types")),o=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=o("in"),r.ForOfStatement=o("of"),r.ForAwaitStatement=o("await"),r.ContinueStatement=i("continue"),r.ReturnStatement=i("return","argument"),r.BreakStatement=i("break"),r.ThrowStatement=i("throw","argument")},{"babel-runtime/core-js/get-iterator":120,"babel-types":178}],83:[function(e,t,r){"use strict";r.__esModule=!0,r.TaggedTemplateExpression=function(e){this.print(e.tag,e),this.print(e.quasi,e)},r.TemplateElement=function(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)},r.TemplateLiteral=function(e){for(var t=e.quasis,r=0;r0&&this.space(),this.print(i,e),n1&&void 0!==arguments[1]?arguments[1]:{},a=arguments[2];(0,i.default)(this,t);var c=r.tokens||[],p=function(e,t,r){var n=" ";if(e&&"string"==typeof e){var i=(0,o.default)(e).indent;i&&" "!==i&&(n=i)}var s={auxiliaryCommentBefore:t.auxiliaryCommentBefore,auxiliaryCommentAfter:t.auxiliaryCommentAfter,shouldPrintComment:t.shouldPrintComment,retainLines:t.retainLines,retainFunctionParens:t.retainFunctionParens,comments:null==t.comments||t.comments,compact:t.compact,minified:t.minified,concise:t.concise,quotes:t.quotes||function(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"}(e,r),jsonCompatibleStrings:t.jsonCompatibleStrings,indent:{adjustMultilineComment:!0,style:n,base:0},flowCommaSeparator:t.flowCommaSeparator};return s.minified?(s.compact=!0,s.shouldPrintComment=s.shouldPrintComment||function(){return s.comments}):s.shouldPrintComment=s.shouldPrintComment||function(e){return s.comments||e.indexOf("@license")>=0||e.indexOf("@preserve")>=0},"auto"===s.compact&&(s.compact=e.length>5e5,s.compact&&console.error("[BABEL] "+l.get("codeGeneratorDeopt",t.filename,"500KB"))),s.compact&&(s.indent.adjustMultilineComment=!1),s}(a,n,c),h=n.sourceMaps?new u.default(n,a):null,f=(0,s.default)(this,e.call(this,p,h,c));return f.ast=r,f}return(0,a.default)(t,e),t.prototype.generate=function(){return e.prototype.generate.call(this,this.ast)},t}(n(e("./printer")).default);r.CodeGenerator=function(){function e(t,r,n){(0,i.default)(this,e),this._generator=new c(t,r,n)}return e.prototype.generate=function(){return this._generator.generate()},e}()},{"./printer":89,"./source-map":90,"babel-messages":110,"babel-runtime/helpers/classCallCheck":134,"babel-runtime/helpers/inherits":135,"babel-runtime/helpers/possibleConstructorReturn":137,"detect-indent":309}],86:[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,c.default)(e),i=Array.isArray(n),s=0,n=i?n:(0,l.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a,u=f.FLIPPED_ALIAS_KEYS[o];if(u)for(var p=u,h=Array.isArray(p),d=0,p=h?p:(0,l.default)(p);;){var m;if(h){if(d>=p.length)break;m=p[d++]}else{if((d=p.next()).done)break;m=d.value}t(m,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!!f.isCallExpression(e)||!!f.isMemberExpression(e)&&(o(e.object)||!e.computed&&o(e.property))}function u(e,t,r){if(!e)return 0;f.isExpressionStatement(e)&&(e=e.expression);var n=a(m,e,t);if(!n){var i=a(y,e,t);if(i)for(var s=0;s1&&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],l=e[--a];a>0;){if(u.isExpressionStatement(l,{expression:o})||u.isTaggedTemplateExpression(l)||s&&u.isExportDefaultDeclaration(l,{declaration:o})||n&&u.isArrowFunctionExpression(l,{body:o}))return!0;if(!(u.isCallExpression(l,{callee:o})||u.isSequenceExpression(l)&&l.expressions[0]===o||u.isMemberExpression(l,{object:o})||u.isConditional(l,{test:o})||u.isBinary(l,{left:o})||u.isAssignmentExpression(l,{left:o})))return!1;o=l,l=e[--a]}return!1}r.__esModule=!0,r.AwaitExpression=r.FunctionTypeAnnotation=void 0,r.NullableTypeAnnotation=n,r.UpdateExpression=function(e,t){return u.isMemberExpression(t)&&t.object===e},r.ObjectExpression=function(e,t,r){return o(r,{considerArrow:!0})},r.DoExpression=function(e,t,r){return o(r)},r.Binary=function(e,t){if((u.isCallExpression(t)||u.isNewExpression(t))&&t.callee===e||u.isUnaryLike(t)||u.isMemberExpression(t)&&t.object===e||u.isAwaitExpression(t))return!0;if(u.isBinary(t)){var r=t.operator,n=l[r],i=e.operator,s=l[i];if(n===s&&t.right===e&&!u.isLogicalExpression(t)||n>s)return!0}return!1},r.BinaryExpression=function(e,t){return"in"===e.operator&&(u.isVariableDeclarator(t)||u.isFor(t))},r.SequenceExpression=function(e,t){return!(u.isForStatement(t)||u.isThrowStatement(t)||u.isReturnStatement(t)||u.isIfStatement(t)&&t.test===e||u.isWhileStatement(t)&&t.test===e||u.isForInStatement(t)&&t.right===e||u.isSwitchStatement(t)&&t.discriminant===e||u.isExpressionStatement(t)&&t.expression===e)},r.YieldExpression=i,r.ClassExpression=function(e,t,r){return o(r,{considerDefaultExports:!0})},r.UnaryLike=s,r.FunctionExpression=function(e,t,r){return o(r,{considerDefaultExports:!0})},r.ArrowFunctionExpression=function(e,t){return!!(u.isExportDeclaration(t)||u.isBinaryExpression(t)||u.isLogicalExpression(t)||u.isUnaryExpression(t)||u.isTaggedTemplateExpression(t))||s(e,t)},r.ConditionalExpression=a,r.AssignmentExpression=function(e){return!!u.isObjectPattern(e.left)||a.apply(void 0,arguments)};var 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}(e("babel-types")),l={"||":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=i},{"babel-types":178}],88:[function(e,t,r){"use strict";function n(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return o.isMemberExpression(e)?(n(e.object,t),e.computed&&n(e.property,t)):o.isBinary(e)||o.isAssignmentExpression(e)?(n(e.left,t),n(e.right,t)):o.isCallExpression(e)?(t.hasCall=!0,n(e.callee,t)):o.isFunction(e)?t.hasFunction=!0:o.isIdentifier(e)&&(t.hasHelper=t.hasHelper||i(e.callee)),t}function i(e){return o.isMemberExpression(e)?i(e.object)||i(e.property):o.isIdentifier(e)?"require"===e.name||"_"===e.name[0]:o.isCallExpression(e)?i(e.callee):!(!o.isBinary(e)&&!o.isAssignmentExpression(e))&&(o.isIdentifier(e.left)&&i(e.left)||i(e.right))}function s(e){return o.isLiteral(e)||o.isObjectExpression(e)||o.isArrayExpression(e)||o.isIdentifier(e)||o.isMemberExpression(e)}var a=function(e){return e&&e.__esModule?e:{default:e}}(e("lodash/map")),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}(e("babel-types"));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(o.isFunction(e.left)||o.isFunction(e.right))return{after:!0}},Literal:function(e){if("use strict"===e.value)return{after:!0}},CallExpression:function(e){if(o.isFunction(e.callee)||i(e))return{before:!0,after:!0}},VariableDeclaration:function(e){for(var t=0;t0?new g.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,f.default)(+e)&&!E.test(e)&&!v.test(e)&&!x.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)this.space();else 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)this.space();else{var s=0;if(null!=t.start&&!t._ignoreUserWhitespace&&this._whitespace)if(e){var a=t.leadingComments,o=a&&(0,p.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,h.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=y.needsWhitespaceAfter;e&&(c=y.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,o.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;this._printComment(s)}},e}();r.default=A;for(var D=[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")],C=0;C=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]).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=i,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134}],92:[function(e,t,r){arguments[4][62][0].apply(r,arguments)},{"./util":101,dup:62}],93:[function(e,t,r){arguments[4][63][0].apply(r,arguments)},{"./base64":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)},{dup:65}],96:[function(e,t,r){arguments[4][66][0].apply(r,arguments)},{"./util":101,dup:66}],97:[function(e,t,r){arguments[4][67][0].apply(r,arguments)},{dup:67}],98:[function(e,t,r){arguments[4][68][0].apply(r,arguments)},{"./array-set":92,"./base64-vlq":93,"./binary-search":95,"./quick-sort":97,"./util":101,dup:68}],99:[function(e,t,r){arguments[4][69][0].apply(r,arguments)},{"./array-set":92,"./base64-vlq":93,"./mapping-list":96,"./util":101,dup:69}],100:[function(e,t,r){arguments[4][70][0].apply(r,arguments)},{"./source-map-generator":99,"./util":101,dup:70}],101:[function(e,t,r){arguments[4][71][0].apply(r,arguments)},{dup:71}],102:[function(e,t,r){arguments[4][72][0].apply(r,arguments)},{"./lib/source-map-consumer":98,"./lib/source-map-generator":99,"./lib/source-node":100,dup:72}],103:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=u.objectExpression([]);return(0,s.default)(e).forEach(function(r){var n=e[r],i=u.objectExpression([]),a=u.objectProperty(n._key,i,n._computed);(0,s.default)(n).forEach(function(e){var t=n[e];if("_"!==e[0]){var r=t;(u.isClassMethod(t)||u.isClassProperty(t))&&(t=t.value);var s=u.objectProperty(u.identifier(e),t);u.inheritsComments(s,r),u.removeComments(r),i.properties.push(s)}}),t.properties.push(a)}),t}r.__esModule=!0;var s=n(e("babel-runtime/core-js/object/keys"));r.push=function(e,t,r,n,i){var s=u.toKeyAlias(t),l={};if((0,o.default)(e,s)&&(l=e[s]),e[s]=l,l._inherits=l._inherits||[],l._inherits.push(t),l._key=t.key,t.computed&&(l._computed=!0),t.decorators){var c=l.decorators=l.decorators||u.arrayExpression([]);c.elements=c.elements.concat(t.decorators.map(function(e){return e.expression}).reverse())}if(l.value||l.initializer)throw n.buildCodeFrameError(t,"Key conflict with sibling node");var p=void 0,h=void 0;(u.isObjectProperty(t)||u.isObjectMethod(t)||u.isClassMethod(t))&&(p=u.toComputedKey(t,t.key)),u.isObjectProperty(t)||u.isClassProperty(t)?h=t.value:(u.isObjectMethod(t)||u.isClassMethod(t))&&((h=u.functionExpression(null,t.params,t.body,t.generator,t.async)).returnType=t.returnType);var f=function(e){return!u.isClassMethod(e)&&!u.isObjectMethod(e)||"get"!==e.kind&&"set"!==e.kind?"value":e.kind}(t);return r&&"value"===f||(r=f),i&&u.isStringLiteral(p)&&("value"===r||"initializer"===r)&&u.isFunctionExpression(h)&&(h=(0,a.default)({id:p,node:h,scope:i})),h&&(u.inheritsComments(h,t),l[r]=h),l},r.hasComputed=function(e){for(var t in e)if(e[t]._computed)return!0;return!1},r.toComputedObjectFromClass=function(e){for(var t=u.arrayExpression([]),r=0;r1&&void 0!==arguments[1]&&arguments[1];(0,o.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 p.callExpression(this.file.addHelper("set"),[a(this.getObjectRef(),this.isStatic),r?e:p.stringLiteral(e.name),t,p.thisExpression()])},e.prototype.getSuperProperty=function(e,t){return p.callExpression(this.file.addHelper("get"),[a(this.getObjectRef(),this.isStatic),t?e:p.stringLiteral(e.name),p.thisExpression()])},e.prototype.replace=function(){this.methodPath.traverse(f,this)},e.prototype.getLooseSuperProperty=function(e,t){var r=this.methodNode,n=this.superRef||p.identifier("Function");return t.property===e?void 0:p.isCallExpression(t,{callee:e})?void 0:p.isMemberExpression(t)&&!r.static?p.memberExpression(n,p.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(!p.isMemberExpression(r))return;if(!p.isSuper(r.object))return;return p.appendToMemberExpression(r,p.identifier("call")),t.arguments.unshift(p.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"),[p.variableDeclaration("var",[p.variableDeclarator(e,r.left)]),p.expressionStatement(p.assignmentExpression("=",r.left,p.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,a=e.node;if(function(e,t){return!!p.isSuper(e)&&!p.isMemberExpression(t,{computed:!1})&&!p.isCallExpression(t,{callee:e})}(a,i))throw e.buildCodeFrameError(c.get("classesIllegalBareSuper"));if(p.isCallExpression(a)){var o=a.callee;if(p.isSuper(o))return;s(o)&&(t=o.property,r=o.computed,n=a.arguments)}else if(p.isMemberExpression(a)&&p.isSuper(a.object))t=a.property,r=a.computed;else{if(p.isUpdateExpression(a)&&s(a.argument)){var u=p.binaryExpression(a.operator[0],a.argument,p.numericLiteral(1));if(a.prefix)return this.specHandleAssignmentExpression(null,e,u);var l=e.scope.generateUidIdentifier("ref");return this.specHandleAssignmentExpression(l,e,u).concat(p.expressionStatement(l))}if(p.isAssignmentExpression(a)&&s(a.left))return this.specHandleAssignmentExpression(null,e,a)}if(t){var h=this.getSuperProperty(t,r);return n?this.optimiseCall(h,n):h}},e.prototype.optimiseCall=function(e,t){var r=p.thisExpression();return r[h]=!0,(0,l.default)(e,r,t)},e}();r.default=d,t.exports=r.default},{"babel-helper-optimise-call-expression":106,"babel-messages":110,"babel-runtime/core-js/symbol":129,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],108:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-template")),i={};r.default=i,i.typeof=(0,n.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'),i.jsx=(0,n.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'),i.asyncIterator=(0,n.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'),i.asyncGenerator=(0,n.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'),i.asyncGeneratorDelegate=(0,n.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'),i.asyncToGenerator=(0,n.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'),i.classCallCheck=(0,n.default)('\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError("Cannot call a class as a function");\n }\n });\n'),i.createClass=(0,n.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'),i.defineEnumerableProperties=(0,n.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'),i.defaults=(0,n.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"),i.defineProperty=(0,n.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"),i.extends=(0,n.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"),i.get=(0,n.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'),i.inherits=(0,n.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'),i.instanceof=(0,n.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'),i.interopRequireDefault=(0,n.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"),i.interopRequireWildcard=(0,n.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"),i.newArrowCheck=(0,n.default)('\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError("Cannot instantiate an arrow function");\n }\n });\n'),i.objectDestructuringEmpty=(0,n.default)('\n (function (obj) {\n if (obj == null) throw new TypeError("Cannot destructure undefined");\n });\n'),i.objectWithoutProperties=(0,n.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"),i.possibleConstructorReturn=(0,n.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'),i.selfGlobal=(0,n.default)('\n typeof global === "undefined" ? self : global\n'),i.set=(0,n.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'),i.slicedToArray=(0,n.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'),i.slicedToArrayLoose=(0,n.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'),i.taggedTemplateLiteral=(0,n.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"),i.taggedTemplateLiteralLoose=(0,n.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"),i.temporalRef=(0,n.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'),i.temporalUndefined=(0,n.default)("\n ({})\n"),i.toArray=(0,n.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"),i.toConsumableArray=(0,n.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":139}],109:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=a.default[e];if(!t)throw new ReferenceError("Unknown helper "+e);return t().expression}r.__esModule=!0,r.list=void 0;var s=n(e("babel-runtime/core-js/object/keys"));r.get=i;var a=n(e("./helpers"));r.list=(0,s.default)(a.default).map(function(e){return e.replace(/^_/,"")}).filter(function(e){return"__esModule"!==e});r.default=i},{"./helpers":108,"babel-runtime/core-js/object/keys":127}],110:[function(e,t,r){"use strict";function n(e){return e.map(function(e){if(null!=e&&e.inspect)return e.inspect();try{return(0,i.default)(e)||e+""}catch(t){return s.inspect(e)}})}r.__esModule=!0,r.MESSAGES=void 0;var i=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/json/stringify"));r.get=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),s=1;s4&&void 0!==arguments[4]&&arguments[4];if(t||(t=e.node),!h.isFor(r))for(var s=0;s0&&e.traverse(g,t),e.skip()}},p.visitor]),g=c.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)}}},p.visitor]),b={enter:function(e,t){var r=e.node;e.parent;if(e.isForStatement()){if(a(r.init)){var n=t.pushDeclar(r.init);1===n.length?r.init=n[0]:r.init=h.sequenceExpression(n)}}else if(e.isFor())a(r.left)&&(t.pushDeclar(r.left),r.left=r.left.declarations[0].id);else if(a(r))e.replaceWithMultiple(t.pushDeclar(r).map(function(e){return h.expressionStatement(e)}));else if(e.isFunction())return e.skip()}},v={LabeledStatement:function(e,t){var r=e.node;t.innerLabels.push(r.label.name)}},x={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)}}},E={Loop:function(e,t){var r=t.ignoreLabeless;t.ignoreLabeless=!0,e.traverse(E,t),t.ignoreLabeless=r,e.skip()},Function:function(e){e.skip()},SwitchCase:function(e,t){var r=t.inSwitchCase;t.inSwitchCase=!0,e.traverse(E,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=function(e){return h.isBreakStatement(e)?"break":h.isContinueStatement(e)?"continue":void 0}(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(h.isBreakStatement(r)&&h.isSwitchCase(n))return}t.hasBreakContinue=!0,t.map[a]=r,s=h.stringLiteral(a)}e.isReturnStatement()&&(t.hasReturn=!0,s=h.objectExpression([h.objectProperty(h.identifier("v"),r.argument||i.buildUndefinedNode())])),s&&((s=h.returnStatement(s))[this.LOOP_IGNORE]=!0,e.skip(),e.replaceWith(h.inherits(s,r)))}}},A=function(){function e(t,r,n,i,s){(0,l.default)(this,e),this.parent=n,this.scope=i,this.file=s,this.blockPath=r,this.block=r.node,this.outsideLetReferences=(0,u.default)(null),this.hasLetReferences=!1,this.letReferences=(0,u.default)(null),this.body=[],t&&(this.loopParent=t.parent,this.loopLabel=h.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(h.isFunction(this.parent)||h.isProgram(this.block))this.updateScopeInfo();else if(this.hasLetReferences)return t?this.wrapClosure():this.remap(),this.updateScopeInfo(t),this.loopLabel&&!h.isLabeledStatement(this.loopParent)?h.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,f.default)(t),s=(0,f.default)(t),a=this.blockPath.isSwitchStatement(),o=h.functionExpression(null,i,h.blockStatement(a?[e]:e.body));o.shadow=!0,this.addContinuations(o);var u=o;this.loop&&(u=this.scope.generateUidIdentifier("loop"),this.loopPath.insertBefore(h.variableDeclaration("var",[h.variableDeclarator(u,o)])));var l=h.callExpression(u,s),p=this.scope.generateUidIdentifier("ret");c.default.hasType(o.body,this.scope,"YieldExpression",h.FUNCTION_TYPES)&&(o.generator=!0,l=h.yieldExpression(l,!0));c.default.hasType(o.body,this.scope,"AwaitExpression",h.FUNCTION_TYPES)&&(o.async=!0,l=h.awaitExpression(l)),this.buildClosure(p,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(h.expressionStatement(t))},e.prototype.addContinuations=function(e){var t={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(e,x,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=c.push(i,e,r,this.file,n);return t&&(s.enumerable=h.booleanLiteral(!0)),s},e.prototype.constructorMeMaybe=function(){for(var e=!1,t=this.path.get("body.body"),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()).done)break;i=n.value}if(e=i.equals("kind","constructor"))break}if(!e){var a=void 0,o=void 0;if(this.isDerived){var u=f().expression;a=u.params,o=u.body}else a=[],o=h.blockStatement([]);this.path.get("body").unshiftContainer("body",h.classMethod("constructor",h.identifier("constructor"),a,o))}},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),h.inherits(this.constructor,this.userConstructor),h.inherits(e,this.userConstructor.body)}this.pushDescriptors()},e.prototype.pushBody=function(){for(var e=this.path.get("body.body"),t=Array.isArray(e),r=0,e=t?e:(0,s.default)(e);;){var n;if(t){if(r>=e.length)break;n=e[r++]}else{if((r=e.next()).done)break;n=r.value}var i=n,a=i.node;if(i.isClassProperty())throw i.buildCodeFrameError("Missing class properties transform.");if(a.decorators)throw i.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");if(h.isClassMethod(a)){var o="constructor"===a.kind;if(o&&(i.traverse(m,this),!this.hasBareSuper&&this.isDerived))throw i.buildCodeFrameError("missing super() call in constructor");var l=new u.default({forceSuperMemoisation:o,methodPath:i,methodNode:a,objectRef:this.classRef,superRef:this.superName,isStatic:a.static,isLoose:this.isLoose,scope:this.scope,file:this.file},!0);l.replace(),o?this.pushConstructor(l,a,i):this.pushMethod(a,i)}}},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=c.toClassObject(this.instanceMutatorMap)),this.hasStaticDescriptors&&(r=c.toClassObject(this.staticMutatorMap)),t||r){t&&(t=c.toComputedObjectFromClass(t)),r&&(r=c.toComputedObjectFromClass(r));var n=h.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()).done)break;c=l.value}var p=c;this.wrapSuperCall(p,i,a,r),n&&p.find(function(e){return e===t||(e.isLoop()||e.isConditional()?(n=!1,!0):void 0)})}for(var f=this.superThises,d=Array.isArray(f),m=0,f=d?f:(0,s.default)(f);;){var g;if(d){if(m>=f.length)break;g=f[m++]}else{if((m=f.next()).done)break;g=m.value}g.replaceWith(a)}var b=function(t){return h.callExpression(e.file.addHelper("possibleConstructorReturn"),[a].concat(t||[]))},v=r.get("body");v.length&&!v.pop().isReturnStatement()&&r.pushContainer("body",h.returnStatement(n?a:b()));for(var x=this.superReturns,E=Array.isArray(x),A=0,x=E?x:(0,s.default)(x);;){var D;if(E){if(A>=x.length)break;D=x[A++]}else{if((A=x.next()).done)break;D=A.value}var C=D;if(C.node.argument){var S=C.scope.generateDeclaredUidIdentifier("ret");C.get("argument").replaceWithMultiple([h.assignmentExpression("=",S,C.node.argument),b(S)])}else C.get("argument").replaceWith(b())}}},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,h.inheritsComments(n,t),n._ignoreUserWhitespace=!0,n.params=t.params,h.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(h.expressionStatement(h.callExpression(this.file.addHelper("inherits"),[this.classRef,this.superName]))))},e}();r.default=g,t.exports=r.default},{"babel-helper-define-map":103,"babel-helper-optimise-call-expression":106,"babel-helper-replace-supers":107,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-template":139,"babel-traverse":143,"babel-types":178}],119:[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},{}],120:[function(e,t,r){t.exports={default:e("core-js/library/fn/get-iterator"),__esModule:!0}},{"core-js/library/fn/get-iterator":194}],121:[function(e,t,r){t.exports={default:e("core-js/library/fn/json/stringify"),__esModule:!0}},{"core-js/library/fn/json/stringify":195}],122:[function(e,t,r){t.exports={default:e("core-js/library/fn/map"),__esModule:!0}},{"core-js/library/fn/map":196}],123:[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":197}],124:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/assign"),__esModule:!0}},{"core-js/library/fn/object/assign":198}],125:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/create"),__esModule:!0}},{"core-js/library/fn/object/create":199}],126:[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":200}],127:[function(e,t,r){t.exports={default:e("core-js/library/fn/object/keys"),__esModule:!0}},{"core-js/library/fn/object/keys":201}],128:[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":202}],129:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol"),__esModule:!0}},{"core-js/library/fn/symbol":204}],130:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol/for"),__esModule:!0}},{"core-js/library/fn/symbol/for":203}],131:[function(e,t,r){t.exports={default:e("core-js/library/fn/symbol/iterator"),__esModule:!0}},{"core-js/library/fn/symbol/iterator":205}],132:[function(e,t,r){t.exports={default:e("core-js/library/fn/weak-map"),__esModule:!0}},{"core-js/library/fn/weak-map":206}],133:[function(e,t,r){t.exports={default:e("core-js/library/fn/weak-set"),__esModule:!0}},{"core-js/library/fn/weak-set":207}],134:[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")}},{}],135:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("../core-js/object/set-prototype-of")),s=n(e("../core-js/object/create")),a=n(e("../helpers/typeof"));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,a.default)(t)));e.prototype=(0,s.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i.default?(0,i.default)(e,t):e.__proto__=t)}},{"../core-js/object/create":125,"../core-js/object/set-prototype-of":128,"../helpers/typeof":138}],136:[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}},{}],137:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("../helpers/typeof"));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,n.default)(t))&&"function"!=typeof t?e:t}},{"../helpers/typeof":138}],138:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("../core-js/symbol/iterator")),s=n(e("../core-js/symbol")),a="function"==typeof s.default&&"symbol"==typeof i.default?function(e){return typeof e}:function(e){return e&&"function"==typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":typeof e};r.default="function"==typeof s.default&&"symbol"===a(i.default)?function(e){return void 0===e?"undefined":a(e)}:function(e){return e&&"function"==typeof s.default&&e.constructor===s.default&&e!==s.default.prototype?"symbol":void 0===e?"undefined":a(e)}},{"../core-js/symbol":129,"../core-js/symbol/iterator":131}],139:[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}}r.__esModule=!0;var s=i(e("babel-runtime/core-js/symbol"));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,o.default)({allowReturnOutsideFunction:!0,allowSuperOutsideMethod:!0,preserveComments:!1},t);var n=function(){var i=void 0;try{i=c.parse(e,t),i=l.default.removeProperties(i,{preserveComments:t.preserveComments}),l.default.cheap(i,function(e){e[h]=!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;r1?r.body:r.body[0]}(n(),t)}};var a=i(e("lodash/cloneDeep")),o=i(e("lodash/assign")),u=i(e("lodash/has")),l=i(e("babel-traverse")),c=n(e("babylon")),p=n(e("babel-types")),h="_fromTemplate",f=(0,s.default)(),d={noScope:!0,enter:function(e,t){var r=e.node;if(r[f])return e.skip();p.isExpressionStatement(r)&&(r=r.expression);var n=void 0;if(p.isIdentifier(r)&&r[h])if((0,u.default)(t[0],r.name))n=t[0][r.name];else if("$"===r.name[0]){var i=+r.name.slice(1);t[i]&&(n=t[i])}null===n&&e.remove(),n&&(n[f]=!0,e.replaceInline(n))},exit:function(e){var t=e.node;t.loc||l.default.clearNode(t)}};t.exports=r.default},{"babel-runtime/core-js/symbol":129,"babel-traverse":143,"babel-types":178,babylon:186,"lodash/assign":488,"lodash/cloneDeep":492,"lodash/has":504}],140:[function(e,t,r){"use strict";function n(){r.path=a=new s.default}function i(){r.scope=o=new s.default}r.__esModule=!0,r.scope=r.path=void 0;var s=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/weak-map"));r.clear=function(){n(),i()},r.clearPath=n,r.clearScope=i;var a=r.path=new s.default,o=r.scope=new s.default},{"babel-runtime/core-js/weak-map":132}],141:[function(e,t,r){(function(n){"use strict";function i(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var s=i(e("babel-runtime/core-js/get-iterator")),a=i(e("babel-runtime/helpers/classCallCheck")),o=i(e("./path")),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}(e("babel-types")),l="test"===n.env.NODE_ENV,c=function(){function e(t,r,n,i){(0,a.default)(this,e),this.queue=null,this.parentPath=i,this.scope=t,this.state=n,this.opts=r}return e.prototype.shouldVisit=function(e){var t=this.opts;if(t.enter||t.exit)return!0;if(t[e.type])return!0;var r=u.VISITOR_KEYS[e.type];if(!r||!r.length)return!1;for(var n=r,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()).done)break;o=a.value}if(e[o])return!0}return!1},e.prototype.create=function(e,t,r,n){return o.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[a++]}else{if((a=n.next()).done)break;o=a.value}var u=o;if(u.resync(),0!==u.contexts.length&&u.contexts[u.contexts.length-1]===this||u.pushContext(this),null!==u.key&&(l&&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 c=e,p=Array.isArray(c),h=0,c=p?c:(0,s.default)(c);;){var f;if(p){if(h>=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}f.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=c,t.exports=r.default}).call(this,e("_process"))},{"./path":150,_process:550,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],142:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/helpers/classCallCheck"));r.default=function e(t,r){(0,n.default)(this,e),this.file=t,this.options=r},t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134}],143:[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(f.get("traverseNeedsParent",e.type));h.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=i(e("babel-runtime/core-js/get-iterator")),u=e("./path");Object.defineProperty(r,"NodePath",{enumerable:!0,get:function(){return i(u).default}});var l=e("./scope");Object.defineProperty(r,"Scope",{enumerable:!0,get:function(){return i(l).default}});var c=e("./hub");Object.defineProperty(r,"Hub",{enumerable:!0,get:function(){return i(c).default}}),r.default=s;var p=i(e("./context")),h=n(e("./visitors")),f=n(e("babel-messages")),d=i(e("lodash/includes")),m=n(e("babel-types")),y=n(e("./cache"));r.visitors=h,s.visitors=h,s.verify=h.verify,s.explode=h.explode,s.NodePath=e("./path"),s.Scope=e("./scope"),s.Hub=e("./hub"),s.cheap=function(e,t){return m.traverseFast(e,t)},s.node=function(e,t,r,n,i,s){var a=m.VISITOR_KEYS[e.type];if(a)for(var u=new p.default(r,t,n,i),l=a,c=Array.isArray(l),h=0,l=c?l:(0,o.default)(l);;){var f;if(c){if(h>=l.length)break;f=l[h++]}else{if((h=l.next()).done)break;f=h.value}var d=f;if((!s||!s[d])&&u.visit(e,d))return}},s.clearNode=function(e,t){m.removeProperties(e,t),y.path.delete(e)},s.removeProperties=function(e,t){return m.traverseFast(e,s.clearNode,t),e},s.hasType=function(e,t,r,n){if((0,d.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(){y.clear()}).clearPath=y.clearPath,s.clearCache.clearScope=y.clearScope,s.copyCache=function(e,t){y.path.has(e)&&y.path.set(t,y.path.get(e))}},{"./cache":140,"./context":141,"./hub":142,"./path":150,"./scope":162,"./visitors":164,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-types":178,"lodash/includes":507}],144:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.findParent=function(e){for(var t=this;t=t.parentPath;)if(e(t))return t;return null},r.find=function(e){var t=this;do{if(e(t))return t}while(t=t.parentPath);return null},r.getFunctionParent=function(){return this.findParent(function(e){return e.isFunction()||e.isProgram()})},r.getStatementParent=function(){var e=this;do{if(Array.isArray(e.container))return e}while(e=e.parentPath)},r.getEarliestCommonAncestorFrom=function(e){return this.getDeepestCommonAncestorFrom(e,function(e,t,r){for(var n=void 0,a=s.VISITOR_KEYS[e.type],o=r,u=Array.isArray(o),l=0,o=u?o:(0,i.default)(o);;){var c;if(u){if(l>=o.length)break;c=o[l++]}else{if((l=o.next()).done)break;c=l.value}var p=c[t+1];n?p.listKey&&n.listKey===p.listKey&&p.keya.indexOf(p.parentKey)&&(n=p):n=p}return n})},r.getDeepestCommonAncestorFrom=function(e,t){var r=this;if(!e.length)return this;if(1===e.length)return e[0];var n=1/0,s=void 0,a=void 0,o=e.map(function(e){var t=[];do{t.unshift(e)}while((e=e.parentPath)&&e!==r);return t.length=p.length)break;d=p[f++]}else{if((f=p.next()).done)break;d=f.value}if(d[l]!==c)break e}s=l,a=c}if(a)return t?t(a,s,o):a;throw new Error("Couldn't find intersection")},r.getAncestry=function(){var e=this,t=[];do{t.push(e)}while(e=e.parentPath);return t},r.isAncestor=function(e){return e.isDescendant(this)},r.isDescendant=function(e){return!!this.findParent(function(t){return t===e})},r.inType=function(){for(var e=this;e;){for(var t=arguments,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}var a=s;if(e.node.type===a)return!0}e=e.parentPath}return!1},r.inShadow=function(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}};var 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}(e("babel-types"));n(e("./index"))},{"./index":150,"babel-runtime/core-js/get-iterator":120,"babel-types":178}],145:[function(e,t,r){"use strict";r.__esModule=!0,r.shareCommentsWithSiblings=function(){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)}}}},r.addComment=function(e,t,r){this.addComments(e,[{type:r?"CommentLine":"CommentBlock",value:t}])},r.addComments=function(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}}}},{}],146:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.call=function(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])},r._call=function(e){if(!e)return!1;for(var t=e,r=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}var a=s;if(a){var o=this.node;if(!o)return!0;if(a.call(this.state,this,this.state))throw new Error("Unexpected return value from visitor method "+a);if(this.node!==o)return!0;if(this.shouldStop||this.shouldSkip||this.removed)return!0}}return!1},r.isBlacklisted=function(){var e=this.opts.blacklist;return e&&e.indexOf(this.node.type)>-1},r.visit=function(){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..."}),s.default.node(this.node,this.opts,this.scope,this.state,this,this.skipKeys),this.call("exit"),this.shouldStop))},r.skip=function(){this.shouldSkip=!0},r.skipKey=function(e){this.skipKeys[e]=!0},r.stop=function(){this.shouldStop=!0,this.shouldSkip=!0},r.setScope=function(){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()}},r.setContext=function(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},r.resync=function(){this.removed||(this._resyncParent(),this._resyncList(),this._resyncKey())},r._resyncParent=function(){this.parentPath&&(this.parent=this.parentPath.node)},r._resyncKey=function(){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=Array.isArray(t),n=0,t=r?t:(0,i.default)(t);;){var s;if(r){if(n>=t.length)break;s=t[n++]}else{if((n=t.next()).done)break;s=n.value}s.maybeQueue(e)}},r._getQueueContexts=function(){for(var e=this,t=this.contexts;!t.length;)t=(e=e.parentPath).contexts;return t};var s=n(e("../index"))},{"../index":143,"babel-runtime/core-js/get-iterator":120}],147:[function(e,t,r){"use strict";r.__esModule=!0,r.toComputedKey=function(){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||n.isIdentifier(t)&&(t=n.stringLiteral(t.name)),t},r.ensureBlock=function(){return n.ensureBlock(this.node)},r.arrowFunctionToShadowed=function(){if(this.isArrowFunctionExpression()){this.ensureBlock();var e=this.node;e.expression=!1,e.type="FunctionExpression",e.shadow=e.shadow||!0}};var n=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}(e("babel-types"))},{"babel-types":178}],148:[function(e,t,r){(function(t){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/typeof")),s=n(e("babel-runtime/core-js/get-iterator")),a=n(e("babel-runtime/core-js/map"));r.evaluateTruthy=function(){var e=this.evaluate();if(e.confident)return!!e.value},r.evaluate=function(){function e(e){n&&(l=e,n=!1)}function r(a){var l=a.node;if(c.has(l)){var p=c.get(l);return p.resolved?p.value:void e(a)}var h={resolved:!1};c.set(l,h);var f=function(a){if(n){var l=a.node;if(a.isSequenceExpression()){var c=a.get("expressions");return r(c[c.length-1])}if(a.isStringLiteral()||a.isNumericLiteral()||a.isBooleanLiteral())return l.value;if(a.isNullLiteral())return null;if(a.isTemplateLiteral()){for(var p="",h=0,f=a.get("expressions"),d=l.quasis,m=Array.isArray(d),y=0,d=m?d:(0,s.default)(d);;){var g;if(m){if(y>=d.length)break;g=d[y++]}else{if((y=d.next()).done)break;g=y.value}if(!n)break;p+=g.value.cooked;var b=f[h++];b&&(p+=String(r(b)))}if(!n)return;return p}if(a.isConditionalExpression()){var v=r(a.get("test"));if(!n)return;return r(v?a.get("consequent"):a.get("alternate"))}if(a.isExpressionWrapper())return r(a.get("expression"));if(a.isMemberExpression()&&!a.parentPath.isCallExpression({callee:l})){var x=a.get("property"),E=a.get("object");if(E.isLiteral()&&x.isIdentifier()){var A=E.node.value,D=void 0===A?"undefined":(0,i.default)(A);if("number"===D||"string"===D)return A[x.node.name]}}if(a.isReferencedIdentifier()){var C=a.scope.getBinding(l.name);if(C&&C.constantViolations.length>0)return e(C.path);if(C&&a.node.start=F.length)break;B=F[P++]}else{if((P=F.next()).done)break;B=P.value}var O=B;if(!(O=O.evaluate()).confident)return e(O);k.push(O.value)}return k}if(a.isObjectExpression()){for(var j={},N=a.get("properties"),I=Array.isArray(N),L=0,N=I?N:(0,s.default)(N);;){var M;if(I){if(L>=N.length)break;M=N[L++]}else{if((L=N.next()).done)break;M=L.value}var R=M;if(R.isObjectMethod()||R.isSpreadProperty())return e(R);var V=R.get("key"),U=V;if(R.node.computed){if(!(U=U.evaluate()).confident)return e(V);U=U.value}else U=U.isIdentifier()?U.node.name:U.node.value;var q=R.get("value"),G=q.evaluate();if(!G.confident)return e(q);G=G.value,j[U]=G}return j}if(a.isLogicalExpression()){var X=n,W=r(a.get("left")),J=n;n=X;var K=r(a.get("right")),z=n;switch(n=J&&z,l.operator){case"||":if(W&&J)return n=!0,W;if(!n)return;return W||K;case"&&":if((!W&&J||!K&&z)&&(n=!0),!n)return;return W&&K}}if(a.isBinaryExpression()){var Y=r(a.get("left"));if(!n)return;var H=r(a.get("right"));if(!n)return;switch(l.operator){case"-":return Y-H;case"+":return Y+H;case"/":return Y/H;case"*":return Y*H;case"%":return Y%H;case"**":return Math.pow(Y,H);case"<":return Y":return Y>H;case"<=":return Y<=H;case">=":return Y>=H;case"==":return Y==H;case"!=":return Y!=H;case"===":return Y===H;case"!==":return Y!==H;case"|":return Y|H;case"&":return Y&H;case"^":return Y^H;case"<<":return Y<>":return Y>>H;case">>>":return Y>>>H}}if(a.isCallExpression()){var $=a.get("callee"),Q=void 0,Z=void 0;if($.isIdentifier()&&!a.scope.getBinding($.node.name,!0)&&o.indexOf($.node.name)>=0&&(Z=t[l.callee.name]),$.isMemberExpression()){var ee=$.get("object"),te=$.get("property");if(ee.isIdentifier()&&te.isIdentifier()&&o.indexOf(ee.node.name)>=0&&u.indexOf(te.node.name)<0&&(Q=t[ee.node.name],Z=Q[te.node.name]),ee.isLiteral()&&te.isIdentifier()){var re=(0,i.default)(ee.node.value);"string"!==re&&"number"!==re||(Q=ee.node.value,Z=Q[te.node.name])}}if(Z){var ne=a.get("arguments").map(r);if(!n)return;return Z.apply(Q,ne)}}e(a)}}(a);return n&&(h.resolved=!0,h.value=f),f}var n=!0,l=void 0,c=new a.default,p=r(this);return n||(p=void 0),{confident:n,deopt:l,value:p}};var o=["String","Number","Math"],u=["random"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/map":122,"babel-runtime/helpers/typeof":138}],149:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/object/create")),s=n(e("babel-runtime/core-js/get-iterator"));r.getStatementParent=function(){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},r.getOpposite=function(){return"left"===this.key?this.getSibling("right"):"right"===this.key?this.getSibling("left"):void 0},r.getCompletionRecords=function(){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},r.getSibling=function(e){return a.default.get({parentPath:this.parentPath,parent:this.parent,container:this.container,listKey:this.listKey,key:e})},r.getPrevSibling=function(){return this.getSibling(this.key-1)},r.getNextSibling=function(){return this.getSibling(this.key+1)},r.getAllNextSiblings=function(){for(var e=this.key,t=this.getSibling(++e),r=[];t.node;)r.push(t),t=this.getSibling(++e);return r},r.getAllPrevSiblings=function(){for(var e=this.key,t=this.getSibling(--e),r=[];t.node;)r.push(t),t=this.getSibling(--e);return r},r.get=function(e,t){!0===t&&(t=this.context);var r=e.split(".");return 1===r.length?this._getKey(e,t):this._getPattern(r,t)},r._getKey=function(e,t){var r=this,n=this.node,i=n[e];return Array.isArray(i)?i.map(function(s,o){return a.default.get({listKey:e,parentPath:r,parent:n,container:i,key:o}).setContext(t)}):a.default.get({parentPath:this,parent:n,container:n,key:e}).setContext(t)},r._getPattern=function(e,t){for(var r=this,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()).done)break;o=a.value}var u=o;r="."===u?r.parentPath:Array.isArray(r)?r[u]:r.get(u,t)}return r},r.getBindingIdentifiers=function(e){return o.getBindingIdentifiers(this.node,e)},r.getOuterBindingIdentifiers=function(e){return o.getOuterBindingIdentifiers(this.node,e)},r.getBindingIdentifierPaths=function(){for(var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=[].concat(this),n=(0,i.default)(null);r.length;){var s=r.shift();if(s&&s.node){var a=o.getBindingIdentifiers.keys[s.node.type];if(s.isIdentifier())e?(n[s.node.name]=n[s.node.name]||[]).push(s):n[s.node.name]=s;else if(s.isExportDeclaration()){var u=s.get("declaration");u.isDeclaration()&&r.push(u)}else{if(t){if(s.isFunctionDeclaration()){r.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,c.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){f.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){m.enabled&&m(this.getPathLocation()+" "+this.type+": "+e())},e}();r.default=y,(0,p.default)(y.prototype,e("./ancestry")),(0,p.default)(y.prototype,e("./inference")),(0,p.default)(y.prototype,e("./replacement")),(0,p.default)(y.prototype,e("./evaluation")),(0,p.default)(y.prototype,e("./conversion")),(0,p.default)(y.prototype,e("./introspection")),(0,p.default)(y.prototype,e("./context")),(0,p.default)(y.prototype,e("./removal")),(0,p.default)(y.prototype,e("./modification")),(0,p.default)(y.prototype,e("./family")),(0,p.default)(y.prototype,e("./comments"));for(var g=function(){if(v){if(x>=b.length)return"break";E=b[x++]}else{if((x=b.next()).done)return"break";E=x.value}var e=E,t="is"+e;y.prototype[t]=function(e){return f[t](this.node,e)},y.prototype["assert"+e]=function(r){if(!this[t](r))throw new TypeError("Expected node path of type "+e)}},b=f.TYPES,v=Array.isArray(b),x=0,b=v?b:(0,s.default)(b);;){var E;if("break"===g())break}var A=function(e){if("_"===e[0])return"continue";f.TYPES.indexOf(e)<0&&f.TYPES.push(e);var t=o[e];y.prototype["is"+e]=function(e){return t.checkPath(this,e)}};for(var D in o){A(D)}t.exports=r.default},{"../cache":140,"../index":143,"../scope":162,"./ancestry":144,"./comments":145,"./context":146,"./conversion":147,"./evaluation":148,"./family":149,"./inference":151,"./introspection":154,"./lib/virtual-types":157,"./modification":158,"./removal":159,"./replacement":160,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-types":178,debug:165,invariant:318,"lodash/assign":488}],151:[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,t,r){if("string"===e)return o.isStringTypeAnnotation(t);if("number"===e)return o.isNumberTypeAnnotation(t);if("boolean"===e)return o.isBooleanTypeAnnotation(t);if("any"===e)return o.isAnyTypeAnnotation(t);if("mixed"===e)return o.isMixedTypeAnnotation(t);if("empty"===e)return o.isEmptyTypeAnnotation(t);if("void"===e)return o.isVoidTypeAnnotation(t);if(r)return!1;throw new Error("Unknown base type "+e)}r.__esModule=!0;var s=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.getTypeAnnotation=function(){if(this.typeAnnotation)return this.typeAnnotation;var e=this._getTypeAnnotation()||o.anyTypeAnnotation();return o.isTypeAnnotation(e)&&(e=e.typeAnnotation),this.typeAnnotation=e},r._getTypeAnnotation=function(){var e=this.node;if(e){if(e.typeAnnotation)return e.typeAnnotation;var t=a[e.type];return t?t.call(this,e):(t=a[this.parentPath.type])&&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()?o.stringTypeAnnotation():"left"===r.key&&n.isForOfStatement()?o.anyTypeAnnotation():o.voidTypeAnnotation()}},r.isBaseType=function(e,t){return i(e,this.getTypeAnnotation(),t)},r.couldBeBaseType=function(e){var t=this.getTypeAnnotation();if(o.isAnyTypeAnnotation(t))return!0;if(o.isUnionTypeAnnotation(t)){for(var r=t.types,n=Array.isArray(r),a=0,r=n?r:(0,s.default)(r);;){var u;if(n){if(a>=r.length)break;u=r[a++]}else{if((a=r.next()).done)break;u=a.value}var l=u;if(o.isAnyTypeAnnotation(l)||i(e,l,!0))return!0}return!1}return i(e,t,!0)},r.baseTypeStrictlyMatches=function(e){var t=this.getTypeAnnotation();if(e=e.getTypeAnnotation(),!o.isAnyTypeAnnotation(t)&&o.isFlowBaseAnnotation(t))return e.type===t.type},r.isGenericType=function(e){var t=this.getTypeAnnotation();return o.isGenericTypeAnnotation(t)&&o.isIdentifier(t.id,{name:e})};var a=n(e("./inferers")),o=n(e("babel-types"))},{"./inferers":153,"babel-runtime/core-js/get-iterator":120,"babel-types":178}],152:[function(e,t,r){"use strict";function n(e,t,r){var n=e.constantViolations.slice();return n.unshift(e.path),n.filter(function(e){var n=(e=e.resolve())._guessExecutionStatusRelativeTo(t);return r&&"function"===n&&r.push(e),"before"===n})}function i(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():o.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(r)>=0?o.numberTypeAnnotation():void 0;if("==="===r){var a=void 0,u=void 0;if(i.isUnaryExpression({operator:"typeof"})?(a=i,u=n):n.isUnaryExpression({operator:"typeof"})&&(a=n,u=i),(u||a)&&(u=u.resolve()).isLiteral()){if("string"==typeof u.node.value&&a.get("argument").isIdentifier({name:e}))return o.createTypeAnnotationBasedOnTypeof(u.node.value)}}}function s(e,t){var r=function(e){for(var t=void 0;t=e.parentPath;){if(t.isIfStatement()||t.isConditionalExpression())return"test"===e.key?void 0:t;e=t}}(e);if(r){var n=[r.get("test")],a=[];do{var u=n.shift().resolve();if(u.isLogicalExpression()&&(n.push(u.get("left")),n.push(u.get("right"))),u.isBinaryExpression()){var l=i(t,u);l&&a.push(l)}}while(n.length);return a.length?{typeAnnotation:o.createUnionTypeAnnotation(a),ifStatement:r}:s(r,t)}}r.__esModule=!0;var a=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.default=function(e){if(this.isReferenced()){var t=this.scope.getBinding(e.name);return t?t.identifier.typeAnnotation?t.identifier.typeAnnotation:function(e,t){var r=e.scope.getBinding(t),i=[];e.typeAnnotation=o.unionTypeAnnotation(i);var u=[],l=n(r,e,u),c=s(e,t);if(c){var p=n(r,c.ifStatement);l=l.filter(function(e){return p.indexOf(e)<0}),i.push(c.typeAnnotation)}if(l.length)for(var h=l=l.concat(u),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()).done)break;m=d.value}var y=m;i.push(y.getTypeAnnotation())}if(i.length)return o.createUnionTypeAnnotation(i)}(this,e.name):"undefined"===e.name?o.voidTypeAnnotation():"NaN"===e.name||"Infinity"===e.name?o.numberTypeAnnotation():void e.name}};var 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}(e("babel-types"));t.exports=r.default},{"babel-runtime/core-js/get-iterator":120,"babel-types":178}],153:[function(e,t,r){"use strict";function n(e){return e.typeAnnotation}function i(){return l.genericTypeAnnotation(l.identifier("Array"))}function s(){return i()}function a(){return l.genericTypeAnnotation(l.identifier("Function"))}function o(e){if((e=e.resolve()).isFunction()){if(e.is("async"))return e.is("generator")?l.genericTypeAnnotation(l.identifier("AsyncIterator")):l.genericTypeAnnotation(l.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 u=e("./inferer-reference");Object.defineProperty(r,"Identifier",{enumerable:!0,get:function(){return function(e){return e&&e.__esModule?e:{default:e}}(u).default}}),r.VariableDeclarator=function(){return this.get("id").isIdentifier()?this.get("init").getTypeAnnotation():void 0},r.TypeCastExpression=n,r.NewExpression=function(e){if(this.get("callee").isIdentifier())return l.genericTypeAnnotation(e.callee)},r.TemplateLiteral=function(){return l.stringTypeAnnotation()},r.UnaryExpression=function(e){var t=e.operator;return"void"===t?l.voidTypeAnnotation():l.NUMBER_UNARY_OPERATORS.indexOf(t)>=0?l.numberTypeAnnotation():l.STRING_UNARY_OPERATORS.indexOf(t)>=0?l.stringTypeAnnotation():l.BOOLEAN_UNARY_OPERATORS.indexOf(t)>=0?l.booleanTypeAnnotation():void 0},r.BinaryExpression=function(e){var t=e.operator;if(l.NUMBER_BINARY_OPERATORS.indexOf(t)>=0)return l.numberTypeAnnotation();if(l.BOOLEAN_BINARY_OPERATORS.indexOf(t)>=0)return l.booleanTypeAnnotation();if("+"===t){var r=this.get("right"),n=this.get("left");return n.isBaseType("number")&&r.isBaseType("number")?l.numberTypeAnnotation():n.isBaseType("string")||r.isBaseType("string")?l.stringTypeAnnotation():l.unionTypeAnnotation([l.stringTypeAnnotation(),l.numberTypeAnnotation()])}},r.LogicalExpression=function(){return l.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(),this.get("right").getTypeAnnotation()])},r.ConditionalExpression=function(){return l.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(),this.get("alternate").getTypeAnnotation()])},r.SequenceExpression=function(){return this.get("expressions").pop().getTypeAnnotation()},r.AssignmentExpression=function(){return this.get("right").getTypeAnnotation()},r.UpdateExpression=function(e){var t=e.operator;if("++"===t||"--"===t)return l.numberTypeAnnotation()},r.StringLiteral=function(){return l.stringTypeAnnotation()},r.NumericLiteral=function(){return l.numberTypeAnnotation()},r.BooleanLiteral=function(){return l.booleanTypeAnnotation()},r.NullLiteral=function(){return l.nullLiteralTypeAnnotation()},r.RegExpLiteral=function(){return l.genericTypeAnnotation(l.identifier("RegExp"))},r.ObjectExpression=function(){return l.genericTypeAnnotation(l.identifier("Object"))},r.ArrayExpression=i,r.RestElement=s,r.CallExpression=function(){return o(this.get("callee"))},r.TaggedTemplateExpression=function(){return o(this.get("tag"))};var 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}(e("babel-types"));n.validParent=!0,s.validParent=!0,r.FunctionExpression=a,r.ArrowFunctionExpression=a,r.FunctionDeclaration=a,r.ClassExpression=a,r.ClassDeclaration=a},{"./inferer-reference":152,"babel-types":178}],154:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=this.node&&this.node[e];return t&&Array.isArray(t)?!!t.length:!!t}r.__esModule=!0,r.is=void 0;var s=n(e("babel-runtime/core-js/get-iterator"));r.matchesPattern=function(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(o.isIdentifier(a)){if(!r(a.name))return!1}else if(o.isLiteral(a)){if(!r(a.value))return!1}else{if(o.isMemberExpression(a)){if(a.computed&&!o.isLiteral(a.property))return!1;i.unshift(a.property),i.unshift(a.object);continue}if(!o.isThisExpression(a))return!1;if(!r("this"))return!1}if(++s>n.length)return!1}return s===n.length},r.has=i,r.isStatic=function(){return this.scope.isStatic(this.node)},r.isnt=function(e){return!this.has(e)},r.equals=function(e,t){return this.node[e]===t},r.isNodeType=function(e){return o.isType(this.type,e)},r.canHaveVariableDeclarationOrExpression=function(){return("init"===this.key||"left"===this.key)&&this.parentPath.isFor()},r.canSwapBetweenExpressionAndStatement=function(e){return!("body"!==this.key||!this.parentPath.isArrowFunctionExpression())&&(this.isExpression()?o.isBlockStatement(e):!!this.isBlockStatement()&&o.isExpression(e))},r.isCompletionRecord=function(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},r.isStatementOrBlock=function(){return!this.parentPath.isLabeledStatement()&&!o.isBlockStatement(this.container)&&(0,a.default)(o.STATEMENT_OR_BLOCK_KEYS,this.key)},r.referencesImport=function(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))},r.getSource=function(){var e=this.node;return e.end?this.hub.file.code.slice(e.start,e.end):""},r.willIMaybeExecuteBefore=function(e){return"after"!==this._guessExecutionStatusRelativeTo(e)},r._guessExecutionStatusRelativeTo=function(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,u=void 0,l=void 0;for(l=0;l=0){a=c;break}}if(!a)return"before";var p=i[u-1],h=s[l-1];return p&&h?p.listKey&&p.container===h.container?p.key>h.key?"before":"after":o.VISITOR_KEYS[p.type].indexOf(p.key)>o.VISITOR_KEYS[h.type].indexOf(h.key)?"before":"after":"before"},r._guessExecutionStatusRelativeToDifferentFunctions=function(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,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()).done)break;u=o.value}var l=u;if("callee"!==l.key||!l.parentPath.isCallExpression())return}for(var c=void 0,p=n,h=Array.isArray(p),f=0,p=h?p:(0,s.default)(p);;){var d;if(h){if(f>=p.length)break;d=p[f++]}else{if((f=p.next()).done)break;d=f.value}var m=d;if(!m.find(function(e){return e.node===t.node})){var y=this._guessExecutionStatusRelativeTo(m);if(c){if(c!==y)return}else c=y}}return c}},r.resolve=function(e,t){return this._resolve(e,t)||this},r._resolve=function(e,t){if(!(t&&t.indexOf(this)>=0))if((t=t||[]).push(this),this.isVariableDeclarator()){if(this.get("id").isIdentifier())return this.get("init").resolve(e,t)}else if(this.isReferencedIdentifier()){var r=this.scope.getBinding(this.node.name);if(!r)return;if(!r.constant)return;if("module"===r.kind)return;if(r.path!==this){var n=r.path.resolve(e,t);if(this.find(function(e){return e.node===n.node}))return;return n}}else{if(this.isTypeCastExpression())return this.get("expression").resolve(e,t);if(e&&this.isMemberExpression()){var i=this.toComputedKey();if(!o.isLiteral(i))return;var a=i.value,u=this.get("object").resolve(e,t);if(u.isObjectExpression())for(var l=u.get("properties"),c=Array.isArray(l),p=0,l=c?l:(0,s.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if((p=l.next()).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(u.isArrayExpression()&&!isNaN(+a)){var y=u.get("elements")[a];if(y)return y.resolve(e,t)}}}};var a=n(e("lodash/includes")),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}(e("babel-types"));r.is=i},{"babel-runtime/core-js/get-iterator":120,"babel-types":178,"lodash/includes":507}],155:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator")),s=n(e("babel-runtime/helpers/classCallCheck")),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),u={ReferencedIdentifier:function(e,t){if(!e.isJSXIdentifier()||!a.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)}}},l=function(){function e(t,r){(0,s.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 s=n.constantViolations,a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var l=u;this.getAttachmentParentForPath(l).key>e.key&&(e=l)}}}return e.parentPath.isExportDeclaration()&&(e=e.parentPath),e}},e.prototype._getAttachmentPath=function(){var e=this.scopes.pop();if(e){if(e.path.isFunction()){if(this.hasOwnParamBindings(e)){if(this.scope===e)return;return e.path.get("body").get("body")[0]}return this.getNextScopeAttachmentParent()}return e.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(u,this),this.getCompatibleScopes();var t=this.getAttachmentPath();if(t&&t.getFunctionParent()!==this.path.getFunctionParent()){var r=t.scope.generateUidIdentifier("ref"),n=o.variableDeclarator(r,this.path.node);t[this.attachAfter?"insertAfter":"insertBefore"]([t.isVariableDeclarator()?n:o.variableDeclaration("var",[n])]);var i=this.path.parentPath;i.isJSXElement()&&this.path.container===i.node.children&&(r=o.JSXExpressionContainer(r)),this.path.replaceWith(r)}}},e}();r.default=l,t.exports=r.default},{"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],156:[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}]},{}],157:[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":178}],158:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/typeof")),s=n(e("babel-runtime/core-js/get-iterator"));r.insertBefore=function(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(l.blockStatement(e))}return[this]},r._containerInsert=function(e,t){this.updateSiblingKeys(e,t.length);for(var r=[],n=0;n=c.length)break;f=c[h++]}else{if((h=c.next()).done)break;f=h.value}var d=f;d.setScope(),d.debug(function(){return"Inserted."});for(var m=l,y=Array.isArray(m),g=0,m=y?m:(0,s.default)(m);;){var b;if(y){if(g>=m.length)break;b=m[g++]}else{if((g=m.next()).done)break;b=g.value}b.maybeQueue(d,!0)}}return r},r._containerInsertBefore=function(e){return this._containerInsert(this.key,e)},r._containerInsertAfter=function(e){return this._containerInsert(this.key+1,e)},r._maybePopFromStatements=function(e){var t=e[e.length-1];(l.isIdentifier(t)||l.isExpressionStatement(t)&&l.isIdentifier(t.expression))&&!this.isCompletionRecord()&&e.pop()},r.insertAfter=function(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(l.expressionStatement(l.assignmentExpression("=",t,this.node))),e.push(l.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(l.blockStatement(e))}return[this]},r.updateSiblingKeys=function(e,t){if(this.parent)for(var r=a.path.get(this.parent),n=0;n=e&&(i.key+=t)}},r._verifyNodeList=function(e){if(!e)return[];e.constructor!==Array&&(e=[e]);for(var t=0;t0&&void 0!==arguments[0]?arguments[0]:this.scope;return new o.default(this,e).run()};var a=e("../cache"),o=n(e("./lib/hoister")),u=n(e("./index")),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}(e("babel-types"))},{"../cache":140,"./index":150,"./lib/hoister":155,"babel-runtime/core-js/get-iterator":120,"babel-runtime/helpers/typeof":138,"babel-types":178}],159:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/get-iterator"));r.remove=function(){this._assertUnremoved(),this.resync(),this._callRemovalHooks()?this._markRemoved():(this.shareCommentsWithSiblings(),this._remove(),this._markRemoved())},r._callRemovalHooks=function(){for(var e=i.hooks,t=Array.isArray(e),r=0,e=t?e:(0,n.default)(e);;){var s;if(t){if(r>=e.length)break;s=e[r++]}else{if((r=e.next()).done)break;s=r.value}if(s(this,this.parentPath))return!0}},r._remove=function(){Array.isArray(this.container)?(this.container.splice(this.key,1),this.updateSiblingKeys(this.key,-1)):this._replaceWith(null)},r._markRemoved=function(){this.shouldSkip=!0,this.removed=!0,this.node=null},r._assertUnremoved=function(){if(this.removed)throw this.buildCodeFrameError("NodePath has been removed so is read-only.")};var i=e("./lib/removal-hooks")},{"./lib/removal-hooks":156,"babel-runtime/core-js/get-iterator":120}],160:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/core-js/get-iterator"));r.replaceWithMultiple=function(e){this.resync(),e=this._verifyNodeList(e),l.inheritLeadingComments(e[0],this.node),l.inheritTrailingComments(e[e.length-1],this.node),this.node=this.container[this.key]=null,this.insertAfter(e),this.node?this.requeue():this.remove()},r.replaceWithSourceString=function(e){this.resync();try{e="("+e+")",e=(0,u.parse)(e)}catch(r){var t=r.loc;throw t&&(r.message+=" - make sure this is an expression.",r.message+="\n"+(0,s.default)(e,t.line,t.column+1)),r}return e=e.program.body[0].expression,a.default.removeProperties(e),this.replaceWith(e)},r.replaceWith=function(e){if(this.resync(),this.removed)throw new Error("You can't replace this node, we've already removed it");if(e instanceof o.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()&&!l.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")&&l.isExpression(e)&&(this.canHaveVariableDeclarationOrExpression()||this.canSwapBetweenExpressionAndStatement(e)||this.parentPath.isExportDefaultDeclaration()||(e=l.expressionStatement(e))),this.isNodeType("Expression")&&l.isStatement(e)&&!this.canHaveVariableDeclarationOrExpression()&&!this.canSwapBetweenExpressionAndStatement(e))return this.replaceExpressionWithStatements([e]);var t=this.node;t&&(l.inheritsComments(e,t),l.removeComments(t)),this._replaceWith(e),this.type=e.type,this.setScope(),this.requeue()}},r._replaceWith=function(e){if(!this.container)throw new ReferenceError("Container is falsy");this.inList?l.validate(this.parent,this.key,[e]):l.validate(this.parent,this.key,e),this.debug(function(){return"Replace with "+(e&&e.type)}),this.node=this.container[this.key]=e},r.replaceExpressionWithStatements=function(e){this.resync();var t=l.toSequenceExpression(e,this.scope);if(l.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=l.functionExpression(null,[],l.blockStatement(e));n.shadow=!0,this.replaceWith(l.callExpression(n,[])),this.traverse(c);for(var s=this.get("callee").getCompletionRecords(),a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var p=u;if(p.isExpressionStatement()){var h=p.findParent(function(e){return e.isLoop()});if(h){var f=h.getData("expressionReplacementReturnUid");if(f)f=l.identifier(f.name);else{var d=this.get("callee");f=d.scope.generateDeclaredUidIdentifier("ret"),d.get("body").pushContainer("body",l.returnStatement(f)),h.setData("expressionReplacementReturnUid",f)}p.get("expression").replaceWith(l.assignmentExpression("=",f,p.node.expression))}else p.replaceWith(l.returnStatement(p.node.expression))}}return this.node}this.replaceWith(t)}},r.replaceInline=function(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)};var s=n(e("babel-code-frame")),a=n(e("../index")),o=n(e("./index")),u=e("babylon"),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}(e("babel-types")),c={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=[],s=e.node.declarations,a=Array.isArray(s),o=0,s=a?s:(0,i.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var c=u;c.init&&n.push(l.expressionStatement(l.assignmentExpression("=",c.id,c.init)))}e.replaceWithMultiple(n)}}}},{"../index":143,"./index":150,"babel-code-frame":21,"babel-runtime/core-js/get-iterator":120,"babel-types":178,babylon:186}],161:[function(e,t,r){"use strict";r.__esModule=!0;var n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/helpers/classCallCheck")),i=function(){function e(t){var r=t.existing,i=t.identifier,s=t.scope,a=t.path,o=t.kind;(0,n.default)(this,e),this.identifier=i,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=i,t.exports=r.default},{"babel-runtime/helpers/classCallCheck":134}],162:[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){if(v.isModuleDeclaration(e))if(e.source)s(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,c.default)(r);;){var a;if(n){if(i>=r.length)break;a=r[i++]}else{if((i=r.next()).done)break;a=i.value}s(a,t)}else e.declaration&&s(e.declaration,t);else if(v.isModuleSpecifier(e))s(e.local,t);else if(v.isMemberExpression(e))s(e.object,t),s(e.property,t);else if(v.isIdentifier(e))t.push(e.name);else if(v.isLiteral(e))t.push(e.value);else if(v.isCallExpression(e))s(e.callee,t);else if(v.isObjectExpression(e)||v.isObjectPattern(e))for(var o=e.properties,u=Array.isArray(o),l=0,o=u?o:(0,c.default)(o);;){var p;if(u){if(l>=o.length)break;p=o[l++]}else{if((l=o.next()).done)break;p=l.value}var h=p;s(h.key||h.argument,t)}}r.__esModule=!0;var a=i(e("babel-runtime/core-js/object/keys")),o=i(e("babel-runtime/core-js/object/create")),u=i(e("babel-runtime/core-js/map")),l=i(e("babel-runtime/helpers/classCallCheck")),c=i(e("babel-runtime/core-js/get-iterator")),p=i(e("lodash/includes")),h=i(e("lodash/repeat")),f=i(e("./lib/renamer")),d=i(e("../index")),m=i(e("lodash/defaults")),y=n(e("babel-messages")),g=i(e("./binding")),b=i(e("globals")),v=n(e("babel-types")),x=e("../cache"),E=0,A={For:function(e){for(var t=v.FOR_INIT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).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(v.isClassDeclaration(n)||v.isFunctionDeclaration(n)){var i=n.id;if(!i)return;var s=r.getBinding(i.name);s&&s.reference(e)}else if(v.isVariableDeclaration(n))for(var a=n.declarations,o=Array.isArray(a),u=0,a=o?a:(0,c.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var p=l,h=v.getBindingIdentifiers(p);for(var f in h){var d=r.getBinding(f);d&&d.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=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;s.isFunctionDeclaration()&&e.scope.getBlockParent().registerDeclaration(s)}}},D=0,C=function(){function e(t,r){if((0,l.default)(this,e),r&&r.block===t.node)return r;var n=function(e,t,r){for(var n=x.scope.get(e.node)||[],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()).done)break;o=a.value}var u=o;if(u.parent===t&&u.path===e)return u}n.push(r),x.scope.has(e.node)||x.scope.set(e.node,n)}(t,r,this);if(n)return n;this.uid=D++,this.parent=r,this.hub=t.hub,this.parentBlock=t.parent,this.block=t.node,this.path=t,this.labels=new u.default}return e.prototype.traverse=function(e,t,r){(0,d.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 v.identifier(this.generateUid(e))},e.prototype.generateUid=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"temp";e=v.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;v.isAssignmentExpression(e)?r=e.left:v.isVariableDeclarator(e)?r=e.id:(v.isObjectProperty(r)||v.isObjectMethod(r))&&(r=r.key);var n=[];s(r,n);var i=n.join("$");return i=i.replace(/^_/,"")||t||"ref",this.generateUidIdentifier(i.slice(0,20))},e.prototype.isStatic=function(e){if(v.isThisExpression(e)||v.isSuper(e))return!0;if(v.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,y.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 f.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,h.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(v.isIdentifier(e)){var n=this.getBinding(e.name);if(n&&n.constant&&n.path.isGenericType("Array"))return e}if(v.isArrayExpression(e))return e;if(v.isIdentifier(e,{name:"arguments"}))return v.callExpression(v.memberExpression(v.memberExpression(v.memberExpression(v.identifier("Array"),v.identifier("prototype")),v.identifier("slice")),v.identifier("call")),[e]);var i="toArray",s=[e];return!0===t?i="toConsumableArray":t&&(s.push(v.numericLiteral(t)),i="slicedToArray"),v.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=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i;this.registerBinding(e.node.kind,s)}else if(e.isClassDeclaration())this.registerBinding("let",e);else if(e.isImportDeclaration())for(var a=e.get("specifiers"),o=Array.isArray(a),u=0,a=o?a:(0,c.default)(a);;){var l;if(o){if(u>=a.length)break;l=a[u++]}else{if((u=a.next()).done)break;l=u.value}var p=l;this.registerBinding("module",p)}else if(e.isExportDeclaration()){var h=e.get("declaration");(h.isClassDeclaration()||h.isFunctionDeclaration()||h.isVariableDeclaration())&&this.registerDeclaration(h)}else this.registerBinding("unknown",e)},e.prototype.buildUndefinedNode=function(){return this.hasBinding("undefined")?v.unaryExpression("void",v.numericLiteral(0),!0):v.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=Array.isArray(n),s=0,n=i?n:(0,c.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a;this.registerBinding(e,o)}else{var u=this.getProgramParent(),l=t.getBindingIdentifiers(!0);for(var p in l)for(var h=l[p],f=Array.isArray(h),d=0,h=f?h:(0,c.default)(h);;){var m;if(f){if(d>=h.length)break;m=h[d++]}else{if((d=h.next()).done)break;m=d.value}var y=m,b=this.getOwnBinding(p);if(b){if(b.identifier===y)continue;this.checkBlockScopedCollisions(b,e,p,y)}b&&b.path.isFlow()&&(b=null),u.references[p]=!0,this.bindings[p]=new g.default({identifier:y,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(v.isIdentifier(e)){var r=this.getBinding(e.name);return!!r&&(!t||r.constant)}if(v.isClass(e))return!(e.superClass&&!this.isPure(e.superClass,t))&&this.isPure(e.body,t);if(v.isClassBody(e)){for(var n=e.body,i=Array.isArray(n),s=0,n=i?n:(0,c.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}var o=a;if(!this.isPure(o,t))return!1}return!0}if(v.isBinary(e))return this.isPure(e.left,t)&&this.isPure(e.right,t);if(v.isArrayExpression(e)){for(var u=e.elements,l=Array.isArray(u),p=0,u=l?u:(0,c.default)(u);;){var h;if(l){if(p>=u.length)break;h=u[p++]}else{if((p=u.next()).done)break;h=p.value}var f=h;if(!this.isPure(f,t))return!1}return!0}if(v.isObjectExpression(e)){for(var d=e.properties,m=Array.isArray(d),y=0,d=m?d:(0,c.default)(d);;){var g;if(m){if(y>=d.length)break;g=d[y++]}else{if((y=d.next()).done)break;g=y.value}var b=g;if(!this.isPure(b,t))return!1}return!0}return v.isClassMethod(e)?!(e.computed&&!this.isPure(e.key,t))&&("get"!==e.kind&&"set"!==e.kind):v.isClassProperty(e)||v.isObjectProperty(e)?!(e.computed&&!this.isPure(e.key,t))&&this.isPure(e.value,t):v.isUnaryExpression(e)?this.isPure(e.argument,t):v.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(){E++,this._crawl(),E--},e.prototype._crawl=function(){var e=this.path;if(this.references=(0,o.default)(null),this.bindings=(0,o.default)(null),this.globals=(0,o.default)(null),this.uids=(0,o.default)(null),this.data=(0,o.default)(null),e.isLoop())for(var t=v.FOR_INIT_KEYS,r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).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[v.NOT_LOCAL_BINDING]||this.registerBinding("local",e.get("id"),e)),e.isClassExpression()&&e.has("id")&&(e.get("id").node[v.NOT_LOCAL_BINDING]||this.registerBinding("local",e)),e.isFunction())for(var u=e.get("params"),l=Array.isArray(u),p=0,u=l?u:(0,c.default)(u);;){var h;if(l){if(p>=u.length)break;h=u[p++]}else{if((p=u.next()).done)break;h=p.value}var f=h;this.registerBinding("param",f)}e.isCatchClause()&&this.registerBinding("let",e);if(!this.getProgramParent().crawling){var d={references:[],constantViolations:[],assignments:[]};this.crawling=!0,e.traverse(A,d),this.crawling=!1;for(var m=d.assignments,y=Array.isArray(m),g=0,m=y?m:(0,c.default)(m);;){var b;if(y){if(g>=m.length)break;b=m[g++]}else{if((g=m.next()).done)break;b=g.value}var x=b,E=x.getBindingIdentifiers(),D=void 0;for(var C in E)x.scope.getBinding(C)||(D=D||x.scope.getProgramParent()).addGlobal(E[C]);x.scope.registerConstantViolation(x)}for(var S=d.references,_=Array.isArray(S),w=0,S=_?S:(0,c.default)(S);;){var k;if(_){if(w>=S.length)break;k=S[w++]}else{if((w=S.next()).done)break;k=w.value}var F=k,T=F.scope.getBinding(F.node.name);T?T.reference(F):F.scope.getProgramParent().addGlobal(F.node)}for(var P=d.constantViolations,B=Array.isArray(P),O=0,P=B?P:(0,c.default)(P);;){var j;if(B){if(O>=P.length)break;j=P[O++]}else{if((O=P.next()).done)break;j=O.value}var N=j;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())&&(v.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=v.variableDeclaration(n,[]);o._generated=!0,o._blockHoist=i;a=t.unshiftContainer("body",[o])[0],r||t.setData(s,a)}var u=v.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,o.default)(null),t=this;do{(0,m.default)(e,t.bindings),t=t.parent}while(t);return e},e.prototype.getAllBindingsOfKind=function(){for(var e=(0,o.default)(null),t=arguments,r=Array.isArray(t),n=0,t=r?t:(0,c.default)(t);;){var i;if(r){if(n>=t.length)break;i=t[n++]}else{if((n=t.next()).done)break;i=n.value}var s=i,a=this;do{for(var u in a.bindings){var l=a.bindings[u];l.kind===s&&(e[u]=l)}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===E&&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 7. 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,p.default)(e.globals,t))||!(r||!(0,p.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}();C.globals=(0,a.default)(b.default.builtin),C.contextVariables=["arguments","undefined","Infinity","NaN"],r.default=C,t.exports=r.default},{"../cache":140,"../index":143,"./binding":161,"./lib/renamer":163,"babel-messages":110,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/map":122,"babel-runtime/core-js/object/create":125,"babel-runtime/core-js/object/keys":127,"babel-runtime/helpers/classCallCheck":134,"babel-types":178,globals:313,"lodash/defaults":495,"lodash/includes":507,"lodash/repeat":530}],163:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.__esModule=!0;var i=n(e("babel-runtime/helpers/classCallCheck")),s=(n(e("../binding")),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}(e("babel-types"))),a={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)}},o=function(){function e(t,r,n){(0,i.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 a in n){var o=a===this.oldName?this.newName:a,u=r?"default":a;i.push(s.exportSpecifier(s.identifier(o),s.identifier(u)))}if(i.length){var l=s.exportNamedDeclaration(null,i);e.isFunctionDeclaration()&&(l._blockHoist=3),t.insertAfter(l),t.replaceWith(e.node)}}},e.prototype.rename=function(e){var t=this.binding,r=this.oldName,n=this.newName,i=t.scope,s=t.path.find(function(e){return e.isDeclaration()||e.isFunctionExpression()});s&&this.maybeConvertFromExportDeclaration(s),i.traverse(e||i.block,a,this),e||(i.removeOwnBinding(r),i.bindings[n]=t,this.binding.identifier.name=n),t.type},e}();r.default=o,t.exports=r.default},{"../binding":161,"babel-runtime/helpers/classCallCheck":134,"babel-types":178}],164:[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(!l(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,f.default)(i);;){var p;if(s){if(o>=i.length)break;p=i[o++]}else{if((o=i.next()).done)break;p=o.value}e[p]=n}}}a(e),delete e.__esModule,function(e){for(var t in e)if(!l(t)){var r=e[t];"function"==typeof r&&(e[t]={enter:r})}}(e),u(e);for(var m=(0,h.default)(e),b=Array.isArray(m),v=0,m=b?m:(0,f.default)(m);;){var x;if(b){if(v>=m.length)break;x=m[v++]}else{if((v=m.next()).done)break;x=v.value}var E=x;if(!l(E)){var A=d[E];if(A){var D=e[E];for(var C in D)D[C]=function(e,t){var r=function(r){if(e.checkPath(r))return t.apply(this,arguments)};return r.toString=function(){return t.toString()},r}(A,D[C]);if(delete e[E],A.types)for(var S=A.types,_=Array.isArray(S),w=0,S=_?S:(0,f.default)(S);;){var k;if(_){if(w>=S.length)break;k=S[w++]}else{if((w=S.next()).done)break;k=w.value}var F=k;e[F]?c(e[F],D):e[F]=D}else c(e,D)}}}for(var T in e)if(!l(T)){var P=e[T],B=y.FLIPPED_ALIAS_KEYS[T],O=y.DEPRECATED_KEYS[T];if(O&&(console.trace("Visitor defined for "+T+" but it has been renamed to "+O),B=[O]),B){delete e[T];for(var j=B,N=Array.isArray(j),I=0,j=N?j:(0,f.default)(j);;){var L;if(N){if(I>=j.length)break;L=j[I++]}else{if((I=j.next()).done)break;L=I.value}var M=L,R=e[M];R?c(R,P):e[M]=(0,g.default)(P)}}}for(var V in e)l(V)||u(e[V]);return e}function a(e){if(!e._verified){if("function"==typeof e)throw new Error(m.get("traverseVerifyRootFunction"));for(var t in e)if("enter"!==t&&"exit"!==t||o(t,e[t]),!l(t)){if(y.TYPES.indexOf(t)<0)throw new Error(m.get("traverseVerifyNodeType",t));var r=e[t];if("object"===(void 0===r?"undefined":(0,p.default)(r)))for(var n in r){if("enter"!==n&&"exit"!==n)throw new Error(m.get("traverseVerifyVisitorProperty",t,n));o(t+"."+n,r[n])}}e._verified=!0}}function o(e,t){for(var r=[].concat(t),n=Array.isArray(r),i=0,r=n?r:(0,f.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).done)break;s=i.value}var a=s;if("function"!=typeof a)throw new TypeError("Non-function found defined in "+e+" with type "+(void 0===a?"undefined":(0,p.default)(a)))}}function u(e){e.enter&&!Array.isArray(e.enter)&&(e.enter=[e.enter]),e.exit&&!Array.isArray(e.exit)&&(e.exit=[e.exit])}function l(e){return"_"===e[0]||("enter"===e||"exit"===e||"shouldSkip"===e||("blacklist"===e||"noScope"===e||"skipKeys"===e))}function c(e,t){for(var r in t)e[r]=[].concat(e[r]||[],t[r])}r.__esModule=!0;var p=i(e("babel-runtime/helpers/typeof")),h=i(e("babel-runtime/core-js/object/keys")),f=i(e("babel-runtime/core-js/get-iterator"));r.explode=s,r.verify=a,r.merge=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments[2],n={},i=0;i=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},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(i())}).call(this,e("_process"))},{"./debug":166,_process:550}],166:[function(e,t,r){arguments[4][60][0].apply(r,arguments)},{dup:60,ms:543}],167:[function(e,t,r){"use strict";r.__esModule=!0,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 n=function(e){return e&&e.__esModule?e:{default:e}}(e("babel-runtime/core-js/symbol/for")),i=(r.STATEMENT_OR_BLOCK_KEYS=["consequent","body","alternate"],r.FLATTENABLE_KEYS=["body","expressions"],r.FOR_INIT_KEYS=["left","init"],r.COMMENT_KEYS=["leadingComments","trailingComments","innerComments"],r.LOGICAL_OPERATORS=["||","&&"],r.UPDATE_OPERATORS=["++","--"],r.BOOLEAN_NUMBER_BINARY_OPERATORS=[">","<",">=","<="]),s=r.EQUALITY_BINARY_OPERATORS=["==","===","!=","!=="],a=r.COMPARISON_BINARY_OPERATORS=[].concat(s,["in","instanceof"]),o=r.BOOLEAN_BINARY_OPERATORS=[].concat(a,i),u=r.NUMBER_BINARY_OPERATORS=["-","/","%","*","**","&","|",">>",">>>","<<","^"],l=(r.BINARY_OPERATORS=["+"].concat(u,o),r.BOOLEAN_UNARY_OPERATORS=["delete","!"]),c=r.NUMBER_UNARY_OPERATORS=["+","-","++","--","~"],p=r.STRING_UNARY_OPERATORS=["typeof"];r.UNARY_OPERATORS=["void"].concat(l,c,p),r.INHERIT_KEYS={optional:["typeAnnotation","typeParameters","returnType"],force:["start","loc","end"]},r.BLOCK_SCOPED_SYMBOL=(0,n.default)("var used to be block scoped"),r.NOT_LOCAL_BINDING=(0,n.default)("should not be considered a local binding")},{"babel-runtime/core-js/symbol/for":130}],168:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e,t,r){for(var n=[],s=!0,a=e,o=Array.isArray(a),u=0,a=o?a:(0,l.default)(a);;){var c;if(o){if(u>=a.length)break;c=a[u++]}else{if((u=a.next()).done)break;c=u.value}var p=c;if(s=!1,h.isExpression(p))n.push(p);else if(h.isExpressionStatement(p))n.push(p.expression);else if(h.isVariableDeclaration(p)){if("var"!==p.kind)return;for(var f=p.declarations,d=Array.isArray(f),m=0,f=d?f:(0,l.default)(f);;){var y;if(d){if(m>=f.length)break;y=f[m++]}else{if((m=f.next()).done)break;y=m.value}var g=y,b=h.getBindingIdentifiers(g);for(var v in b)r.push({kind:p.kind,id:b[v]});g.init&&n.push(h.assignmentExpression("=",g.id,g.init))}s=!0}else if(h.isIfStatement(p)){var x=p.consequent?i([p.consequent],t,r):t.buildUndefinedNode(),E=p.alternate?i([p.alternate],t,r):t.buildUndefinedNode();if(!x||!E)return;n.push(h.conditionalExpression(p.test,x,E))}else if(h.isBlockStatement(p)){var A=i(p.body,t,r);if(!A)return;n.push(A)}else{if(!h.isEmptyStatement(p))return;s=!0}}return s&&n.push(t.buildUndefinedNode()),1===n.length?n[0]:h.sequenceExpression(n)}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.key,r=void 0;return"method"===e.kind?s.increment()+"":(r=h.isIdentifier(t)?t.name:h.isStringLiteral(t)?(0,u.default)(t.value):(0,u.default)(h.removePropertiesDeep(h.cloneDeep(t))),e.computed&&(r="["+r+"]"),e.static&&(r="static:"+r),r)}function a(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():""}),h.isValidIdentifier(e)||(e="_"+e),e||"_"}r.__esModule=!0;var o=n(e("babel-runtime/core-js/number/max-safe-integer")),u=n(e("babel-runtime/core-js/json/stringify")),l=n(e("babel-runtime/core-js/get-iterator"));r.toComputedKey=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e.key||e.property;return e.computed||h.isIdentifier(t)&&(t=h.stringLiteral(t.name)),t},r.toSequenceExpression=function(e,t){if(e&&e.length){var r=[],n=i(e,t,r);if(n){for(var s=r,a=Array.isArray(s),o=0,s=a?s:(0,l.default)(s);;){var u;if(a){if(o>=s.length)break;u=s[o++]}else{if((o=s.next()).done)break;u=o.value}var c=u;t.push(c)}return n}}},r.toKeyAlias=s,r.toIdentifier=a,r.toBindingIdentifierName=function(e){return"eval"!==(e=a(e))&&"arguments"!==e||(e="_"+e),e},r.toStatement=function(e,t){if(h.isStatement(e))return e;var r=!1,n=void 0;if(h.isClass(e))r=!0,n="ClassDeclaration";else if(h.isFunction(e))r=!0,n="FunctionDeclaration";else if(h.isAssignmentExpression(e))return h.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},r.toExpression=function(e){if(h.isExpressionStatement(e)&&(e=e.expression),h.isExpression(e))return e;if(h.isClass(e)?e.type="ClassExpression":h.isFunction(e)&&(e.type="FunctionExpression"),!h.isExpression(e))throw new Error("cannot turn "+e.type+" to an expression");return e},r.toBlock=function(e,t){return h.isBlockStatement(e)?e:(h.isEmptyStatement(e)&&(e=[]),Array.isArray(e)||(h.isStatement(e)||(e=h.isFunction(t)?h.returnStatement(e):h.expressionStatement(e)),e=[e]),h.blockStatement(e))},r.valueToNode=function(e){if(void 0===e)return h.identifier("undefined");if(!0===e||!1===e)return h.booleanLiteral(e);if(null===e)return h.nullLiteral();if("string"==typeof e)return h.stringLiteral(e);if("number"==typeof e)return h.numericLiteral(e);if((0,p.default)(e)){var t=e.source,r=e.toString().match(/\/([a-z]+|)$/)[1];return h.regExpLiteral(t,r)}if(Array.isArray(e))return h.arrayExpression(e.map(h.valueToNode));if((0,c.default)(e)){var n=[];for(var i in e){var s=void 0;s=h.isValidIdentifier(i)?h.identifier(i):h.stringLiteral(i),n.push(h.objectProperty(s,h.valueToNode(e[i])))}return h.objectExpression(n)}throw new Error("don't know how to turn this value into a node")};var c=n(e("lodash/isPlainObject")),p=n(e("lodash/isRegExp")),h=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}(e("./index"));s.uid=0,s.increment=function(){return s.uid>=o.default?s.uid=0:s.uid++}},{"./index":178,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/core-js/number/max-safe-integer":123,"lodash/isPlainObject":518,"lodash/isRegExp":519}],169:[function(e,t,r){"use strict";var n=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}(e("../index")),i=e("../constants"),s=e("./index"),a=function(e){return e&&e.__esModule?e:{default:e}}(s);(0,a.default)("ArrayExpression",{fields:{elements:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeOrValueType)("null","Expression","SpreadElement"))),default:[]}},visitor:["elements"],aliases:["Expression"]}),(0,a.default)("AssignmentExpression",{fields:{operator:{validate:(0,s.assertValueType)("string")},left:{validate:(0,s.assertNodeType)("LVal")},right:{validate:(0,s.assertNodeType)("Expression")}},builder:["operator","left","right"],visitor:["left","right"],aliases:["Expression"]}),(0,a.default)("BinaryExpression",{builder:["operator","left","right"],fields:{operator:{validate:s.assertOneOf.apply(void 0,i.BINARY_OPERATORS)},left:{validate:(0,s.assertNodeType)("Expression")},right:{validate:(0,s.assertNodeType)("Expression")}},visitor:["left","right"],aliases:["Binary","Expression"]}),(0,a.default)("Directive",{visitor:["value"],fields:{value:{validate:(0,s.assertNodeType)("DirectiveLiteral")}}}),(0,a.default)("DirectiveLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("string")}}}),(0,a.default)("BlockStatement",{builder:["body","directives"],visitor:["directives","body"],fields:{directives:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Directive"))),default:[]},body:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Statement")))}},aliases:["Scopable","BlockParent","Block","Statement"]}),(0,a.default)("BreakStatement",{visitor:["label"],fields:{label:{validate:(0,s.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),(0,a.default)("CallExpression",{visitor:["callee","arguments"],fields:{callee:{validate:(0,s.assertNodeType)("Expression")},arguments:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Expression","SpreadElement")))}},aliases:["Expression"]}),(0,a.default)("CatchClause",{visitor:["param","body"],fields:{param:{validate:(0,s.assertNodeType)("Identifier")},body:{validate:(0,s.assertNodeType)("BlockStatement")}},aliases:["Scopable"]}),(0,a.default)("ConditionalExpression",{visitor:["test","consequent","alternate"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},consequent:{validate:(0,s.assertNodeType)("Expression")},alternate:{validate:(0,s.assertNodeType)("Expression")}},aliases:["Expression","Conditional"]}),(0,a.default)("ContinueStatement",{visitor:["label"],fields:{label:{validate:(0,s.assertNodeType)("Identifier"),optional:!0}},aliases:["Statement","Terminatorless","CompletionStatement"]}),(0,a.default)("DebuggerStatement",{aliases:["Statement"]}),(0,a.default)("DoWhileStatement",{visitor:["test","body"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("Statement")}},aliases:["Statement","BlockParent","Loop","While","Scopable"]}),(0,a.default)("EmptyStatement",{aliases:["Statement"]}),(0,a.default)("ExpressionStatement",{visitor:["expression"],fields:{expression:{validate:(0,s.assertNodeType)("Expression")}},aliases:["Statement","ExpressionWrapper"]}),(0,a.default)("File",{builder:["program","comments","tokens"],visitor:["program"],fields:{program:{validate:(0,s.assertNodeType)("Program")}}}),(0,a.default)("ForInStatement",{visitor:["left","right","body"],aliases:["Scopable","Statement","For","BlockParent","Loop","ForXStatement"],fields:{left:{validate:(0,s.assertNodeType)("VariableDeclaration","LVal")},right:{validate:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("ForStatement",{visitor:["init","test","update","body"],aliases:["Scopable","Statement","For","BlockParent","Loop"],fields:{init:{validate:(0,s.assertNodeType)("VariableDeclaration","Expression"),optional:!0},test:{validate:(0,s.assertNodeType)("Expression"),optional:!0},update:{validate:(0,s.assertNodeType)("Expression"),optional:!0},body:{validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("FunctionDeclaration",{builder:["id","params","body","generator","async"],visitor:["id","params","body","returnType","typeParameters"],fields:{id:{validate:(0,s.assertNodeType)("Identifier")},params:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("LVal")))},body:{validate:(0,s.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,s.assertValueType)("boolean")},async:{default:!1,validate:(0,s.assertValueType)("boolean")}},aliases:["Scopable","Function","BlockParent","FunctionParent","Statement","Pureish","Declaration"]}),(0,a.default)("FunctionExpression",{inherits:"FunctionDeclaration",aliases:["Scopable","Function","BlockParent","FunctionParent","Expression","Pureish"],fields:{id:{validate:(0,s.assertNodeType)("Identifier"),optional:!0},params:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("LVal")))},body:{validate:(0,s.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,s.assertValueType)("boolean")},async:{default:!1,validate:(0,s.assertValueType)("boolean")}}}),(0,a.default)("Identifier",{builder:["name"],visitor:["typeAnnotation"],aliases:["Expression","LVal"],fields:{name:{validate:function(e,t,r){n.isValidIdentifier(r)}},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator")))}}}),(0,a.default)("IfStatement",{visitor:["test","consequent","alternate"],aliases:["Statement","Conditional"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},consequent:{validate:(0,s.assertNodeType)("Statement")},alternate:{optional:!0,validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("LabeledStatement",{visitor:["label","body"],aliases:["Statement"],fields:{label:{validate:(0,s.assertNodeType)("Identifier")},body:{validate:(0,s.assertNodeType)("Statement")}}}),(0,a.default)("StringLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("string")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("NumericLiteral",{builder:["value"],deprecatedAlias:"NumberLiteral",fields:{value:{validate:(0,s.assertValueType)("number")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("NullLiteral",{aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("BooleanLiteral",{builder:["value"],fields:{value:{validate:(0,s.assertValueType)("boolean")}},aliases:["Expression","Pureish","Literal","Immutable"]}),(0,a.default)("RegExpLiteral",{builder:["pattern","flags"],deprecatedAlias:"RegexLiteral",aliases:["Expression","Literal"],fields:{pattern:{validate:(0,s.assertValueType)("string")},flags:{validate:(0,s.assertValueType)("string"),default:""}}}),(0,a.default)("LogicalExpression",{builder:["operator","left","right"],visitor:["left","right"],aliases:["Binary","Expression"],fields:{operator:{validate:s.assertOneOf.apply(void 0,i.LOGICAL_OPERATORS)},left:{validate:(0,s.assertNodeType)("Expression")},right:{validate:(0,s.assertNodeType)("Expression")}}}),(0,a.default)("MemberExpression",{builder:["object","property","computed"],visitor:["object","property"],aliases:["Expression","LVal"],fields:{object:{validate:(0,s.assertNodeType)("Expression")},property:{validate:function(e,t,r){var n=e.computed?"Expression":"Identifier";(0,s.assertNodeType)(n)(e,t,r)}},computed:{default:!1}}}),(0,a.default)("NewExpression",{visitor:["callee","arguments"],aliases:["Expression"],fields:{callee:{validate:(0,s.assertNodeType)("Expression")},arguments:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Expression","SpreadElement")))}}}),(0,a.default)("Program",{visitor:["directives","body"],builder:["body","directives"],fields:{directives:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Directive"))),default:[]},body:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Statement")))}},aliases:["Scopable","BlockParent","Block","FunctionParent"]}),(0,a.default)("ObjectExpression",{visitor:["properties"],aliases:["Expression"],fields:{properties:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("ObjectMethod","ObjectProperty","SpreadProperty")))}}}),(0,a.default)("ObjectMethod",{builder:["kind","key","params","body","computed"],fields:{kind:{validate:(0,s.chain)((0,s.assertValueType)("string"),(0,s.assertOneOf)("method","get","set")),default:"method"},computed:{validate:(0,s.assertValueType)("boolean"),default:!1},key:{validate:function(e,t,r){var n=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];s.assertNodeType.apply(void 0,n)(e,t,r)}},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator")))},body:{validate:(0,s.assertNodeType)("BlockStatement")},generator:{default:!1,validate:(0,s.assertValueType)("boolean")},async:{default:!1,validate:(0,s.assertValueType)("boolean")}},visitor:["key","params","body","decorators","returnType","typeParameters"],aliases:["UserWhitespacable","Function","Scopable","BlockParent","FunctionParent","Method","ObjectMember"]}),(0,a.default)("ObjectProperty",{builder:["key","value","computed","shorthand","decorators"],fields:{computed:{validate:(0,s.assertValueType)("boolean"),default:!1},key:{validate:function(e,t,r){var n=e.computed?["Expression"]:["Identifier","StringLiteral","NumericLiteral"];s.assertNodeType.apply(void 0,n)(e,t,r)}},value:{validate:(0,s.assertNodeType)("Expression","Pattern","RestElement")},shorthand:{validate:(0,s.assertValueType)("boolean"),default:!1},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator"))),optional:!0}},visitor:["key","value","decorators"],aliases:["UserWhitespacable","Property","ObjectMember"]}),(0,a.default)("RestElement",{visitor:["argument","typeAnnotation"],aliases:["LVal"],fields:{argument:{validate:(0,s.assertNodeType)("LVal")},decorators:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Decorator")))}}}),(0,a.default)("ReturnStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,s.assertNodeType)("Expression"),optional:!0}}}),(0,a.default)("SequenceExpression",{visitor:["expressions"],fields:{expressions:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Expression")))}},aliases:["Expression"]}),(0,a.default)("SwitchCase",{visitor:["test","consequent"],fields:{test:{validate:(0,s.assertNodeType)("Expression"),optional:!0},consequent:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("Statement")))}}}),(0,a.default)("SwitchStatement",{visitor:["discriminant","cases"],aliases:["Statement","BlockParent","Scopable"],fields:{discriminant:{validate:(0,s.assertNodeType)("Expression")},cases:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("SwitchCase")))}}}),(0,a.default)("ThisExpression",{aliases:["Expression"]}),(0,a.default)("ThrowStatement",{visitor:["argument"],aliases:["Statement","Terminatorless","CompletionStatement"],fields:{argument:{validate:(0,s.assertNodeType)("Expression")}}}),(0,a.default)("TryStatement",{visitor:["block","handler","finalizer"],aliases:["Statement"],fields:{body:{validate:(0,s.assertNodeType)("BlockStatement")},handler:{optional:!0,handler:(0,s.assertNodeType)("BlockStatement")},finalizer:{optional:!0,validate:(0,s.assertNodeType)("BlockStatement")}}}),(0,a.default)("UnaryExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!0},argument:{validate:(0,s.assertNodeType)("Expression")},operator:{validate:s.assertOneOf.apply(void 0,i.UNARY_OPERATORS)}},visitor:["argument"],aliases:["UnaryLike","Expression"]}),(0,a.default)("UpdateExpression",{builder:["operator","argument","prefix"],fields:{prefix:{default:!1},argument:{validate:(0,s.assertNodeType)("Expression")},operator:{validate:s.assertOneOf.apply(void 0,i.UPDATE_OPERATORS)}},visitor:["argument"],aliases:["Expression"]}),(0,a.default)("VariableDeclaration",{builder:["kind","declarations"],visitor:["declarations"],aliases:["Statement","Declaration"],fields:{kind:{validate:(0,s.chain)((0,s.assertValueType)("string"),(0,s.assertOneOf)("var","let","const"))},declarations:{validate:(0,s.chain)((0,s.assertValueType)("array"),(0,s.assertEach)((0,s.assertNodeType)("VariableDeclarator")))}}}),(0,a.default)("VariableDeclarator",{visitor:["id","init"],fields:{id:{validate:(0,s.assertNodeType)("LVal")},init:{optional:!0,validate:(0,s.assertNodeType)("Expression")}}}),(0,a.default)("WhileStatement",{visitor:["test","body"],aliases:["Statement","BlockParent","Loop","While","Scopable"],fields:{test:{validate:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("BlockStatement","Statement")}}}),(0,a.default)("WithStatement",{visitor:["object","body"],aliases:["Statement"],fields:{object:{object:(0,s.assertNodeType)("Expression")},body:{validate:(0,s.assertNodeType)("BlockStatement","Statement")}}})},{"../constants":167,"../index":178,"./index":173}],170:[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)("Identifier","Pattern","RestElement")))},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":173}],171:[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":173}],172:[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)("DeclareOpaqueType",{visitor:["id","typeParameters","supertype"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareVariable",{visitor:["id"],aliases:["Flow","FlowDeclaration","Statement","Declaration"],fields:{}}),(0,i.default)("DeclareExportDeclaration",{visitor:["declaration","specifiers","source"],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)("OpaqueType",{visitor:["id","typeParameters","impltype","supertype"],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)("ObjectTypeSpreadProperty",{visitor:["argument"],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":173}],173:[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,u.default)(e)}function s(e){function t(t,r,n){if(!(i(n)===e))throw new TypeError("Property "+r+" expected type of "+e+" but got "+i(n))}return t.type=e,t}r.__esModule=!0,r.DEPRECATED_KEYS=r.BUILDER_KEYS=r.NODE_FIELDS=r.ALIAS_KEYS=r.VISITOR_KEYS=void 0;var a=n(e("babel-runtime/core-js/get-iterator")),o=n(e("babel-runtime/core-js/json/stringify")),u=n(e("babel-runtime/helpers/typeof"));r.assertEach=function(e){function t(t,r,n){if(Array.isArray(n))for(var i=0;i=s.length)break;p=s[c++]}else{if((c=s.next()).done)break;p=c.value}var h=p;if(l.is(h,n)){i=!0;break}}if(!i)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,o.default)(r)+" but instead got "+(0,o.default)(n&&n.type))}for(var t=arguments.length,r=Array(t),n=0;n=u.length)break;h=u[p++]}else{if((p=u.next()).done)break;h=p.value}var f=h;if(i(n)===f||l.is(f,n)){s=!0;break}}if(!s)throw new TypeError("Property "+t+" of "+e.type+" expected node to be of a type "+(0,o.default)(r)+" but instead got "+(0,o.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()).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&&m[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&&(d[t.deprecatedAlias]=e);for(var n=t.visitor.concat(t.builder),o=Array.isArray(n),u=0,n=o?n:(0,a.default)(n);;){var l;if(o){if(u>=n.length)break;l=n[u++]}else{if((u=n.next()).done)break;l=u.value}var y=l;t.fields[y]=t.fields[y]||{}}for(var g in t.fields){var b=t.fields[g];-1===t.builder.indexOf(g)&&(b.optional=!0),void 0===b.default?b.default=null:b.validate||(b.validate=s(i(b.default)))}c[e]=t.visitor,f[e]=t.builder,h[e]=t.fields,p[e]=t.aliases,m[e]=t};var 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}(e("../index")),c=r.VISITOR_KEYS={},p=r.ALIAS_KEYS={},h=r.NODE_FIELDS={},f=r.BUILDER_KEYS={},d=r.DEPRECATED_KEYS={},m={}},{"../index":178,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/helpers/typeof":138}],174:[function(e,t,r){"use strict";e("./index"),e("./core"),e("./es2015"),e("./flow"),e("./jsx"),e("./misc"),e("./experimental")},{"./core":169,"./es2015":170,"./experimental":171,"./flow":172,"./index":173,"./jsx":175,"./misc":176}],175:[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":173}],176:[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":173}],177:[function(e,t,r){"use strict";function n(e){for(var t={},r={},s=[],a=[],o=0;o=0)){if(i.isAnyTypeAnnotation(u))return[u];if(i.isFlowBaseAnnotation(u))r[u.type]=u;else if(i.isUnionTypeAnnotation(u))s.indexOf(u.types)<0&&(e=e.concat(u.types),s.push(u.types));else if(i.isGenericTypeAnnotation(u)){var l=u.id.name;if(t[l]){var c=t[l];c.typeParameters?u.typeParameters&&(c.typeParameters.params=n(c.typeParameters.params.concat(u.typeParameters.params))):c=u.typeParameters}else t[l]=u}else a.push(u)}}for(var p in r)a.push(r[p]);for(var h in t)a.push(t[h]);return a}r.__esModule=!0,r.createUnionTypeAnnotation=function(e){var t=n(e);return 1===t.length?t[0]:i.unionTypeAnnotation(t)},r.removeTypeDuplicates=n,r.createTypeAnnotationBasedOnTypeof=function(e){if("string"===e)return i.stringTypeAnnotation();if("number"===e)return i.numberTypeAnnotation();if("undefined"===e)return i.voidTypeAnnotation();if("boolean"===e)return i.booleanTypeAnnotation();if("function"===e)return i.genericTypeAnnotation(i.identifier("Function"));if("object"===e)return i.genericTypeAnnotation(i.identifier("Object"));if("symbol"===e)return i.genericTypeAnnotation(i.identifier("Symbol"));throw new Error("Invalid typeof value")};var 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}(e("./index"))},{"./index":178}],178:[function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function i(e){var t=F["is"+e];t||(t=F["is"+e]=function(t,r){return F.is(e,t,r)}),F["assert"+e]=function(r,n){if(n=n||{},!t(r,n))throw new Error("Expected type "+(0,b.default)(e)+" with option "+(0,b.default)(n))}}function s(e,t){if(e===t)return!0;if(F.ALIAS_KEYS[t])return!1;var r=F.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,y.default)(n);;){var a;if(i){if(s>=n.length)break;a=n[s++]}else{if((s=n.next()).done)break;a=s.value}if(e===a)return!0}}return!1}function a(e,t,r){if(e){var n=F.NODE_FIELDS[e.type];if(n){var i=n[t];i&&i.validate&&(i.optional&&null==r||i.validate(e,t,r))}}}function o(e){if(!e)return e;var t={};for(var r in e)"_"!==r[0]&&(t[r]=e[r]);return t}function u(e,t){p("trailingComments",e,t)}function l(e,t){p("leadingComments",e,t)}function c(e,t){p("innerComments",e,t)}function p(e,t,r){t&&r&&(t[e]=(0,_.default)([].concat(t[e],r[e]).filter(Boolean)))}function h(e){return!(!e||!w.VISITOR_KEYS[e.type])}function f(e,t,r){if(e){var n=F.VISITOR_KEYS[e.type];if(n){t(e,r=r||{});for(var 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()).done)break;o=a.value}var u=e[o];if(Array.isArray(u))for(var l=u,c=Array.isArray(l),p=0,l=c?l:(0,y.default)(l);;){var h;if(c){if(p>=l.length)break;h=l[p++]}else{if((p=l.next()).done)break;h=p.value}f(h,t,r)}else f(u,t,r)}}}}function d(e,t){for(var r=(t=t||{}).preserveComments?O:j,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()).done)break;s=i.value}var a=s;null!=e[a]&&(e[a]=void 0)}for(var o in e)"_"===o[0]&&null!=e[o]&&(e[o]=void 0);for(var u=(0,m.default)(e),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()).done)break;p=c.value}e[p]=null}}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 m=n(e("babel-runtime/core-js/object/get-own-property-symbols")),y=n(e("babel-runtime/core-js/get-iterator")),g=n(e("babel-runtime/core-js/object/keys")),b=n(e("babel-runtime/core-js/json/stringify")),v=e("./constants");Object.defineProperty(r,"STATEMENT_OR_BLOCK_KEYS",{enumerable:!0,get:function(){return v.STATEMENT_OR_BLOCK_KEYS}}),Object.defineProperty(r,"FLATTENABLE_KEYS",{enumerable:!0,get:function(){return v.FLATTENABLE_KEYS}}),Object.defineProperty(r,"FOR_INIT_KEYS",{enumerable:!0,get:function(){return v.FOR_INIT_KEYS}}),Object.defineProperty(r,"COMMENT_KEYS",{enumerable:!0,get:function(){return v.COMMENT_KEYS}}),Object.defineProperty(r,"LOGICAL_OPERATORS",{enumerable:!0,get:function(){return v.LOGICAL_OPERATORS}}),Object.defineProperty(r,"UPDATE_OPERATORS",{enumerable:!0,get:function(){return v.UPDATE_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.BOOLEAN_NUMBER_BINARY_OPERATORS}}),Object.defineProperty(r,"EQUALITY_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.EQUALITY_BINARY_OPERATORS}}),Object.defineProperty(r,"COMPARISON_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.COMPARISON_BINARY_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.BOOLEAN_BINARY_OPERATORS}}),Object.defineProperty(r,"NUMBER_BINARY_OPERATORS",{enumerable:!0,get:function(){return v.NUMBER_BINARY_OPERATORS}}),Object.defineProperty(r,"BINARY_OPERATORS",{enumerable:!0,get:function(){return v.BINARY_OPERATORS}}),Object.defineProperty(r,"BOOLEAN_UNARY_OPERATORS",{enumerable:!0,get:function(){return v.BOOLEAN_UNARY_OPERATORS}}),Object.defineProperty(r,"NUMBER_UNARY_OPERATORS",{enumerable:!0,get:function(){return v.NUMBER_UNARY_OPERATORS}}),Object.defineProperty(r,"STRING_UNARY_OPERATORS",{enumerable:!0,get:function(){return v.STRING_UNARY_OPERATORS}}),Object.defineProperty(r,"UNARY_OPERATORS",{enumerable:!0,get:function(){return v.UNARY_OPERATORS}}),Object.defineProperty(r,"INHERIT_KEYS",{enumerable:!0,get:function(){return v.INHERIT_KEYS}}),Object.defineProperty(r,"BLOCK_SCOPED_SYMBOL",{enumerable:!0,get:function(){return v.BLOCK_SCOPED_SYMBOL}}),Object.defineProperty(r,"NOT_LOCAL_BINDING",{enumerable:!0,get:function(){return v.NOT_LOCAL_BINDING}}),r.is=function(e,t,r){return!!t&&!!s(t.type,e)&&(void 0===r||F.shallowEqual(t,r))},r.isType=s,r.validate=a,r.shallowEqual=function(e,t){for(var r=(0,g.default)(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()).done)break;s=i.value}var a=s;if(e[a]!==t[a])return!1}return!0},r.appendToMemberExpression=function(e,t,r){return e.object=F.memberExpression(e.object,e.property,e.computed),e.property=t,e.computed=!!r,e},r.prependToMemberExpression=function(e,t){return e.object=F.memberExpression(t,e.object),e},r.ensureBlock=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"body";return e[t]=F.toBlock(e[t],e)},r.clone=o,r.cloneWithoutLoc=function(e){var t=o(e);return delete t.loc,t},r.cloneDeep=function(e){if(!e)return e;var t={};for(var r in e)if("_"!==r[0]){var n=e[r];n&&(n.type?n=F.cloneDeep(n):Array.isArray(n)&&(n=n.map(F.cloneDeep))),t[r]=n}return t},r.buildMatchMemberExpression=function(e,t){var r=e.split(".");return function(e){if(!F.isMemberExpression(e))return!1;for(var n=[e],i=0;n.length;){var s=n.shift();if(t&&i===r.length)return!0;if(F.isIdentifier(s)){if(r[i]!==s.name)return!1}else{if(!F.isStringLiteral(s)){if(F.isMemberExpression(s)){if(s.computed&&!F.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}},r.removeComments=function(e){for(var t=F.COMMENT_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()).done)break;i=n.value}delete e[i]}return e},r.inheritsComments=function(e,t){return u(e,t),l(e,t),c(e,t),e},r.inheritTrailingComments=u,r.inheritLeadingComments=l,r.inheritInnerComments=c,r.inherits=function(e,t){if(!e||!t)return e;for(var r=F.INHERIT_KEYS.optional,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()).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=F.INHERIT_KEYS.force,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()).done)break;p=c.value}var h=p;e[h]=t[h]}return F.inheritsComments(e,t),e},r.assertNode=function(e){if(!h(e))throw new TypeError("Not a valid node "+(e&&e.type))},r.isNode=h,r.traverseFast=f,r.removeProperties=d,r.removePropertiesDeep=function(e,t){return f(e,d,t),e};var x=e("./retrievers");Object.defineProperty(r,"getBindingIdentifiers",{enumerable:!0,get:function(){return x.getBindingIdentifiers}}),Object.defineProperty(r,"getOuterBindingIdentifiers",{enumerable:!0,get:function(){return x.getOuterBindingIdentifiers}});var E=e("./validators");Object.defineProperty(r,"isBinding",{enumerable:!0,get:function(){return E.isBinding}}),Object.defineProperty(r,"isReferenced",{enumerable:!0,get:function(){return E.isReferenced}}),Object.defineProperty(r,"isValidIdentifier",{enumerable:!0,get:function(){return E.isValidIdentifier}}),Object.defineProperty(r,"isLet",{enumerable:!0,get:function(){return E.isLet}}),Object.defineProperty(r,"isBlockScoped",{enumerable:!0,get:function(){return E.isBlockScoped}}),Object.defineProperty(r,"isVar",{enumerable:!0,get:function(){return E.isVar}}),Object.defineProperty(r,"isSpecifierDefault",{enumerable:!0,get:function(){return E.isSpecifierDefault}}),Object.defineProperty(r,"isScope",{enumerable:!0,get:function(){return E.isScope}}),Object.defineProperty(r,"isImmutable",{enumerable:!0,get:function(){return E.isImmutable}}),Object.defineProperty(r,"isNodesEquivalent",{enumerable:!0,get:function(){return E.isNodesEquivalent}});var A=e("./converters");Object.defineProperty(r,"toComputedKey",{enumerable:!0,get:function(){return A.toComputedKey}}),Object.defineProperty(r,"toSequenceExpression",{enumerable:!0,get:function(){return A.toSequenceExpression}}),Object.defineProperty(r,"toKeyAlias",{enumerable:!0,get:function(){return A.toKeyAlias}}),Object.defineProperty(r,"toIdentifier",{enumerable:!0,get:function(){return A.toIdentifier}}),Object.defineProperty(r,"toBindingIdentifierName",{enumerable:!0,get:function(){return A.toBindingIdentifierName}}),Object.defineProperty(r,"toStatement",{enumerable:!0,get:function(){return A.toStatement}}),Object.defineProperty(r,"toExpression",{enumerable:!0,get:function(){return A.toExpression}}),Object.defineProperty(r,"toBlock",{enumerable:!0,get:function(){return A.toBlock}}),Object.defineProperty(r,"valueToNode",{enumerable:!0,get:function(){return A.valueToNode}});var D=e("./flow");Object.defineProperty(r,"createUnionTypeAnnotation",{enumerable:!0,get:function(){return D.createUnionTypeAnnotation}}),Object.defineProperty(r,"removeTypeDuplicates",{enumerable:!0,get:function(){return D.removeTypeDuplicates}}),Object.defineProperty(r,"createTypeAnnotationBasedOnTypeof",{enumerable:!0,get:function(){return D.createTypeAnnotationBasedOnTypeof}});var C=n(e("to-fast-properties")),S=n(e("lodash/clone")),_=n(e("lodash/uniq"));e("./definitions/init");var w=e("./definitions"),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}(e("./react")),F=r;r.VISITOR_KEYS=w.VISITOR_KEYS,r.ALIAS_KEYS=w.ALIAS_KEYS,r.NODE_FIELDS=w.NODE_FIELDS,r.BUILDER_KEYS=w.BUILDER_KEYS,r.DEPRECATED_KEYS=w.DEPRECATED_KEYS,r.react=k;for(var T in F.VISITOR_KEYS)i(T);F.FLIPPED_ALIAS_KEYS={},(0,g.default)(F.ALIAS_KEYS).forEach(function(e){F.ALIAS_KEYS[e].forEach(function(t){(F.FLIPPED_ALIAS_KEYS[t]=F.FLIPPED_ALIAS_KEYS[t]||[]).push(e)})}),(0,g.default)(F.FLIPPED_ALIAS_KEYS).forEach(function(e){F[e.toUpperCase()+"_TYPES"]=F.FLIPPED_ALIAS_KEYS[e],i(e)});r.TYPES=(0,g.default)(F.VISITOR_KEYS).concat((0,g.default)(F.FLIPPED_ALIAS_KEYS)).concat((0,g.default)(F.DEPRECATED_KEYS));(0,g.default)(F.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),o=0,i=s?i:(0,y.default)(i);;){var u;if(s){if(o>=i.length)break;u=i[o++]}else{if((o=i.next()).done)break;u=o.value}var l=u,c=F.NODE_FIELDS[e][l],p=arguments[n++];void 0===p&&(p=(0,S.default)(c.default)),t[l]=p}for(var h in t)a(t,h,t[h]);return t}var r=F.BUILDER_KEYS[e];F[e]=t,F[e[0].toLowerCase()+e.slice(1)]=t});var P=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=F.DEPRECATED_KEYS[e];F[e]=F[e[0].toLowerCase()+e.slice(1)]=t(F[r]),F["is"+e]=t(F["is"+r]),F["assert"+e]=t(F["assert"+r])};for(var B in F.DEPRECATED_KEYS)P(B);(0,C.default)(F),(0,C.default)(F.VISITOR_KEYS);var O=["tokens","start","end","loc","raw","rawValue"],j=F.COMMENT_KEYS.concat(["comments"]).concat(O)},{"./constants":167,"./converters":168,"./definitions":173,"./definitions/init":174,"./flow":177,"./react":179,"./retrievers":180,"./validators":181,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/json/stringify":121,"babel-runtime/core-js/object/get-own-property-symbols":126,"babel-runtime/core-js/object/keys":127,"lodash/clone":491,"lodash/uniq":540,"to-fast-properties":607}],179:[function(e,t,r){"use strict";function n(e,t){for(var r=e.value.split(/\r\n|\n|\r/),n=0,s=0;s=r.length)break;l=r[u++]}else{if((u=r.next()).done)break;l=u.value}var p=l;if((0,a.default)(e[p])!==(0,a.default)(t[p]))return!1;if(Array.isArray(e[p])){if(!Array.isArray(t[p]))return!1;if(e[p].length!==t[p].length)return!1;for(var h=0;h=0)return!0}else if(i===e)return!0}return!1},r.isReferenced=function(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,o.default)(r);;){var s;if(n){if(i>=r.length)break;s=r[i++]}else{if((i=r.next()).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},r.isValidIdentifier=function(e){return"string"==typeof e&&!l.default.keyword.isReservedWordES6(e,!0)&&"await"!==e&&l.default.keyword.isIdentifierNameES6(e)},r.isLet=function(e){return c.isVariableDeclaration(e)&&("var"!==e.kind||e[p.BLOCK_SCOPED_SYMBOL])},r.isBlockScoped=function(e){return c.isFunctionDeclaration(e)||c.isClassDeclaration(e)||c.isLet(e)},r.isVar=function(e){return c.isVariableDeclaration(e,{kind:"var"})&&!e[p.BLOCK_SCOPED_SYMBOL]},r.isSpecifierDefault=function(e){return c.isImportDefaultSpecifier(e)||c.isIdentifier(e.imported||e.exported,{name:"default"})},r.isScope=function(e,t){return(!c.isBlockStatement(e)||!c.isFunction(t,{body:e}))&&c.isScopable(e)},r.isImmutable=function(e){return!!c.isType(e.type,"Immutable")||!!c.isIdentifier(e)&&"undefined"===e.name},r.isNodesEquivalent=i;var u=e("./retrievers"),l=n(e("esutils")),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}(e("./index")),p=e("./constants")},{"./constants":167,"./index":178,"./retrievers":180,"babel-runtime/core-js/get-iterator":120,"babel-runtime/core-js/object/keys":127,"babel-runtime/helpers/typeof":138,esutils:185}],182:[function(e,t,r){arguments[4][25][0].apply(r,arguments)},{dup:25}],183:[function(e,t,r){arguments[4][26][0].apply(r,arguments)},{dup:26}],184:[function(e,t,r){arguments[4][27][0].apply(r,arguments)},{"./code":183,dup:27}],185:[function(e,t,r){arguments[4][28][0].apply(r,arguments)},{"./ast":182,"./code":183,"./keyword":184,dup:28}],186:[function(e,t,r){"use strict";function n(e){return e=e.split(" "),function(t){return e.indexOf(t)>=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&&g.test(String.fromCharCode(e)):i(e,v)))}function a(e){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&b.test(String.fromCharCode(e)):i(e,v)||i(e,x))))}function o(e){return 10===e||13===e||8232===e||8233===e}function u(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(55296+(e-65536>>10),56320+(e-65536&1023))}function l(e,t,r,n){return e.type=t,e.end=r,e.loc.end=n,this.processComment(e),e}function c(e){return e[e.length-1]}function p(e){return e&&"Property"===e.type&&"init"===e.kind&&!1===e.method}function h(e){return"JSXIdentifier"===e.type?e.name:"JSXNamespacedName"===e.type?e.namespace.name+":"+e.name.name:"JSXMemberExpression"===e.type?h(e.object)+"."+h(e.property):void 0}Object.defineProperty(r,"__esModule",{value:!0});var f={6:n("enum await"),strict:n("implements interface let package private protected public static yield"),strictBind:n("eval arguments")},d=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"),m="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿕ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",y="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",g=new RegExp("["+m+"]"),b=new RegExp("["+m+y+"]");m=y=null;var v=[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],x=[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],E={sourceType:"script",sourceFilename:void 0,startLine:1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,plugins:[],strictMode:null},A="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},D=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},C=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)},S=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},_=!0,w=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};D(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},k=function(e){function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return D(this,t),n.keyword=r,S(this,e.call(this,r,n))}return C(t,e),t}(w),F=function(e){function t(r,n){return D(this,t),S(this,e.call(this,r,{beforeExpr:_,binop:n}))}return C(t,e),t}(w),T={num:new w("num",{startsExpr:!0}),regexp:new w("regexp",{startsExpr:!0}),string:new w("string",{startsExpr:!0}),name:new w("name",{startsExpr:!0}),eof:new w("eof"),bracketL:new w("[",{beforeExpr:_,startsExpr:!0}),bracketR:new w("]"),braceL:new w("{",{beforeExpr:_,startsExpr:!0}),braceBarL:new w("{|",{beforeExpr:_,startsExpr:!0}),braceR:new w("}"),braceBarR:new w("|}"),parenL:new w("(",{beforeExpr:_,startsExpr:!0}),parenR:new w(")"),comma:new w(",",{beforeExpr:_}),semi:new w(";",{beforeExpr:_}),colon:new w(":",{beforeExpr:_}),doubleColon:new w("::",{beforeExpr:_}),dot:new w("."),question:new w("?",{beforeExpr:_}),arrow:new w("=>",{beforeExpr:_}),template:new w("template"),ellipsis:new w("...",{beforeExpr:_}),backQuote:new w("`",{startsExpr:!0}),dollarBraceL:new w("${",{beforeExpr:_,startsExpr:!0}),at:new w("@"),eq:new w("=",{beforeExpr:_,isAssign:!0}),assign:new w("_=",{beforeExpr:_,isAssign:!0}),incDec:new w("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new w("prefix",{beforeExpr:_,prefix:!0,startsExpr:!0}),logicalOR:new F("||",1),logicalAND:new F("&&",2),bitwiseOR:new F("|",3),bitwiseXOR:new F("^",4),bitwiseAND:new F("&",5),equality:new F("==/!=",6),relational:new F("",7),bitShift:new F("<>",8),plusMin:new w("+/-",{beforeExpr:_,binop:9,prefix:!0,startsExpr:!0}),modulo:new F("%",10),star:new F("*",10),slash:new F("/",10),exponent:new w("**",{beforeExpr:_,binop:11,rightAssociative:!0})},P={break:new k("break"),case:new k("case",{beforeExpr:_}),catch:new k("catch"),continue:new k("continue"),debugger:new k("debugger"),default:new k("default",{beforeExpr:_}),do:new k("do",{isLoop:!0,beforeExpr:_}),else:new k("else",{beforeExpr:_}),finally:new k("finally"),for:new k("for",{isLoop:!0}),function:new k("function",{startsExpr:!0}),if:new k("if"),return:new k("return",{beforeExpr:_}),switch:new k("switch"),throw:new k("throw",{beforeExpr:_}),try:new k("try"),var:new k("var"),let:new k("let"),const:new k("const"),while:new k("while",{isLoop:!0}),with:new k("with"),new:new k("new",{beforeExpr:_,startsExpr:!0}),this:new k("this",{startsExpr:!0}),super:new k("super",{startsExpr:!0}),class:new k("class"),extends:new k("extends",{beforeExpr:_}),export:new k("export"),import:new k("import",{startsExpr:!0}),yield:new k("yield",{beforeExpr:_,startsExpr:!0}),null:new k("null",{startsExpr:!0}),true:new k("true",{startsExpr:!0}),false:new k("false",{startsExpr:!0}),in:new k("in",{beforeExpr:_,binop:7}),instanceof:new k("instanceof",{beforeExpr:_,binop:7}),typeof:new k("typeof",{beforeExpr:_,prefix:!0,startsExpr:!0}),void:new k("void",{beforeExpr:_,prefix:!0,startsExpr:!0}),delete:new k("delete",{beforeExpr:_,prefix:!0,startsExpr:!0})};Object.keys(P).forEach(function(e){T["_"+e]=P[e]});var B=/\r\n?|\n|\u2028|\u2029/,O=new RegExp(B.source,"g"),j=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,N=function e(t,r,n,i){D(this,e),this.token=t,this.isExpr=!!r,this.preserveSpace=!!n,this.override=i},I={braceStatement:new N("{",!1),braceExpression:new N("{",!0),templateQuasi:new N("${",!0),parenStatement:new N("(",!1),parenExpression:new N("(",!0),template:new N("`",!0,!0,function(e){return e.readTmplToken()}),functionExpression:new N("function",!0)};T.parenR.updateContext=T.braceR.updateContext=function(){if(1!==this.state.context.length){var e=this.state.context.pop();e===I.braceStatement&&this.curContext()===I.functionExpression?(this.state.context.pop(),this.state.exprAllowed=!1):e===I.templateQuasi?this.state.exprAllowed=!0:this.state.exprAllowed=!e.isExpr}else this.state.exprAllowed=!0},T.name.updateContext=function(e){this.state.exprAllowed=!1,e!==T._let&&e!==T._const&&e!==T._var||B.test(this.input.slice(this.state.end))&&(this.state.exprAllowed=!0)},T.braceL.updateContext=function(e){this.state.context.push(this.braceIsBlock(e)?I.braceStatement:I.braceExpression),this.state.exprAllowed=!0},T.dollarBraceL.updateContext=function(){this.state.context.push(I.templateQuasi),this.state.exprAllowed=!0},T.parenL.updateContext=function(e){var t=e===T._if||e===T._for||e===T._with||e===T._while;this.state.context.push(t?I.parenStatement:I.parenExpression),this.state.exprAllowed=!0},T.incDec.updateContext=function(){},T._function.updateContext=function(){this.curContext()!==I.braceStatement&&this.state.context.push(I.functionExpression),this.state.exprAllowed=!1},T.backQuote.updateContext=function(){this.curContext()===I.template?this.state.context.pop():this.state.context.push(I.template),this.state.exprAllowed=!1};var L=function e(t,r){D(this,e),this.line=t,this.column=r},M=function e(t,r){D(this,e),this.start=t,this.end=r},R=function(){function e(){D(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.inClassProperty=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=T.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=[I.braceStatement],this.exprAllowed=!0,this.containsEsc=this.containsOctal=!1,this.octalPosition=null,this.invalidTemplateEscapePosition=null,this.exportedIdentifiers=[],this},e.prototype.curPosition=function(){return new L(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}(),V={},U=["jsx","doExpressions","objectRestSpread","decorators","classProperties","exportExtensions","asyncGenerators","functionBind","functionSent","dynamicImport","flow"],q=function(e){function t(r,n){D(this,t),r=function(e){var t={};for(var r in E)t[r]=e&&r in e?e[r]:E[r];return t}(r);var i=S(this,e.call(this,r,n));return i.options=r,i.inModule="module"===i.options.sourceType,i.input=n,i.plugins=i.loadPlugins(i.options.plugins),i.filename=r.sourceFilename,0===i.state.pos&&"#"===i.input[0]&&"!"===i.input[1]&&i.skipLineComment(2),i}return C(t,e),t.prototype.isReservedWord=function(e){return"await"===e?this.inModule:f[6](e)},t.prototype.hasPlugin=function(e){return!!(this.plugins["*"]&&U.indexOf(e)>-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(V).filter(function(e){return"flow"!==e&&"estree"!==e});t.push("flow"),t.forEach(function(t){var r=V[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})).push("flow"),e.indexOf("estree")>=0&&(e=e.filter(function(e){return"estree"!==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()).done)break;s=i.value}var a=s;if(!t[a]){t[a]=!0;var o=V[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}(function(){function e(t,r){D(this,e),this.state=new R,this.state.init(t,r)}return e.prototype.next=function(){this.isLookahead||this.state.tokens.push(new function e(t){D(this,e),this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new M(t.startLoc,t.endLoc)}(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 d(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(T.num)||this.match(T.string)){for(this.state.pos=this.state.start;this.state.pos=this.input.length?this.finishToken(T.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);if(e<=55295||e>=57344)return e;return(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 M(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,O.lastIndex=t;for(var n=void 0;(n=O.exec(this.input))&&n.index8&&e<14||e>=5760&&j.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(T.ellipsis)):(++this.state.pos,this.finishToken(T.dot))},e.prototype.readToken_slash=function(){if(this.state.exprAllowed)return++this.state.pos,this.readRegexp();return 61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.assign,2):this.finishOp(T.slash,1)},e.prototype.readToken_mult_modulo=function(e){var t=42===e?T.star:T.modulo,r=1,n=this.input.charCodeAt(this.state.pos+1);return 42===n&&(r++,n=this.input.charCodeAt(this.state.pos+2),t=T.exponent),61===n&&(r++,t=T.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?T.logicalOR:T.logicalAND,2):61===t?this.finishOp(T.assign,2):124===e&&125===t&&this.hasPlugin("flow")?this.finishOp(T.braceBarR,2):this.finishOp(124===e?T.bitwiseOR:T.bitwiseAND,1)},e.prototype.readToken_caret=function(){return 61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.assign,2):this.finishOp(T.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)&&B.test(this.input.slice(this.state.lastTokEnd,this.state.pos))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(T.incDec,2):61===t?this.finishOp(T.assign,2):this.finishOp(T.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(T.assign,r+1):this.finishOp(T.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(T.relational,r))},e.prototype.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.state.pos+1);return 61===t?this.finishOp(T.equality,61===this.input.charCodeAt(this.state.pos+2)?3:2):61===e&&62===t?(this.state.pos+=2,this.finishToken(T.arrow)):this.finishOp(61===e?T.eq:T.prefix,1)},e.prototype.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.state.pos,this.finishToken(T.parenL);case 41:return++this.state.pos,this.finishToken(T.parenR);case 59:return++this.state.pos,this.finishToken(T.semi);case 44:return++this.state.pos,this.finishToken(T.comma);case 91:return++this.state.pos,this.finishToken(T.bracketL);case 93:return++this.state.pos,this.finishToken(T.bracketR);case 123:return this.hasPlugin("flow")&&124===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.braceBarL,2):(++this.state.pos,this.finishToken(T.braceL));case 125:return++this.state.pos,this.finishToken(T.braceR);case 58:return this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(T.doubleColon,2):(++this.state.pos,this.finishToken(T.colon));case 63:return++this.state.pos,this.finishToken(T.question);case 64:return++this.state.pos,this.finishToken(T.at);case 96:return++this.state.pos,this.finishToken(T.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(T.prefix,1)}this.raise(this.state.pos,"Unexpected character '"+u(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(B.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(T.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(T.num,t)},e.prototype.readNumber=function(e){var t=this.state.pos,r=48===this.input.charCodeAt(t),n=!1;e||null!==this.readInt(10)||this.raise(t,"Invalid number"),r&&this.state.pos==t+1&&(r=!1);var i=this.input.charCodeAt(this.state.pos);46!==i||r||(++this.state.pos,this.readInt(10),n=!0,i=this.input.charCodeAt(this.state.pos)),69!==i&&101!==i||r||(43!==(i=this.input.charCodeAt(++this.state.pos))&&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?this.state.strict?this.raise(t,"Invalid number"):o=/[89]/.test(a)?parseInt(a,10):parseInt(a,8):o=parseInt(a,10),this.finishToken(T.num,o)},e.prototype.readCodePoint=function(e){var t=void 0;if(123===this.input.charCodeAt(this.state.pos)){var r=++this.state.pos;if(t=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos,e),++this.state.pos,null===t)--this.state.invalidTemplateEscapePosition;else if(t>1114111){if(!e)return this.state.invalidTemplateEscapePosition=r-2,null;this.raise(r,"Code point out of bounds")}}else t=this.readHexChar(4,e);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):(o(n)&&this.raise(this.state.start,"Unterminated string constant"),++this.state.pos)}return t+=this.input.slice(r,this.state.pos++),this.finishToken(T.string,t)},e.prototype.readTmplToken=function(){for(var e="",t=this.state.pos,r=!1;;){this.state.pos>=this.input.length&&this.raise(this.state.start,"Unterminated template");var n=this.input.charCodeAt(this.state.pos);if(96===n||36===n&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(T.template)?36===n?(this.state.pos+=2,this.finishToken(T.dollarBraceL)):(++this.state.pos,this.finishToken(T.backQuote)):(e+=this.input.slice(t,this.state.pos),this.finishToken(T.template,r?null:e));if(92===n){e+=this.input.slice(t,this.state.pos);var i=this.readEscapedChar(!0);null===i?r=!0:e+=i,t=this.state.pos}else if(o(n)){switch(e+=this.input.slice(t,this.state.pos),++this.state.pos,n){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(n)}++this.state.curLine,this.state.lineStart=this.state.pos,t=this.state.pos}else++this.state.pos}},e.prototype.readEscapedChar=function(e){var t=!e,r=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,r){case 110:return"\n";case 114:return"\r";case 120:var n=this.readHexChar(2,t);return null===n?null:String.fromCharCode(n);case 117:var i=this.readCodePoint(t);return null===i?null:u(i);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(r>=48&&r<=55){var s=this.state.pos-1,a=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],o=parseInt(a,8);if(o>255&&(a=a.slice(0,-1),o=parseInt(a,8)),o>0){if(e)return this.state.invalidTemplateEscapePosition=s,null;this.state.strict?this.raise(s,"Octal literal in strict mode"):this.state.containsOctal||(this.state.containsOctal=!0,this.state.octalPosition=s)}return this.state.pos+=a.length-1,String.fromCharCode(o)}return String.fromCharCode(r)}},e.prototype.readHexChar=function(e,t){var r=this.state.pos,n=this.readInt(16,e);return null===n&&(t?this.raise(r,"Bad character escape sequence"):(this.state.pos=r-1,this.state.invalidTemplateEscapePosition=r-1)),n},e.prototype.readWord1=function(){this.state.containsEsc=!1;for(var e="",t=!0,r=this.state.pos;this.state.pos1&&void 0!==arguments[1]?arguments[1]:"Unexpected token";t&&"object"===(void 0===t?"undefined":A(t))&&t.label&&(t="Unexpected token, expected "+t.label),this.raise(null!=e?e:this.state.start,t)};var X=q.prototype;X.parseTopLevel=function(e,t){return t.sourceType=this.options.sourceType,this.parseBlockBody(t,!0,!0,T.eof),e.program=this.finishNode(t,"Program"),e.comments=this.state.comments,e.tokens=this.state.tokens,this.finishNode(e,"File")};var W={kind:"loop"},J={kind:"switch"};X.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)},X.parseStatement=function(e,t){this.match(T.at)&&this.parseDecorators(!0);var r=this.state.type,n=this.startNode();switch(r){case T._break:case T._continue:return this.parseBreakContinueStatement(n,r.keyword);case T._debugger:return this.parseDebuggerStatement(n);case T._do:return this.parseDoStatement(n);case T._for:return this.parseForStatement(n);case T._function:return e||this.unexpected(),this.parseFunctionStatement(n);case T._class:return e||this.unexpected(),this.parseClass(n,!0);case T._if:return this.parseIfStatement(n);case T._return:return this.parseReturnStatement(n);case T._switch:return this.parseSwitchStatement(n);case T._throw:return this.parseThrowStatement(n);case T._try:return this.parseTryStatement(n);case T._let:case T._const:e||this.unexpected();case T._var:return this.parseVarStatement(n,r);case T._while:return this.parseWhileStatement(n);case T._with:return this.parseWithStatement(n);case T.braceL:return this.parseBlock();case T.semi:return this.parseEmptyStatement(n);case T._export:case T._import:if(this.hasPlugin("dynamicImport")&&this.lookahead().type===T.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===T._import?this.parseImport(n):this.parseExport(n);case T.name:if("async"===this.state.value){var i=this.state.clone();if(this.next(),this.match(T._function)&&!this.canInsertSemicolon())return this.expect(T._function),this.parseFunction(n,!0,!1,!0);this.state=i}}var s=this.state.value,a=this.parseExpression();return r===T.name&&"Identifier"===a.type&&this.eat(T.colon)?this.parseLabeledStatement(n,s,a):this.parseExpressionStatement(n,a)},X.takeDecorators=function(e){this.state.decorators.length&&(e.decorators=this.state.decorators,this.state.decorators=[])},X.parseDecorators=function(e){for(;this.match(T.at);){var t=this.parseDecorator();this.state.decorators.push(t)}e&&this.match(T._export)||this.match(T._class)||this.raise(this.state.start,"Leading decorators must be attached to a class declaration")},X.parseDecorator=function(){this.hasPlugin("decorators")||this.unexpected();var e=this.startNode();return this.next(),e.expression=this.parseMaybeAssign(),this.finishNode(e,"Decorator")},X.parseBreakContinueStatement=function(e,t){var r="break"===t;this.next(),this.isLineTerminator()?e.label=null:this.match(T.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()).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(T._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")},X.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},X.parseBlock=function(e){var t=this.startNode();return this.expect(T.braceL),this.parseBlockBody(t,e,!1,T.braceR),this.finishNode(t,"BlockStatement")},X.isValidDirective=function(e){return"ExpressionStatement"===e.type&&"StringLiteral"===e.expression.type&&!e.expression.extra.parenthesized},X.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)},X.parseFor=function(e,t){return e.init=t,this.expect(T.semi),e.test=this.match(T.semi)?null:this.parseExpression(),this.expect(T.semi),e.update=this.match(T.parenR)?null:this.parseExpression(),this.expect(T.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,"ForStatement")},X.parseForIn=function(e,t,r){var n=void 0;return r?(this.eatContextual("of"),n="ForAwaitStatement"):(n=this.match(T._in)?"ForInStatement":"ForOfStatement",this.next()),e.left=t,e.right=this.parseExpression(),this.expect(T.parenR),e.body=this.parseStatement(!1),this.state.labels.pop(),this.finishNode(e,n)},X.parseVar=function(e,t,r){for(e.declarations=[],e.kind=r.keyword;;){var n=this.startNode();if(this.parseVarHead(n),this.eat(T.eq)?n.init=this.parseMaybeAssign(t):r!==T._const||this.match(T._in)||this.isContextual("of")?"Identifier"===n.id.type||t&&(this.match(T._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(T.comma))break}return e},X.parseVarHead=function(e){e.id=this.parseBindingAtom(),this.checkLVal(e.id,!0,void 0,"variable declaration")},X.parseFunction=function(e,t,r,n,i){var s=this.state.inMethod;return this.state.inMethod=!1,this.initFunction(e,n),this.match(T.star)&&(e.async&&!this.hasPlugin("asyncGenerators")?this.unexpected():(e.generator=!0,this.next())),!t||i||this.match(T.name)||this.match(T._yield)||this.unexpected(),(this.match(T.name)||this.match(T._yield))&&(e.id=this.parseBindingIdentifier()),this.parseFunctionParams(e),this.parseFunctionBody(e,r),this.state.inMethod=s,this.finishNode(e,t?"FunctionDeclaration":"FunctionExpression")},X.parseFunctionParams=function(e){this.expect(T.parenL),e.params=this.parseBindingList(T.parenR)},X.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")},X.isClassProperty=function(){return this.match(T.eq)||this.match(T.semi)||this.match(T.braceR)},X.isClassMethod=function(){return this.match(T.parenL)},X.isNonstaticConstructor=function(e){return!(e.computed||e.static||"constructor"!==e.key.name&&"constructor"!==e.key.value)},X.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(T.braceL);!this.eat(T.braceR);)if(this.eat(T.semi))i.length>0&&this.raise(this.state.lastTokEnd,"Decorators must not be followed by a semicolon");else if(this.match(T.at))i.push(this.parseDecorator());else{var a=this.startNode();if(i.length&&(a.decorators=i,i=[]),a.static=!1,this.match(T.name)&&"static"===this.state.value){var o=this.parseIdentifier(!0);if(this.isClassMethod()){a.kind="method",a.computed=!1,a.key=o,this.parseClassMethod(s,a,!1,!1);continue}if(this.isClassProperty()){a.computed=!1,a.key=o,s.body.push(this.parseClassProperty(a));continue}a.static=!0}if(this.eat(T.star))a.kind="method",this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't be a generator"),a.computed||!a.static||"prototype"!==a.key.name&&"prototype"!==a.key.value||this.raise(a.key.start,"Classes may not have static property named prototype"),this.parseClassMethod(s,a,!0,!1);else{var u=this.match(T.name),l=this.parsePropertyName(a);if(a.computed||!a.static||"prototype"!==a.key.name&&"prototype"!==a.key.value||this.raise(a.key.start,"Classes may not have static property named prototype"),this.isClassMethod())this.isNonstaticConstructor(a)?(n?this.raise(l.start,"Duplicate constructor in the same class"):a.decorators&&this.raise(a.start,"You can't attach decorators to a class constructor"),n=!0,a.kind="constructor"):a.kind="method",this.parseClassMethod(s,a,!1,!1);else if(this.isClassProperty())this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Classes may not have a non-static field named 'constructor'"),s.body.push(this.parseClassProperty(a));else if(u&&"async"===l.name&&!this.isLineTerminator()){var c=this.hasPlugin("asyncGenerators")&&this.eat(T.star);a.kind="method",this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't be an async function"),this.parseClassMethod(s,a,c,!0)}else!u||"get"!==l.name&&"set"!==l.name||this.isLineTerminator()&&this.match(T.star)?this.hasPlugin("classConstructorCall")&&u&&"call"===l.name&&this.match(T.name)&&"constructor"===this.state.value?(r?this.raise(a.start,"Duplicate constructor call in the same class"):a.decorators&&this.raise(a.start,"You can't attach decorators to a class constructor"),r=!0,a.kind="constructorCall",this.parsePropertyName(a),this.parseClassMethod(s,a,!1,!1)):this.isLineTerminator()?(this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Classes may not have a non-static field named 'constructor'"),s.body.push(this.parseClassProperty(a))):this.unexpected():(a.kind=l.name,this.parsePropertyName(a),this.isNonstaticConstructor(a)&&this.raise(a.key.start,"Constructor can't have get/set modifier"),this.parseClassMethod(s,a,!1,!1),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},X.parseClassProperty=function(e){return this.state.inClassProperty=!0,this.match(T.eq)?(this.hasPlugin("classProperties")||this.unexpected(),this.next(),e.value=this.parseMaybeAssign()):e.value=null,this.semicolon(),this.state.inClassProperty=!1,this.finishNode(e,"ClassProperty")},X.parseClassMethod=function(e,t,r,n){this.parseMethod(t,r,n),e.body.push(this.finishNode(t,"ClassMethod"))},X.parseClassId=function(e,t,r){this.match(T.name)?e.id=this.parseIdentifier():r||!t?e.id=null:this.unexpected()},X.parseClassSuper=function(e){e.superClass=this.eat(T._extends)?this.parseExprSubscripts():null},X.parseExport=function(e){if(this.next(),this.match(T.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(T.comma)&&this.lookahead().type===T.star){this.expect(T.comma);var n=this.startNode();this.expect(T.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(T._default)){var i=this.startNode(),s=!1;return this.eat(T._function)?i=this.parseFunction(i,!0,!1,!1,!0):this.match(T._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")},X.parseExportDeclaration=function(){return this.parseStatement(!0)},X.isExportDefaultSpecifier=function(){if(this.match(T.name))return"async"!==this.state.value;if(!this.match(T._default))return!1;var e=this.lookahead();return e.type===T.comma||e.type===T.name&&"from"===e.value},X.parseExportSpecifiersMaybe=function(e){this.eat(T.comma)&&(e.specifiers=e.specifiers.concat(this.parseExportSpecifiers()))},X.parseExportFrom=function(e,t){this.eatContextual("from")?(e.source=this.match(T.string)?this.parseExprAtom():this.unexpected(),this.checkExport(e)):t?this.unexpected():e.source=null,this.semicolon()},X.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")},X.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()).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()).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)}},X.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()).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()).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)},X.checkDuplicateExports=function(e,t){this.state.exportedIdentifiers.indexOf(t)>-1&&this.raiseDuplicateExportError(e,t),this.state.exportedIdentifiers.push(t)},X.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.")},X.parseExportSpecifiers=function(){var e=[],t=!0,r=void 0;for(this.expect(T.braceL);!this.eat(T.braceR);){if(t)t=!1;else if(this.expect(T.comma),this.eat(T.braceR))break;var n=this.match(T._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},X.parseImport=function(e){return this.eat(T._import),this.match(T.string)?(e.specifiers=[],e.source=this.parseExprAtom()):(e.specifiers=[],this.parseImportSpecifiers(e),this.expectContextual("from"),e.source=this.match(T.string)?this.parseExprAtom():this.unexpected()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},X.parseImportSpecifiers=function(e){var t=!0;if(this.match(T.name)){var r=this.state.start,n=this.state.startLoc;if(e.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(),r,n)),!this.eat(T.comma))return}if(this.match(T.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(T.braceL);!this.eat(T.braceR);){if(t)t=!1;else if(this.eat(T.colon)&&this.unexpected(null,"ES2015 named imports do not destructure. Use another statement for destructuring after the import."),this.expect(T.comma),this.eat(T.braceR))break;this.parseImportSpecifier(e)}},X.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"))},X.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 z=q.prototype;z.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()).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";var u=e.argument;this.toAssignable(u,t,r);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 l="Invalid left-hand side"+(r?" in "+r:"expression");this.raise(e.start,l)}return e},z.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()).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()).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 Y=q.prototype;Y.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)}},Y.getExpression=function(){this.nextToken();var e=this.parseExpression();return this.match(T.eof)||this.unexpected(),e},Y.parseExpression=function(e,t){var r=this.state.start,n=this.state.startLoc,i=this.parseMaybeAssign(e,t);if(this.match(T.comma)){var s=this.startNodeAt(r,n);for(s.expressions=[i];this.eat(T.comma);)s.expressions.push(this.parseMaybeAssign(e,t));return this.toReferencedList(s.expressions),this.finishNode(s,"SequenceExpression")}return i},Y.parseMaybeAssign=function(e,t,r,n){var i=this.state.start,s=this.state.startLoc;if(this.match(T._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(T.parenL)||this.match(T.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(T.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},Y.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)},Y.parseConditional=function(e,t,r,n){if(this.eat(T.question)){var i=this.startNodeAt(r,n);return i.test=e,i.consequent=this.parseMaybeAssign(),this.expect(T.colon),i.alternate=this.parseMaybeAssign(t),this.finishNode(i,"ConditionalExpression")}return e},Y.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)},Y.parseExprOp=function(e,t,r,n,i){var s=this.state.type.binop;if(!(null==s||i&&this.match(T._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===T.logicalOR||o===T.logicalAND?"LogicalExpression":"BinaryExpression"),this.parseExprOp(a,t,r,n,i)}return e},Y.parseMaybeUnary=function(e){if(this.state.type.prefix){var t=this.startNode(),r=this.match(T.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!==T.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},Y.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)},Y.parseSubscripts=function(e,t,r,n){for(;;){if(!n&&this.eat(T.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(T.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(T.bracketL)){var a=this.startNodeAt(t,r);a.object=e,a.property=this.parseExpression(),a.computed=!0,this.expect(T.bracketR),e=this.finishNode(a,"MemberExpression")}else if(!n&&this.match(T.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(T.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(T.backQuote))return e;var l=this.startNodeAt(t,r);l.tag=e,l.quasi=this.parseTemplate(!0),e=this.finishNode(l,"TaggedTemplateExpression")}}},Y.parseCallExpressionArguments=function(e,t){for(var r=[],n=void 0,i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(T.comma),this.eat(e))break;this.match(T.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},Y.shouldParseAsyncArrow=function(){return this.match(T.arrow)},Y.parseAsyncArrowFromCallExpression=function(e,t){return this.expect(T.arrow),this.parseArrowExpression(e,t.arguments,!0)},Y.parseNoCallExpr=function(){var e=this.state.start,t=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),e,t,!0)},Y.parseExprAtom=function(e){var t=this.state.potentialArrowAt===this.state.start,r=void 0;switch(this.state.type){case T._super:return this.state.inMethod||this.state.inClassProperty||this.options.allowSuperOutsideMethod||this.raise(this.state.start,"'super' outside of function or class"),r=this.startNode(),this.next(),this.match(T.parenL)||this.match(T.bracketL)||this.match(T.dot)||this.unexpected(),this.match(T.parenL)&&"constructor"!==this.state.inMethod&&!this.options.allowSuperOutsideMethod&&this.raise(r.start,"super() outside of class constructor"),this.finishNode(r,"Super");case T._import:return this.hasPlugin("dynamicImport")||this.unexpected(),r=this.startNode(),this.next(),this.match(T.parenL)||this.unexpected(null,T.parenL),this.finishNode(r,"Import");case T._this:return r=this.startNode(),this.next(),this.finishNode(r,"ThisExpression");case T._yield:this.state.inGenerator&&this.unexpected();case T.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(T._function)&&!this.canInsertSemicolon())return this.next(),this.parseFunction(r,!1,!1,!0);if(t&&"async"===s.name&&this.match(T.name)){var a=[this.parseIdentifier()];return this.expect(T.arrow),this.parseArrowExpression(r,a,!0)}}return t&&!this.canInsertSemicolon()&&this.eat(T.arrow)?this.parseArrowExpression(r,[s]):s;case T._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 T.regexp:var c=this.state.value;return r=this.parseLiteral(c.value,"RegExpLiteral"),r.pattern=c.pattern,r.flags=c.flags,r;case T.num:return this.parseLiteral(this.state.value,"NumericLiteral");case T.string:return this.parseLiteral(this.state.value,"StringLiteral");case T._null:return r=this.startNode(),this.next(),this.finishNode(r,"NullLiteral");case T._true:case T._false:return r=this.startNode(),r.value=this.match(T._true),this.next(),this.finishNode(r,"BooleanLiteral");case T.parenL:return this.parseParenAndDistinguishExpression(null,null,t);case T.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(T.bracketR,!0,e),this.toReferencedList(r.elements),this.finishNode(r,"ArrayExpression");case T.braceL:return this.parseObj(!1,e);case T._function:return this.parseFunctionExpression();case T.at:this.parseDecorators();case T._class:return r=this.startNode(),this.takeDecorators(r),this.parseClass(r,!1);case T._new:return this.parseNew();case T.backQuote:return this.parseTemplate(!1);case T.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()}},Y.parseFunctionExpression=function(){var e=this.startNode(),t=this.parseIdentifier(!0);return this.state.inGenerator&&this.eat(T.dot)&&this.hasPlugin("functionSent")?this.parseMetaProperty(e,t,"sent"):this.parseFunction(e,!1)},Y.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")},Y.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)},Y.parseParenExpression=function(){this.expect(T.parenL);var e=this.parseExpression();return this.expect(T.parenR),e},Y.parseParenAndDistinguishExpression=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;var n=void 0;this.expect(T.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(T.parenR);){if(l)l=!1;else if(this.expect(T.comma,u.start||null),this.match(T.parenR)){p=this.state.start;break}if(this.match(T.ellipsis)){var h=this.state.start,f=this.state.startLoc;c=this.state.start,a.push(this.parseParenItem(this.parseRest(),h,f));break}a.push(this.parseMaybeAssign(!1,o,this.parseParenItem,u))}var d=this.state.start,m=this.state.startLoc;this.expect(T.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()).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)).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},Y.shouldParseArrow=function(){return!this.canInsertSemicolon()},Y.parseArrow=function(e){if(this.eat(T.arrow))return e},Y.parseParenItem=function(e){return e},Y.parseNew=function(){var e=this.startNode(),t=this.parseIdentifier(!0);if(this.eat(T.dot)){var r=this.parseMetaProperty(e,t,"target");return this.state.inFunction||this.raise(r.property.start,"new.target can only be used in functions"),r}return e.callee=this.parseNoCallExpr(),this.eat(T.parenL)?(e.arguments=this.parseExprList(T.parenR),this.toReferencedList(e.arguments)):e.arguments=[],this.finishNode(e,"NewExpression")},Y.parseTemplateElement=function(e){var t=this.startNode();return null===this.state.value&&(e&&this.hasPlugin("templateInvalidEscapes")?this.state.invalidTemplateEscapePosition=null:this.raise(this.state.invalidTemplateEscapePosition,"Invalid escape sequence in template")),t.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),t.tail=this.match(T.backQuote),this.finishNode(t,"TemplateElement")},Y.parseTemplate=function(e){var t=this.startNode();this.next(),t.expressions=[];var r=this.parseTemplateElement(e);for(t.quasis=[r];!r.tail;)this.expect(T.dollarBraceL),t.expressions.push(this.parseExpression()),this.expect(T.braceR),t.quasis.push(r=this.parseTemplateElement(e));return this.next(),this.finishNode(t,"TemplateLiteral")},Y.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(T.braceR);){if(i)i=!1;else if(this.expect(T.comma),this.eat(T.braceR))break;for(;this.match(T.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(T.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(T.braceR))break;if(this.match(T.comma)&&this.lookahead().type===T.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(T.star)),!e&&this.isContextual("async")){u&&this.unexpected();var f=this.parseIdentifier();this.match(T.colon)||this.match(T.parenL)||this.match(T.braceR)||this.match(T.eq)||this.match(T.comma)?(o.key=f,o.computed=!1):(l=!0,this.hasPlugin("asyncGenerators")&&(u=this.eat(T.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")},Y.isGetterOrSetterMethod=function(e,t){return!t&&!e.computed&&"Identifier"===e.key.type&&("get"===e.key.name||"set"===e.key.name)&&(this.match(T.string)||this.match(T.num)||this.match(T.bracketL)||this.match(T.name)||this.state.type.keyword)},Y.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")}},Y.parseObjectMethod=function(e,t,r,n){return r||t||this.match(T.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},Y.parseObjectProperty=function(e,t,r,n,i){return this.eat(T.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:(this.checkReservedWord(e.key.name,e.key.start,!0,!0),n?e.value=this.parseMaybeDefault(t,r,e.key.__clone()):this.match(T.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"))},Y.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},Y.parsePropertyName=function(e){if(this.eat(T.bracketL))e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(T.bracketR);else{e.computed=!1;var t=this.state.inPropertyName;this.state.inPropertyName=!0,e.key=this.match(T.num)||this.match(T.string)?this.parseExprAtom():this.parseIdentifier(!0),this.state.inPropertyName=t}return e.key},Y.initFunction=function(e,t){e.id=null,e.generator=!1,e.expression=!1,e.async=!!t},Y.parseMethod=function(e,t,r){var n=this.state.inMethod;return this.state.inMethod=e.kind||!0,this.initFunction(e,r),this.expect(T.parenL),e.params=this.parseBindingList(T.parenR),e.generator=!!t,this.parseFunctionBody(e),this.state.inMethod=n,e},Y.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")},Y.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()).done)break;s=i.value}if("use strict"===s.value.value)return!0}return!1},Y.parseFunctionBody=function(e,t){var r=t&&!this.match(T.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()).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}},Y.parseExprList=function(e,t,r){for(var n=[],i=!0;!this.eat(e);){if(i)i=!1;else if(this.expect(T.comma),this.eat(e))break;n.push(this.parseExprListItem(t,r))}return n},Y.parseExprListItem=function(e,t,r){return e&&this.match(T.comma)?null:this.match(T.ellipsis)?this.parseSpread(t):this.parseMaybeAssign(!1,t,this.parseParenItem,r)},Y.parseIdentifier=function(e){var t=this.startNode();return e||this.checkReservedWord(this.state.value,this.state.start,!!this.state.type.keyword,!1),this.match(T.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")},Y.checkReservedWord=function(e,t,r,n){(this.isReservedWord(e)||r&&this.isKeyword(e))&&this.raise(t,e+" is a reserved word"),this.state.strict&&(f.strict(e)||n&&f.strictBind(e))&&this.raise(t,e+" is a reserved word in strict mode")},Y.parseAwait=function(e){return this.state.inAsync||this.unexpected(),this.match(T.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")},Y.parseYield=function(){var e=this.startNode();return this.next(),this.match(T.semi)||this.canInsertSemicolon()||!this.match(T.star)&&!this.state.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(T.star),e.argument=this.parseMaybeAssign()),this.finishNode(e,"YieldExpression")};var H=q.prototype,$=["leadingComments","trailingComments","innerComments"],Q=function(){function e(t,r,n){D(this,e),this.type="",this.start=t,this.end=0,this.loc=new M(r),n&&(this.loc.filename=n)}return e.prototype.__clone=function(){var t=new e;for(var r in this)$.indexOf(r)<0&&(t[r]=this[r]);return t},e}();H.startNode=function(){return new Q(this.state.start,this.state.startLoc,this.filename)},H.startNodeAt=function(e,t){return new Q(e,t,this.filename)},H.finishNode=function(e,t){return l.call(this,e,t,this.state.lastTokEnd,this.state.lastTokEndLoc)},H.finishNodeAt=function(e,t,r,n){return l.call(this,e,t,r,n)};q.prototype.raise=function(e,t){var r=function(e,t){for(var r=1,n=0;;){O.lastIndex=n;var i=O.exec(e);if(!(i&&i.index0)){var t=this.state.commentStack,r=void 0,n=void 0,i=void 0,s=void 0,a=void 0;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=e.end?(i=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else{var o=c(t);t.length>0&&o.trailingComments&&o.trailingComments[0].start>=e.end&&(i=o.trailingComments,o.trailingComments=null)}for(t.length>0&&c(t).start>=e.start&&(r=t.pop());t.length>0&&c(t).start>=e.start;)n=t.pop();if(!n&&r&&(n=r),r&&this.state.leadingComments.length>0){var u=c(this.state.leadingComments);if("ObjectProperty"===r.type){if(u.start>=e.start&&this.state.commentPreviousNode){for(a=0;a0&&(r.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}else if("CallExpression"===e.type&&e.arguments&&e.arguments.length){var l=c(e.arguments);l&&u.start>=l.start&&u.end<=e.end&&this.state.commentPreviousNode&&this.state.leadingComments.length>0&&(l.trailingComments=this.state.leadingComments,this.state.leadingComments=[])}}if(n){if(n.leadingComments)if(n!==e&&c(n.leadingComments).end<=e.start)e.leadingComments=n.leadingComments,n.leadingComments=null;else for(s=n.leadingComments.length-2;s>=0;--s)if(n.leadingComments[s].end<=e.start){e.leadingComments=n.leadingComments.splice(0,s+1);break}}else if(this.state.leadingComments.length>0)if(c(this.state.leadingComments).end<=e.start){if(this.state.commentPreviousNode)for(a=0;a0&&(e.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(s=0;se.start);s++);e.leadingComments=this.state.leadingComments.slice(0,s),0===e.leadingComments.length&&(e.leadingComments=null),0===(i=this.state.leadingComments.slice(s)).length&&(i=null)}this.state.commentPreviousNode=e,i&&(i.length&&i[0].start>=e.start&&c(i).end<=e.end?e.innerComments=i:e.trailingComments=i),t.push(e)}};var ee=q.prototype;ee.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},ee.estreeParseLiteral=function(e){return this.parseLiteral(e,"Literal")},ee.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 te=["any","mixed","empty","bool","boolean","number","string","void","null"],re=q.prototype;re.flowParseTypeInitialiser=function(e){var t=this.state.inType;this.state.inType=!0,this.expect(e||T.colon);var r=this.flowParseType();return this.state.inType=t,r},re.flowParsePredicate=function(){var e=this.startNode(),t=this.state.startLoc,r=this.state.start;this.expect(T.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(T.parenL)?(e.expression=this.parseExpression(),this.expect(T.parenR),this.finishNode(e,"DeclaredPredicate")):this.finishNode(e,"InferredPredicate")},re.flowParseTypeAndPredicateInitialiser=function(){var e=this.state.inType;this.state.inType=!0,this.expect(T.colon);var t=null,r=null;return this.match(T.modulo)?(this.state.inType=e,r=this.flowParsePredicate()):(t=this.flowParseType(),this.state.inType=e,this.match(T.modulo)&&(r=this.flowParsePredicate())),[t,r]},re.flowParseDeclareClass=function(e){return this.next(),this.flowParseInterfaceish(e,!0),this.finishNode(e,"DeclareClass")},re.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(T.parenL);var i=this.flowParseFunctionTypeParams();r.params=i.params,r.rest=i.rest,this.expect(T.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")},re.flowParseDeclare=function(e){return this.match(T._class)?this.flowParseDeclareClass(e):this.match(T._function)?this.flowParseDeclareFunction(e):this.match(T._var)?this.flowParseDeclareVariable(e):this.isContextual("module")?this.lookahead().type===T.dot?this.flowParseDeclareModuleExports(e):this.flowParseDeclareModule(e):this.isContextual("type")?this.flowParseDeclareTypeAlias(e):this.isContextual("opaque")?this.flowParseDeclareOpaqueType(e):this.isContextual("interface")?this.flowParseDeclareInterface(e):this.match(T._export)?this.flowParseDeclareExportDeclaration(e):void this.unexpected()},re.flowParseDeclareExportDeclaration=function(e){if(this.expect(T._export),this.isContextual("opaque"))return e.declaration=this.flowParseDeclare(this.startNode()),e.default=!1,this.finishNode(e,"DeclareExportDeclaration");throw this.unexpected()},re.flowParseDeclareVariable=function(e){return this.next(),e.id=this.flowParseTypeAnnotatableIdentifier(),this.semicolon(),this.finishNode(e,"DeclareVariable")},re.flowParseDeclareModule=function(e){this.next(),this.match(T.string)?e.id=this.parseExprAtom():e.id=this.parseIdentifier();var t=e.body=this.startNode(),r=t.body=[];for(this.expect(T.braceL);!this.match(T.braceR);){var n=this.startNode();if(this.match(T._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(T.braceR),this.finishNode(t,"BlockStatement"),this.finishNode(e,"DeclareModule")},re.flowParseDeclareModuleExports=function(e){return this.expectContextual("module"),this.expect(T.dot),this.expectContextual("exports"),e.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(e,"DeclareModuleExports")},re.flowParseDeclareTypeAlias=function(e){return this.next(),this.flowParseTypeAlias(e),this.finishNode(e,"DeclareTypeAlias")},re.flowParseDeclareOpaqueType=function(e){return this.next(),this.flowParseOpaqueType(e,!0),this.finishNode(e,"DeclareOpaqueType")},re.flowParseDeclareInterface=function(e){return this.next(),this.flowParseInterfaceish(e),this.finishNode(e,"DeclareInterface")},re.flowParseInterfaceish=function(e){if(e.id=this.parseIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.extends=[],e.mixins=[],this.eat(T._extends))do{e.extends.push(this.flowParseInterfaceExtends())}while(this.eat(T.comma));if(this.isContextual("mixins")){this.next();do{e.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(T.comma))}e.body=this.flowParseObjectType(!0,!1,!1)},re.flowParseInterfaceExtends=function(){var e=this.startNode();return e.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterInstantiation():e.typeParameters=null,this.finishNode(e,"InterfaceExtends")},re.flowParseInterface=function(e){return this.flowParseInterfaceish(e,!1),this.finishNode(e,"InterfaceDeclaration")},re.flowParseRestrictedIdentifier=function(e){return te.indexOf(this.state.value)>-1&&this.raise(this.state.start,"Cannot overwrite primitive type "+this.state.value),this.parseIdentifier(e)},re.flowParseTypeAlias=function(e){return e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.right=this.flowParseTypeInitialiser(T.eq),this.semicolon(),this.finishNode(e,"TypeAlias")},re.flowParseOpaqueType=function(e,t){return this.expectContextual("type"),e.id=this.flowParseRestrictedIdentifier(),this.isRelational("<")?e.typeParameters=this.flowParseTypeParameterDeclaration():e.typeParameters=null,e.supertype=null,this.match(T.colon)&&(e.supertype=this.flowParseTypeInitialiser(T.colon)),e.impltype=null,t||(e.impltype=this.flowParseTypeInitialiser(T.eq)),this.semicolon(),this.finishNode(e,"OpaqueType")},re.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(T.eq)&&(this.eat(T.eq),e.default=this.flowParseType()),this.finishNode(e,"TypeParameter")},re.flowParseTypeParameterDeclaration=function(){var e=this.state.inType,t=this.startNode();t.params=[],this.state.inType=!0,this.isRelational("<")||this.match(T.jsxTagStart)?this.next():this.unexpected();do{t.params.push(this.flowParseTypeParameter()),this.isRelational(">")||this.expect(T.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterDeclaration")},re.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(T.comma);return this.expectRelational(">"),this.state.inType=t,this.finishNode(e,"TypeParameterInstantiation")},re.flowParseObjectPropertyKey=function(){return this.match(T.num)||this.match(T.string)?this.parseExprAtom():this.parseIdentifier(!0)},re.flowParseObjectTypeIndexer=function(e,t,r){return e.static=t,this.expect(T.bracketL),this.lookahead().type===T.colon?(e.id=this.flowParseObjectPropertyKey(),e.key=this.flowParseTypeInitialiser()):(e.id=null,e.key=this.flowParseType()),this.expect(T.bracketR),e.value=this.flowParseTypeInitialiser(),e.variance=r,this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeIndexer")},re.flowParseObjectTypeMethodish=function(e){for(e.params=[],e.rest=null,e.typeParameters=null,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(T.parenL);!this.match(T.parenR)&&!this.match(T.ellipsis);)e.params.push(this.flowParseFunctionTypeParam()),this.match(T.parenR)||this.expect(T.comma);return this.eat(T.ellipsis)&&(e.rest=this.flowParseFunctionTypeParam()),this.expect(T.parenR),e.returnType=this.flowParseTypeInitialiser(),this.finishNode(e,"FunctionTypeAnnotation")},re.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")},re.flowParseObjectTypeCallProperty=function(e,t){var r=this.startNode();return e.static=t,e.value=this.flowParseObjectTypeMethodish(r),this.flowObjectTypeSemicolon(),this.finishNode(e,"ObjectTypeCallProperty")},re.flowParseObjectType=function(e,t,r){var n=this.state.inType;this.state.inType=!0;var i=this.startNode(),s=void 0,a=void 0,o=!1;i.callProperties=[],i.properties=[],i.indexers=[];var u=void 0,l=void 0;for(t&&this.match(T.braceBarL)?(this.expect(T.braceBarL),u=T.braceBarR,l=!0):(this.expect(T.braceL),u=T.braceR,l=!1),i.exact=l;!this.match(u);){var c=!1,p=this.state.start,h=this.state.startLoc;s=this.startNode(),e&&this.isContextual("static")&&this.lookahead().type!==T.colon&&(this.next(),o=!0);var f=this.state.start,d=this.flowParseVariance();this.match(T.bracketL)?i.indexers.push(this.flowParseObjectTypeIndexer(s,o,d)):this.match(T.parenL)||this.isRelational("<")?(d&&this.unexpected(f),i.callProperties.push(this.flowParseObjectTypeCallProperty(s,o))):this.match(T.ellipsis)?(r||this.unexpected(null,"Spread operator cannot appear in class or interface definitions"),d&&this.unexpected(d.start,"Spread properties cannot have variance"),this.expect(T.ellipsis),s.argument=this.flowParseType(),this.flowObjectTypeSemicolon(),i.properties.push(this.finishNode(s,"ObjectTypeSpreadProperty"))):(a=this.flowParseObjectPropertyKey(),this.isRelational("<")||this.match(T.parenL)?(d&&this.unexpected(d.start),i.properties.push(this.flowParseObjectTypeMethod(p,h,o,a))):(this.eat(T.question)&&(c=!0),s.key=a,s.value=this.flowParseTypeInitialiser(),s.optional=c,s.static=o,s.variance=d,this.flowObjectTypeSemicolon(),i.properties.push(this.finishNode(s,"ObjectTypeProperty")))),o=!1}this.expect(u);var m=this.finishNode(i,"ObjectTypeAnnotation");return this.state.inType=n,m},re.flowObjectTypeSemicolon=function(){this.eat(T.semi)||this.eat(T.comma)||this.match(T.braceR)||this.match(T.braceBarR)||this.unexpected()},re.flowParseQualifiedTypeIdentifier=function(e,t,r){e=e||this.state.start,t=t||this.state.startLoc;for(var n=r||this.parseIdentifier();this.eat(T.dot);){var i=this.startNodeAt(e,t);i.qualification=n,i.id=this.parseIdentifier(),n=this.finishNode(i,"QualifiedTypeIdentifier")}return n},re.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")},re.flowParseTypeofType=function(){var e=this.startNode();return this.expect(T._typeof),e.argument=this.flowParsePrimaryType(),this.finishNode(e,"TypeofTypeAnnotation")},re.flowParseTupleType=function(){var e=this.startNode();for(e.types=[],this.expect(T.bracketL);this.state.pos0&&void 0!==arguments[0]?arguments[0]:[],rest:null};!this.match(T.parenR)&&!this.match(T.ellipsis);)e.params.push(this.flowParseFunctionTypeParam()),this.match(T.parenR)||this.expect(T.comma);return this.eat(T.ellipsis)&&(e.rest=this.flowParseFunctionTypeParam()),e},re.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)}},re.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 T.name:return this.flowIdentToTypeAnnotation(e,t,r,this.parseIdentifier());case T.braceL:return this.flowParseObjectType(!1,!1,!0);case T.braceBarL:return this.flowParseObjectType(!1,!0,!0);case T.bracketL:return this.flowParseTupleType();case T.relational:if("<"===this.state.value)return r.typeParameters=this.flowParseTypeParameterDeclaration(),this.expect(T.parenL),n=this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(T.parenR),this.expect(T.arrow),r.returnType=this.flowParseType(),this.finishNode(r,"FunctionTypeAnnotation");break;case T.parenL:if(this.next(),!this.match(T.parenR)&&!this.match(T.ellipsis))if(this.match(T.name)){var o=this.lookahead().type;s=o!==T.question&&o!==T.colon}else s=!0;if(s){if(this.state.noAnonFunctionType=!1,i=this.flowParseType(),this.state.noAnonFunctionType=a,this.state.noAnonFunctionType||!(this.match(T.comma)||this.match(T.parenR)&&this.lookahead().type===T.arrow))return this.expect(T.parenR),i;this.eat(T.comma)}return n=i?this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(i)]):this.flowParseFunctionTypeParams(),r.params=n.params,r.rest=n.rest,this.expect(T.parenR),this.expect(T.arrow),r.returnType=this.flowParseType(),r.typeParameters=null,this.finishNode(r,"FunctionTypeAnnotation");case T.string:return this.parseLiteral(this.state.value,"StringLiteralTypeAnnotation");case T._true:case T._false:return r.value=this.match(T._true),this.next(),this.finishNode(r,"BooleanLiteralTypeAnnotation");case T.plusMin:if("-"===this.state.value)return this.next(),this.match(T.num)||this.unexpected(null,"Unexpected token, expected number"),this.parseLiteral(-this.state.value,"NumericLiteralTypeAnnotation",r.start,r.loc.start);this.unexpected();case T.num:return this.parseLiteral(this.state.value,"NumericLiteralTypeAnnotation");case T._null:return r.value=this.match(T._null),this.next(),this.finishNode(r,"NullLiteralTypeAnnotation");case T._this:return r.value=this.match(T._this),this.next(),this.finishNode(r,"ThisTypeAnnotation");case T.star:return this.next(),this.finishNode(r,"ExistentialTypeParam");default:if("typeof"===this.state.type.keyword)return this.flowParseTypeofType()}this.unexpected()},re.flowParsePostfixType=function(){for(var e=this.state.start,t=this.state.startLoc,r=this.flowParsePrimaryType();!this.canInsertSemicolon()&&this.match(T.bracketL);){var n=this.startNodeAt(e,t);n.elementType=r,this.expect(T.bracketL),this.expect(T.bracketR),r=this.finishNode(n,"ArrayTypeAnnotation")}return r},re.flowParsePrefixType=function(){var e=this.startNode();return this.eat(T.question)?(e.typeAnnotation=this.flowParsePrefixType(),this.finishNode(e,"NullableTypeAnnotation")):this.flowParsePostfixType()},re.flowParseAnonFunctionWithoutParens=function(){var e=this.flowParsePrefixType();if(!this.state.noAnonFunctionType&&this.eat(T.arrow)){var t=this.startNodeAt(e.start,e.loc.start);return t.params=[this.reinterpretTypeAsFunctionTypeParam(e)],t.rest=null,t.returnType=this.flowParseType(),t.typeParameters=null,this.finishNode(t,"FunctionTypeAnnotation")}return e},re.flowParseIntersectionType=function(){var e=this.startNode();this.eat(T.bitwiseAND);var t=this.flowParseAnonFunctionWithoutParens();for(e.types=[t];this.eat(T.bitwiseAND);)e.types.push(this.flowParseAnonFunctionWithoutParens());return 1===e.types.length?t:this.finishNode(e,"IntersectionTypeAnnotation")},re.flowParseUnionType=function(){var e=this.startNode();this.eat(T.bitwiseOR);var t=this.flowParseIntersectionType();for(e.types=[t];this.eat(T.bitwiseOR);)e.types.push(this.flowParseIntersectionType());return 1===e.types.length?t:this.finishNode(e,"UnionTypeAnnotation")},re.flowParseType=function(){var e=this.state.inType;this.state.inType=!0;var t=this.flowParseUnionType();return this.state.inType=e,t},re.flowParseTypeAnnotation=function(){var e=this.startNode();return e.typeAnnotation=this.flowParseTypeInitialiser(),this.finishNode(e,"TypeAnnotation")},re.flowParseTypeAndPredicateAnnotation=function(){var e=this.startNode(),t=this.flowParseTypeAndPredicateInitialiser();return e.typeAnnotation=t[0],e.predicate=t[1],this.finishNode(e,"TypeAnnotation")},re.flowParseTypeAnnotatableIdentifier=function(){var e=this.flowParseRestrictedIdentifier();return this.match(T.colon)&&(e.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(e,e.type)),e},re.typeCastToParameter=function(e){return e.expression.typeAnnotation=e.typeAnnotation,this.finishNodeAt(e.expression,e.expression.type,e.typeAnnotation.end,e.typeAnnotation.loc.end)},re.flowParseVariance=function(){var e=null;return this.match(T.plusMin)&&("+"===this.state.value?e="plus":"-"===this.state.value&&(e="minus"),this.next()),e};var ne=String.fromCodePoint;if(!ne){var ie=String.fromCharCode,se=Math.floor;ne=function(){var e=[],t=void 0,r=void 0,n=-1,i=arguments.length;if(!i)return"";for(var s="";++n1114111||se(a)!=a)throw RangeError("Invalid code point: "+a);a<=65535?e.push(a):(t=55296+((a-=65536)>>10),r=a%1024+56320,e.push(t,r)),(n+1==i||e.length>16384)&&(s+=ie.apply(null,e),e.length=0)}return s}}var ae=ne,oe={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:"♦"},ue=/^[\da-fA-F]+$/,le=/^\d+$/;I.j_oTag=new N("...",!0,!0),T.jsxName=new w("jsxName"),T.jsxText=new w("jsxText",{beforeExpr:!0}),T.jsxTagStart=new w("jsxTagStart",{startsExpr:!0}),T.jsxTagEnd=new w("jsxTagEnd"),T.jsxTagStart.updateContext=function(){this.state.context.push(I.j_expr),this.state.context.push(I.j_oTag),this.state.exprAllowed=!1},T.jsxTagEnd.updateContext=function(e){var t=this.state.context.pop();t===I.j_oTag&&e===T.slash||t===I.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===I.j_expr):this.state.exprAllowed=!0};var ce=q.prototype;ce.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(T.jsxTagStart)):this.getTokenFromCode(r):(e+=this.input.slice(t,this.state.pos),this.finishToken(T.jsxText,e));case 38:e+=this.input.slice(t,this.state.pos),e+=this.jsxReadEntity(),t=this.state.pos;break;default:o(r)?(e+=this.input.slice(t,this.state.pos),e+=this.jsxReadNewLine(!0),t=this.state.pos):++this.state.pos}}},ce.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},ce.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):o(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(T.string,t)},ce.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(T.relational)&&"<"===this.state.value&&this.raise(this.state.start,"Adjacent JSX elements must be wrapped in an enclosing tag"),this.finishNode(r,"JSXElement")},ce.jsxParseElement=function(){var e=this.state.start,t=this.state.startLoc;return this.next(),this.jsxParseElementAt(e,t)};V.estree=function(e){e.extend("checkDeclaration",function(e){return function(t){p(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()).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("stmtToDirective",function(e){return function(t){var r=e.call(this,t),n=t.expression.value;return r.value.value=n,r}}),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?n-1:0),s=1;s2?n-2:0),s=2;s=a.length)break;l=a[u++]}else{if((u=a.next()).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))}})},V.flow=function(e){e.extend("parseFunctionBody",function(e){return function(t,r){return this.match(T.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(T.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(T._class)||this.match(T.name)||this.match(T._function)||this.match(T._var)||this.match(T._export))return this.flowParseDeclare(t)}else if(this.match(T.name)){if("interface"===r.name)return this.flowParseInterface(t);if("type"===r.name)return this.flowParseTypeAlias(t);if("opaque"===r.name)return this.flowParseOpaqueType(t,!1)}return e.call(this,t,r)}}),e.extend("shouldParseExportDeclaration",function(e){return function(){return this.isContextual("type")||this.isContextual("interface")||this.isContextual("opaque")||e.call(this)}}),e.extend("isExportDefaultSpecifier",function(e){return function(){return(!this.match(T.name)||"type"!==this.state.value&&"interface"!==this.state.value&&"opaque"!==this.state.value)&&e.call(this)}}),e.extend("parseConditional",function(e){return function(t,r,n,i,s){if(s&&this.match(T.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(T.question)&&(t.optional=!0),this.match(T.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"ExportNamedDeclaration"===(t=e.call(this,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(T.braceL)?(t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t),null):this.flowParseTypeAlias(r)}if(this.isContextual("opaque")){t.exportKind="type";var n=this.startNode();return this.next(),this.flowParseOpaqueType(n,!1)}if(this.isContextual("interface")){t.exportKind="type";var i=this.startNode();return this.next(),this.flowParseInterface(i)}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(T.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;s=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())=0?u:l;n.length&&(o=[s,a])}return o}t.exports=n,n.range=s},{}],188:[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 a[e>>18&63]+a[e>>12&63]+a[e>>6&63]+a[63&e]}function s(e,t,r){for(var n,s=[],a=t;a0?l-4:l;var c=0;for(t=0;t>16&255,a[c++]=i>>8&255,a[c++]=255&i;return 2===s?(i=o[e.charCodeAt(t)]<<2|o[e.charCodeAt(t+1)]>>4,a[c++]=255&i):1===s&&(i=o[e.charCodeAt(t)]<<10|o[e.charCodeAt(t+1)]<<4|o[e.charCodeAt(t+2)]>>2,a[c++]=i>>8&255,a[c++]=255&i),a},r.fromByteArray=function(e){for(var t,r=e.length,n=r%3,i="",o=[],u=0,l=r-n;ul?l:u+16383));return 1===n?(t=e[r-1],i+=a[t>>2],i+=a[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=a[t>>10],i+=a[t>>4&63],i+=a[t<<2&63],i+="="),o.push(i),o.join("")};for(var a=[],o=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,p=l.length;c=t}function c(e,t){var r=[],i=h("{","}",e);if(!i||/\$$/.test(i.pre))return[e];var f=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),d=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),y=f||d,g=i.body.indexOf(",")>=0;if(!y&&!g)return i.post.match(/,.*\}/)?(e=i.pre+"{"+i.body+m+i.post,c(e)):[e];var b;if(y)b=i.body.split(/\.\./);else if(1===(b=s(i.body)).length&&1===(b=c(b[0],!1).map(a)).length){return(E=i.post.length?c(i.post,!1):[""]).map(function(e){return i.pre+b[0]+e})}var v,x=i.pre,E=i.post.length?c(i.post,!1):[""];if(y){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,_=u;D0){var P=new Array(T+1).join("0");F=k<0?"-"+P+F.slice(1):P+F}}v.push(F)}}else v=p(b,function(e){return c(e,!1)});for(var B=0;BN)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 o(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 T(e)?function(e,t,r){if(t<0||e.byteLength=N)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+N.toString(16)+" bytes");return 0|e}function c(e,t){if(i.isBuffer(e))return e.length;if(P(e)||T(e))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 w(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return k(e).length;default:if(n)return w(e).length;t=(""+t).toLowerCase(),n=!0}}function p(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 function(e,t,r){var n=e.length;(!t||t<0)&&(t=0);(!r||r<0||r>n)&&(r=n);for(var i="",s=t;s2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,B(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:d(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):d(e,[t],r,n,s);throw new TypeError("val must be string, number or Buffer")}function d(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;a>8,i=r%256,s.push(i),s.push(n);return s}(t,e.length-r),e,r,n)}function E(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?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:128==(192&(u=e[i+1]))&&(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 function(e){var t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nr)throw new RangeError("Trying to access beyond buffer length")}function D(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 C(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 S(e,t,r,n,i){return t=+t,r>>>=0,i||C(e,0,r,4),j.write(e,t,r,n,23,4),r+4}function _(e,t,r,n,i){return t=+t,r>>>=0,i||C(e,0,r,8),j.write(e,t,r,n,52,8),r+8}function w(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 k(e){return O.toByteArray(function(e){if((e=e.trim().replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function T(e){return e instanceof ArrayBuffer||null!=e&&null!=e.constructor&&"ArrayBuffer"===e.constructor.name&&"number"==typeof e.byteLength}function P(e){return"function"==typeof ArrayBuffer.isView&&ArrayBuffer.isView(e)}function B(e){return e!=e}var O=e("base64-js"),j=e("ieee754");r.Buffer=i,r.SlowBuffer=function(e){return+e!=e&&(e=0),i.alloc(+e)},r.INSPECT_MAX_BYTES=50;var N=2147483647;r.kMaxLength=N,(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}}())||"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 function(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)}(e,t,r)},i.allocUnsafe=function(e){return o(e)},i.allocUnsafeSlow=function(e){return o(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 m(this,e,t,r);case"utf8":case"utf-8":return y(this,e,t,r);case"ascii":return g(this,e,t,r);case"latin1":case"binary":return b(this,e,t,r);case"base64":return v(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(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 I=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||A(e,t,this.length);for(var n=this[e],i=1,s=0;++s>>=0,t>>>=0,r||A(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||A(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||A(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||A(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||A(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||A(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||A(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||A(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||A(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||A(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||A(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||A(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||A(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||A(e,4,this.length),j.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||A(e,4,this.length),j.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||A(e,8,this.length),j.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||A(e,8,this.length),j.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){D(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){D(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||D(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||D(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||D(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||D(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||D(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);D(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);D(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||D(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||D(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||D(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||D(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||D(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 S(this,e,t,!0,r)},i.prototype.writeFloatBE=function(e,t,r){return S(this,e,t,!1,r)},i.prototype.writeDoubleLE=function(e,t,r){return _(this,e,t,!0,r)},i.prototype.writeDoubleBE=function(e,t,r){return _(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;ac;)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-absolute-index":273,"./_to-iobject":275,"./_to-length":276}],214:[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":216,"./_ctx":224,"./_iobject":238,"./_to-length":276,"./_to-object":277}],215:[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)&&("function"!=typeof(t=e.constructor)||t!==Array&&!i(t.prototype)||(t=void 0),n(t)&&null===(t=t[s])&&(t=void 0)),void 0===t?Array:t}},{"./_is-array":240,"./_is-object":241,"./_wks":283}],216:[function(e,t,r){var n=e("./_array-species-constructor");t.exports=function(e,t){return new(n(e))(t)}},{"./_array-species-constructor":215}],217:[function(e,t,r){var n=e("./_cof"),i=e("./_wks")("toStringTag"),s="Arguments"==n(function(){return arguments}());t.exports=function(e){var t,r,a;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(r=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),i))?r:s?n(t):"Object"==(a=n(t))&&"function"==typeof t.callee?"Arguments":a}},{"./_cof":218,"./_wks":283}],218:[function(e,t,r){var n={}.toString;t.exports=function(e){return n.call(e).slice(8,-1)}},{}],219:[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("./_for-of"),l=e("./_iter-define"),c=e("./_iter-step"),p=e("./_set-species"),h=e("./_descriptors"),f=e("./_meta").fastKey,d=e("./_validate-collection"),m=h?"_s":"size",y=function(e,t){var r,n=f(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,l){var c=e(function(e,n){o(e,c,t,"_i"),e._t=t,e._i=i(null),e._f=void 0,e._l=void 0,e[m]=0,void 0!=n&&u(n,r,e[l],e)});return s(c.prototype,{clear:function(){for(var e=d(this,t),r=e._i,n=e._f;n;n=n.n)n.r=!0,n.p&&(n.p=n.p.n=void 0),delete r[n.i];e._f=e._l=void 0,e[m]=0},delete:function(e){var r=d(this,t),n=y(r,e);if(n){var i=n.n,s=n.p;delete r._i[n.i],n.r=!0,s&&(s.n=i),i&&(i.p=s),r._f==n&&(r._f=i),r._l==n&&(r._l=s),r[m]--}return!!n},forEach:function(e){d(this,t);for(var r,n=a(e,arguments.length>1?arguments[1]:void 0,3);r=r?r.n:this._f;)for(n(r.v,r.k,this);r&&r.r;)r=r.p},has:function(e){return!!y(d(this,t),e)}}),h&&n(c.prototype,"size",{get:function(){return d(this,t)[m]}}),c},def:function(e,t,r){var n,i,s=y(e,t);return s?s.v=r:(e._l=s={i:i=f(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){l(e,t,function(e,r){this._t=d(e,t),this._k=r,this._l=void 0},function(){for(var e=this._k,t=this._l;t&&t.r;)t=t.p;return this._t&&(this._l=t=t?t.n:this._t._f)?"keys"==e?c(0,t.k):"values"==e?c(0,t.v):c(0,[t.k,t.v]):(this._t=void 0,c(1))},r?"entries":"values",!r,!0),p(t)}}},{"./_an-instance":210,"./_ctx":224,"./_descriptors":226,"./_for-of":232,"./_iter-define":244,"./_iter-step":245,"./_meta":248,"./_object-create":250,"./_object-dp":251,"./_redefine-all":263,"./_set-species":268,"./_validate-collection":280}],220:[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":212,"./_classof":217}],221:[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=e("./_validate-collection"),h=l(5),f=l(6),d=0,m=function(e){return e._l||(e._l=new y)},y=function(){this.a=[]},g=function(e,t){return h(e.a,function(e){return e[0]===t})};y.prototype={get:function(e){var t=g(this,e);if(t)return t[1]},has:function(e){return!!g(this,e)},set:function(e,t){var r=g(this,e);r?r[1]=t:this.a.push([e,t])},delete:function(e){var t=f(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._t=t,e._i=d++,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 r=i(e);return!0===r?m(p(this,t)).delete(e):r&&c(r,this._i)&&delete r[this._i]},has:function(e){if(!a(e))return!1;var r=i(e);return!0===r?m(p(this,t)).has(e):r&&c(r,this._i)}}),l},def:function(e,t,r){var n=i(s(t),!0);return!0===n?m(e).set(t,r):n[e._i]=r,e},ufstore:m}},{"./_an-instance":210,"./_an-object":211,"./_array-methods":214,"./_for-of":232,"./_has":234,"./_is-object":241,"./_meta":248,"./_redefine-all":263,"./_validate-collection":280}],222:[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})}),b||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":210,"./_array-methods":214,"./_descriptors":226,"./_export":230,"./_fails":231,"./_for-of":232,"./_global":233,"./_hide":235,"./_is-object":241,"./_meta":248,"./_object-dp":251,"./_redefine-all":263,"./_set-to-string-tag":269}],223:[function(e,t,r){var n=t.exports={version:"2.5.1"};"number"==typeof __e&&(__e=n)},{}],224:[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":208}],225:[function(e,t,r){t.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},{}],226:[function(e,t,r){t.exports=!e("./_fails")(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},{"./_fails":231}],227:[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":233,"./_is-object":241}],228:[function(e,t,r){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},{}],229:[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":256,"./_object-keys":259,"./_object-pie":260}],230:[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":223,"./_ctx":224,"./_global":233,"./_hide":235}],231:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],232:[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}).BREAK=l,r.RETURN=c},{"./_an-object":211,"./_ctx":224,"./_is-array-iter":239,"./_iter-call":242,"./_to-length":276,"./core.get-iterator-method":284}],233:[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)},{}],234:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],235:[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":226,"./_object-dp":251,"./_property-desc":262}],236:[function(e,t,r){var n=e("./_global").document;t.exports=n&&n.documentElement},{"./_global":233}],237:[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":226,"./_dom-create":227,"./_fails":231}],238:[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":218}],239:[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":246,"./_wks":283}],240:[function(e,t,r){var n=e("./_cof");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"./_cof":218}],241:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],242:[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":211}],243:[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":235,"./_object-create":250,"./_property-desc":262,"./_set-to-string-tag":269,"./_wks":283}],244:[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&&E.next&&(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":230,"./_has":234,"./_hide":235,"./_iter-create":243,"./_iterators":246,"./_library":247,"./_object-gpo":257,"./_redefine":264,"./_set-to-string-tag":269,"./_wks":283}],245:[function(e,t,r){t.exports=function(e,t){return{value:t,done:!!e}}},{}],246:[function(e,t,r){t.exports={}},{}],247:[function(e,t,r){t.exports=!0},{}],248:[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=t.exports={KEY:n,NEED:!1,fastKey: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},getWeak:function(e,t){if(!s(e,n)){if(!u(e))return!0;if(!t)return!1;c(e)}return e[n].w},onFreeze:function(e){return l&&p.NEED&&u(e)&&!s(e,n)&&c(e),e}}},{"./_fails":231,"./_has":234,"./_is-object":241,"./_object-dp":251,"./_uid":279}],249:[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":231,"./_iobject":238,"./_object-gops":256,"./_object-keys":259,"./_object-pie":260,"./_to-object":277}],250:[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).open(),t.write(" - - - - \ 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 deleted file mode 100644 index e33dcb7c1..000000000 --- a/node_modules/azure-storage/browser/samples/sample-file.html +++ /dev/null @@ -1,586 +0,0 @@ - - - - - - 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 IE11 and latest Chrome. -
-
- -

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.file.js in your HTML file for file operations. -

-

-<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.File.createFileServiceWithSas(fileUri, 'SAS_TOKEN');
-
-

- You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable AzureStorage.File will be set, which is the start point where we can create service objects for file and access to the storage utilities. -

-
-
- How to get full detailed API definitions? Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs. - Please check API details on Azure Storage API reference documents. The JavaScript global variable AzureStorage.File is just like the object require('azure-storage') returns in Node.js, but limits to File related interfaces. - Go to FileService to view possible methods provided by FileService class. -
-
-
-
- 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 functional file(s) needed, such as "azure-storage.file.js" for file operation.
  • -
  • 3. Using keyword "AzureStorage.File" to access to Azure storage JavaScript APIs for files.
  • -
  • 4. Referring to API documents for detailed API definitions.
  • -
-

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 deleted file mode 100644 index cf02c0b51..000000000 --- a/node_modules/azure-storage/browser/samples/sample-queue.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - 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 IE11 and latest Chrome. -
-
- -

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.queue.js in your HTML file for queue operations. -

-

-<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.Queue.createQueueServiceWithSas(queueUri, 'SAS_TOKEN');
-
-

- You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable AzureStorage.Queue will be set, which is the start point where we can create service objects for queue and access to the storage utilities. -

-
-
- How to get full detailed API definitions? Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs. - Please check API details on Azure Storage API reference documents. The JavaScript global variable AzureStorage.Queue is just like the object require('azure-storage') returns in Node.js, but limits to Queue related interfaces. - Go to QueueService to view possible methods provided by QueueService class. -
-
-
-
- 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.Queue.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.Queue.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.Queue.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 functional file(s) needed, such as "azure-storage.queue.js" for queue operation.
  • -
  • 3. Using keyword "AzureStorage.Queue" to access to Azure storage JavaScript APIs for queues.
  • -
  • 4. Referring to API documents for detailed API definitions.
  • -
-

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 deleted file mode 100644 index 7fadab4f1..000000000 --- a/node_modules/azure-storage/browser/samples/sample-table.html +++ /dev/null @@ -1,437 +0,0 @@ - - - - - - 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 IE11 and latest Chrome. -
-
- -

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.table.js in your HTML file for table operations. -

-

-<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.Table.createTableServiceWithSas(tableUri, 'SAS_TOKEN');
-
-

- You can load Azure Storage JavaScript Client Library in a CommonJS or AMD environment by JavaScript module loaders. If no module system is found, global variable AzureStorage.Table will be set, which is the start point where we can create service objects for table and access to the storage utilities. -

-
-
- How to get full detailed API definitions? Currently, the JavaScript Client Library shares almost the same API definitions with Node.js SDK, besides Node.js runtime specific APIs. - Please check API details on Azure Storage API reference documents. The JavaScript global variable AzureStorage.Table is just like the object require('azure-storage') returns in Node.js, but limits to Table related interfaces. - Go to TableService to view possible methods provided by TableService class. -
-
-
-
- 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.Table.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 functional file(s) needed, such as "azure-storage.table.js" for table operation.
  • -
  • 3. Using keyword "AzureStorage.Table" to access to Azure storage JavaScript APIs for tables.
  • -
  • 4. Referring to API documents for detailed API definitions.
  • -
-

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/test/blob/blobservice-upload.js b/node_modules/azure-storage/browser/test/blob/blobservice-upload.js deleted file mode 100644 index b1bd9355f..000000000 --- a/node_modules/azure-storage/browser/test/blob/blobservice-upload.js +++ /dev/null @@ -1,411 +0,0 @@ -// -// 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 assert = require('assert'); -var TestSuite = require('../../../test/framework/test-suite'); -var testUtil = require('../../../test/framework/util'); - -var suite = new TestSuite('blobservice-upload-browser'); - -if (testUtil.isBrowser()) { - var azure = AzureStorage.Blob; - var containerNamesPrefix = 'upload-test-container-'; - var blobNamesPrefix = 'upload-teset-blob-'; - var containerName; - var blobName; - - describe('BlobServiceUpload', function () { - before(function (done) { - blobService = azure.createBlobService(process.env['AZURE_STORAGE_CONNECTION_STRING']); - assert.notEqual(null, blobService, 'blobService should not be null'); - - containerName = suite.getName(containerNamesPrefix); - blobService.createContainerIfNotExists(containerName, function (err) { - assert.equal(err, null); - done(); - }); - }); - - after(function (done) { - blobService.deleteContainerIfExists(containerName, function (err) { - assert.equal(err, null); - done(); - }); - }); - - beforeEach(function () { - blobName = suite.getName(blobNamesPrefix); - }); - - afterEach(function () { - }); - - describe('createBlockBlobFromBrowserFile', function () { - it('upload block blob with invalid type should not work', function () { - try { - blobService.createBlockBlobFromBrowserFile(containerName, blobName, 'abcde', function (err, res, resp) { }); - } catch (e) { - assert.notEqual(e, null); - } - }); - - it('upload block blob with md5 calculation should work', function (done) { - var size = 7 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, { storeBlobContentMD5: true }, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - assert.notEqual(res.contentSettings.contentMD5, null); - done(); - }); - }); - }); - - it('upload block blob with 0 bytes should work', function (done) { - var size = 0; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.BLOCK); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload block blob with 4 * 1024 * 1024 - 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 - 1; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload block blob with 4 * 1024 * 1024 bytes should work', function (done) { - var size = 4 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload block blob with 4 * 1024 * 1024 + 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 + 1; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload block blob with 128 * 1024 * 1024 bytes should work', function (done) { - var size = 128 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createBlockBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - }); - - describe('createPageBlobFromBrowserFile', function () { - it('upload page blob with invalid type should not work', function () { - try { - blobService.createPageBlobFromBrowserFile(containerName, blobName, 'abcde', function (err, res, resp) { }); - } catch (e) { - assert.notEqual(e, null); - } - }); - - it('upload page blob with md5 calculation should work', function (done) { - var size = 3 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createPageBlobFromBrowserFile(containerName, blobName, file, { storeBlobContentMD5: true }, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - assert.notEqual(res.contentSettings.contentMD5, null); - done(); - }); - }); - }); - - it('upload page blob with 0 bytes should work', function (done) { - var file = testUtil.getBrowserFile(blobName, 0); - blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.PAGE); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, 0); - done(); - }); - }); - }); - - it('upload page blob with 4 * 1024 * 1024 - 1 bytes should not work', function () { - var size = 4 * 1024 * 1024 - 1; - var file = testUtil.getBrowserFile(blobName, size); - try { - blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { }); - } catch (e) { - assert.notEqual(e, null); - } - }); - - it('upload page blob with 4 * 1024 * 1024 bytes should work', function (done) { - var size = 4 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload page blob with 128 * 1024 * 1024 bytes should work', function (done) { - var size = 128 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createPageBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - }); - - describe('createAppendBlobFromBrowserFile', function () { - it('upload append blob with invalid type should not work', function () { - try { - blobService.createAppendBlobFromBrowserFile(containerName, blobName, 'abcde', function (err, res, resp) { }); - } catch (e) { - assert.notEqual(e, null); - } - }); - - it('upload append blob with md5 calculation should work', function (done) { - var size = 7 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, { storeBlobContentMD5: true }, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - assert.notEqual(res.contentSettings.contentMD5, null); - done(); - }); - }); - }); - - it('upload append blob with 0 bytes should work', function (done) { - var file = testUtil.getBrowserFile(blobName, 0); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.APPEND); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, 0); - done(); - }); - }); - }); - - it('upload append blob with 4 * 1024 * 1024 - 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 - 1; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload append blob with 4 * 1024 * 1024 bytes should work', function (done) { - var size = 4 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload append blob with 4 * 1024 * 1024 + 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 + 1; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload append blob with 128 * 1024 * 1024 bytes should work', function (done) { - var size = 128 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - }); - - describe('appendFromBrowserFile', function () { - beforeEach(function (done) { - var size = 2 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.createAppendBlobFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('append blob with 0 bytes should work', function (done) { - var file = testUtil.getBrowserFile(blobName, 0); - blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.blobType, AzureStorage.Blob.Constants.BlobConstants.BlobTypes.APPEND); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, 2 * 1024 * 1024); - done(); - }); - }); - }); - - it('append blob with 4 * 1024 * 1024 - 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 - 1; - var file = testUtil.getBrowserFile(blobName, size); - blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size + 2 * 1024 * 1024); - done(); - }); - }); - }); - - it('append blob with 4 * 1024 * 1024 bytes should work', function (done) { - var size = 4 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size + 2 * 1024 * 1024); - done(); - }); - }); - }); - - it('append blob with 4 * 1024 * 1024 + 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 + 1; - var file = testUtil.getBrowserFile(blobName, size); - blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size + 2 * 1024 * 1024); - done(); - }); - }); - }); - - it('append blob with 128 * 1024 * 1024 bytes should work', function (done) { - var size = 128 * 1024 * 1024; - var file = testUtil.getBrowserFile(blobName, size); - blobService.appendFromBrowserFile(containerName, blobName, file, function (err, res, resp) { - assert.equal(err, null); - blobService.getBlobProperties(containerName, blobName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, blobName); - assert.equal(res.contentLength, size + 2 * 1024 * 1024); - done(); - }); - }); - }); - }); - }); -} \ No newline at end of file diff --git a/node_modules/azure-storage/browser/test/bundle.js b/node_modules/azure-storage/browser/test/bundle.js deleted file mode 100644 index 0534a2eda..000000000 --- a/node_modules/azure-storage/browser/test/bundle.js +++ /dev/null @@ -1,62 +0,0 @@ -// -// 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 fs = require('fs'); -var path = require('path'); - -var bs = browserify([ - path.resolve(__dirname, '../../test/services/queue/queueservice-tests.js'), - path.resolve(__dirname, '../../test/services/table/tablebatch-tests.js'), - path.resolve(__dirname, '../../test/services/table/tabledatatype-tests.js'), - path.resolve(__dirname, '../../test/services/table/tablepayload-tests.js'), - path.resolve(__dirname, '../../test/services/table/tablequery-tests.js'), - path.resolve(__dirname, '../../test/services/table/tableservice-gb-tests.js'), - path.resolve(__dirname, '../../test/services/table/tableservice-tests.js'), - path.resolve(__dirname, '../../test/services/blob/blobservice-archive-tests.js'), - path.resolve(__dirname, '../../test/services/blob/blobservice-container-tests.js'), - path.resolve(__dirname, '../../test/services/blob/blobservice-lease-tests.js'), - path.resolve(__dirname, '../../test/services/blob/blobservice-sse-tests.js'), - path.resolve(__dirname, '../../test/services/blob/blobservice-tests.js'), - path.resolve(__dirname, '../../test/services/blob/blobservice-uploaddownload-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-directory-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-file-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-share-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-sharesnapshot-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-sse-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-tests.js'), - path.resolve(__dirname, '../../test/services/file/fileservice-uploaddownload-tests.js'), - path.resolve(__dirname, '../../test/common/connectionstringparsertests.js'), - path.resolve(__dirname, '../../test/common/secondarytests.js'), - path.resolve(__dirname, '../../test/common/servicesettingstests.js'), - path.resolve(__dirname, '../../test/common/servicestatstests.js'), - path.resolve(__dirname, '../../test/common/sharedkey-tests.js'), - path.resolve(__dirname, '../../test/common/storageserviceclienttests.js'), - path.resolve(__dirname, '../../test/common/storageservicesettingstests.js'), - path.resolve(__dirname, '../../test/common/filters/exponentialretrypolicyfilter-tests.js'), - path.resolve(__dirname, '../../test/common/filters/linearretrypolicyfilter-tests.js'), - path.resolve(__dirname, '../../test/common/util/iso8061date-tests.js'), - path.resolve(__dirname, '../../test/common/util/util-tests.js'), - path.resolve(__dirname, '../../test/common/util/validate-tests.js'), - path.resolve(__dirname, '../../test/azure-tests.js'), - path.resolve(__dirname, '../../test/accountsas-tests.js'), - path.resolve(__dirname, './file/fileservice-upload.js'), - path.resolve(__dirname, './blob/blobservice-upload.js') -], { require: ['https'] }).bundle(); - -bs.pipe( - fs.createWriteStream(path.resolve(__dirname, './browser.tests.bundled.js')) -); \ No newline at end of file diff --git a/node_modules/azure-storage/browser/test/file/fileservice-upload.js b/node_modules/azure-storage/browser/test/file/fileservice-upload.js deleted file mode 100644 index 69720114f..000000000 --- a/node_modules/azure-storage/browser/test/file/fileservice-upload.js +++ /dev/null @@ -1,155 +0,0 @@ -// -// 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 assert = require('assert'); -var TestSuite = require('../../../test/framework/test-suite'); -var testUtil = require('../../../test/framework/util'); - -var suite = new TestSuite('fileservice-upload-browser'); - -if (testUtil.isBrowser()) { - var azure = AzureStorage.File; - var shareNamesPrefix = 'upload-test-share-'; - var fileNamesPrefix = 'upload-test-file-'; - var shareName; - var fileName; - - describe('FileServiceUpload', function () { - before(function (done) { - fileService = azure.createFileService(process.env['AZURE_STORAGE_CONNECTION_STRING']); - assert.notEqual(null, fileService, 'FileService should not be null'); - - shareName = suite.getName(shareNamesPrefix); - fileService.createShareIfNotExists(shareName, function (err) { - assert.equal(err, null); - done(); - }); - }); - - after(function (done) { - fileService.deleteShareIfExists(shareName, function (err) { - assert.equal(err, null); - done(); - }); - }); - - beforeEach(function () { - fileName = suite.getName(fileNamesPrefix); - }); - - afterEach(function (done) { - fileService.deleteFileIfExists(shareName, '', fileName, function (err) { - assert.equal(err, null); - done(); - }); - }); - - describe('createFileFromBrowserFile', function () { - it('upload file with invalid type should not work', function () { - try { - fileService.createFileFromBrowserFile(shareName, '', fileName, 'abcde', function (err, res, resp) {}); - } catch (e) { - assert.notEqual(e, null); - } - }); - - it('upload file with md5 calculation should work', function (done) { - var size = 33 * 1024 * 1024; - var file = testUtil.getBrowserFile(fileName, size); - fileService.createFileFromBrowserFile(shareName, '', fileName, file, { storeFileContentMD5: true}, function (err, res, resp) { - assert.equal(err, null); - fileService.getFileProperties(shareName, '', fileName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, fileName); - assert.equal(res.contentLength, size); - assert.notEqual(res.contentSettings.contentMD5, null); - done(); - }); - }); - }); - - it('upload file with 0 bytes should work', function (done) { - var file = testUtil.getBrowserFile(fileName, 0); - fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) { - assert.equal(err, null); - fileService.getFileProperties(shareName, '', fileName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, fileName); - assert.equal(res.contentLength, 0); - done(); - }); - }); - }); - - it('upload file with 4 * 1024 * 1024 - 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 - 1; - var file = testUtil.getBrowserFile(fileName, size); - fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) { - assert.equal(err, null); - fileService.getFileProperties(shareName, '', fileName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, fileName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload file with 4 * 1024 * 1024 bytes should work', function (done) { - var size = 4 * 1024 * 1024; - var file = testUtil.getBrowserFile(fileName, size); - fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) { - assert.equal(err, null); - fileService.getFileProperties(shareName, '', fileName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, fileName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload file with 4 * 1024 * 1024 + 1 bytes should work', function (done) { - var size = 4 * 1024 * 1024 + 1; - var file = testUtil.getBrowserFile(fileName, size); - fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) { - assert.equal(err, null); - fileService.getFileProperties(shareName, '', fileName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, fileName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - - it('upload file with 128 * 1024 * 1024 bytes should work', function (done) { - var size = 128 * 1024 * 1024; - var file = testUtil.getBrowserFile(fileName, size); - fileService.createFileFromBrowserFile(shareName, '', fileName, file, function (err, res, resp) { - assert.equal(err, null); - fileService.getFileProperties(shareName, '', fileName, function (err, res) { - assert.equal(err, null); - assert.equal(res.name, fileName); - assert.equal(res.contentLength, size); - done(); - }); - }); - }); - }); - }); -} \ 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 deleted file mode 100644 index be5dd70cf..000000000 --- a/node_modules/azure-storage/examples/samples/blobuploaddownloadsample.js +++ /dev/null @@ -1,246 +0,0 @@ -// -// 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 deleted file mode 100644 index fa3f2bd45..000000000 --- a/node_modules/azure-storage/examples/samples/continuationsample.js +++ /dev/null @@ -1,159 +0,0 @@ -// -// 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 deleted file mode 100644 index 2f73bd1e2..000000000 --- a/node_modules/azure-storage/examples/samples/requestresponseeventssample.js +++ /dev/null @@ -1,96 +0,0 @@ -// -// 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 deleted file mode 100644 index b5321f0df..000000000 --- a/node_modules/azure-storage/examples/samples/retrypolicysample.js +++ /dev/null @@ -1,230 +0,0 @@ -// -// 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 deleted file mode 100644 index 7924d7b07..000000000 --- a/node_modules/azure-storage/examples/samples/sassample.js +++ /dev/null @@ -1,218 +0,0 @@ -// -// 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 deleted file mode 100644 index 766a8727e..000000000 --- a/node_modules/azure-storage/examples/samples/snapshotsample.js +++ /dev/null @@ -1,219 +0,0 @@ -// -// 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 deleted file mode 100644 index d91e4fffc..000000000 --- a/node_modules/azure-storage/examples/samples/tablequerysample.js +++ /dev/null @@ -1,165 +0,0 @@ -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 deleted file mode 100644 index e11772016..000000000 --- a/node_modules/azure-storage/gruntfile.js +++ /dev/null @@ -1,106 +0,0 @@ -// -// 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 deleted file mode 100644 index 162d85483..000000000 --- a/node_modules/azure-storage/jsdoc/jsdoc.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "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 and JavaScript", - "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/karma.conf.js b/node_modules/azure-storage/karma.conf.js deleted file mode 100644 index 9576663ad..000000000 --- a/node_modules/azure-storage/karma.conf.js +++ /dev/null @@ -1,90 +0,0 @@ -module.exports = function (config) { - config.set({ - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: './', - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['mocha'], - - plugins: [ - 'karma-mocha', - 'karma-mocha-reporter', - 'karma-chrome-launcher', - 'karma-edge-launcher', - 'karma-firefox-launcher', - 'karma-ie-launcher', - 'karma-env-preprocessor' - ], - - // list of files / patterns to load in the browser - files: [ - 'browser/bundle/azure-storage.blob.js', - 'browser/bundle/azure-storage.table.js', - 'browser/bundle/azure-storage.queue.js', - 'browser/bundle/azure-storage.file.js', - 'browser/test/browser.tests.bundled.js' - ], - - // list of files / patterns to exclude - exclude: [], - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - '**/*.js': ['env'], - }, - - // inject following environment values into browser testing with window.__env__ - // environment values MUST be exported or set with same console running "karma start" - // https://www.npmjs.com/package/karma-env-preprocessor - envPreprocessor: [ - 'AZURE_STORAGE_CONNECTION_STRING', - 'AZURE_STORAGE_CONNECTION_STRING_SSE_ENABLED_ACCOUNT', - 'AZURE_STORAGE_CONNECTION_STRING_BLOB_ACCOUNT', - 'AZURE_STORAGE_CONNECTION_STRING_PREMIUM_ACCOUNT' - ], - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['mocha'], - - // web server port - port: 9876, - - // enable / disable colors in the output (reporters and logs) - colors: true, - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - // 'Chrome', 'Firefox', 'Edge', 'IE' - browsers: ['Chrome'], - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: false, - - // Concurrency level - // how many browser should be started simultaneous - concurrency: 1, - - browserNoActivityTimeout: 600000, - - client: { - mocha: { - // change Karma's debug.html to the mocha web reporter - reporter: 'html', - timeout: '600000' - } - } - }) -} \ 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 deleted file mode 100644 index 813e3c414..000000000 --- a/node_modules/azure-storage/lib/azure-storage.js +++ /dev/null @@ -1,369 +0,0 @@ -// -// 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 deleted file mode 100644 index 320738c6e..000000000 --- a/node_modules/azure-storage/lib/common/common.browser.js +++ /dev/null @@ -1,21 +0,0 @@ -// -// 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 deleted file mode 100644 index 3331d7f2a..000000000 --- a/node_modules/azure-storage/lib/common/common.core.js +++ /dev/null @@ -1,67 +0,0 @@ -// -// 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 deleted file mode 100644 index 1b9bfa93b..000000000 --- a/node_modules/azure-storage/lib/common/common.node.js +++ /dev/null @@ -1,22 +0,0 @@ -// -// 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 deleted file mode 100644 index 7526e63a7..000000000 --- a/node_modules/azure-storage/lib/common/diagnostics/logger.js +++ /dev/null @@ -1,148 +0,0 @@ -// -// 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 deleted file mode 100644 index c1f2e71af..000000000 --- a/node_modules/azure-storage/lib/common/errors/errors.js +++ /dev/null @@ -1,68 +0,0 @@ -// -// 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 deleted file mode 100644 index a6fe63f24..000000000 --- a/node_modules/azure-storage/lib/common/filters/exponentialretrypolicyfilter.js +++ /dev/null @@ -1,95 +0,0 @@ -// -// 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 deleted file mode 100644 index 3bbe6d0e5..000000000 --- a/node_modules/azure-storage/lib/common/filters/linearretrypolicyfilter.js +++ /dev/null @@ -1,75 +0,0 @@ -// -// 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 deleted file mode 100644 index 28e099445..000000000 --- a/node_modules/azure-storage/lib/common/filters/retrypolicyfilter.js +++ /dev/null @@ -1,234 +0,0 @@ -// -// 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' || - returnObject.error.message === 'XHR error' // stream-http XHR network error message in browsers - ) - ) - ) { - 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 deleted file mode 100644 index 4fa76c7db..000000000 --- a/node_modules/azure-storage/lib/common/http/webresource.js +++ /dev/null @@ -1,324 +0,0 @@ -// -// 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 deleted file mode 100644 index 9aea459ea..000000000 --- a/node_modules/azure-storage/lib/common/md5-wrapper/md5.browser.js +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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 deleted file mode 100644 index eb28fb1df..000000000 --- a/node_modules/azure-storage/lib/common/md5-wrapper/md5.node.js +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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 deleted file mode 100644 index b05289c5b..000000000 --- a/node_modules/azure-storage/lib/common/md5-wrapper/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 deleted file mode 100644 index abe4906d3..000000000 --- a/node_modules/azure-storage/lib/common/models/aclresult.js +++ /dev/null @@ -1,122 +0,0 @@ -// -// 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 deleted file mode 100644 index 01095d8d9..000000000 --- a/node_modules/azure-storage/lib/common/models/servicepropertiesresult.js +++ /dev/null @@ -1,427 +0,0 @@ -// -// 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 deleted file mode 100644 index b2060ae9b..000000000 --- a/node_modules/azure-storage/lib/common/models/servicestatsparser.js +++ /dev/null @@ -1,34 +0,0 @@ -// -// 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 deleted file mode 100644 index c5ece1e1e..000000000 --- a/node_modules/azure-storage/lib/common/request-wrapper/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "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 deleted file mode 100644 index df893b919..000000000 --- a/node_modules/azure-storage/lib/common/request-wrapper/request.browser.js +++ /dev/null @@ -1,258 +0,0 @@ -// -// 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 deleted file mode 100644 index c49e60366..000000000 --- a/node_modules/azure-storage/lib/common/request-wrapper/request.node.js +++ /dev/null @@ -1,17 +0,0 @@ -// -// 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 deleted file mode 100644 index d5c64bfed..000000000 --- a/node_modules/azure-storage/lib/common/services/servicesettings.js +++ /dev/null @@ -1,262 +0,0 @@ -// -// 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 deleted file mode 100644 index 629233e0a..000000000 --- a/node_modules/azure-storage/lib/common/services/storageserviceclient.js +++ /dev/null @@ -1,1355 +0,0 @@ -// -// 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 deleted file mode 100644 index aec29473d..000000000 --- a/node_modules/azure-storage/lib/common/services/storageservicesettings.js +++ /dev/null @@ -1,420 +0,0 @@ -// -// 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 deleted file mode 100644 index e1f7f099a..000000000 --- a/node_modules/azure-storage/lib/common/signing/hmacsha256sign.js +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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 deleted file mode 100644 index 9acfc8b97..000000000 --- a/node_modules/azure-storage/lib/common/signing/sharedaccesssignature.js +++ /dev/null @@ -1,56 +0,0 @@ -// -// 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 deleted file mode 100644 index a31b4d751..000000000 --- a/node_modules/azure-storage/lib/common/signing/sharedkey.js +++ /dev/null @@ -1,500 +0,0 @@ -// -// 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.Resources`. -* @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 deleted file mode 100644 index 612d7eb0b..000000000 --- a/node_modules/azure-storage/lib/common/streams/batchoperation.js +++ /dev/null @@ -1,425 +0,0 @@ -// -// 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 deleted file mode 100644 index c20340b4c..000000000 --- a/node_modules/azure-storage/lib/common/streams/browserfilereadstream.js +++ /dev/null @@ -1,61 +0,0 @@ -// -// 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 deleted file mode 100644 index c1df94661..000000000 --- a/node_modules/azure-storage/lib/common/streams/bufferstream.js +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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 deleted file mode 100644 index 1d5e2b48e..000000000 --- a/node_modules/azure-storage/lib/common/streams/chunkallocator.js +++ /dev/null @@ -1,128 +0,0 @@ -// -// 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 deleted file mode 100644 index 3475aa3f4..000000000 --- a/node_modules/azure-storage/lib/common/streams/chunkstream.js +++ /dev/null @@ -1,321 +0,0 @@ -// -// 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 deleted file mode 100644 index af3727158..000000000 --- a/node_modules/azure-storage/lib/common/streams/chunkstreamwithstream.js +++ /dev/null @@ -1,103 +0,0 @@ -// -// 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 deleted file mode 100644 index 8c4a52420..000000000 --- a/node_modules/azure-storage/lib/common/streams/filereadstream.js +++ /dev/null @@ -1,261 +0,0 @@ -// -// 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 deleted file mode 100644 index 130a4bde3..000000000 --- a/node_modules/azure-storage/lib/common/streams/rangestream.js +++ /dev/null @@ -1,293 +0,0 @@ -// -// 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 deleted file mode 100644 index 933336562..000000000 --- a/node_modules/azure-storage/lib/common/streams/readablefs.js +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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 deleted file mode 100644 index 9d724f488..000000000 --- a/node_modules/azure-storage/lib/common/streams/speedsummary.js +++ /dev/null @@ -1,205 +0,0 @@ -// -// 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 deleted file mode 100644 index 342621221..000000000 --- a/node_modules/azure-storage/lib/common/util/accesscondition.js +++ /dev/null @@ -1,166 +0,0 @@ -// -// 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 deleted file mode 100644 index 1609b9674..000000000 --- a/node_modules/azure-storage/lib/common/util/constants.js +++ /dev/null @@ -1,2536 +0,0 @@ -// -// 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.2', - - /** - * 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 deleted file mode 100644 index b2e5f06a4..000000000 --- a/node_modules/azure-storage/lib/common/util/date.js +++ /dev/null @@ -1,69 +0,0 @@ -// -// 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 deleted file mode 100644 index 69541fe02..000000000 --- a/node_modules/azure-storage/lib/common/util/iso8061date.js +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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 deleted file mode 100644 index 06f6e1295..000000000 --- a/node_modules/azure-storage/lib/common/util/patch-xmlbuilder.js +++ /dev/null @@ -1,31 +0,0 @@ -// -// 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 deleted file mode 100644 index e0b112b8c..000000000 --- a/node_modules/azure-storage/lib/common/util/sr.js +++ /dev/null @@ -1,76 +0,0 @@ -// -// 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 deleted file mode 100644 index 0c5caa3a2..000000000 --- a/node_modules/azure-storage/lib/common/util/storageutilities.js +++ /dev/null @@ -1,42 +0,0 @@ -// -// 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 deleted file mode 100644 index dddc47f21..000000000 --- a/node_modules/azure-storage/lib/common/util/util.js +++ /dev/null @@ -1,618 +0,0 @@ -// -// 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 deleted file mode 100644 index 2128caa6a..000000000 --- a/node_modules/azure-storage/lib/common/util/validate.js +++ /dev/null @@ -1,560 +0,0 @@ -// -// 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 deleted file mode 100644 index d81f7cec7..000000000 --- a/node_modules/azure-storage/lib/services/blob/blobservice.browser.js +++ /dev/null @@ -1,319 +0,0 @@ -// -// 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 deleted file mode 100644 index 1c290421a..000000000 --- a/node_modules/azure-storage/lib/services/blob/blobservice.core.js +++ /dev/null @@ -1,5733 +0,0 @@ -// -// 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 {Readable} A Node.js Readable 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 {Writable} writeStream The Node.js Writable 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 {string} [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 {Writable} A Node.js Writable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} writeStream The Node.js Writable 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 {Writable} writeStream The Node.js Writable 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 deleted file mode 100644 index 0e4622586..000000000 --- a/node_modules/azure-storage/lib/services/blob/blobservice.node.js +++ /dev/null @@ -1,461 +0,0 @@ -// -// 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 deleted file mode 100644 index d03758f70..000000000 --- a/node_modules/azure-storage/lib/services/blob/blobutilities.js +++ /dev/null @@ -1,136 +0,0 @@ -// -// 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 deleted file mode 100644 index 7881f7075..000000000 --- a/node_modules/azure-storage/lib/services/blob/internal/blockrangestream.js +++ /dev/null @@ -1,203 +0,0 @@ -// -// 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 deleted file mode 100644 index d97e562ff..000000000 --- a/node_modules/azure-storage/lib/services/blob/internal/pagerangestream.js +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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 deleted file mode 100644 index 2b32b1d35..000000000 --- a/node_modules/azure-storage/lib/services/blob/models/blobresult.js +++ /dev/null @@ -1,304 +0,0 @@ -// -// 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 deleted file mode 100644 index 54f7b822b..000000000 --- a/node_modules/azure-storage/lib/services/blob/models/blocklistresult.js +++ /dev/null @@ -1,85 +0,0 @@ -// -// 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 deleted file mode 100644 index 6139de460..000000000 --- a/node_modules/azure-storage/lib/services/blob/models/containerresult.js +++ /dev/null @@ -1,116 +0,0 @@ -// -// 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 deleted file mode 100644 index 8163b372e..000000000 --- a/node_modules/azure-storage/lib/services/blob/models/leaseresult.js +++ /dev/null @@ -1,73 +0,0 @@ -// -// 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 deleted file mode 100644 index 79bbed217..000000000 --- a/node_modules/azure-storage/lib/services/file/fileservice.browser.js +++ /dev/null @@ -1,95 +0,0 @@ -// -// 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 deleted file mode 100644 index d2605be33..000000000 --- a/node_modules/azure-storage/lib/services/file/fileservice.core.js +++ /dev/null @@ -1,3937 +0,0 @@ -// -// 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 {string} [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 {Readable} A Node.js Readable 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 {Writable} writeStream The Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} writeStream The Node.js Writable 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 {Writable} writeStream The Node.js Writable 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 deleted file mode 100644 index 32bee8d83..000000000 --- a/node_modules/azure-storage/lib/services/file/fileservice.node.js +++ /dev/null @@ -1,182 +0,0 @@ -// -// 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 deleted file mode 100644 index c227b893e..000000000 --- a/node_modules/azure-storage/lib/services/file/fileutilities.js +++ /dev/null @@ -1,72 +0,0 @@ -// -// 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 deleted file mode 100644 index e7e9327d8..000000000 --- a/node_modules/azure-storage/lib/services/file/internal/filerangestream.js +++ /dev/null @@ -1,46 +0,0 @@ -// -// 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 deleted file mode 100644 index f39d32e86..000000000 --- a/node_modules/azure-storage/lib/services/file/models/directoryresult.js +++ /dev/null @@ -1,58 +0,0 @@ -// -// 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 deleted file mode 100644 index 818cdbf37..000000000 --- a/node_modules/azure-storage/lib/services/file/models/fileresult.js +++ /dev/null @@ -1,207 +0,0 @@ -// -// 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 deleted file mode 100644 index 398ad8187..000000000 --- a/node_modules/azure-storage/lib/services/file/models/shareresult.js +++ /dev/null @@ -1,84 +0,0 @@ -// -// 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 deleted file mode 100644 index 0586a85ce..000000000 --- a/node_modules/azure-storage/lib/services/queue/models/queuemessageresult.js +++ /dev/null @@ -1,131 +0,0 @@ -// -// 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 deleted file mode 100644 index 0b91ee99b..000000000 --- a/node_modules/azure-storage/lib/services/queue/models/queueresult.js +++ /dev/null @@ -1,72 +0,0 @@ -// -// 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 deleted file mode 100644 index c99bd2af4..000000000 --- a/node_modules/azure-storage/lib/services/queue/queuemessageencoder.js +++ /dev/null @@ -1,182 +0,0 @@ -// -// 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 deleted file mode 100644 index b92ab451f..000000000 --- a/node_modules/azure-storage/lib/services/queue/queueservice.js +++ /dev/null @@ -1,1468 +0,0 @@ -// -// 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 deleted file mode 100644 index 6786fd043..000000000 --- a/node_modules/azure-storage/lib/services/queue/queueutilities.js +++ /dev/null @@ -1,39 +0,0 @@ -// -// 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 deleted file mode 100644 index 47edd4da0..000000000 --- a/node_modules/azure-storage/lib/services/table/internal/edmhandler.js +++ /dev/null @@ -1,197 +0,0 @@ -// -// 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 deleted file mode 100644 index 344b639fb..000000000 --- a/node_modules/azure-storage/lib/services/table/internal/odatahandler.js +++ /dev/null @@ -1,217 +0,0 @@ -// -// 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 deleted file mode 100644 index 6bbac20ea..000000000 --- a/node_modules/azure-storage/lib/services/table/internal/requesthandler.js +++ /dev/null @@ -1,135 +0,0 @@ -// -// 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 deleted file mode 100644 index 42cccdbbd..000000000 --- a/node_modules/azure-storage/lib/services/table/internal/sharedkeytable.js +++ /dev/null @@ -1,92 +0,0 @@ -// -// 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 deleted file mode 100644 index 4e39ad950..000000000 --- a/node_modules/azure-storage/lib/services/table/models/batchresult.js +++ /dev/null @@ -1,232 +0,0 @@ -// -// 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 deleted file mode 100644 index ac96ce741..000000000 --- a/node_modules/azure-storage/lib/services/table/models/entityresult.js +++ /dev/null @@ -1,62 +0,0 @@ -// -// 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 deleted file mode 100644 index c6228287b..000000000 --- a/node_modules/azure-storage/lib/services/table/models/tableresult.js +++ /dev/null @@ -1,37 +0,0 @@ -// -// 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 deleted file mode 100644 index 98bb3aecb..000000000 --- a/node_modules/azure-storage/lib/services/table/tablebatch.js +++ /dev/null @@ -1,209 +0,0 @@ -// -// 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 deleted file mode 100644 index 9e225eee4..000000000 --- a/node_modules/azure-storage/lib/services/table/tablequery.js +++ /dev/null @@ -1,419 +0,0 @@ -// -// 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 deleted file mode 100644 index 6ddf5505d..000000000 --- a/node_modules/azure-storage/lib/services/table/tableservice.js +++ /dev/null @@ -1,1391 +0,0 @@ -// -// 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 deleted file mode 100644 index c3f3d4e16..000000000 --- a/node_modules/azure-storage/lib/services/table/tableutilities.js +++ /dev/null @@ -1,154 +0,0 @@ -// -// 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/extend/.npmignore b/node_modules/azure-storage/node_modules/extend/.npmignore deleted file mode 100644 index 30d74d258..000000000 --- a/node_modules/azure-storage/node_modules/extend/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/extend/.travis.yml b/node_modules/azure-storage/node_modules/extend/.travis.yml deleted file mode 100644 index c99d4002f..000000000 --- a/node_modules/azure-storage/node_modules/extend/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - "0.10" - - 0.8 - - 0.6 diff --git a/node_modules/azure-storage/node_modules/extend/README.md b/node_modules/azure-storage/node_modules/extend/README.md deleted file mode 100644 index ddaee06c3..000000000 --- a/node_modules/azure-storage/node_modules/extend/README.md +++ /dev/null @@ -1,59 +0,0 @@ -[![Build Status][1]][2] [![dependency status][9]][10] [![dev dependency status][11]][12] - -# extend() for Node.js [![Version Badge][8]][3] - -`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true. - -## Installation - -This package is available on [npm][3] 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.* - -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. - -### 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][4]. - -## Acknowledgements - -All credit to the jQuery authors for perfecting this amazing utility. - -Ported to Node.js by [Stefan Thomas][5] with contributions by [Jonathan Buchanan][6] and [Jordan Harband][7]. - -[1]: https://travis-ci.org/justmoon/node-extend.png -[2]: https://travis-ci.org/justmoon/node-extend -[3]: https://npmjs.org/package/extend -[4]: http://opensource.org/licenses/MIT -[5]: https://github.com/justmoon -[6]: https://github.com/insin -[7]: https://github.com/ljharb -[8]: http://vb.teelaun.ch/justmoon/node-extend.svg -[9]: https://david-dm.org/justmoon/node-extend.png -[10]: https://david-dm.org/justmoon/node-extend -[11]: https://david-dm.org/justmoon/node-extend/dev-status.png -[12]: https://david-dm.org/justmoon/node-extend#info=devDependencies - diff --git a/node_modules/azure-storage/node_modules/extend/index.js b/node_modules/azure-storage/node_modules/extend/index.js deleted file mode 100644 index be7300b3d..000000000 --- a/node_modules/azure-storage/node_modules/extend/index.js +++ /dev/null @@ -1,78 +0,0 @@ -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -function isPlainObject(obj) { - if (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval) - return false; - - var has_own_constructor = hasOwn.call(obj, 'constructor'); - var has_is_property_of_method = hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !has_own_constructor && !has_is_property_of_method) - 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 key === undefined || hasOwn.call( obj, key ); -}; - -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && typeof target !== "function") { - target = {}; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = Array.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && Array.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 ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; diff --git a/node_modules/azure-storage/node_modules/extend/package.json b/node_modules/azure-storage/node_modules/extend/package.json deleted file mode 100644 index da1b37a32..000000000 --- a/node_modules/azure-storage/node_modules/extend/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "extend@~1.2.1", - "_id": "extend@1.2.1", - "_inBundle": false, - "_integrity": "sha1-oPX9bPyDpf5J72mNYOyKYk3UV2w=", - "_location": "/azure-storage/extend", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "extend@~1.2.1", - "name": "extend", - "escapedName": "extend", - "rawSpec": "~1.2.1", - "saveSpec": null, - "fetchSpec": "~1.2.1" - }, - "_requiredBy": [ - "/azure-storage" - ], - "_resolved": "https://registry.npmjs.org/extend/-/extend-1.2.1.tgz", - "_shasum": "a0f5fd6cfc83a5fe49ef698d60ec8a624dd4576c", - "_spec": "extend@~1.2.1", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot\\node_modules\\azure-storage", - "author": { - "name": "Stefan Thomas", - "email": "justmoon@members.fsf.org", - "url": "http://www.justmoon.net" - }, - "bugs": { - "url": "https://github.com/justmoon/node-extend/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "url": "https://github.com/ljharb" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Port of jQuery.extend for Node.js", - "devDependencies": { - "tape": "~1.1.0" - }, - "homepage": "https://github.com/justmoon/node-extend#readme", - "keywords": [ - "extend", - "clone", - "merge" - ], - "main": "index", - "name": "extend", - "repository": { - "type": "git", - "url": "git+https://github.com/justmoon/node-extend.git" - }, - "scripts": { - "test": "node test/index.js" - }, - "version": "1.2.1" -} diff --git a/node_modules/azure-storage/node_modules/request/CHANGELOG.md b/node_modules/azure-storage/node_modules/request/CHANGELOG.md deleted file mode 100644 index af76719b4..000000000 --- a/node_modules/azure-storage/node_modules/request/CHANGELOG.md +++ /dev/null @@ -1,674 +0,0 @@ -## 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 deleted file mode 100644 index a4a9aee0c..000000000 --- a/node_modules/azure-storage/node_modules/request/LICENSE +++ /dev/null @@ -1,55 +0,0 @@ -Apache License - -Version 2.0, January 2004 - -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -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 deleted file mode 100644 index cedc19d51..000000000 --- a/node_modules/azure-storage/node_modules/request/README.md +++ /dev/null @@ -1,1097 +0,0 @@ - -# 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) -- [Promises & Async/Await](#promises--asyncawait) -- [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) - - ---- - - -## Promises & Async/Await - -`request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017. - -Several alternative interfaces are provided by the request team, including: -- [`request-promise`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises) -- [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises) -- [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises) - - -[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 that 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.METHOD() - -These HTTP method convenience functions act just like `request()` but with a default method already set for you: - -- *request.get()*: Defaults to `method: "GET"`. -- *request.post()*: Defaults to `method: "POST"`. -- *request.put()*: Defaults to `method: "PUT"`. -- *request.patch()*: Defaults to `method: "PATCH"`. -- *request.del() / request.delete()*: Defaults to `method: "DELETE"`. -- *request.head()*: Defaults to `method: "HEAD"`. -- *request.options()*: Defaults to `method: "OPTIONS"`. - -### 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 deleted file mode 100644 index f9b480a1d..000000000 --- a/node_modules/azure-storage/node_modules/request/index.js +++ /dev/null @@ -1,155 +0,0 @@ -// 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') -var cookies = require('./lib/cookies') -var 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.options = verbFunc('options') -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 deleted file mode 100644 index 42f9adaec..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/auth.js +++ /dev/null @@ -1,167 +0,0 @@ -'use strict' - -var caseless = require('caseless') -var uuid = require('uuid') -var helpers = require('./helpers') - -var md5 = helpers.md5 -var 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 - var 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 - var 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 deleted file mode 100644 index bd5d46bea..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/cookies.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict' - -var tough = require('tough-cookie') - -var Cookie = tough.Cookie -var 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 deleted file mode 100644 index 4633ba5f6..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/getProxyFromURI.js +++ /dev/null @@ -1,79 +0,0 @@ -'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) - var zoneHost = formatHostname(zoneParts[0]) - var zonePort = zoneParts[1] - var hasPort = zone.indexOf(':') > -1 - - return {hostname: zoneHost, port: zonePort, hasPort: hasPort} -} - -function uriInNoProxy (uri, noProxy) { - var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') - var hostname = formatHostname(uri.hostname) - var 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) - var 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 deleted file mode 100644 index 2f660309d..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/har.js +++ /dev/null @@ -1,205 +0,0 @@ -'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 deleted file mode 100644 index 8b2a7e6eb..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/helpers.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict' - -var jsonSafeStringify = require('json-stringify-safe') -var crypto = require('crypto') -var 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 deleted file mode 100644 index d6b981277..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/multipart.js +++ /dev/null @@ -1,112 +0,0 @@ -'use strict' - -var uuid = require('uuid') -var CombinedStream = require('combined-stream') -var isstream = require('isstream') -var 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 - var chunked = false - var 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) - var 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 deleted file mode 100644 index 0c9c57cfe..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/oauth.js +++ /dev/null @@ -1,148 +0,0 @@ -'use strict' - -var url = require('url') -var qs = require('qs') -var caseless = require('caseless') -var uuid = require('uuid') -var oauth = require('oauth-sign') -var crypto = require('crypto') -var 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 // eslint-disable-line camelcase - delete oa.oauth_consumer_secret - delete oa.oauth_private_key - - var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase - 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, // eslint-disable-line camelcase - token_secret // eslint-disable-line camelcase - ) - - 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 || {} - var method = self.request.method || '' - var headers = caseless(self.request.headers) - var body = self.request.body || '' - var qsLib = self.request.qsLib || qs - - var form - var query - var contentType = headers.get('content-type') || '' - var formContentType = 'application/x-www-form-urlencoded' - var 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 deleted file mode 100644 index 4a32cd149..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/querystring.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict' - -var qs = require('qs') -var 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 deleted file mode 100644 index b9150e77c..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/redirect.js +++ /dev/null @@ -1,154 +0,0 @@ -'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 - var 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 - var 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 deleted file mode 100644 index 4479003f6..000000000 --- a/node_modules/azure-storage/node_modules/request/lib/tunnel.js +++ /dev/null @@ -1,175 +0,0 @@ -'use strict' - -var url = require('url') -var 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 - var protocol = uriObject.protocol - var 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 - var 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 - var 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 deleted file mode 100644 index 90b31938e..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/.eslintrc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "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 deleted file mode 100644 index 0284c86da..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/.jscs.json +++ /dev/null @@ -1,175 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 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 deleted file mode 100644 index 30d74d258..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/.npmignore +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 6bf696c87..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/.travis.yml +++ /dev/null @@ -1,179 +0,0 @@ -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 deleted file mode 100644 index 0fe528764..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/CHANGELOG.md +++ /dev/null @@ -1,77 +0,0 @@ -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 deleted file mode 100644 index e16d6a56c..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 5b8249aa9..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/README.md +++ /dev/null @@ -1,81 +0,0 @@ -[![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 deleted file mode 100644 index 1500a2f37..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/component.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "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 deleted file mode 100644 index bbe53f660..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/index.js +++ /dev/null @@ -1,86 +0,0 @@ -'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 deleted file mode 100644 index b97130ab8..000000000 --- a/node_modules/azure-storage/node_modules/request/node_modules/extend/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "_from": "extend@~3.0.1", - "_id": "extend@3.0.1", - "_inBundle": false, - "_integrity": "sha1-p1Xqe8Gt/MWjHOfnYtuq3F5jZEQ=", - "_location": "/azure-storage/request/extend", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "extend@~3.0.1", - "name": "extend", - "escapedName": "extend", - "rawSpec": "~3.0.1", - "saveSpec": null, - "fetchSpec": "~3.0.1" - }, - "_requiredBy": [ - "/azure-storage/request" - ], - "_resolved": "https://registry.npmjs.org/extend/-/extend-3.0.1.tgz", - "_shasum": "a755ea7bc1adfcc5a31ce7e762dbaadc5e636444", - "_spec": "extend@~3.0.1", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot\\node_modules\\azure-storage\\node_modules\\request", - "author": { - "name": "Stefan Thomas", - "email": "justmoon@members.fsf.org", - "url": "http://www.justmoon.net" - }, - "bugs": { - "url": "https://github.com/justmoon/node-extend/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "url": "https://github.com/ljharb" - } - ], - "dependencies": {}, - "deprecated": false, - "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" - }, - "homepage": "https://github.com/justmoon/node-extend#readme", - "keywords": [ - "extend", - "clone", - "merge" - ], - "license": "MIT", - "main": "index", - "name": "extend", - "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 deleted file mode 100644 index a891e4e58..000000000 --- a/node_modules/azure-storage/node_modules/request/package.json +++ /dev/null @@ -1,117 +0,0 @@ -{ - "_from": "request@~2.83.0", - "_id": "request@2.83.0", - "_inBundle": false, - "_integrity": "sha512-lR3gD69osqm6EYLk9wB/G1W/laGWjzH90t1vEa2xuxHD5KUrSzp9pUSfTm+YC5Nxt2T8nMPEvKlhbQayU7bgFw==", - "_location": "/azure-storage/request", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "request@~2.83.0", - "name": "request", - "escapedName": "request", - "rawSpec": "~2.83.0", - "saveSpec": null, - "fetchSpec": "~2.83.0" - }, - "_requiredBy": [ - "/azure-storage" - ], - "_resolved": "https://registry.npmjs.org/request/-/request-2.83.0.tgz", - "_shasum": "ca0b65da02ed62935887808e6f510381034e3356", - "_spec": "request@~2.83.0", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot\\node_modules\\azure-storage", - "author": { - "name": "Mikeal Rogers", - "email": "mikeal.rogers@gmail.com" - }, - "bugs": { - "url": "http://github.com/request/request/issues" - }, - "bundleDependencies": false, - "dependencies": { - "aws-sign2": "~0.7.0", - "aws4": "^1.6.0", - "caseless": "~0.12.0", - "combined-stream": "~1.0.5", - "extend": "~3.0.1", - "forever-agent": "~0.6.1", - "form-data": "~2.3.1", - "har-validator": "~5.0.3", - "hawk": "~6.0.2", - "http-signature": "~1.2.0", - "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": "^2.1.0", - "qs": "~6.5.1", - "safe-buffer": "^5.1.1", - "stringstream": "~0.0.5", - "tough-cookie": "~2.3.3", - "tunnel-agent": "^0.6.0", - "uuid": "^3.1.0" - }, - "deprecated": false, - "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": "^2.0.2", - "coveralls": "^2.11.4", - "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", - "standard": "^9.0.0", - "tape": "^4.6.0", - "taper": "^0.5.0" - }, - "engines": { - "node": ">= 4" - }, - "files": [ - "lib/", - "index.js", - "request.js" - ], - "greenkeeper": { - "ignore": [ - "hawk", - "har-validator" - ] - }, - "homepage": "https://github.com/request/request#readme", - "keywords": [ - "http", - "simple", - "util", - "utility" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "request", - "repository": { - "type": "git", - "url": "git+https://github.com/request/request.git" - }, - "scripts": { - "lint": "standard", - "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.83.0" -} diff --git a/node_modules/azure-storage/node_modules/request/request.js b/node_modules/azure-storage/node_modules/request/request.js deleted file mode 100644 index ff19ca39c..000000000 --- a/node_modules/azure-storage/node_modules/request/request.js +++ /dev/null @@ -1,1552 +0,0 @@ -'use strict' - -var http = require('http') -var https = require('https') -var url = require('url') -var util = require('util') -var stream = require('stream') -var zlib = require('zlib') -var hawk = require('hawk') -var aws2 = require('aws-sign2') -var aws4 = require('aws4') -var httpSignature = require('http-signature') -var mime = require('mime-types') -var stringstream = require('stringstream') -var caseless = require('caseless') -var ForeverAgent = require('forever-agent') -var FormData = require('form-data') -var extend = require('extend') -var isstream = require('isstream') -var isTypedArray = require('is-typedarray').strict -var helpers = require('./lib/helpers') -var cookies = require('./lib/cookies') -var getProxyFromURI = require('./lib/getProxyFromURI') -var Querystring = require('./lib/querystring').Querystring -var Har = require('./lib/har').Har -var Auth = require('./lib/auth').Auth -var OAuth = require('./lib/oauth').OAuth -var Multipart = require('./lib/multipart').Multipart -var Redirect = require('./lib/redirect').Redirect -var Tunnel = require('./lib/tunnel').Tunnel -var now = require('performance-now') -var Buffer = require('safe-buffer').Buffer - -var safeStringify = helpers.safeStringify -var isReadStream = helpers.isReadStream -var toBase64 = helpers.toBase64 -var defer = helpers.defer -var copy = helpers.copy -var version = helpers.version -var 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 - var defaultModules = {'http:': http, 'https:': https} - var 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) { // eslint-disable-line handle-callback-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) - } else { // if no callback - 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 = [] - var bufferLength = 0 - var 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(':') - var host = unixParts[0] - var 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/validator/CHANGELOG.md b/node_modules/azure-storage/node_modules/validator/CHANGELOG.md deleted file mode 100644 index 0ae5c5cfb..000000000 --- a/node_modules/azure-storage/node_modules/validator/CHANGELOG.md +++ /dev/null @@ -1,419 +0,0 @@ -#### 9.4.1 - -- Patched a [REDOS](https://en.wikipedia.org/wiki/ReDoS) vulnerability in `isDataURI` -- New and improved locales - ([#788](https://github.com/chriso/validator.js/pull/788)) - -#### 9.4.0 - -- Added an option to `isMobilePhone` to require a country code - ([#769](https://github.com/chriso/validator.js/pull/769)) -- New and improved locales - ([#785](https://github.com/chriso/validator.js/pull/785)) - -#### 9.3.0 - -- New and improved locales - ([#763](https://github.com/chriso/validator.js/pull/763), - [#768](https://github.com/chriso/validator.js/pull/768), - [#774](https://github.com/chriso/validator.js/pull/774), - [#777](https://github.com/chriso/validator.js/pull/777), - [#779](https://github.com/chriso/validator.js/pull/779)) - -#### 9.2.0 - -- Added an `isMimeType()` validator - ([#760](https://github.com/chriso/validator.js/pull/760)) -- New and improved locales - ([#753](https://github.com/chriso/validator.js/pull/753), - [#755](https://github.com/chriso/validator.js/pull/755), - [#764](https://github.com/chriso/validator.js/pull/764)) - -#### 9.1.2 - -- Fixed a bug with the `isFloat` validator - ([#752](https://github.com/chriso/validator.js/pull/752)) - -#### 9.1.1 - -- Locale fixes - ([#738](https://github.com/chriso/validator.js/pull/738), - [#739](https://github.com/chriso/validator.js/pull/739)) - -#### 9.1.0 - -- Added an `isISO31661Alpha2()` validator - ([#734](https://github.com/chriso/validator.js/pull/734)) -- New locales - ([#735](https://github.com/chriso/validator.js/pull/735), - [#737](https://github.com/chriso/validator.js/pull/737)) - -#### 9.0.0 - -- `normalizeEmail()` no longer validates the email address - ([#725](https://github.com/chriso/validator.js/pull/725)) -- Added locale-aware validation to `isFloat()` and `isDecimal()` - ([#721](https://github.com/chriso/validator.js/pull/721)) -- Added an `isPort()` validator - ([#733](https://github.com/chriso/validator.js/pull/733)) -- New locales - ([#731](https://github.com/chriso/validator.js/pull/731)) - -#### 8.2.0 - -- Added an `isHash()` validator - ([#711](https://github.com/chriso/validator.js/pull/711)) -- Control decimal places in `isCurrency()` - ([#713](https://github.com/chriso/validator.js/pull/713)) -- New and improved locales - ([#700](https://github.com/chriso/validator.js/pull/700), - [#701](https://github.com/chriso/validator.js/pull/701), - [#714](https://github.com/chriso/validator.js/pull/714), - [#715](https://github.com/chriso/validator.js/pull/715), - [#718](https://github.com/chriso/validator.js/pull/718)) - -#### 8.1.0 - -- Fix `require('validator/lib/isIS8601')` calls - ([#688](https://github.com/chriso/validator.js/issues/688)) -- Added an `isLatLong()` and `isPostalCode()` validator - ([#684](https://github.com/chriso/validator.js/pull/684)) -- Allow comma in email display names - ([#692](https://github.com/chriso/validator.js/pull/692)) -- Add missing string to `unescape()` - ([#690](https://github.com/chriso/validator.js/pull/690)) -- Fix `isMobilePhone()` with Node <= 6.x - ([#681](https://github.com/chriso/validator.js/issues/681)) -- New locales - ([#695](https://github.com/chriso/validator.js/pull/695)) - -#### 8.0.0 - -- `isURL()` now requires the `require_tld: false` option to validate `localhost` - ([#675](https://github.com/chriso/validator.js/issues/675)) -- `isURL()` now rejects URLs that are protocol only - ([#642](https://github.com/chriso/validator.js/issues/642)) -- Fixed a bug where `isMobilePhone()` would silently return false if the locale was invalid or unsupported - ([#657](https://github.com/chriso/validator.js/issues/657)) - -#### 7.2.0 - -- Added an option to validate any phone locale - ([#663](https://github.com/chriso/validator.js/pull/663)) -- Fixed a bug in credit card validation - ([#672](https://github.com/chriso/validator.js/pull/672)) -- Disallow whitespace, including unicode whitespace, in TLDs - ([#677](https://github.com/chriso/validator.js/pull/677)) -- New locales - ([#673](https://github.com/chriso/validator.js/pull/673), - [#676](https://github.com/chriso/validator.js/pull/676)) - -#### 7.1.0 - -- Added an `isISRC()` validator for [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code) - ([#660](https://github.com/chriso/validator.js/pull/660)) -- Fixed a bug in credit card validation - ([#670](https://github.com/chriso/validator.js/pull/670)) -- Reduced the maximum allowed address in `isEmail()` based on - [RFC3696 errata](http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690) - ([#655](https://github.com/chriso/validator.js/issues/655)) -- New locales - ([#647](https://github.com/chriso/validator.js/pull/647), - [#667](https://github.com/chriso/validator.js/pull/667), - [#667](https://github.com/chriso/validator.js/pull/667), - [#671](https://github.com/chriso/validator.js/pull/671)) - -#### 7.0.0 - -- Remove `isDate()` - -#### 6.3.0 - -- Allow values like `-.01` in `isFloat()` - ([#618](https://github.com/chriso/validator.js/issues/618)) -- New locales - ([#616](https://github.com/chriso/validator.js/pull/616), - [#622](https://github.com/chriso/validator.js/pull/622), - [#627](https://github.com/chriso/validator.js/pull/627), - [#630](https://github.com/chriso/validator.js/pull/630)) - -#### 6.2.1 - -- Disallow `<` and `>` in URLs - ([#613](https://github.com/chriso/validator.js/issues/613)) -- New locales - ([#610](https://github.com/chriso/validator.js/pull/610)) - -#### 6.2.0 - -- Added an option to require an email display name - ([#607](https://github.com/chriso/validator.js/pull/607)) -- Added support for `lt` and `gt` to `isInt()` - ([#588](https://github.com/chriso/validator.js/pull/588)) -- New locales - ([#601](https://github.com/chriso/validator.js/pull/601)) - -#### 6.1.0 - -- Added support for greater or less than in `isFloat()` - ([#544](https://github.com/chriso/validator.js/issues/544)) -- Added support for ISSN validation via `isISSN()` - ([#593](https://github.com/chriso/validator.js/pull/593)) -- Fixed a bug in `normalizeEmail()` - ([#594](https://github.com/chriso/validator.js/issues/594)) -- New locales - ([#585](https://github.com/chriso/validator.js/pull/585)) - -#### 6.0.0 - -- Renamed `isNull()` to `isEmpty()` - ([#574](https://github.com/chriso/validator.js/issues/574)) -- Backslash is now escaped in `escape()` - ([#516](https://github.com/chriso/validator.js/issues/516)) -- Improved `normalizeEmail()` - ([#583](https://github.com/chriso/validator.js/pull/583)) -- Allow leading zeroes by default in `isInt()` - ([#532](https://github.com/chriso/validator.js/pull/532)) - -#### 5.7.0 - -- Added support for IPv6 in `isURL()` - ([#564](https://github.com/chriso/validator.js/issues/564)) -- Added support for urls without a host (e.g. `file:///foo.txt`) in `isURL()` - ([#563](https://github.com/chriso/validator.js/issues/563)) -- Added support for regular expressions in the `isURL()` host whitelist and blacklist - ([#562](https://github.com/chriso/validator.js/issues/562)) -- Added support for MasterCard 2-Series BIN - ([#576](https://github.com/chriso/validator.js/pull/576)) -- New locales - ([#575](https://github.com/chriso/validator.js/pull/575), - [#552](https://github.com/chriso/validator.js/issues/552)) - -#### 5.6.0 - -- Added an `isMD5()` validator - ([#557](https://github.com/chriso/validator.js/pull/557)) -- Fixed an exceptional case in `isDate()` - ([#566](https://github.com/chriso/validator.js/pull/566)) -- New locales - ([#559](https://github.com/chriso/validator.js/pull/559), - [#568](https://github.com/chriso/validator.js/pull/568), - [#571](https://github.com/chriso/validator.js/pull/571), - [#573](https://github.com/chriso/validator.js/pull/573)) - -#### 5.5.0 - -- Fixed a regex denial of service in `trim()` and `rtrim()` - ([#556](https://github.com/chriso/validator.js/pull/556)) -- Added an Algerian locale to `isMobilePhone()` - ([#540](https://github.com/chriso/validator.js/pull/540)) -- Fixed the Hungarian locale in `isAlpha()` and `isAlphanumeric()` - ([#541](https://github.com/chriso/validator.js/pull/541)) -- Added a Polish locale to `isMobilePhone()` - ([#545](https://github.com/chriso/validator.js/pull/545)) - -#### 5.4.0 - -- Accept Union Pay credit cards in `isCreditCard()` - ([#539](https://github.com/chriso/validator.js/pull/539)) -- Added Danish locale to `isMobilePhone()` - ([#538](https://github.com/chriso/validator.js/pull/538)) -- Added Hungarian locales to `isAlpha()`, `isAlphanumeric()` and `isMobilePhone()` - ([#537](https://github.com/chriso/validator.js/pull/537)) - -#### 5.3.0 - -- Added an `allow_leading_zeroes` option to `isInt()` - ([#532](https://github.com/chriso/validator.js/pull/532)) -- Adjust Chinese mobile phone validation - ([#523](https://github.com/chriso/validator.js/pull/523)) -- Added a Canadian locale to `isMobilePhone()` - ([#524](https://github.com/chriso/validator.js/issues/524)) - -#### 5.2.0 - -- Added a `isDataURI()` validator - ([#521](https://github.com/chriso/validator.js/pull/521)) -- Added Czech locales - ([#522](https://github.com/chriso/validator.js/pull/522)) -- Fixed a bug with `isURL()` when protocol was missing and "://" appeared in the query - ([#518](https://github.com/chriso/validator.js/issues/518)) - -#### 5.1.0 - -- Added a `unescape()` HTML function - ([#509](https://github.com/chriso/validator.js/pull/509)) -- Added a Malaysian locale to `isMobilePhone()` - ([#507](https://github.com/chriso/validator.js/pull/507)) -- Added Polish locales to `isAlpha()` and `isAlphanumeric()` - ([#506](https://github.com/chriso/validator.js/pull/506)) -- Added Turkish locales to `isAlpha()`, `isAlphanumeric()` and `isMobilePhone()` - ([#512](https://github.com/chriso/validator.js/pull/512)) -- Allow >1 underscore in hostnames when using `allow_underscores` - ([#510](https://github.com/chriso/validator.js/issues/510)) - -#### 5.0.0 - -- Migrate to ES6 - ([#496](https://github.com/chriso/validator.js/pull/496)) -- Break the library up so that individual functions can be imported - ([#496](https://github.com/chriso/validator.js/pull/496)) -- Remove auto-coercion of input to a string - ([#496](https://github.com/chriso/validator.js/pull/496)) -- Remove the `extend()` function - ([#496](https://github.com/chriso/validator.js/pull/496)) -- Added Arabic locales to `isAlpha()` and `isAlphanumeric()` - ([#496](https://github.com/chriso/validator.js/pull/496#issuecomment-184781730)) -- Fix validation of very large base64 strings - ([#503](https://github.com/chriso/validator.js/pull/503)) - -#### 4.9.0 - -- Added a Russian locale to `isAlpha()` and `isAlphanumeric()` - ([#499](https://github.com/chriso/validator.js/pull/499)) -- Remove the restriction on adjacent hyphens in hostnames - ([#500](https://github.com/chriso/validator.js/issues/500)) - -#### 4.8.0 - -- Added Spanish, French, Portuguese and Dutch support for `isAlpha()` and `isAlphanumeric()` - ([#492](https://github.com/chriso/validator.js/pull/492)) -- Added a Brazilian locale to `isMobilePhone()` - ([#489](https://github.com/chriso/validator.js/pull/489)) -- Reject IPv4 addresses with invalid zero padding - ([#490](https://github.com/chriso/validator.js/pull/490)) -- Fix the client-side version when used with RequireJS - ([#494](https://github.com/chriso/validator.js/issues/494)) - -#### 4.7.1 - -- Use [node-depd](https://github.com/dougwilson/nodejs-depd) to print deprecation notices - ([#487](https://github.com/chriso/validator.js/issues/487)) - -#### 4.7.0 - -- Print a deprecation warning if validator input is not a string - ([1f67e1e](https://github.com/chriso/validator.js/commit/1f67e1e15198c0ae735151290dc8dc2bf14da254)). - Note that this will be an error in v5. -- Added a German locale to `isMobilePhone()`, `isAlpha()` and `isAlphanumeric()` - ([#477](https://github.com/chriso/validator.js/pull/477)) -- Added a Finnish locale to `isMobilePhone()` - ([#455](https://github.com/chriso/validator.js/pull/455)) - -#### 4.6.1 - -- Fix coercion of objects: `Object.toString()` is `[object Object]` not `""` - ([a57f3c8](https://github.com/chriso/validator.js/commit/a57f3c843c715fba2664ee22ec80e9e28e88e0a6)) - -#### 4.6.0 - -- Added a Spanish locale to `isMobilePhone()` - ([#481](https://github.com/chriso/validator.js/pull/481)) -- Fix string coercion of objects created with `Object.create(null)` - ([#484](https://github.com/chriso/validator.js/issues/484)) - -#### 4.5.2 - -- Fix a timezone issue with short-form ISO 8601 dates, e.g. - `validator.isDate('2011-12-21')` - ([#480](https://github.com/chriso/validator.js/issues/480)) - -#### 4.5.1 - -- Make `isLength()` / `isByteLength()` accept `{min, max}` as options object. - ([#474](https://github.com/chriso/validator.js/issues/474)) - -#### 4.5.0 - -- Add validation for Indian mobile phone numbers - ([#471](https://github.com/chriso/validator.js/pull/471)) -- Tweak Greek and Chinese mobile phone validation - ([#467](https://github.com/chriso/validator.js/pull/467), - [#468](https://github.com/chriso/validator.js/pull/468)) -- Fixed a bug in `isDate()` when validating ISO 8601 dates without a timezone - ([#472](https://github.com/chriso/validator.js/issues/472)) - -#### 4.4.1 - -- Allow triple hyphens in IDNA hostnames - ([#466](https://github.com/chriso/validator.js/issues/466)) - -#### 4.4.0 - -- Added `isMACAddress()` validator - ([#458](https://github.com/chriso/validator.js/pull/458)) -- Added `isWhitelisted()` validator - ([#462](https://github.com/chriso/validator.js/pull/462)) -- Added a New Zealand locale to `isMobilePhone()` - ([#452](https://github.com/chriso/validator.js/pull/452)) -- Added options to control GMail address normalization - ([#460](https://github.com/chriso/validator.js/pull/460)) - -#### 4.3.0 - -- Support Ember CLI module definitions - ([#448](https://github.com/chriso/validator.js/pull/448)) -- Added a Vietnam locale to `isMobilePhone()` - ([#451](https://github.com/chriso/validator.js/pull/451)) - -#### 4.2.1 - -- Fix `isDate()` handling of RFC2822 timezones - ([#447](https://github.com/chriso/validator.js/pull/447)) - -#### 4.2.0 - -- Fix `isDate()` handling of ISO8601 timezones - ([#444](https://github.com/chriso/validator.js/pull/444)) -- Fix the incorrect `isFloat('.') === true` - ([#443](https://github.com/chriso/validator.js/pull/443)) -- Added a Norwegian locale to `isMobilePhone()` - ([#439](https://github.com/chriso/validator.js/pull/439)) - -#### 4.1.0 - -- General `isDate()` improvements - ([#431](https://github.com/chriso/validator.js/pull/431)) -- Tests now require node 4.0+ - ([#438](https://github.com/chriso/validator.js/pull/438)) - -#### 4.0.6 - -- Added a Taiwan locale to `isMobilePhone()` - ([#432](https://github.com/chriso/validator.js/pull/432)) -- Fixed a bug in `isBefore()` where it would return `null` - ([#436](https://github.com/chriso/validator.js/pull/436)) - -#### 4.0.5 - -- Fixed a denial of service vulnerability in the `isEmail()` regex - ([#152](https://github.com/chriso/validator.js/issues/152#issuecomment-131874928)) - -#### 4.0.4 - -- Reverted the leap year validation in `isDate()` as it introduced some regressions - ([#422](https://github.com/chriso/validator.js/issues/422), [#423](https://github.com/chriso/validator.js/issues/423)) - -#### 4.0.3 - -- Added leap year validation to `isDate()` - ([#418](https://github.com/chriso/validator.js/pull/418)) - -#### 4.0.2 - -- Fixed `isDecimal()` with an empty string - ([#419](https://github.com/chriso/validator.js/issues/419)) - -#### 4.0.1 - -- Fixed `isByteLength()` with certain strings - ([09f0c6d](https://github.com/chriso/validator.js/commit/09f0c6d2321f0c78af6a7de42e91b63955e4c01e)) -- Put length restrictions on email parts - ([#258](https://github.com/chriso/validator.js/issues/258#issuecomment-127173612)) - -#### 4.0.0 - -- Simplified the `isEmail()` regex and fixed some edge cases - ([#258](https://github.com/chriso/validator.js/issues/258#issuecomment-127173612)) -- Added ISO 8601 date validation via `isISO8601()` - ([#373](https://github.com/chriso/validator.js/issues/373)) diff --git a/node_modules/azure-storage/node_modules/validator/LICENSE b/node_modules/azure-storage/node_modules/validator/LICENSE deleted file mode 100644 index 37a807cbc..000000000 --- a/node_modules/azure-storage/node_modules/validator/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2016 Chris O'Hara - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -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/validator/README.md b/node_modules/azure-storage/node_modules/validator/README.md deleted file mode 100644 index 39ba581dd..000000000 --- a/node_modules/azure-storage/node_modules/validator/README.md +++ /dev/null @@ -1,209 +0,0 @@ -# validator.js - -[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Downloads][downloads-image]][npm-url] - -A library of string validators and sanitizers. - -## Strings only - -**This library validates and sanitizes strings only.** - -If you're not sure if your input is a string, coerce it using `input + ''`. -Passing anything other than a string is an error. - -## Installation and Usage - -### Server-side usage - -Install the library with `npm install validator` - -#### No ES6 - -```javascript -var validator = require('validator'); - -validator.isEmail('foo@bar.com'); //=> true -``` - -#### ES6 - -```javascript -import validator from 'validator'; -``` - -Or, import only a subset of the library: - -```javascript -import isEmail from 'validator/lib/isEmail'; -``` - -### Client-side usage - -The library can be loaded either as a standalone script, or through an [AMD][amd]-compatible loader - -```html - - -``` - -The library can also be installed through [bower][bower] - -```bash -$ bower install validator-js -``` - -## Validators - -Here is a list of the validators currently available. - -Validator | Description ---------------------------------------- | -------------------------------------- -***contains(str, seed)*** | check if the string contains the seed. -**equals(str, comparison)** | check if the string matches the comparison. -**isAfter(str [, date])** | check if the string is a date that's after the specified date (defaults to now). -**isAlpha(str [, locale])** | check if the string contains only letters (a-zA-Z).

Locale is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`) and defaults to `en-US`. -**isAlphanumeric(str [, locale])** | check if the string contains only letters and numbers.

Locale is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sk-SK', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`) and defaults to `en-US`. -**isAscii(str)** | check if the string contains ASCII chars only. -**isBase64(str)** | check if a string is base64 encoded. -**isBefore(str [, date])** | check if the string is a date that's before the specified date. -**isBoolean(str)** | check if a string is a boolean. -**isByteLength(str, options)** | check if the string's length (in UTF-8 bytes) falls in a range.

`options` is an object which defaults to `{min:0, max: undefined}`. -**isCreditCard(str)** | check if the string is a credit card. -**isCurrency(str, options)** | check if the string is a valid currency amount.

`options` is an object which defaults to `{symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_decimal: true, require_decimal: false, digits_after_decimal: [2], allow_space_after_digits: false}`.
**Note:** The array `digits_after_decimal` is filled with the exact number of digits allowd not a range, for example a range 1 to 3 will be given as [1, 2, 3]. -**isDataURI(str)** | check if the string is a [data uri format](https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs). -**isDecimal(str, options)** | check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc.

`options` is an object which defaults to `{force_decimal: false, decimal_digits: '1,', locale: 'en-US'}`

`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`.
**Note:** `decimal_digits` is given as a range like '1,3', a specific value like '3' or min like '1,'. -**isDivisibleBy(str, number)** | check if the string is a number that's divisible by another. -**isEmail(str [, options])** | check if the string is an email.

`options` is an object which defaults to `{ allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true }`. If `allow_display_name` is set to true, the validator will also match `Display Name `. If `require_display_name` is set to true, the validator will reject strings without the format `Display Name `. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, e-mail addresses without having TLD in their domain will also be matched. -**isEmpty(str)** | check if the string has a length of zero. -**isFQDN(str [, options])** | check if the string is a fully qualified domain name (e.g. domain.com).

`options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false }`. -**isFloat(str [, options])** | check if the string is a float.

`options` is an object which can contain the keys `min`, `max`, `gt`, and/or `lt` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`) it also has `locale` as an option.

`min` and `max` are equivalent to 'greater or equal' and 'less or equal', respectively while `gt` and `lt` are their strict counterparts.

`locale` determine the decimal separator and is one of `['ar', 'ar-AE', 'ar-BH', 'ar-DZ', 'ar-EG', 'ar-IQ', 'ar-JO', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-QA', 'ar-QM', 'ar-SA', 'ar-SD', 'ar-SY', 'ar-TN', 'ar-YE', 'bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'en-AU', 'en-GB', 'en-HK', 'en-IN', 'en-NZ', 'en-US', 'en-ZA', 'en-ZM', 'es-ES', 'fr-FR', 'hu-HU', 'it-IT', 'nb-NO', 'nl-NL', 'nn-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'sr-RS', 'sr-RS@latin', 'sv-SE', 'tr-TR', 'uk-UA']`. -**isFullWidth(str)** | check if the string contains any full-width chars. -**isHalfWidth(str)** | check if the string contains any half-width chars. -**isHash(str, algorithm)** | check if the string is a hash of type algorithm.

Algorithm is one of `['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']` -**isHexColor(str)** | check if the string is a hexadecimal color. -**isHexadecimal(str)** | check if the string is a hexadecimal number. -**isIP(str [, version])** | check if the string is an IP (version 4 or 6). -**isISBN(str [, version])** | check if the string is an ISBN (version 10 or 13). -**isISSN(str [, options])** | check if the string is an [ISSN](https://en.wikipedia.org/wiki/International_Standard_Serial_Number).

`options` is an object which defaults to `{ case_sensitive: false, require_hyphen: false }`. If `case_sensitive` is true, ISSNs with a lowercase `'x'` as the check digit are rejected. -**isISIN(str)** | check if the string is an [ISIN][ISIN] (stock/security identifier). -**isISO8601(str)** | check if the string is a valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date. -**isISO31661Alpha2(str)** | check if the string is a valid [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) officially assigned country code. -**isISRC(str)** | check if the string is a [ISRC](https://en.wikipedia.org/wiki/International_Standard_Recording_Code). -**isIn(str, values)** | check if the string is in a array of allowed values. -**isInt(str [, options])** | check if the string is an integer.

`options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). `options` can also contain the key `allow_leading_zeroes`, which when set to false will disallow integer values with leading zeroes (e.g. `{ allow_leading_zeroes: false }`). Finally, `options` can contain the keys `gt` and/or `lt` which will enforce integers being greater than or less than, respectively, the value provided (e.g. `{gt: 1, lt: 4}` for a number between 1 and 4). -**isJSON(str)** | check if the string is valid JSON (note: uses JSON.parse). -**isLatLong(str)**                     | check if the string is a valid latitude-longitude coordinate in the format `lat,long` or `lat, long`. -**isLength(str, options)** | check if the string's length falls in a range.

`options` is an object which defaults to `{min:0, max: undefined}`. Note: this function takes into account surrogate pairs. -**isLowercase(str)** | check if the string is lowercase. -**isMACAddress(str)** | check if the string is a MAC address. -**isMD5(str)** | check if the string is a MD5 hash. -**isMimeType(str)** | check if the string matches to a valid [MIME type](https://en.wikipedia.org/wiki/Media_type) format -**isMobilePhone(str, locale)** | check if the string is a mobile phone number,

(locale is one of `['ar-AE', 'ar-DZ', 'ar-EG', 'ar-JO', 'ar-SA', 'ar-SY', 'be-BY', 'bg-BG', 'cs-CZ', 'de-DE', 'da-DK', 'el-GR', 'en-AU', 'en-CA', 'en-GB', 'en-HK', 'en-IN', 'en-KE', 'en-NG', 'en-NZ', 'en-RW', 'en-SG', 'en-UG', 'en-US', 'en-TZ', 'en-ZA', 'en-ZM', 'en-PK', 'es-ES', 'et-EE', 'fa-IR', 'fi-FI', 'fr-FR', 'he-IL', 'hu-HU', 'it-IT', 'ja-JP', 'kk-KZ', 'ko-KR', 'lt-LT', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'pt-BR', 'ro-RO', 'ru-RU', 'sk-SK', 'sr-RS', 'th-TH', 'tr-TR', 'uk-UA', 'vi-VN', 'zh-CN', 'zh-HK', 'zh-TW']` OR 'any'. If 'any' is used, function will check if any of the locales match).

`options` is an optional object that can be supplied with the following keys: `strictMode`, if this is set to `true`, the mobile phone number must be supplied with the country code and therefore must start with `+`. -**isMongoId(str)** | check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid]. -**isMultibyte(str)** | check if the string contains one or more multibyte chars. -**isNumeric(str)** | check if the string contains only numbers. -**isPort(str)** | check if the string is a valid port number. -**isPostalCode(str, locale)** | check if the string is a postal code,

(locale is one of `[ 'AT', 'AU', 'BE', 'BG', 'CA', 'CH', 'CZ', 'DE', 'DK', 'DZ', 'ES', 'FI', 'FR', 'GB', 'GR', 'IL', 'IN', 'IS', 'IT', 'JP', 'KE', 'LI', 'MX', 'NL', 'NO', 'PL', 'PT', 'RO', 'RU', 'SA', 'SE', 'TW', 'US', 'ZA', 'ZM' ]` OR 'any'. If 'any' is used, function will check if any of the locals match). -**isSurrogatePair(str)** | check if the string contains any surrogate pairs chars. -**isURL(str [, options])** | check if the string is an URL.

`options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_host: true, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }`. -**isUUID(str [, version])** | check if the string is a UUID (version 3, 4 or 5). -**isUppercase(str)** | check if the string is uppercase. -**isVariableWidth(str)** | check if the string contains a mixture of full and half-width chars. -**isWhitelisted(str, chars)** | checks characters if they appear in the whitelist. -**matches(str, pattern [, modifiers])** | check if string matches the pattern.

Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`. - -## Sanitizers - -Here is a list of the sanitizers currently available. - -Sanitizer | Description --------------------------------------- | ------------------------------- -**blacklist(input, chars)** | remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `blacklist(input, '\\[\\]')`. -**escape(input)** | replace `<`, `>`, `&`, `'`, `"` and `/` with HTML entities. -**unescape(input)** | replaces HTML encoded entities with `<`, `>`, `&`, `'`, `"` and `/`. -**ltrim(input [, chars])** | trim characters from the left-side of the input. -**normalizeEmail(email [, options])** | canonicalizes an email address. (This doesn't validate that the input is an email, if you want to validate the email use isEmail beforehand)

`options` is an object with the following keys and default values:
  • *all_lowercase: true* - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it's case insensitive per RFC 1035.
  • *gmail_lowercase: true* - GMail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, GMail addresses are lowercased regardless of the value of this setting.
  • *gmail_remove_dots: true*: Removes dots from the local part of the email address, as GMail ignores them (e.g. "john.doe" and "johndoe" are considered equal).
  • *gmail_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@gmail.com" becomes "foo@gmail.com").
  • *gmail_convert_googlemaildotcom: true*: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent.
  • *outlookdotcom_lowercase: true* - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Outlook.com addresses are lowercased regardless of the value of this setting.
  • *outlookdotcom_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@outlook.com" becomes "foo@outlook.com").
  • *yahoo_lowercase: true* - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, Yahoo Mail addresses are lowercased regardless of the value of this setting.
  • *yahoo_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "foo-bar@yahoo.com" becomes "foo@yahoo.com").
  • *icloud_lowercase: true* - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when *all_lowercase* is set to false. Please note that when *all_lowercase* is true, iCloud addresses are lowercased regardless of the value of this setting.
  • *icloud_remove_subaddress: true*: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@icloud.com" becomes "foo@icloud.com").
-**rtrim(input [, chars])** | trim characters from the right-side of the input. -**stripLow(input [, keep_new_lines])** | remove characters with a numerical value < 32 and 127, mostly control characters. If `keep_new_lines` is `true`, newline characters are preserved (`\n` and `\r`, hex `0xA` and `0xD`). Unicode-safe in JavaScript. -**toBoolean(input [, strict])** | convert the input string to a boolean. Everything except for `'0'`, `'false'` and `''` returns `true`. In strict mode only `'1'` and `'true'` return `true`. -**toDate(input)** | convert the input string to a date, or `null` if the input is not a date. -**toFloat(input)** | convert the input string to a float, or `NaN` if the input is not a float. -**toInt(input [, radix])** | convert the input string to an integer, or `NaN` if the input is not an integer. -**trim(input [, chars])** | trim characters (whitespace by default) from both sides of the input. -**whitelist(input, chars)** | remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`. - -### XSS Sanitization - -XSS sanitization was removed from the library in [2d5d6999](https://github.com/chriso/validator.js/commit/2d5d6999541add350fb396ef02dc42ca3215049e). - -For an alternative, have a look at Yahoo's [xss-filters library](https://github.com/yahoo/xss-filters) or at [DOMPurify](https://github.com/cure53/DOMPurify). - -## Contributing - -In general, we follow the "fork-and-pull" Git workflow. - -1. Fork the repo on GitHub -2. Clone the project to your own machine -3. Work on your fork - 1. Make your changes and additions - 2. Change or add tests if needed - 3. Run tests and make sure they pass - 4. Add changes to README.md if needed -4. Commit changes to your own branch -5. **Make sure** you merge the latest from "upstream" and resolve conflicts if there is any -6. Repeat step 3(3) above -7. Push your work back up to your fork -8. Submit a Pull request so that we can review your changes - -## Tests - -Tests are using mocha, to run the tests use: - -```sh -$ npm test -``` - -## Reading - -Remember, validating can be troublesome sometimes. See [A list of articles about programming assumptions commonly made that aren't true](https://github.com/jameslk/awesome-falsehoods). - -## License (MIT) - -``` -Copyright (c) 2017 Chris O'Hara - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` - -[downloads-image]: http://img.shields.io/npm/dm/validator.svg - -[npm-url]: https://npmjs.org/package/validator -[npm-image]: http://img.shields.io/npm/v/validator.svg - -[travis-url]: https://travis-ci.org/chriso/validator.js -[travis-image]: http://img.shields.io/travis/chriso/validator.js.svg - -[amd]: http://requirejs.org/docs/whyamd.html -[bower]: http://bower.io/ - -[mongoid]: http://docs.mongodb.org/manual/reference/object-id/ -[ISIN]: https://en.wikipedia.org/wiki/International_Securities_Identification_Number diff --git a/node_modules/azure-storage/node_modules/validator/index.js b/node_modules/azure-storage/node_modules/validator/index.js deleted file mode 100644 index 1139da5f0..000000000 --- a/node_modules/azure-storage/node_modules/validator/index.js +++ /dev/null @@ -1,351 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _toDate = require('./lib/toDate'); - -var _toDate2 = _interopRequireDefault(_toDate); - -var _toFloat = require('./lib/toFloat'); - -var _toFloat2 = _interopRequireDefault(_toFloat); - -var _toInt = require('./lib/toInt'); - -var _toInt2 = _interopRequireDefault(_toInt); - -var _toBoolean = require('./lib/toBoolean'); - -var _toBoolean2 = _interopRequireDefault(_toBoolean); - -var _equals = require('./lib/equals'); - -var _equals2 = _interopRequireDefault(_equals); - -var _contains = require('./lib/contains'); - -var _contains2 = _interopRequireDefault(_contains); - -var _matches = require('./lib/matches'); - -var _matches2 = _interopRequireDefault(_matches); - -var _isEmail = require('./lib/isEmail'); - -var _isEmail2 = _interopRequireDefault(_isEmail); - -var _isURL = require('./lib/isURL'); - -var _isURL2 = _interopRequireDefault(_isURL); - -var _isMACAddress = require('./lib/isMACAddress'); - -var _isMACAddress2 = _interopRequireDefault(_isMACAddress); - -var _isIP = require('./lib/isIP'); - -var _isIP2 = _interopRequireDefault(_isIP); - -var _isFQDN = require('./lib/isFQDN'); - -var _isFQDN2 = _interopRequireDefault(_isFQDN); - -var _isBoolean = require('./lib/isBoolean'); - -var _isBoolean2 = _interopRequireDefault(_isBoolean); - -var _isAlpha = require('./lib/isAlpha'); - -var _isAlpha2 = _interopRequireDefault(_isAlpha); - -var _isAlphanumeric = require('./lib/isAlphanumeric'); - -var _isAlphanumeric2 = _interopRequireDefault(_isAlphanumeric); - -var _isNumeric = require('./lib/isNumeric'); - -var _isNumeric2 = _interopRequireDefault(_isNumeric); - -var _isPort = require('./lib/isPort'); - -var _isPort2 = _interopRequireDefault(_isPort); - -var _isLowercase = require('./lib/isLowercase'); - -var _isLowercase2 = _interopRequireDefault(_isLowercase); - -var _isUppercase = require('./lib/isUppercase'); - -var _isUppercase2 = _interopRequireDefault(_isUppercase); - -var _isAscii = require('./lib/isAscii'); - -var _isAscii2 = _interopRequireDefault(_isAscii); - -var _isFullWidth = require('./lib/isFullWidth'); - -var _isFullWidth2 = _interopRequireDefault(_isFullWidth); - -var _isHalfWidth = require('./lib/isHalfWidth'); - -var _isHalfWidth2 = _interopRequireDefault(_isHalfWidth); - -var _isVariableWidth = require('./lib/isVariableWidth'); - -var _isVariableWidth2 = _interopRequireDefault(_isVariableWidth); - -var _isMultibyte = require('./lib/isMultibyte'); - -var _isMultibyte2 = _interopRequireDefault(_isMultibyte); - -var _isSurrogatePair = require('./lib/isSurrogatePair'); - -var _isSurrogatePair2 = _interopRequireDefault(_isSurrogatePair); - -var _isInt = require('./lib/isInt'); - -var _isInt2 = _interopRequireDefault(_isInt); - -var _isFloat = require('./lib/isFloat'); - -var _isFloat2 = _interopRequireDefault(_isFloat); - -var _isDecimal = require('./lib/isDecimal'); - -var _isDecimal2 = _interopRequireDefault(_isDecimal); - -var _isHexadecimal = require('./lib/isHexadecimal'); - -var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal); - -var _isDivisibleBy = require('./lib/isDivisibleBy'); - -var _isDivisibleBy2 = _interopRequireDefault(_isDivisibleBy); - -var _isHexColor = require('./lib/isHexColor'); - -var _isHexColor2 = _interopRequireDefault(_isHexColor); - -var _isISRC = require('./lib/isISRC'); - -var _isISRC2 = _interopRequireDefault(_isISRC); - -var _isMD = require('./lib/isMD5'); - -var _isMD2 = _interopRequireDefault(_isMD); - -var _isHash = require('./lib/isHash'); - -var _isHash2 = _interopRequireDefault(_isHash); - -var _isJSON = require('./lib/isJSON'); - -var _isJSON2 = _interopRequireDefault(_isJSON); - -var _isEmpty = require('./lib/isEmpty'); - -var _isEmpty2 = _interopRequireDefault(_isEmpty); - -var _isLength = require('./lib/isLength'); - -var _isLength2 = _interopRequireDefault(_isLength); - -var _isByteLength = require('./lib/isByteLength'); - -var _isByteLength2 = _interopRequireDefault(_isByteLength); - -var _isUUID = require('./lib/isUUID'); - -var _isUUID2 = _interopRequireDefault(_isUUID); - -var _isMongoId = require('./lib/isMongoId'); - -var _isMongoId2 = _interopRequireDefault(_isMongoId); - -var _isAfter = require('./lib/isAfter'); - -var _isAfter2 = _interopRequireDefault(_isAfter); - -var _isBefore = require('./lib/isBefore'); - -var _isBefore2 = _interopRequireDefault(_isBefore); - -var _isIn = require('./lib/isIn'); - -var _isIn2 = _interopRequireDefault(_isIn); - -var _isCreditCard = require('./lib/isCreditCard'); - -var _isCreditCard2 = _interopRequireDefault(_isCreditCard); - -var _isISIN = require('./lib/isISIN'); - -var _isISIN2 = _interopRequireDefault(_isISIN); - -var _isISBN = require('./lib/isISBN'); - -var _isISBN2 = _interopRequireDefault(_isISBN); - -var _isISSN = require('./lib/isISSN'); - -var _isISSN2 = _interopRequireDefault(_isISSN); - -var _isMobilePhone = require('./lib/isMobilePhone'); - -var _isMobilePhone2 = _interopRequireDefault(_isMobilePhone); - -var _isCurrency = require('./lib/isCurrency'); - -var _isCurrency2 = _interopRequireDefault(_isCurrency); - -var _isISO = require('./lib/isISO8601'); - -var _isISO2 = _interopRequireDefault(_isISO); - -var _isISO31661Alpha = require('./lib/isISO31661Alpha2'); - -var _isISO31661Alpha2 = _interopRequireDefault(_isISO31661Alpha); - -var _isBase = require('./lib/isBase64'); - -var _isBase2 = _interopRequireDefault(_isBase); - -var _isDataURI = require('./lib/isDataURI'); - -var _isDataURI2 = _interopRequireDefault(_isDataURI); - -var _isMimeType = require('./lib/isMimeType'); - -var _isMimeType2 = _interopRequireDefault(_isMimeType); - -var _isLatLong = require('./lib/isLatLong'); - -var _isLatLong2 = _interopRequireDefault(_isLatLong); - -var _isPostalCode = require('./lib/isPostalCode'); - -var _isPostalCode2 = _interopRequireDefault(_isPostalCode); - -var _ltrim = require('./lib/ltrim'); - -var _ltrim2 = _interopRequireDefault(_ltrim); - -var _rtrim = require('./lib/rtrim'); - -var _rtrim2 = _interopRequireDefault(_rtrim); - -var _trim = require('./lib/trim'); - -var _trim2 = _interopRequireDefault(_trim); - -var _escape = require('./lib/escape'); - -var _escape2 = _interopRequireDefault(_escape); - -var _unescape = require('./lib/unescape'); - -var _unescape2 = _interopRequireDefault(_unescape); - -var _stripLow = require('./lib/stripLow'); - -var _stripLow2 = _interopRequireDefault(_stripLow); - -var _whitelist = require('./lib/whitelist'); - -var _whitelist2 = _interopRequireDefault(_whitelist); - -var _blacklist = require('./lib/blacklist'); - -var _blacklist2 = _interopRequireDefault(_blacklist); - -var _isWhitelisted = require('./lib/isWhitelisted'); - -var _isWhitelisted2 = _interopRequireDefault(_isWhitelisted); - -var _normalizeEmail = require('./lib/normalizeEmail'); - -var _normalizeEmail2 = _interopRequireDefault(_normalizeEmail); - -var _toString = require('./lib/util/toString'); - -var _toString2 = _interopRequireDefault(_toString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var version = '9.4.1'; - -var validator = { - version: version, - toDate: _toDate2.default, - toFloat: _toFloat2.default, - toInt: _toInt2.default, - toBoolean: _toBoolean2.default, - equals: _equals2.default, - contains: _contains2.default, - matches: _matches2.default, - isEmail: _isEmail2.default, - isURL: _isURL2.default, - isMACAddress: _isMACAddress2.default, - isIP: _isIP2.default, - isFQDN: _isFQDN2.default, - isBoolean: _isBoolean2.default, - isAlpha: _isAlpha2.default, - isAlphanumeric: _isAlphanumeric2.default, - isNumeric: _isNumeric2.default, - isPort: _isPort2.default, - isLowercase: _isLowercase2.default, - isUppercase: _isUppercase2.default, - isAscii: _isAscii2.default, - isFullWidth: _isFullWidth2.default, - isHalfWidth: _isHalfWidth2.default, - isVariableWidth: _isVariableWidth2.default, - isMultibyte: _isMultibyte2.default, - isSurrogatePair: _isSurrogatePair2.default, - isInt: _isInt2.default, - isFloat: _isFloat2.default, - isDecimal: _isDecimal2.default, - isHexadecimal: _isHexadecimal2.default, - isDivisibleBy: _isDivisibleBy2.default, - isHexColor: _isHexColor2.default, - isISRC: _isISRC2.default, - isMD5: _isMD2.default, - isHash: _isHash2.default, - isJSON: _isJSON2.default, - isEmpty: _isEmpty2.default, - isLength: _isLength2.default, - isByteLength: _isByteLength2.default, - isUUID: _isUUID2.default, - isMongoId: _isMongoId2.default, - isAfter: _isAfter2.default, - isBefore: _isBefore2.default, - isIn: _isIn2.default, - isCreditCard: _isCreditCard2.default, - isISIN: _isISIN2.default, - isISBN: _isISBN2.default, - isISSN: _isISSN2.default, - isMobilePhone: _isMobilePhone2.default, - isPostalCode: _isPostalCode2.default, - isCurrency: _isCurrency2.default, - isISO8601: _isISO2.default, - isISO31661Alpha2: _isISO31661Alpha2.default, - isBase64: _isBase2.default, - isDataURI: _isDataURI2.default, - isMimeType: _isMimeType2.default, - isLatLong: _isLatLong2.default, - ltrim: _ltrim2.default, - rtrim: _rtrim2.default, - trim: _trim2.default, - escape: _escape2.default, - unescape: _unescape2.default, - stripLow: _stripLow2.default, - whitelist: _whitelist2.default, - blacklist: _blacklist2.default, - isWhitelisted: _isWhitelisted2.default, - normalizeEmail: _normalizeEmail2.default, - toString: _toString2.default -}; - -exports.default = validator; -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/alpha.js b/node_modules/azure-storage/node_modules/validator/lib/alpha.js deleted file mode 100644 index 8456bc41c..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/alpha.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -var alpha = exports.alpha = { - 'en-US': /^[A-Z]+$/i, - 'bg-BG': /^[А-Я]+$/i, - 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, - 'da-DK': /^[A-ZÆØÅ]+$/i, - 'de-DE': /^[A-ZÄÖÜß]+$/i, - 'el-GR': /^[Α-ω]+$/i, - 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i, - 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, - 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i, - 'nb-NO': /^[A-ZÆØÅ]+$/i, - 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i, - 'nn-NO': /^[A-ZÆØÅ]+$/i, - 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i, - 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i, - 'pt-PT': /^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i, - 'ru-RU': /^[А-ЯЁ]+$/i, - 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, - 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i, - 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i, - 'sv-SE': /^[A-ZÅÄÖ]+$/i, - 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i, - 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i, - ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/ -}; - -var alphanumeric = exports.alphanumeric = { - 'en-US': /^[0-9A-Z]+$/i, - 'bg-BG': /^[0-9А-Я]+$/i, - 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, - 'da-DK': /^[0-9A-ZÆØÅ]+$/i, - 'de-DE': /^[0-9A-ZÄÖÜß]+$/i, - 'el-GR': /^[0-9Α-ω]+$/i, - 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i, - 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, - 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i, - 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i, - 'nb-NO': /^[0-9A-ZÆØÅ]+$/i, - 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i, - 'nn-NO': /^[0-9A-ZÆØÅ]+$/i, - 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i, - 'pt-PT': /^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i, - 'ru-RU': /^[0-9А-ЯЁ]+$/i, - 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, - 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i, - 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i, - 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i, - 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i, - 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i, - ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/ -}; - -var decimal = exports.decimal = { - 'en-US': '.', - ar: '٫' -}; - -var englishLocales = exports.englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM']; - -for (var locale, i = 0; i < englishLocales.length; i++) { - locale = 'en-' + englishLocales[i]; - alpha[locale] = alpha['en-US']; - alphanumeric[locale] = alphanumeric['en-US']; - decimal[locale] = decimal['en-US']; -} - -// Source: http://www.localeplanet.com/java/ -var arabicLocales = exports.arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE']; - -for (var _locale, _i = 0; _i < arabicLocales.length; _i++) { - _locale = 'ar-' + arabicLocales[_i]; - alpha[_locale] = alpha.ar; - alphanumeric[_locale] = alphanumeric.ar; - decimal[_locale] = decimal.ar; -} - -// Source: https://en.wikipedia.org/wiki/Decimal_mark -var dotDecimal = exports.dotDecimal = []; -var commaDecimal = exports.commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'es-ES', 'fr-FR', 'it-IT', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-Pl', 'pt-PT', 'ru-RU', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA']; - -for (var _i2 = 0; _i2 < dotDecimal.length; _i2++) { - decimal[dotDecimal[_i2]] = decimal['en-US']; -} - -for (var _i3 = 0; _i3 < commaDecimal.length; _i3++) { - decimal[commaDecimal[_i3]] = ','; -} - -alpha['pt-BR'] = alpha['pt-PT']; -alphanumeric['pt-BR'] = alphanumeric['pt-PT']; -decimal['pt-BR'] = decimal['pt-PT']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/blacklist.js b/node_modules/azure-storage/node_modules/validator/lib/blacklist.js deleted file mode 100644 index 41ecdf0f6..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/blacklist.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = blacklist; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function blacklist(str, chars) { - (0, _assertString2.default)(str); - return str.replace(new RegExp('[' + chars + ']+', 'g'), ''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/contains.js b/node_modules/azure-storage/node_modules/validator/lib/contains.js deleted file mode 100644 index 025e8012e..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/contains.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = contains; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _toString = require('./util/toString'); - -var _toString2 = _interopRequireDefault(_toString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function contains(str, elem) { - (0, _assertString2.default)(str); - return str.indexOf((0, _toString2.default)(elem)) >= 0; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/equals.js b/node_modules/azure-storage/node_modules/validator/lib/equals.js deleted file mode 100644 index 30ac76a05..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/equals.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = equals; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function equals(str, comparison) { - (0, _assertString2.default)(str); - return str === comparison; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/escape.js b/node_modules/azure-storage/node_modules/validator/lib/escape.js deleted file mode 100644 index abcd60774..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/escape.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = escape; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function escape(str) { - (0, _assertString2.default)(str); - return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`'); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isAfter.js b/node_modules/azure-storage/node_modules/validator/lib/isAfter.js deleted file mode 100644 index 9c84d67cf..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isAfter.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isAfter; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _toDate = require('./toDate'); - -var _toDate2 = _interopRequireDefault(_toDate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isAfter(str) { - var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); - - (0, _assertString2.default)(str); - var comparison = (0, _toDate2.default)(date); - var original = (0, _toDate2.default)(str); - return !!(original && comparison && original > comparison); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isAlpha.js b/node_modules/azure-storage/node_modules/validator/lib/isAlpha.js deleted file mode 100644 index 4aff94c83..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isAlpha.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isAlpha; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _alpha = require('./alpha'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isAlpha(str) { - var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; - - (0, _assertString2.default)(str); - if (locale in _alpha.alpha) { - return _alpha.alpha[locale].test(str); - } - throw new Error('Invalid locale \'' + locale + '\''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isAlphanumeric.js b/node_modules/azure-storage/node_modules/validator/lib/isAlphanumeric.js deleted file mode 100644 index 9fb36a799..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isAlphanumeric.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isAlphanumeric; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _alpha = require('./alpha'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isAlphanumeric(str) { - var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; - - (0, _assertString2.default)(str); - if (locale in _alpha.alphanumeric) { - return _alpha.alphanumeric[locale].test(str); - } - throw new Error('Invalid locale \'' + locale + '\''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isAscii.js b/node_modules/azure-storage/node_modules/validator/lib/isAscii.js deleted file mode 100644 index 55171e844..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isAscii.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isAscii; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable no-control-regex */ -var ascii = /^[\x00-\x7F]+$/; -/* eslint-enable no-control-regex */ - -function isAscii(str) { - (0, _assertString2.default)(str); - return ascii.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isBase64.js b/node_modules/azure-storage/node_modules/validator/lib/isBase64.js deleted file mode 100644 index 0b4a807f5..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isBase64.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isBase64; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var notBase64 = /[^A-Z0-9+\/=]/i; - -function isBase64(str) { - (0, _assertString2.default)(str); - var len = str.length; - if (!len || len % 4 !== 0 || notBase64.test(str)) { - return false; - } - var firstPaddingChar = str.indexOf('='); - return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '='; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isBefore.js b/node_modules/azure-storage/node_modules/validator/lib/isBefore.js deleted file mode 100644 index b4e3cf625..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isBefore.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isBefore; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _toDate = require('./toDate'); - -var _toDate2 = _interopRequireDefault(_toDate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isBefore(str) { - var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); - - (0, _assertString2.default)(str); - var comparison = (0, _toDate2.default)(date); - var original = (0, _toDate2.default)(str); - return !!(original && comparison && original < comparison); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isBoolean.js b/node_modules/azure-storage/node_modules/validator/lib/isBoolean.js deleted file mode 100644 index 7dbd26f8c..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isBoolean.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isBoolean; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isBoolean(str) { - (0, _assertString2.default)(str); - return ['true', 'false', '1', '0'].indexOf(str) >= 0; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isByteLength.js b/node_modules/azure-storage/node_modules/validator/lib/isByteLength.js deleted file mode 100644 index 5ec897c6b..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isByteLength.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -exports.default = isByteLength; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable prefer-rest-params */ -function isByteLength(str, options) { - (0, _assertString2.default)(str); - var min = void 0; - var max = void 0; - if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { - min = options.min || 0; - max = options.max; - } else { - // backwards compatibility: isByteLength(str, min [, max]) - min = arguments[1]; - max = arguments[2]; - } - var len = encodeURI(str).split(/%..|./).length - 1; - return len >= min && (typeof max === 'undefined' || len <= max); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isCreditCard.js b/node_modules/azure-storage/node_modules/validator/lib/isCreditCard.js deleted file mode 100644 index 2e204ef5c..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isCreditCard.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isCreditCard; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable max-len */ -var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|62[0-9]{14})$/; -/* eslint-enable max-len */ - -function isCreditCard(str) { - (0, _assertString2.default)(str); - var sanitized = str.replace(/[- ]+/g, ''); - if (!creditCard.test(sanitized)) { - return false; - } - var sum = 0; - var digit = void 0; - var tmpNum = void 0; - var shouldDouble = void 0; - for (var i = sanitized.length - 1; i >= 0; i--) { - digit = sanitized.substring(i, i + 1); - tmpNum = parseInt(digit, 10); - if (shouldDouble) { - tmpNum *= 2; - if (tmpNum >= 10) { - sum += tmpNum % 10 + 1; - } else { - sum += tmpNum; - } - } else { - sum += tmpNum; - } - shouldDouble = !shouldDouble; - } - return !!(sum % 10 === 0 ? sanitized : false); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isCurrency.js b/node_modules/azure-storage/node_modules/validator/lib/isCurrency.js deleted file mode 100644 index 5be44ef75..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isCurrency.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isCurrency; - -var _merge = require('./util/merge'); - -var _merge2 = _interopRequireDefault(_merge); - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function currencyRegex(options) { - var decimal_digits = '\\d{' + options.digits_after_decimal[0] + '}'; - options.digits_after_decimal.forEach(function (digit, index) { - if (index !== 0) decimal_digits = decimal_digits + '|\\d{' + digit + '}'; - }); - var symbol = '(\\' + options.symbol.replace(/\./g, '\\.') + ')' + (options.require_symbol ? '' : '?'), - negative = '-?', - whole_dollar_amount_without_sep = '[1-9]\\d*', - whole_dollar_amount_with_sep = '[1-9]\\d{0,2}(\\' + options.thousands_separator + '\\d{3})*', - valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep], - whole_dollar_amount = '(' + valid_whole_dollar_amounts.join('|') + ')?', - decimal_amount = '(\\' + options.decimal_separator + '(' + decimal_digits + '))' + (options.require_decimal ? '' : '?'); - var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); - - // default is negative sign before symbol, but there are two other options (besides parens) - if (options.allow_negatives && !options.parens_for_negatives) { - if (options.negative_sign_after_digits) { - pattern += negative; - } else if (options.negative_sign_before_digits) { - pattern = negative + pattern; - } - } - - // South African Rand, for example, uses R 123 (space) and R-123 (no space) - if (options.allow_negative_sign_placeholder) { - pattern = '( (?!\\-))?' + pattern; - } else if (options.allow_space_after_symbol) { - pattern = ' ?' + pattern; - } else if (options.allow_space_after_digits) { - pattern += '( (?!$))?'; - } - - if (options.symbol_after_digits) { - pattern += symbol; - } else { - pattern = symbol + pattern; - } - - if (options.allow_negatives) { - if (options.parens_for_negatives) { - pattern = '(\\(' + pattern + '\\)|' + pattern + ')'; - } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) { - pattern = negative + pattern; - } - } - - // ensure there's a dollar and/or decimal amount, and that - // it doesn't start with a space or a negative sign followed by a space - return new RegExp('^(?!-? )(?=.*\\d)' + pattern + '$'); -} - -var default_currency_options = { - symbol: '$', - require_symbol: false, - allow_space_after_symbol: false, - symbol_after_digits: false, - allow_negatives: true, - parens_for_negatives: false, - negative_sign_before_digits: false, - negative_sign_after_digits: false, - allow_negative_sign_placeholder: false, - thousands_separator: ',', - decimal_separator: '.', - allow_decimal: true, - require_decimal: false, - digits_after_decimal: [2], - allow_space_after_digits: false -}; - -function isCurrency(str, options) { - (0, _assertString2.default)(str); - options = (0, _merge2.default)(options, default_currency_options); - return currencyRegex(options).test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isDataURI.js b/node_modules/azure-storage/node_modules/validator/lib/isDataURI.js deleted file mode 100644 index 34146adf2..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isDataURI.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isDataURI; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i; - -var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i; - -var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i; - -function isDataURI(str) { - (0, _assertString2.default)(str); - var data = str.split(','); - if (data.length < 2) { - return false; - } - var attributes = data.shift().trim().split(';'); - var schemeAndMediaType = attributes.shift(); - if (schemeAndMediaType.substr(0, 5) !== 'data:') { - return false; - } - var mediaType = schemeAndMediaType.substr(5); - if (mediaType !== '' && !validMediaType.test(mediaType)) { - return false; - } - for (var i = 0; i < attributes.length; i++) { - if (i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') { - // ok - } else if (!validAttribute.test(attributes[i])) { - return false; - } - } - for (var _i = 0; _i < data.length; _i++) { - if (!validData.test(data[_i])) { - return false; - } - } - return true; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isDecimal.js b/node_modules/azure-storage/node_modules/validator/lib/isDecimal.js deleted file mode 100644 index 7a66dace5..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isDecimal.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isDecimal; - -var _merge = require('./util/merge'); - -var _merge2 = _interopRequireDefault(_merge); - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _alpha = require('./alpha'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function decimalRegExp(options) { - var regExp = new RegExp('^[-+]?([0-9]+)?(\\' + _alpha.decimal[options.locale] + '[0-9]{' + options.decimal_digits + '})' + (options.force_decimal ? '' : '?') + '$'); - return regExp; -} - -var default_decimal_options = { - force_decimal: false, - decimal_digits: '1,', - locale: 'en-US' -}; - -var blacklist = ['', '-', '+']; - -function isDecimal(str, options) { - (0, _assertString2.default)(str); - options = (0, _merge2.default)(options, default_decimal_options); - if (options.locale in _alpha.decimal) { - return !blacklist.includes(str.replace(/ /g, '')) && decimalRegExp(options).test(str); - } - throw new Error('Invalid locale \'' + options.locale + '\''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isDivisibleBy.js b/node_modules/azure-storage/node_modules/validator/lib/isDivisibleBy.js deleted file mode 100644 index 133603999..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isDivisibleBy.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isDivisibleBy; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _toFloat = require('./toFloat'); - -var _toFloat2 = _interopRequireDefault(_toFloat); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isDivisibleBy(str, num) { - (0, _assertString2.default)(str); - return (0, _toFloat2.default)(str) % parseInt(num, 10) === 0; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isEmail.js b/node_modules/azure-storage/node_modules/validator/lib/isEmail.js deleted file mode 100644 index 0944805be..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isEmail.js +++ /dev/null @@ -1,89 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isEmail; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _merge = require('./util/merge'); - -var _merge2 = _interopRequireDefault(_merge); - -var _isByteLength = require('./isByteLength'); - -var _isByteLength2 = _interopRequireDefault(_isByteLength); - -var _isFQDN = require('./isFQDN'); - -var _isFQDN2 = _interopRequireDefault(_isFQDN); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var default_email_options = { - allow_display_name: false, - require_display_name: false, - allow_utf8_local_part: true, - require_tld: true -}; - -/* eslint-disable max-len */ -/* eslint-disable no-control-regex */ -var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\,\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i; -var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i; -var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i; -var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i; -var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i; -/* eslint-enable max-len */ -/* eslint-enable no-control-regex */ - -function isEmail(str, options) { - (0, _assertString2.default)(str); - options = (0, _merge2.default)(options, default_email_options); - - if (options.require_display_name || options.allow_display_name) { - var display_email = str.match(displayName); - if (display_email) { - str = display_email[1]; - } else if (options.require_display_name) { - return false; - } - } - - var parts = str.split('@'); - var domain = parts.pop(); - var user = parts.join('@'); - - var lower_domain = domain.toLowerCase(); - if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') { - user = user.replace(/\./g, '').toLowerCase(); - } - - if (!(0, _isByteLength2.default)(user, { max: 64 }) || !(0, _isByteLength2.default)(domain, { max: 254 })) { - return false; - } - - if (!(0, _isFQDN2.default)(domain, { require_tld: options.require_tld })) { - return false; - } - - if (user[0] === '"') { - user = user.slice(1, user.length - 1); - return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user); - } - - var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart; - - var user_parts = user.split('.'); - for (var i = 0; i < user_parts.length; i++) { - if (!pattern.test(user_parts[i])) { - return false; - } - } - - return true; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isEmpty.js b/node_modules/azure-storage/node_modules/validator/lib/isEmpty.js deleted file mode 100644 index f3e39e4df..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isEmpty.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isEmpty; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isEmpty(str) { - (0, _assertString2.default)(str); - return str.length === 0; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isFQDN.js b/node_modules/azure-storage/node_modules/validator/lib/isFQDN.js deleted file mode 100644 index 9ac148da5..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isFQDN.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isFQDN; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _merge = require('./util/merge'); - -var _merge2 = _interopRequireDefault(_merge); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var default_fqdn_options = { - require_tld: true, - allow_underscores: false, - allow_trailing_dot: false -}; - -function isFQDN(str, options) { - (0, _assertString2.default)(str); - options = (0, _merge2.default)(options, default_fqdn_options); - - /* Remove the optional trailing dot before checking validity */ - if (options.allow_trailing_dot && str[str.length - 1] === '.') { - str = str.substring(0, str.length - 1); - } - var parts = str.split('.'); - if (options.require_tld) { - var tld = parts.pop(); - if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { - return false; - } - // disallow spaces - if (/[\s\u2002-\u200B\u202F\u205F\u3000\uFEFF\uDB40\uDC20]/.test(tld)) { - return false; - } - } - for (var part, i = 0; i < parts.length; i++) { - part = parts[i]; - if (options.allow_underscores) { - part = part.replace(/_/g, ''); - } - if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) { - return false; - } - // disallow full-width chars - if (/[\uff01-\uff5e]/.test(part)) { - return false; - } - if (part[0] === '-' || part[part.length - 1] === '-') { - return false; - } - } - return true; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isFloat.js b/node_modules/azure-storage/node_modules/validator/lib/isFloat.js deleted file mode 100644 index b81b2ae08..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isFloat.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isFloat; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _alpha = require('./alpha'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isFloat(str, options) { - (0, _assertString2.default)(str); - options = options || {}; - var float = new RegExp('^(?:[-+])?(?:[0-9]+)?(?:\\' + (options.locale ? _alpha.decimal[options.locale] : '.') + '[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$'); - if (str === '' || str === '.' || str === '-' || str === '+') { - return false; - } - return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max) && (!options.hasOwnProperty('lt') || str < options.lt) && (!options.hasOwnProperty('gt') || str > options.gt); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isFullWidth.js b/node_modules/azure-storage/node_modules/validator/lib/isFullWidth.js deleted file mode 100644 index 4215f8186..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isFullWidth.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.fullWidth = undefined; -exports.default = isFullWidth; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var fullWidth = exports.fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; - -function isFullWidth(str) { - (0, _assertString2.default)(str); - return fullWidth.test(str); -} \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isHalfWidth.js b/node_modules/azure-storage/node_modules/validator/lib/isHalfWidth.js deleted file mode 100644 index 986c63245..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isHalfWidth.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.halfWidth = undefined; -exports.default = isHalfWidth; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var halfWidth = exports.halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; - -function isHalfWidth(str) { - (0, _assertString2.default)(str); - return halfWidth.test(str); -} \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isHash.js b/node_modules/azure-storage/node_modules/validator/lib/isHash.js deleted file mode 100644 index 32cc29b9f..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isHash.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isHash; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var lengths = { - md5: 32, - md4: 32, - sha1: 40, - sha256: 64, - sha384: 96, - sha512: 128, - ripemd128: 32, - ripemd160: 40, - tiger128: 32, - tiger160: 40, - tiger192: 48, - crc32: 8, - crc32b: 8 -}; - -function isHash(str, algorithm) { - (0, _assertString2.default)(str); - var hash = new RegExp('^[a-f0-9]{' + lengths[algorithm] + '}$'); - return hash.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isHexColor.js b/node_modules/azure-storage/node_modules/validator/lib/isHexColor.js deleted file mode 100644 index 90634710c..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isHexColor.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isHexColor; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{6})$/i; - -function isHexColor(str) { - (0, _assertString2.default)(str); - return hexcolor.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isHexadecimal.js b/node_modules/azure-storage/node_modules/validator/lib/isHexadecimal.js deleted file mode 100644 index fb7808f9d..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isHexadecimal.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isHexadecimal; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hexadecimal = /^[0-9A-F]+$/i; - -function isHexadecimal(str) { - (0, _assertString2.default)(str); - return hexadecimal.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isIP.js b/node_modules/azure-storage/node_modules/validator/lib/isIP.js deleted file mode 100644 index fce2ecbfb..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isIP.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isIP; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; -var ipv6Block = /^[0-9A-F]{1,4}$/i; - -function isIP(str) { - var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; - - (0, _assertString2.default)(str); - version = String(version); - if (!version) { - return isIP(str, 4) || isIP(str, 6); - } else if (version === '4') { - if (!ipv4Maybe.test(str)) { - return false; - } - var parts = str.split('.').sort(function (a, b) { - return a - b; - }); - return parts[3] <= 255; - } else if (version === '6') { - var blocks = str.split(':'); - var foundOmissionBlock = false; // marker to indicate :: - - // At least some OS accept the last 32 bits of an IPv6 address - // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says - // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses, - // and '::a.b.c.d' is deprecated, but also valid. - var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4); - var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8; - - if (blocks.length > expectedNumberOfBlocks) { - return false; - } - // initial or final :: - if (str === '::') { - return true; - } else if (str.substr(0, 2) === '::') { - blocks.shift(); - blocks.shift(); - foundOmissionBlock = true; - } else if (str.substr(str.length - 2) === '::') { - blocks.pop(); - blocks.pop(); - foundOmissionBlock = true; - } - - for (var i = 0; i < blocks.length; ++i) { - // test for a :: which can not be at the string start/end - // since those cases have been handled above - if (blocks[i] === '' && i > 0 && i < blocks.length - 1) { - if (foundOmissionBlock) { - return false; // multiple :: in address - } - foundOmissionBlock = true; - } else if (foundIPv4TransitionBlock && i === blocks.length - 1) { - // it has been checked before that the last - // block is a valid IPv4 address - } else if (!ipv6Block.test(blocks[i])) { - return false; - } - } - if (foundOmissionBlock) { - return blocks.length >= 1; - } - return blocks.length === expectedNumberOfBlocks; - } - return false; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isISBN.js b/node_modules/azure-storage/node_modules/validator/lib/isISBN.js deleted file mode 100644 index fccec2849..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isISBN.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isISBN; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/; -var isbn13Maybe = /^(?:[0-9]{13})$/; -var factor = [1, 3]; - -function isISBN(str) { - var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; - - (0, _assertString2.default)(str); - version = String(version); - if (!version) { - return isISBN(str, 10) || isISBN(str, 13); - } - var sanitized = str.replace(/[\s-]+/g, ''); - var checksum = 0; - var i = void 0; - if (version === '10') { - if (!isbn10Maybe.test(sanitized)) { - return false; - } - for (i = 0; i < 9; i++) { - checksum += (i + 1) * sanitized.charAt(i); - } - if (sanitized.charAt(9) === 'X') { - checksum += 10 * 10; - } else { - checksum += 10 * sanitized.charAt(9); - } - if (checksum % 11 === 0) { - return !!sanitized; - } - } else if (version === '13') { - if (!isbn13Maybe.test(sanitized)) { - return false; - } - for (i = 0; i < 12; i++) { - checksum += factor[i % 2] * sanitized.charAt(i); - } - if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) { - return !!sanitized; - } - } - return false; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isISIN.js b/node_modules/azure-storage/node_modules/validator/lib/isISIN.js deleted file mode 100644 index feb9725a7..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isISIN.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isISIN; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; - -function isISIN(str) { - (0, _assertString2.default)(str); - if (!isin.test(str)) { - return false; - } - - var checksumStr = str.replace(/[A-Z]/g, function (character) { - return parseInt(character, 36); - }); - - var sum = 0; - var digit = void 0; - var tmpNum = void 0; - var shouldDouble = true; - for (var i = checksumStr.length - 2; i >= 0; i--) { - digit = checksumStr.substring(i, i + 1); - tmpNum = parseInt(digit, 10); - if (shouldDouble) { - tmpNum *= 2; - if (tmpNum >= 10) { - sum += tmpNum + 1; - } else { - sum += tmpNum; - } - } else { - sum += tmpNum; - } - shouldDouble = !shouldDouble; - } - - return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isISO31661Alpha2.js b/node_modules/azure-storage/node_modules/validator/lib/isISO31661Alpha2.js deleted file mode 100644 index 1741cc13d..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isISO31661Alpha2.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isISO31661Alpha2; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 -var validISO31661Alpha2CountriesCodes = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW']; - -function isISO31661Alpha2(str) { - (0, _assertString2.default)(str); - return validISO31661Alpha2CountriesCodes.includes(str.toUpperCase()); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isISO8601.js b/node_modules/azure-storage/node_modules/validator/lib/isISO8601.js deleted file mode 100644 index e38f8611b..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isISO8601.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isISO8601; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable max-len */ -// from http://goo.gl/0ejHHW -var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; -/* eslint-enable max-len */ - -function isISO8601(str) { - (0, _assertString2.default)(str); - return iso8601.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isISRC.js b/node_modules/azure-storage/node_modules/validator/lib/isISRC.js deleted file mode 100644 index b567cec43..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isISRC.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isISRC; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// see http://isrc.ifpi.org/en/isrc-standard/code-syntax -var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/; - -function isISRC(str) { - (0, _assertString2.default)(str); - return isrc.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isISSN.js b/node_modules/azure-storage/node_modules/validator/lib/isISSN.js deleted file mode 100644 index 79b05c04e..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isISSN.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isISSN; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var issn = '^\\d{4}-?\\d{3}[\\dX]$'; - -function isISSN(str) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - (0, _assertString2.default)(str); - var testIssn = issn; - testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn; - testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i'); - if (!testIssn.test(str)) { - return false; - } - var issnDigits = str.replace('-', ''); - var position = 8; - var checksum = 0; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = issnDigits[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var digit = _step.value; - - var digitValue = digit.toUpperCase() === 'X' ? 10 : +digit; - checksum += digitValue * position; - --position; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - return checksum % 11 === 0; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isIn.js b/node_modules/azure-storage/node_modules/validator/lib/isIn.js deleted file mode 100644 index 14aecde40..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isIn.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -exports.default = isIn; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _toString = require('./util/toString'); - -var _toString2 = _interopRequireDefault(_toString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isIn(str, options) { - (0, _assertString2.default)(str); - var i = void 0; - if (Object.prototype.toString.call(options) === '[object Array]') { - var array = []; - for (i in options) { - if ({}.hasOwnProperty.call(options, i)) { - array[i] = (0, _toString2.default)(options[i]); - } - } - return array.indexOf(str) >= 0; - } else if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { - return options.hasOwnProperty(str); - } else if (options && typeof options.indexOf === 'function') { - return options.indexOf(str) >= 0; - } - return false; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isInt.js b/node_modules/azure-storage/node_modules/validator/lib/isInt.js deleted file mode 100644 index 45a136700..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isInt.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isInt; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; -var intLeadingZeroes = /^[-+]?[0-9]+$/; - -function isInt(str, options) { - (0, _assertString2.default)(str); - options = options || {}; - - // Get the regex to use for testing, based on whether - // leading zeroes are allowed or not. - var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes; - - // Check min/max/lt/gt - var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min; - var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max; - var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt; - var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt; - - return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isJSON.js b/node_modules/azure-storage/node_modules/validator/lib/isJSON.js deleted file mode 100644 index 3d432c7e0..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isJSON.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -exports.default = isJSON; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isJSON(str) { - (0, _assertString2.default)(str); - try { - var obj = JSON.parse(str); - return !!obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object'; - } catch (e) {/* ignore */} - return false; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isLatLong.js b/node_modules/azure-storage/node_modules/validator/lib/isLatLong.js deleted file mode 100644 index 230d9ad58..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isLatLong.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (str) { - (0, _assertString2.default)(str); - if (!str.includes(',')) return false; - var pair = str.split(','); - return lat.test(pair[0]) && long.test(pair[1]); -}; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/; -var long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/; - -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isLength.js b/node_modules/azure-storage/node_modules/validator/lib/isLength.js deleted file mode 100644 index 432819029..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isLength.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -exports.default = isLength; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable prefer-rest-params */ -function isLength(str, options) { - (0, _assertString2.default)(str); - var min = void 0; - var max = void 0; - if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { - min = options.min || 0; - max = options.max; - } else { - // backwards compatibility: isLength(str, min [, max]) - min = arguments[1]; - max = arguments[2]; - } - var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; - var len = str.length - surrogatePairs.length; - return len >= min && (typeof max === 'undefined' || len <= max); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isLowercase.js b/node_modules/azure-storage/node_modules/validator/lib/isLowercase.js deleted file mode 100644 index 556ec6712..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isLowercase.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isLowercase; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isLowercase(str) { - (0, _assertString2.default)(str); - return str === str.toLowerCase(); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isMACAddress.js b/node_modules/azure-storage/node_modules/validator/lib/isMACAddress.js deleted file mode 100644 index 16d1631de..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isMACAddress.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isMACAddress; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var macAddress = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/; - -function isMACAddress(str) { - (0, _assertString2.default)(str); - return macAddress.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isMD5.js b/node_modules/azure-storage/node_modules/validator/lib/isMD5.js deleted file mode 100644 index 6de9d17fc..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isMD5.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isMD5; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var md5 = /^[a-f0-9]{32}$/; - -function isMD5(str) { - (0, _assertString2.default)(str); - return md5.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isMimeType.js b/node_modules/azure-storage/node_modules/validator/lib/isMimeType.js deleted file mode 100644 index c0d6170fb..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isMimeType.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isMimeType; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* - Checks if the provided string matches to a correct Media type format (MIME type) - - This function only checks is the string format follows the - etablished rules by the according RFC specifications. - This function supports 'charset' in textual media types - (https://tools.ietf.org/html/rfc6657). - - This function does not check against all the media types listed - by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml) - because of lightness purposes : it would require to include - all these MIME types in this librairy, which would weigh it - significantly. This kind of effort maybe is not worth for the use that - this function has in this entire librairy. - - More informations in the RFC specifications : - - https://tools.ietf.org/html/rfc2045 - - https://tools.ietf.org/html/rfc2046 - - https://tools.ietf.org/html/rfc7231#section-3.1.1.1 - - https://tools.ietf.org/html/rfc7231#section-3.1.1.5 -*/ - -// Match simple MIME types -// NB : -// Subtype length must not exceed 100 characters. -// This rule does not comply to the RFC specs (what is the max length ?). -var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i; // eslint-disable-line max-len - -// Handle "charset" in "text/*" -var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len - -// Handle "boundary" in "multipart/*" -var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len - -function isMimeType(str) { - (0, _assertString2.default)(str); - return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isMobilePhone.js b/node_modules/azure-storage/node_modules/validator/lib/isMobilePhone.js deleted file mode 100644 index 289dfa0ee..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isMobilePhone.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isMobilePhone; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable max-len */ -var phones = { - 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/, - 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/, - 'ar-EG': /^((\+?20)|0)?1[012]\d{8}$/, - 'ar-JO': /^(\+?962|0)?7[789]\d{7}$/, - 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/, - 'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/, - 'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/, - 'bg-BG': /^(\+?359|0)?8[789]\d{7}$/, - 'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, - 'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/, - 'de-DE': /^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, - 'el-GR': /^(\+?30|0)?(69\d{8})$/, - 'en-AU': /^(\+?61|0)4\d{8}$/, - 'en-GB': /^(\+?44|0)7\d{9}$/, - 'en-HK': /^(\+?852\-?)?[456789]\d{3}\-?\d{4}$/, - 'en-IN': /^(\+?91|0)?[6789]\d{9}$/, - 'en-KE': /^(\+?254|0)?[7]\d{8}$/, - 'en-NG': /^(\+?234|0)?[789]\d{9}$/, - 'en-NZ': /^(\+?64|0)2\d{7,9}$/, - 'en-PK': /^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$/, - 'en-RW': /^(\+?250|0)?[7]\d{8}$/, - 'en-SG': /^(\+65)?[89]\d{7}$/, - 'en-TZ': /^(\+?255|0)?[67]\d{8}$/, - 'en-UG': /^(\+?256|0)?[7]\d{8}$/, - 'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/, - 'en-ZA': /^(\+?27|0)\d{9}$/, - 'en-ZM': /^(\+?26)?09[567]\d{7}$/, - 'es-ES': /^(\+?34)?(6\d{1}|7[1234])\d{7}$/, - 'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/, - 'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/, - 'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/, - 'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/, - 'fr-FR': /^(\+?33|0)[67]\d{8}$/, - 'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}/, - 'hu-HU': /^(\+?36)(20|30|70)\d{7}$/, - 'id-ID': /^(\+?62|0[1-9])[\s|\d]+$/, - 'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/, - 'ja-JP': /^(\+?81|0)[789]0[ \-]?[1-9]\d{2}[ \-]?\d{5}$/, - 'kk-KZ': /^(\+?7|8)?7\d{9}$/, - 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/, - 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/, - 'lt-LT': /^(\+370|8)\d{8}$/, - 'ms-MY': /^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/, - 'nb-NO': /^(\+?47)?[49]\d{7}$/, - 'nl-BE': /^(\+?32|0)4?\d{8}$/, - 'nn-NO': /^(\+?47)?[49]\d{7}$/, - 'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/, - 'pt-BR': /^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/, - 'pt-PT': /^(\+?351)?9[1236]\d{7}$/, - 'ro-RO': /^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/, - 'ru-RU': /^(\+?7|8)?9\d{9}$/, - 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, - 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/, - 'th-TH': /^(\+66|66|0)\d{9}$/, - 'tr-TR': /^(\+?90|0)?5\d{9}$/, - 'uk-UA': /^(\+?38|8)?0\d{9}$/, - 'vi-VN': /^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/, - 'zh-CN': /^(\+?0?86\-?)?1[3456789]\d{9}$/, - 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/ -}; -/* eslint-enable max-len */ - -// aliases -phones['en-CA'] = phones['en-US']; -phones['fr-BE'] = phones['nl-BE']; -phones['zh-HK'] = phones['en-HK']; - -function isMobilePhone(str, locale, options) { - (0, _assertString2.default)(str); - if (options && options.strictMode && !str.startsWith('+')) { - return false; - } - if (locale in phones) { - return phones[locale].test(str); - } else if (locale === 'any') { - for (var key in phones) { - if (phones.hasOwnProperty(key)) { - var phone = phones[key]; - if (phone.test(str)) { - return true; - } - } - } - return false; - } - throw new Error('Invalid locale \'' + locale + '\''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isMongoId.js b/node_modules/azure-storage/node_modules/validator/lib/isMongoId.js deleted file mode 100644 index 62646bf41..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isMongoId.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isMongoId; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _isHexadecimal = require('./isHexadecimal'); - -var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isMongoId(str) { - (0, _assertString2.default)(str); - return (0, _isHexadecimal2.default)(str) && str.length === 24; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isMultibyte.js b/node_modules/azure-storage/node_modules/validator/lib/isMultibyte.js deleted file mode 100644 index 3411baab0..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isMultibyte.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isMultibyte; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/* eslint-disable no-control-regex */ -var multibyte = /[^\x00-\x7F]/; -/* eslint-enable no-control-regex */ - -function isMultibyte(str) { - (0, _assertString2.default)(str); - return multibyte.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isNumeric.js b/node_modules/azure-storage/node_modules/validator/lib/isNumeric.js deleted file mode 100644 index f3fde3046..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isNumeric.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isNumeric; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var numeric = /^[-+]?[0-9]+$/; - -function isNumeric(str) { - (0, _assertString2.default)(str); - return numeric.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isPort.js b/node_modules/azure-storage/node_modules/validator/lib/isPort.js deleted file mode 100644 index 66e119656..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isPort.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isPort; - -var _isInt = require('./isInt'); - -var _isInt2 = _interopRequireDefault(_isInt); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isPort(str) { - return (0, _isInt2.default)(str, { min: 0, max: 65535 }); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isPostalCode.js b/node_modules/azure-storage/node_modules/validator/lib/isPostalCode.js deleted file mode 100644 index 0d9564396..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isPostalCode.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.locales = undefined; - -exports.default = function (str, locale) { - (0, _assertString2.default)(str); - if (locale in patterns) { - return patterns[locale].test(str); - } else if (locale === 'any') { - for (var key in patterns) { - if (patterns.hasOwnProperty(key)) { - var pattern = patterns[key]; - if (pattern.test(str)) { - return true; - } - } - } - return false; - } - throw new Error('Invalid locale \'' + locale + '\''); -}; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// common patterns -var threeDigit = /^\d{3}$/; -var fourDigit = /^\d{4}$/; -var fiveDigit = /^\d{5}$/; -var sixDigit = /^\d{6}$/; - -var patterns = { - AT: fourDigit, - AU: fourDigit, - BE: fourDigit, - BG: fourDigit, - CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, - CH: fourDigit, - CZ: /^\d{3}\s?\d{2}$/, - DE: fiveDigit, - DK: fourDigit, - DZ: fiveDigit, - ES: fiveDigit, - FI: fiveDigit, - FR: /^\d{2}\s?\d{3}$/, - GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i, - GR: /^\d{3}\s?\d{2}$/, - IL: fiveDigit, - IN: sixDigit, - IS: threeDigit, - IT: fiveDigit, - JP: /^\d{3}\-\d{4}$/, - KE: fiveDigit, - LI: /^(948[5-9]|949[0-7])$/, - MX: fiveDigit, - NL: /^\d{4}\s?[a-z]{2}$/i, - NO: fourDigit, - PL: /^\d{2}\-\d{3}$/, - PT: /^\d{4}\-\d{3}?$/, - RO: sixDigit, - RU: sixDigit, - SA: fiveDigit, - SE: /^\d{3}\s?\d{2}$/, - TW: /^\d{3}(\d{2})?$/, - US: /^\d{5}(-\d{4})?$/, - ZA: fourDigit, - ZM: fiveDigit -}; - -var locales = exports.locales = Object.keys(patterns); \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isSurrogatePair.js b/node_modules/azure-storage/node_modules/validator/lib/isSurrogatePair.js deleted file mode 100644 index d8c7a9d2d..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isSurrogatePair.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isSurrogatePair; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/; - -function isSurrogatePair(str) { - (0, _assertString2.default)(str); - return surrogatePair.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isURL.js b/node_modules/azure-storage/node_modules/validator/lib/isURL.js deleted file mode 100644 index 03babd3d0..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isURL.js +++ /dev/null @@ -1,147 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isURL; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _isFQDN = require('./isFQDN'); - -var _isFQDN2 = _interopRequireDefault(_isFQDN); - -var _isIP = require('./isIP'); - -var _isIP2 = _interopRequireDefault(_isIP); - -var _merge = require('./util/merge'); - -var _merge2 = _interopRequireDefault(_merge); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var default_url_options = { - protocols: ['http', 'https', 'ftp'], - require_tld: true, - require_protocol: false, - require_host: true, - require_valid_protocol: true, - allow_underscores: false, - allow_trailing_dot: false, - allow_protocol_relative_urls: false -}; - -var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; - -function isRegExp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -} - -function checkHost(host, matches) { - for (var i = 0; i < matches.length; i++) { - var match = matches[i]; - if (host === match || isRegExp(match) && match.test(host)) { - return true; - } - } - return false; -} - -function isURL(url, options) { - (0, _assertString2.default)(url); - if (!url || url.length >= 2083 || /[\s<>]/.test(url)) { - return false; - } - if (url.indexOf('mailto:') === 0) { - return false; - } - options = (0, _merge2.default)(options, default_url_options); - var protocol = void 0, - auth = void 0, - host = void 0, - hostname = void 0, - port = void 0, - port_str = void 0, - split = void 0, - ipv6 = void 0; - - split = url.split('#'); - url = split.shift(); - - split = url.split('?'); - url = split.shift(); - - split = url.split('://'); - if (split.length > 1) { - protocol = split.shift(); - if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) { - return false; - } - } else if (options.require_protocol) { - return false; - } else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') { - split[0] = url.substr(2); - } - url = split.join('://'); - - if (url === '') { - return false; - } - - split = url.split('/'); - url = split.shift(); - - if (url === '' && !options.require_host) { - return true; - } - - split = url.split('@'); - if (split.length > 1) { - auth = split.shift(); - if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { - return false; - } - } - hostname = split.join('@'); - - port_str = null; - ipv6 = null; - var ipv6_match = hostname.match(wrapped_ipv6); - if (ipv6_match) { - host = ''; - ipv6 = ipv6_match[1]; - port_str = ipv6_match[2] || null; - } else { - split = hostname.split(':'); - host = split.shift(); - if (split.length) { - port_str = split.join(':'); - } - } - - if (port_str !== null) { - port = parseInt(port_str, 10); - if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { - return false; - } - } - - if (!(0, _isIP2.default)(host) && !(0, _isFQDN2.default)(host, options) && (!ipv6 || !(0, _isIP2.default)(ipv6, 6))) { - return false; - } - - host = host || ipv6; - - if (options.host_whitelist && !checkHost(host, options.host_whitelist)) { - return false; - } - if (options.host_blacklist && checkHost(host, options.host_blacklist)) { - return false; - } - - return true; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isUUID.js b/node_modules/azure-storage/node_modules/validator/lib/isUUID.js deleted file mode 100644 index d37414457..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isUUID.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isUUID; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var uuid = { - 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, - 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, - 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, - all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i -}; - -function isUUID(str) { - var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all'; - - (0, _assertString2.default)(str); - var pattern = uuid[version]; - return pattern && pattern.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isUppercase.js b/node_modules/azure-storage/node_modules/validator/lib/isUppercase.js deleted file mode 100644 index c4f11ebdb..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isUppercase.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isUppercase; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isUppercase(str) { - (0, _assertString2.default)(str); - return str === str.toUpperCase(); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isVariableWidth.js b/node_modules/azure-storage/node_modules/validator/lib/isVariableWidth.js deleted file mode 100644 index 5b1cf1549..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isVariableWidth.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isVariableWidth; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _isFullWidth = require('./isFullWidth'); - -var _isHalfWidth = require('./isHalfWidth'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isVariableWidth(str) { - (0, _assertString2.default)(str); - return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/isWhitelisted.js b/node_modules/azure-storage/node_modules/validator/lib/isWhitelisted.js deleted file mode 100644 index 1a073561e..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/isWhitelisted.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isWhitelisted; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function isWhitelisted(str, chars) { - (0, _assertString2.default)(str); - for (var i = str.length - 1; i >= 0; i--) { - if (chars.indexOf(str[i]) === -1) { - return false; - } - } - return true; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/ltrim.js b/node_modules/azure-storage/node_modules/validator/lib/ltrim.js deleted file mode 100644 index 58b2e3db4..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/ltrim.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = ltrim; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function ltrim(str, chars) { - (0, _assertString2.default)(str); - var pattern = chars ? new RegExp('^[' + chars + ']+', 'g') : /^\s+/g; - return str.replace(pattern, ''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/matches.js b/node_modules/azure-storage/node_modules/validator/lib/matches.js deleted file mode 100644 index 43f788489..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/matches.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = matches; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function matches(str, pattern, modifiers) { - (0, _assertString2.default)(str); - if (Object.prototype.toString.call(pattern) !== '[object RegExp]') { - pattern = new RegExp(pattern, modifiers); - } - return pattern.test(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/normalizeEmail.js b/node_modules/azure-storage/node_modules/validator/lib/normalizeEmail.js deleted file mode 100644 index fb448b32c..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/normalizeEmail.js +++ /dev/null @@ -1,129 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = normalizeEmail; - -var _merge = require('./util/merge'); - -var _merge2 = _interopRequireDefault(_merge); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var default_normalize_email_options = { - // The following options apply to all email addresses - // Lowercases the local part of the email address. - // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024). - // The domain is always lowercased, as per RFC 1035 - all_lowercase: true, - - // The following conversions are specific to GMail - // Lowercases the local part of the GMail address (known to be case-insensitive) - gmail_lowercase: true, - // Removes dots from the local part of the email address, as that's ignored by GMail - gmail_remove_dots: true, - // Removes the subaddress (e.g. "+foo") from the email address - gmail_remove_subaddress: true, - // Conversts the googlemail.com domain to gmail.com - gmail_convert_googlemaildotcom: true, - - // The following conversions are specific to Outlook.com / Windows Live / Hotmail - // Lowercases the local part of the Outlook.com address (known to be case-insensitive) - outlookdotcom_lowercase: true, - // Removes the subaddress (e.g. "+foo") from the email address - outlookdotcom_remove_subaddress: true, - - // The following conversions are specific to Yahoo - // Lowercases the local part of the Yahoo address (known to be case-insensitive) - yahoo_lowercase: true, - // Removes the subaddress (e.g. "-foo") from the email address - yahoo_remove_subaddress: true, - - // The following conversions are specific to iCloud - // Lowercases the local part of the iCloud address (known to be case-insensitive) - icloud_lowercase: true, - // Removes the subaddress (e.g. "+foo") from the email address - icloud_remove_subaddress: true -}; - -// List of domains used by iCloud -var icloud_domains = ['icloud.com', 'me.com']; - -// List of domains used by Outlook.com and its predecessors -// This list is likely incomplete. -// Partial reference: -// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/ -var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; - -// List of domains used by Yahoo Mail -// This list is likely incomplete -var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; - -function normalizeEmail(email, options) { - options = (0, _merge2.default)(options, default_normalize_email_options); - - var raw_parts = email.split('@'); - var domain = raw_parts.pop(); - var user = raw_parts.join('@'); - var parts = [user, domain]; - - // The domain is always lowercased, as it's case-insensitive per RFC 1035 - parts[1] = parts[1].toLowerCase(); - - if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') { - // Address is GMail - if (options.gmail_remove_subaddress) { - parts[0] = parts[0].split('+')[0]; - } - if (options.gmail_remove_dots) { - parts[0] = parts[0].replace(/\./g, ''); - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.gmail_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1]; - } else if (~icloud_domains.indexOf(parts[1])) { - // Address is iCloud - if (options.icloud_remove_subaddress) { - parts[0] = parts[0].split('+')[0]; - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.icloud_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - } else if (~outlookdotcom_domains.indexOf(parts[1])) { - // Address is Outlook.com - if (options.outlookdotcom_remove_subaddress) { - parts[0] = parts[0].split('+')[0]; - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.outlookdotcom_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - } else if (~yahoo_domains.indexOf(parts[1])) { - // Address is Yahoo - if (options.yahoo_remove_subaddress) { - var components = parts[0].split('-'); - parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0]; - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.yahoo_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - } else if (options.all_lowercase) { - // Any other address - parts[0] = parts[0].toLowerCase(); - } - return parts.join('@'); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/rtrim.js b/node_modules/azure-storage/node_modules/validator/lib/rtrim.js deleted file mode 100644 index fa6d8e15d..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/rtrim.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = rtrim; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function rtrim(str, chars) { - (0, _assertString2.default)(str); - var pattern = chars ? new RegExp('[' + chars + ']') : /\s/; - - var idx = str.length - 1; - while (idx >= 0 && pattern.test(str[idx])) { - idx--; - } - - return idx < str.length ? str.substr(0, idx + 1) : str; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/stripLow.js b/node_modules/azure-storage/node_modules/validator/lib/stripLow.js deleted file mode 100644 index bdf395fef..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/stripLow.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = stripLow; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -var _blacklist = require('./blacklist'); - -var _blacklist2 = _interopRequireDefault(_blacklist); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function stripLow(str, keep_new_lines) { - (0, _assertString2.default)(str); - var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F'; - return (0, _blacklist2.default)(str, chars); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/toBoolean.js b/node_modules/azure-storage/node_modules/validator/lib/toBoolean.js deleted file mode 100644 index 8ac35e358..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/toBoolean.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = toBoolean; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toBoolean(str, strict) { - (0, _assertString2.default)(str); - if (strict) { - return str === '1' || str === 'true'; - } - return str !== '0' && str !== 'false' && str !== ''; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/toDate.js b/node_modules/azure-storage/node_modules/validator/lib/toDate.js deleted file mode 100644 index 80e21f386..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/toDate.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = toDate; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toDate(date) { - (0, _assertString2.default)(date); - date = Date.parse(date); - return !isNaN(date) ? new Date(date) : null; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/toFloat.js b/node_modules/azure-storage/node_modules/validator/lib/toFloat.js deleted file mode 100644 index 3a8e256bb..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/toFloat.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = toFloat; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toFloat(str) { - (0, _assertString2.default)(str); - return parseFloat(str); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/toInt.js b/node_modules/azure-storage/node_modules/validator/lib/toInt.js deleted file mode 100644 index 97862a41f..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/toInt.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = toInt; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function toInt(str, radix) { - (0, _assertString2.default)(str); - return parseInt(str, radix || 10); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/trim.js b/node_modules/azure-storage/node_modules/validator/lib/trim.js deleted file mode 100644 index cb945d450..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/trim.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = trim; - -var _rtrim = require('./rtrim'); - -var _rtrim2 = _interopRequireDefault(_rtrim); - -var _ltrim = require('./ltrim'); - -var _ltrim2 = _interopRequireDefault(_ltrim); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function trim(str, chars) { - return (0, _rtrim2.default)((0, _ltrim2.default)(str, chars), chars); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/unescape.js b/node_modules/azure-storage/node_modules/validator/lib/unescape.js deleted file mode 100644 index cdcd7c96c..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/unescape.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = unescape; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function unescape(str) { - (0, _assertString2.default)(str); - return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`'); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/util/assertString.js b/node_modules/azure-storage/node_modules/validator/lib/util/assertString.js deleted file mode 100644 index 4abc1228f..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/util/assertString.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = assertString; -function assertString(input) { - var isString = typeof input === 'string' || input instanceof String; - - if (!isString) { - throw new TypeError('This library (validator.js) validates strings only'); - } -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/util/merge.js b/node_modules/azure-storage/node_modules/validator/lib/util/merge.js deleted file mode 100644 index 68d66fbb8..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/util/merge.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = merge; -function merge() { - var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var defaults = arguments[1]; - - for (var key in defaults) { - if (typeof obj[key] === 'undefined') { - obj[key] = defaults[key]; - } - } - return obj; -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/util/toString.js b/node_modules/azure-storage/node_modules/validator/lib/util/toString.js deleted file mode 100644 index e5d5c0db1..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/util/toString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -exports.default = toString; -function toString(input) { - if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && input !== null) { - if (typeof input.toString === 'function') { - input = input.toString(); - } else { - input = '[object Object]'; - } - } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) { - input = ''; - } - return String(input); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/lib/whitelist.js b/node_modules/azure-storage/node_modules/validator/lib/whitelist.js deleted file mode 100644 index 7a06c5d88..000000000 --- a/node_modules/azure-storage/node_modules/validator/lib/whitelist.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = whitelist; - -var _assertString = require('./util/assertString'); - -var _assertString2 = _interopRequireDefault(_assertString); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function whitelist(str, chars) { - (0, _assertString2.default)(str); - return str.replace(new RegExp('[^' + chars + ']+', 'g'), ''); -} -module.exports = exports['default']; \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/validator/package.json b/node_modules/azure-storage/node_modules/validator/package.json deleted file mode 100644 index 9d1595904..000000000 --- a/node_modules/azure-storage/node_modules/validator/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "_from": "validator@~9.4.1", - "_id": "validator@9.4.1", - "_inBundle": false, - "_integrity": "sha512-YV5KjzvRmSyJ1ee/Dm5UED0G+1L4GZnLN3w6/T+zZm8scVua4sOhYKWTUrKa0H/tMiJyO9QLHMPN+9mB/aMunA==", - "_location": "/azure-storage/validator", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "validator@~9.4.1", - "name": "validator", - "escapedName": "validator", - "rawSpec": "~9.4.1", - "saveSpec": null, - "fetchSpec": "~9.4.1" - }, - "_requiredBy": [ - "/azure-storage" - ], - "_resolved": "https://registry.npmjs.org/validator/-/validator-9.4.1.tgz", - "_shasum": "abf466d398b561cd243050112c6ff1de6cc12663", - "_spec": "validator@~9.4.1", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot\\node_modules\\azure-storage", - "author": { - "name": "Chris O'Hara", - "email": "cohara87@gmail.com" - }, - "bugs": { - "url": "http://github.com/chriso/validator.js/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "String validation and sanitization", - "devDependencies": { - "babel-cli": "^6.24.0", - "babel-plugin-add-module-exports": "^0.2.1", - "babel-preset-es2015": "^6.24.0", - "babel-preset-es2015-rollup": "^3.0.0", - "eslint": "^4.0.0", - "eslint-config-airbnb-base": "^11.2.0", - "eslint-plugin-import": "^2.3.0", - "mocha": "^3.1.2", - "rollup": "^0.43.0", - "rollup-plugin-babel": "^2.7.1", - "uglify-js": "^3.0.19" - }, - "engines": { - "node": ">= 0.10" - }, - "files": [ - "index.js", - "lib", - "README.md", - "LICENCE", - "validator.js", - "validator.min.js" - ], - "homepage": "http://github.com/chriso/validator.js", - "keywords": [ - "validator", - "validation", - "validate", - "sanitization", - "sanitize", - "sanitisation", - "sanitise", - "assert" - ], - "license": "MIT", - "main": "index.js", - "name": "validator", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/chriso/validator.js.git" - }, - "scripts": { - "build": "npm run build:browser && npm run build:node", - "build:browser": "babel-node build-browser && npm run minify", - "build:node": "babel src -d . --presets es2015 --plugins add-module-exports", - "clean": "npm run clean:node && npm run clean:browser", - "clean:browser": "rm -rf validator*.js", - "clean:node": "rm -rf index.js lib", - "lint": "eslint src test", - "lint:fix": "eslint --fix src test", - "minify": "uglifyjs validator.js -o validator.min.js --compress --mangle --comments /Copyright/", - "pretest": "npm run lint && npm run build", - "test": "mocha --reporter spec" - }, - "version": "9.4.1" -} diff --git a/node_modules/azure-storage/node_modules/validator/validator.js b/node_modules/azure-storage/node_modules/validator/validator.js deleted file mode 100644 index d2c06a430..000000000 --- a/node_modules/azure-storage/node_modules/validator/validator.js +++ /dev/null @@ -1,1560 +0,0 @@ -/*! - * Copyright (c) 2016 Chris O'Hara - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.validator = factory()); -}(this, (function () { 'use strict'; - -function assertString(input) { - var isString = typeof input === 'string' || input instanceof String; - - if (!isString) { - throw new TypeError('This library (validator.js) validates strings only'); - } -} - -function toDate(date) { - assertString(date); - date = Date.parse(date); - return !isNaN(date) ? new Date(date) : null; -} - -function toFloat(str) { - assertString(str); - return parseFloat(str); -} - -function toInt(str, radix) { - assertString(str); - return parseInt(str, radix || 10); -} - -function toBoolean(str, strict) { - assertString(str); - if (strict) { - return str === '1' || str === 'true'; - } - return str !== '0' && str !== 'false' && str !== ''; -} - -function equals(str, comparison) { - assertString(str); - return str === comparison; -} - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; -} : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; - -function toString(input) { - if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && input !== null) { - if (typeof input.toString === 'function') { - input = input.toString(); - } else { - input = '[object Object]'; - } - } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) { - input = ''; - } - return String(input); -} - -function contains(str, elem) { - assertString(str); - return str.indexOf(toString(elem)) >= 0; -} - -function matches(str, pattern, modifiers) { - assertString(str); - if (Object.prototype.toString.call(pattern) !== '[object RegExp]') { - pattern = new RegExp(pattern, modifiers); - } - return pattern.test(str); -} - -function merge() { - var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var defaults = arguments[1]; - - for (var key in defaults) { - if (typeof obj[key] === 'undefined') { - obj[key] = defaults[key]; - } - } - return obj; -} - -/* eslint-disable prefer-rest-params */ -function isByteLength(str, options) { - assertString(str); - var min = void 0; - var max = void 0; - if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { - min = options.min || 0; - max = options.max; - } else { - // backwards compatibility: isByteLength(str, min [, max]) - min = arguments[1]; - max = arguments[2]; - } - var len = encodeURI(str).split(/%..|./).length - 1; - return len >= min && (typeof max === 'undefined' || len <= max); -} - -var default_fqdn_options = { - require_tld: true, - allow_underscores: false, - allow_trailing_dot: false -}; - -function isFQDN(str, options) { - assertString(str); - options = merge(options, default_fqdn_options); - - /* Remove the optional trailing dot before checking validity */ - if (options.allow_trailing_dot && str[str.length - 1] === '.') { - str = str.substring(0, str.length - 1); - } - var parts = str.split('.'); - if (options.require_tld) { - var tld = parts.pop(); - if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { - return false; - } - // disallow spaces - if (/[\s\u2002-\u200B\u202F\u205F\u3000\uFEFF\uDB40\uDC20]/.test(tld)) { - return false; - } - } - for (var part, i = 0; i < parts.length; i++) { - part = parts[i]; - if (options.allow_underscores) { - part = part.replace(/_/g, ''); - } - if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) { - return false; - } - // disallow full-width chars - if (/[\uff01-\uff5e]/.test(part)) { - return false; - } - if (part[0] === '-' || part[part.length - 1] === '-') { - return false; - } - } - return true; -} - -var default_email_options = { - allow_display_name: false, - require_display_name: false, - allow_utf8_local_part: true, - require_tld: true -}; - -/* eslint-disable max-len */ -/* eslint-disable no-control-regex */ -var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\,\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i; -var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i; -var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i; -var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i; -var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i; -/* eslint-enable max-len */ -/* eslint-enable no-control-regex */ - -function isEmail(str, options) { - assertString(str); - options = merge(options, default_email_options); - - if (options.require_display_name || options.allow_display_name) { - var display_email = str.match(displayName); - if (display_email) { - str = display_email[1]; - } else if (options.require_display_name) { - return false; - } - } - - var parts = str.split('@'); - var domain = parts.pop(); - var user = parts.join('@'); - - var lower_domain = domain.toLowerCase(); - if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') { - user = user.replace(/\./g, '').toLowerCase(); - } - - if (!isByteLength(user, { max: 64 }) || !isByteLength(domain, { max: 254 })) { - return false; - } - - if (!isFQDN(domain, { require_tld: options.require_tld })) { - return false; - } - - if (user[0] === '"') { - user = user.slice(1, user.length - 1); - return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user); - } - - var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart; - - var user_parts = user.split('.'); - for (var i = 0; i < user_parts.length; i++) { - if (!pattern.test(user_parts[i])) { - return false; - } - } - - return true; -} - -var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; -var ipv6Block = /^[0-9A-F]{1,4}$/i; - -function isIP(str) { - var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; - - assertString(str); - version = String(version); - if (!version) { - return isIP(str, 4) || isIP(str, 6); - } else if (version === '4') { - if (!ipv4Maybe.test(str)) { - return false; - } - var parts = str.split('.').sort(function (a, b) { - return a - b; - }); - return parts[3] <= 255; - } else if (version === '6') { - var blocks = str.split(':'); - var foundOmissionBlock = false; // marker to indicate :: - - // At least some OS accept the last 32 bits of an IPv6 address - // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says - // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses, - // and '::a.b.c.d' is deprecated, but also valid. - var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4); - var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8; - - if (blocks.length > expectedNumberOfBlocks) { - return false; - } - // initial or final :: - if (str === '::') { - return true; - } else if (str.substr(0, 2) === '::') { - blocks.shift(); - blocks.shift(); - foundOmissionBlock = true; - } else if (str.substr(str.length - 2) === '::') { - blocks.pop(); - blocks.pop(); - foundOmissionBlock = true; - } - - for (var i = 0; i < blocks.length; ++i) { - // test for a :: which can not be at the string start/end - // since those cases have been handled above - if (blocks[i] === '' && i > 0 && i < blocks.length - 1) { - if (foundOmissionBlock) { - return false; // multiple :: in address - } - foundOmissionBlock = true; - } else if (foundIPv4TransitionBlock && i === blocks.length - 1) { - // it has been checked before that the last - // block is a valid IPv4 address - } else if (!ipv6Block.test(blocks[i])) { - return false; - } - } - if (foundOmissionBlock) { - return blocks.length >= 1; - } - return blocks.length === expectedNumberOfBlocks; - } - return false; -} - -var default_url_options = { - protocols: ['http', 'https', 'ftp'], - require_tld: true, - require_protocol: false, - require_host: true, - require_valid_protocol: true, - allow_underscores: false, - allow_trailing_dot: false, - allow_protocol_relative_urls: false -}; - -var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; - -function isRegExp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -} - -function checkHost(host, matches) { - for (var i = 0; i < matches.length; i++) { - var match = matches[i]; - if (host === match || isRegExp(match) && match.test(host)) { - return true; - } - } - return false; -} - -function isURL(url, options) { - assertString(url); - if (!url || url.length >= 2083 || /[\s<>]/.test(url)) { - return false; - } - if (url.indexOf('mailto:') === 0) { - return false; - } - options = merge(options, default_url_options); - var protocol = void 0, - auth = void 0, - host = void 0, - hostname = void 0, - port = void 0, - port_str = void 0, - split = void 0, - ipv6 = void 0; - - split = url.split('#'); - url = split.shift(); - - split = url.split('?'); - url = split.shift(); - - split = url.split('://'); - if (split.length > 1) { - protocol = split.shift(); - if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) { - return false; - } - } else if (options.require_protocol) { - return false; - } else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') { - split[0] = url.substr(2); - } - url = split.join('://'); - - if (url === '') { - return false; - } - - split = url.split('/'); - url = split.shift(); - - if (url === '' && !options.require_host) { - return true; - } - - split = url.split('@'); - if (split.length > 1) { - auth = split.shift(); - if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { - return false; - } - } - hostname = split.join('@'); - - port_str = null; - ipv6 = null; - var ipv6_match = hostname.match(wrapped_ipv6); - if (ipv6_match) { - host = ''; - ipv6 = ipv6_match[1]; - port_str = ipv6_match[2] || null; - } else { - split = hostname.split(':'); - host = split.shift(); - if (split.length) { - port_str = split.join(':'); - } - } - - if (port_str !== null) { - port = parseInt(port_str, 10); - if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { - return false; - } - } - - if (!isIP(host) && !isFQDN(host, options) && (!ipv6 || !isIP(ipv6, 6))) { - return false; - } - - host = host || ipv6; - - if (options.host_whitelist && !checkHost(host, options.host_whitelist)) { - return false; - } - if (options.host_blacklist && checkHost(host, options.host_blacklist)) { - return false; - } - - return true; -} - -var macAddress = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/; - -function isMACAddress(str) { - assertString(str); - return macAddress.test(str); -} - -function isBoolean(str) { - assertString(str); - return ['true', 'false', '1', '0'].indexOf(str) >= 0; -} - -var alpha = { - 'en-US': /^[A-Z]+$/i, - 'bg-BG': /^[А-Я]+$/i, - 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, - 'da-DK': /^[A-ZÆØÅ]+$/i, - 'de-DE': /^[A-ZÄÖÜß]+$/i, - 'el-GR': /^[Α-ω]+$/i, - 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i, - 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, - 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i, - 'nb-NO': /^[A-ZÆØÅ]+$/i, - 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i, - 'nn-NO': /^[A-ZÆØÅ]+$/i, - 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i, - 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i, - 'pt-PT': /^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i, - 'ru-RU': /^[А-ЯЁ]+$/i, - 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, - 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i, - 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i, - 'sv-SE': /^[A-ZÅÄÖ]+$/i, - 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i, - 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i, - ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/ -}; - -var alphanumeric = { - 'en-US': /^[0-9A-Z]+$/i, - 'bg-BG': /^[0-9А-Я]+$/i, - 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i, - 'da-DK': /^[0-9A-ZÆØÅ]+$/i, - 'de-DE': /^[0-9A-ZÄÖÜß]+$/i, - 'el-GR': /^[0-9Α-ω]+$/i, - 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i, - 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i, - 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i, - 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i, - 'nb-NO': /^[0-9A-ZÆØÅ]+$/i, - 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i, - 'nn-NO': /^[0-9A-ZÆØÅ]+$/i, - 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i, - 'pt-PT': /^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i, - 'ru-RU': /^[0-9А-ЯЁ]+$/i, - 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i, - 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i, - 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i, - 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i, - 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i, - 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i, - ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/ -}; - -var decimal = { - 'en-US': '.', - ar: '٫' -}; - -var englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM']; - -for (var locale, i = 0; i < englishLocales.length; i++) { - locale = 'en-' + englishLocales[i]; - alpha[locale] = alpha['en-US']; - alphanumeric[locale] = alphanumeric['en-US']; - decimal[locale] = decimal['en-US']; -} - -// Source: http://www.localeplanet.com/java/ -var arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE']; - -for (var _locale, _i = 0; _i < arabicLocales.length; _i++) { - _locale = 'ar-' + arabicLocales[_i]; - alpha[_locale] = alpha.ar; - alphanumeric[_locale] = alphanumeric.ar; - decimal[_locale] = decimal.ar; -} - -// Source: https://en.wikipedia.org/wiki/Decimal_mark -var dotDecimal = []; -var commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'es-ES', 'fr-FR', 'it-IT', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-Pl', 'pt-PT', 'ru-RU', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA']; - -for (var _i2 = 0; _i2 < dotDecimal.length; _i2++) { - decimal[dotDecimal[_i2]] = decimal['en-US']; -} - -for (var _i3 = 0; _i3 < commaDecimal.length; _i3++) { - decimal[commaDecimal[_i3]] = ','; -} - -alpha['pt-BR'] = alpha['pt-PT']; -alphanumeric['pt-BR'] = alphanumeric['pt-PT']; -decimal['pt-BR'] = decimal['pt-PT']; - -function isAlpha(str) { - var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; - - assertString(str); - if (locale in alpha) { - return alpha[locale].test(str); - } - throw new Error('Invalid locale \'' + locale + '\''); -} - -function isAlphanumeric(str) { - var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US'; - - assertString(str); - if (locale in alphanumeric) { - return alphanumeric[locale].test(str); - } - throw new Error('Invalid locale \'' + locale + '\''); -} - -var numeric = /^[-+]?[0-9]+$/; - -function isNumeric(str) { - assertString(str); - return numeric.test(str); -} - -var int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/; -var intLeadingZeroes = /^[-+]?[0-9]+$/; - -function isInt(str, options) { - assertString(str); - options = options || {}; - - // Get the regex to use for testing, based on whether - // leading zeroes are allowed or not. - var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes; - - // Check min/max/lt/gt - var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min; - var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max; - var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt; - var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt; - - return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed; -} - -function isPort(str) { - return isInt(str, { min: 0, max: 65535 }); -} - -function isLowercase(str) { - assertString(str); - return str === str.toLowerCase(); -} - -function isUppercase(str) { - assertString(str); - return str === str.toUpperCase(); -} - -/* eslint-disable no-control-regex */ -var ascii = /^[\x00-\x7F]+$/; -/* eslint-enable no-control-regex */ - -function isAscii(str) { - assertString(str); - return ascii.test(str); -} - -var fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; - -function isFullWidth(str) { - assertString(str); - return fullWidth.test(str); -} - -var halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; - -function isHalfWidth(str) { - assertString(str); - return halfWidth.test(str); -} - -function isVariableWidth(str) { - assertString(str); - return fullWidth.test(str) && halfWidth.test(str); -} - -/* eslint-disable no-control-regex */ -var multibyte = /[^\x00-\x7F]/; -/* eslint-enable no-control-regex */ - -function isMultibyte(str) { - assertString(str); - return multibyte.test(str); -} - -var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/; - -function isSurrogatePair(str) { - assertString(str); - return surrogatePair.test(str); -} - -function isFloat(str, options) { - assertString(str); - options = options || {}; - var float = new RegExp('^(?:[-+])?(?:[0-9]+)?(?:\\' + (options.locale ? decimal[options.locale] : '.') + '[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$'); - if (str === '' || str === '.' || str === '-' || str === '+') { - return false; - } - return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max) && (!options.hasOwnProperty('lt') || str < options.lt) && (!options.hasOwnProperty('gt') || str > options.gt); -} - -function decimalRegExp(options) { - var regExp = new RegExp('^[-+]?([0-9]+)?(\\' + decimal[options.locale] + '[0-9]{' + options.decimal_digits + '})' + (options.force_decimal ? '' : '?') + '$'); - return regExp; -} - -var default_decimal_options = { - force_decimal: false, - decimal_digits: '1,', - locale: 'en-US' -}; - -var blacklist = ['', '-', '+']; - -function isDecimal(str, options) { - assertString(str); - options = merge(options, default_decimal_options); - if (options.locale in decimal) { - return !blacklist.includes(str.replace(/ /g, '')) && decimalRegExp(options).test(str); - } - throw new Error('Invalid locale \'' + options.locale + '\''); -} - -var hexadecimal = /^[0-9A-F]+$/i; - -function isHexadecimal(str) { - assertString(str); - return hexadecimal.test(str); -} - -function isDivisibleBy(str, num) { - assertString(str); - return toFloat(str) % parseInt(num, 10) === 0; -} - -var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{6})$/i; - -function isHexColor(str) { - assertString(str); - return hexcolor.test(str); -} - -// see http://isrc.ifpi.org/en/isrc-standard/code-syntax -var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/; - -function isISRC(str) { - assertString(str); - return isrc.test(str); -} - -var md5 = /^[a-f0-9]{32}$/; - -function isMD5(str) { - assertString(str); - return md5.test(str); -} - -var lengths = { - md5: 32, - md4: 32, - sha1: 40, - sha256: 64, - sha384: 96, - sha512: 128, - ripemd128: 32, - ripemd160: 40, - tiger128: 32, - tiger160: 40, - tiger192: 48, - crc32: 8, - crc32b: 8 -}; - -function isHash(str, algorithm) { - assertString(str); - var hash = new RegExp('^[a-f0-9]{' + lengths[algorithm] + '}$'); - return hash.test(str); -} - -function isJSON(str) { - assertString(str); - try { - var obj = JSON.parse(str); - return !!obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object'; - } catch (e) {/* ignore */} - return false; -} - -function isEmpty(str) { - assertString(str); - return str.length === 0; -} - -/* eslint-disable prefer-rest-params */ -function isLength(str, options) { - assertString(str); - var min = void 0; - var max = void 0; - if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { - min = options.min || 0; - max = options.max; - } else { - // backwards compatibility: isLength(str, min [, max]) - min = arguments[1]; - max = arguments[2]; - } - var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; - var len = str.length - surrogatePairs.length; - return len >= min && (typeof max === 'undefined' || len <= max); -} - -var uuid = { - 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i, - 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, - 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i, - all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i -}; - -function isUUID(str) { - var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all'; - - assertString(str); - var pattern = uuid[version]; - return pattern && pattern.test(str); -} - -function isMongoId(str) { - assertString(str); - return isHexadecimal(str) && str.length === 24; -} - -function isAfter(str) { - var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); - - assertString(str); - var comparison = toDate(date); - var original = toDate(str); - return !!(original && comparison && original > comparison); -} - -function isBefore(str) { - var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date()); - - assertString(str); - var comparison = toDate(date); - var original = toDate(str); - return !!(original && comparison && original < comparison); -} - -function isIn(str, options) { - assertString(str); - var i = void 0; - if (Object.prototype.toString.call(options) === '[object Array]') { - var array = []; - for (i in options) { - if ({}.hasOwnProperty.call(options, i)) { - array[i] = toString(options[i]); - } - } - return array.indexOf(str) >= 0; - } else if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { - return options.hasOwnProperty(str); - } else if (options && typeof options.indexOf === 'function') { - return options.indexOf(str) >= 0; - } - return false; -} - -/* eslint-disable max-len */ -var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|62[0-9]{14})$/; -/* eslint-enable max-len */ - -function isCreditCard(str) { - assertString(str); - var sanitized = str.replace(/[- ]+/g, ''); - if (!creditCard.test(sanitized)) { - return false; - } - var sum = 0; - var digit = void 0; - var tmpNum = void 0; - var shouldDouble = void 0; - for (var i = sanitized.length - 1; i >= 0; i--) { - digit = sanitized.substring(i, i + 1); - tmpNum = parseInt(digit, 10); - if (shouldDouble) { - tmpNum *= 2; - if (tmpNum >= 10) { - sum += tmpNum % 10 + 1; - } else { - sum += tmpNum; - } - } else { - sum += tmpNum; - } - shouldDouble = !shouldDouble; - } - return !!(sum % 10 === 0 ? sanitized : false); -} - -var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; - -function isISIN(str) { - assertString(str); - if (!isin.test(str)) { - return false; - } - - var checksumStr = str.replace(/[A-Z]/g, function (character) { - return parseInt(character, 36); - }); - - var sum = 0; - var digit = void 0; - var tmpNum = void 0; - var shouldDouble = true; - for (var i = checksumStr.length - 2; i >= 0; i--) { - digit = checksumStr.substring(i, i + 1); - tmpNum = parseInt(digit, 10); - if (shouldDouble) { - tmpNum *= 2; - if (tmpNum >= 10) { - sum += tmpNum + 1; - } else { - sum += tmpNum; - } - } else { - sum += tmpNum; - } - shouldDouble = !shouldDouble; - } - - return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10; -} - -var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/; -var isbn13Maybe = /^(?:[0-9]{13})$/; -var factor = [1, 3]; - -function isISBN(str) { - var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; - - assertString(str); - version = String(version); - if (!version) { - return isISBN(str, 10) || isISBN(str, 13); - } - var sanitized = str.replace(/[\s-]+/g, ''); - var checksum = 0; - var i = void 0; - if (version === '10') { - if (!isbn10Maybe.test(sanitized)) { - return false; - } - for (i = 0; i < 9; i++) { - checksum += (i + 1) * sanitized.charAt(i); - } - if (sanitized.charAt(9) === 'X') { - checksum += 10 * 10; - } else { - checksum += 10 * sanitized.charAt(9); - } - if (checksum % 11 === 0) { - return !!sanitized; - } - } else if (version === '13') { - if (!isbn13Maybe.test(sanitized)) { - return false; - } - for (i = 0; i < 12; i++) { - checksum += factor[i % 2] * sanitized.charAt(i); - } - if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) { - return !!sanitized; - } - } - return false; -} - -var issn = '^\\d{4}-?\\d{3}[\\dX]$'; - -function isISSN(str) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - assertString(str); - var testIssn = issn; - testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn; - testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i'); - if (!testIssn.test(str)) { - return false; - } - var issnDigits = str.replace('-', ''); - var position = 8; - var checksum = 0; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = issnDigits[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var digit = _step.value; - - var digitValue = digit.toUpperCase() === 'X' ? 10 : +digit; - checksum += digitValue * position; - --position; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - return checksum % 11 === 0; -} - -/* eslint-disable max-len */ -var phones = { - 'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/, - 'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/, - 'ar-EG': /^((\+?20)|0)?1[012]\d{8}$/, - 'ar-JO': /^(\+?962|0)?7[789]\d{7}$/, - 'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/, - 'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/, - 'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/, - 'bg-BG': /^(\+?359|0)?8[789]\d{7}$/, - 'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, - 'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/, - 'de-DE': /^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/, - 'el-GR': /^(\+?30|0)?(69\d{8})$/, - 'en-AU': /^(\+?61|0)4\d{8}$/, - 'en-GB': /^(\+?44|0)7\d{9}$/, - 'en-HK': /^(\+?852\-?)?[456789]\d{3}\-?\d{4}$/, - 'en-IN': /^(\+?91|0)?[6789]\d{9}$/, - 'en-KE': /^(\+?254|0)?[7]\d{8}$/, - 'en-NG': /^(\+?234|0)?[789]\d{9}$/, - 'en-NZ': /^(\+?64|0)2\d{7,9}$/, - 'en-PK': /^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$/, - 'en-RW': /^(\+?250|0)?[7]\d{8}$/, - 'en-SG': /^(\+65)?[89]\d{7}$/, - 'en-TZ': /^(\+?255|0)?[67]\d{8}$/, - 'en-UG': /^(\+?256|0)?[7]\d{8}$/, - 'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/, - 'en-ZA': /^(\+?27|0)\d{9}$/, - 'en-ZM': /^(\+?26)?09[567]\d{7}$/, - 'es-ES': /^(\+?34)?(6\d{1}|7[1234])\d{7}$/, - 'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/, - 'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/, - 'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/, - 'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/, - 'fr-FR': /^(\+?33|0)[67]\d{8}$/, - 'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}/, - 'hu-HU': /^(\+?36)(20|30|70)\d{7}$/, - 'id-ID': /^(\+?62|0[1-9])[\s|\d]+$/, - 'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/, - 'ja-JP': /^(\+?81|0)[789]0[ \-]?[1-9]\d{2}[ \-]?\d{5}$/, - 'kk-KZ': /^(\+?7|8)?7\d{9}$/, - 'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/, - 'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/, - 'lt-LT': /^(\+370|8)\d{8}$/, - 'ms-MY': /^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/, - 'nb-NO': /^(\+?47)?[49]\d{7}$/, - 'nl-BE': /^(\+?32|0)4?\d{8}$/, - 'nn-NO': /^(\+?47)?[49]\d{7}$/, - 'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/, - 'pt-BR': /^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/, - 'pt-PT': /^(\+?351)?9[1236]\d{7}$/, - 'ro-RO': /^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/, - 'ru-RU': /^(\+?7|8)?9\d{9}$/, - 'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/, - 'sr-RS': /^(\+3816|06)[- \d]{5,9}$/, - 'th-TH': /^(\+66|66|0)\d{9}$/, - 'tr-TR': /^(\+?90|0)?5\d{9}$/, - 'uk-UA': /^(\+?38|8)?0\d{9}$/, - 'vi-VN': /^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/, - 'zh-CN': /^(\+?0?86\-?)?1[3456789]\d{9}$/, - 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/ -}; -/* eslint-enable max-len */ - -// aliases -phones['en-CA'] = phones['en-US']; -phones['fr-BE'] = phones['nl-BE']; -phones['zh-HK'] = phones['en-HK']; - -function isMobilePhone(str, locale, options) { - assertString(str); - if (options && options.strictMode && !str.startsWith('+')) { - return false; - } - if (locale in phones) { - return phones[locale].test(str); - } else if (locale === 'any') { - for (var key in phones) { - if (phones.hasOwnProperty(key)) { - var phone = phones[key]; - if (phone.test(str)) { - return true; - } - } - } - return false; - } - throw new Error('Invalid locale \'' + locale + '\''); -} - -function currencyRegex(options) { - var decimal_digits = '\\d{' + options.digits_after_decimal[0] + '}'; - options.digits_after_decimal.forEach(function (digit, index) { - if (index !== 0) decimal_digits = decimal_digits + '|\\d{' + digit + '}'; - }); - var symbol = '(\\' + options.symbol.replace(/\./g, '\\.') + ')' + (options.require_symbol ? '' : '?'), - negative = '-?', - whole_dollar_amount_without_sep = '[1-9]\\d*', - whole_dollar_amount_with_sep = '[1-9]\\d{0,2}(\\' + options.thousands_separator + '\\d{3})*', - valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep], - whole_dollar_amount = '(' + valid_whole_dollar_amounts.join('|') + ')?', - decimal_amount = '(\\' + options.decimal_separator + '(' + decimal_digits + '))' + (options.require_decimal ? '' : '?'); - var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); - - // default is negative sign before symbol, but there are two other options (besides parens) - if (options.allow_negatives && !options.parens_for_negatives) { - if (options.negative_sign_after_digits) { - pattern += negative; - } else if (options.negative_sign_before_digits) { - pattern = negative + pattern; - } - } - - // South African Rand, for example, uses R 123 (space) and R-123 (no space) - if (options.allow_negative_sign_placeholder) { - pattern = '( (?!\\-))?' + pattern; - } else if (options.allow_space_after_symbol) { - pattern = ' ?' + pattern; - } else if (options.allow_space_after_digits) { - pattern += '( (?!$))?'; - } - - if (options.symbol_after_digits) { - pattern += symbol; - } else { - pattern = symbol + pattern; - } - - if (options.allow_negatives) { - if (options.parens_for_negatives) { - pattern = '(\\(' + pattern + '\\)|' + pattern + ')'; - } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) { - pattern = negative + pattern; - } - } - - // ensure there's a dollar and/or decimal amount, and that - // it doesn't start with a space or a negative sign followed by a space - return new RegExp('^(?!-? )(?=.*\\d)' + pattern + '$'); -} - -var default_currency_options = { - symbol: '$', - require_symbol: false, - allow_space_after_symbol: false, - symbol_after_digits: false, - allow_negatives: true, - parens_for_negatives: false, - negative_sign_before_digits: false, - negative_sign_after_digits: false, - allow_negative_sign_placeholder: false, - thousands_separator: ',', - decimal_separator: '.', - allow_decimal: true, - require_decimal: false, - digits_after_decimal: [2], - allow_space_after_digits: false -}; - -function isCurrency(str, options) { - assertString(str); - options = merge(options, default_currency_options); - return currencyRegex(options).test(str); -} - -/* eslint-disable max-len */ -// from http://goo.gl/0ejHHW -var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; -/* eslint-enable max-len */ - -function isISO8601(str) { - assertString(str); - return iso8601.test(str); -} - -// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 -var validISO31661Alpha2CountriesCodes = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW']; - -function isISO31661Alpha2(str) { - assertString(str); - return validISO31661Alpha2CountriesCodes.includes(str.toUpperCase()); -} - -var notBase64 = /[^A-Z0-9+\/=]/i; - -function isBase64(str) { - assertString(str); - var len = str.length; - if (!len || len % 4 !== 0 || notBase64.test(str)) { - return false; - } - var firstPaddingChar = str.indexOf('='); - return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '='; -} - -var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i; - -var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i; - -var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i; - -function isDataURI(str) { - assertString(str); - var data = str.split(','); - if (data.length < 2) { - return false; - } - var attributes = data.shift().trim().split(';'); - var schemeAndMediaType = attributes.shift(); - if (schemeAndMediaType.substr(0, 5) !== 'data:') { - return false; - } - var mediaType = schemeAndMediaType.substr(5); - if (mediaType !== '' && !validMediaType.test(mediaType)) { - return false; - } - for (var i = 0; i < attributes.length; i++) { - if (i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') { - // ok - } else if (!validAttribute.test(attributes[i])) { - return false; - } - } - for (var _i = 0; _i < data.length; _i++) { - if (!validData.test(data[_i])) { - return false; - } - } - return true; -} - -/* - Checks if the provided string matches to a correct Media type format (MIME type) - - This function only checks is the string format follows the - etablished rules by the according RFC specifications. - This function supports 'charset' in textual media types - (https://tools.ietf.org/html/rfc6657). - - This function does not check against all the media types listed - by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml) - because of lightness purposes : it would require to include - all these MIME types in this librairy, which would weigh it - significantly. This kind of effort maybe is not worth for the use that - this function has in this entire librairy. - - More informations in the RFC specifications : - - https://tools.ietf.org/html/rfc2045 - - https://tools.ietf.org/html/rfc2046 - - https://tools.ietf.org/html/rfc7231#section-3.1.1.1 - - https://tools.ietf.org/html/rfc7231#section-3.1.1.5 -*/ - -// Match simple MIME types -// NB : -// Subtype length must not exceed 100 characters. -// This rule does not comply to the RFC specs (what is the max length ?). -var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i; // eslint-disable-line max-len - -// Handle "charset" in "text/*" -var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len - -// Handle "boundary" in "multipart/*" -var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len - -function isMimeType(str) { - assertString(str); - return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str); -} - -var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/; -var long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/; - -var isLatLong = function (str) { - assertString(str); - if (!str.includes(',')) return false; - var pair = str.split(','); - return lat.test(pair[0]) && long.test(pair[1]); -}; - -// common patterns -var threeDigit = /^\d{3}$/; -var fourDigit = /^\d{4}$/; -var fiveDigit = /^\d{5}$/; -var sixDigit = /^\d{6}$/; - -var patterns = { - AT: fourDigit, - AU: fourDigit, - BE: fourDigit, - BG: fourDigit, - CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, - CH: fourDigit, - CZ: /^\d{3}\s?\d{2}$/, - DE: fiveDigit, - DK: fourDigit, - DZ: fiveDigit, - ES: fiveDigit, - FI: fiveDigit, - FR: /^\d{2}\s?\d{3}$/, - GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i, - GR: /^\d{3}\s?\d{2}$/, - IL: fiveDigit, - IN: sixDigit, - IS: threeDigit, - IT: fiveDigit, - JP: /^\d{3}\-\d{4}$/, - KE: fiveDigit, - LI: /^(948[5-9]|949[0-7])$/, - MX: fiveDigit, - NL: /^\d{4}\s?[a-z]{2}$/i, - NO: fourDigit, - PL: /^\d{2}\-\d{3}$/, - PT: /^\d{4}\-\d{3}?$/, - RO: sixDigit, - RU: sixDigit, - SA: fiveDigit, - SE: /^\d{3}\s?\d{2}$/, - TW: /^\d{3}(\d{2})?$/, - US: /^\d{5}(-\d{4})?$/, - ZA: fourDigit, - ZM: fiveDigit -}; - - - -var isPostalCode = function (str, locale) { - assertString(str); - if (locale in patterns) { - return patterns[locale].test(str); - } else if (locale === 'any') { - for (var key in patterns) { - if (patterns.hasOwnProperty(key)) { - var pattern = patterns[key]; - if (pattern.test(str)) { - return true; - } - } - } - return false; - } - throw new Error('Invalid locale \'' + locale + '\''); -}; - -function ltrim(str, chars) { - assertString(str); - var pattern = chars ? new RegExp('^[' + chars + ']+', 'g') : /^\s+/g; - return str.replace(pattern, ''); -} - -function rtrim(str, chars) { - assertString(str); - var pattern = chars ? new RegExp('[' + chars + ']') : /\s/; - - var idx = str.length - 1; - while (idx >= 0 && pattern.test(str[idx])) { - idx--; - } - - return idx < str.length ? str.substr(0, idx + 1) : str; -} - -function trim(str, chars) { - return rtrim(ltrim(str, chars), chars); -} - -function escape(str) { - assertString(str); - return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(//g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`'); -} - -function unescape(str) { - assertString(str); - return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`'); -} - -function blacklist$1(str, chars) { - assertString(str); - return str.replace(new RegExp('[' + chars + ']+', 'g'), ''); -} - -function stripLow(str, keep_new_lines) { - assertString(str); - var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F'; - return blacklist$1(str, chars); -} - -function whitelist(str, chars) { - assertString(str); - return str.replace(new RegExp('[^' + chars + ']+', 'g'), ''); -} - -function isWhitelisted(str, chars) { - assertString(str); - for (var i = str.length - 1; i >= 0; i--) { - if (chars.indexOf(str[i]) === -1) { - return false; - } - } - return true; -} - -var default_normalize_email_options = { - // The following options apply to all email addresses - // Lowercases the local part of the email address. - // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024). - // The domain is always lowercased, as per RFC 1035 - all_lowercase: true, - - // The following conversions are specific to GMail - // Lowercases the local part of the GMail address (known to be case-insensitive) - gmail_lowercase: true, - // Removes dots from the local part of the email address, as that's ignored by GMail - gmail_remove_dots: true, - // Removes the subaddress (e.g. "+foo") from the email address - gmail_remove_subaddress: true, - // Conversts the googlemail.com domain to gmail.com - gmail_convert_googlemaildotcom: true, - - // The following conversions are specific to Outlook.com / Windows Live / Hotmail - // Lowercases the local part of the Outlook.com address (known to be case-insensitive) - outlookdotcom_lowercase: true, - // Removes the subaddress (e.g. "+foo") from the email address - outlookdotcom_remove_subaddress: true, - - // The following conversions are specific to Yahoo - // Lowercases the local part of the Yahoo address (known to be case-insensitive) - yahoo_lowercase: true, - // Removes the subaddress (e.g. "-foo") from the email address - yahoo_remove_subaddress: true, - - // The following conversions are specific to iCloud - // Lowercases the local part of the iCloud address (known to be case-insensitive) - icloud_lowercase: true, - // Removes the subaddress (e.g. "+foo") from the email address - icloud_remove_subaddress: true -}; - -// List of domains used by iCloud -var icloud_domains = ['icloud.com', 'me.com']; - -// List of domains used by Outlook.com and its predecessors -// This list is likely incomplete. -// Partial reference: -// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/ -var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; - -// List of domains used by Yahoo Mail -// This list is likely incomplete -var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; - -function normalizeEmail(email, options) { - options = merge(options, default_normalize_email_options); - - var raw_parts = email.split('@'); - var domain = raw_parts.pop(); - var user = raw_parts.join('@'); - var parts = [user, domain]; - - // The domain is always lowercased, as it's case-insensitive per RFC 1035 - parts[1] = parts[1].toLowerCase(); - - if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') { - // Address is GMail - if (options.gmail_remove_subaddress) { - parts[0] = parts[0].split('+')[0]; - } - if (options.gmail_remove_dots) { - parts[0] = parts[0].replace(/\./g, ''); - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.gmail_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1]; - } else if (~icloud_domains.indexOf(parts[1])) { - // Address is iCloud - if (options.icloud_remove_subaddress) { - parts[0] = parts[0].split('+')[0]; - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.icloud_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - } else if (~outlookdotcom_domains.indexOf(parts[1])) { - // Address is Outlook.com - if (options.outlookdotcom_remove_subaddress) { - parts[0] = parts[0].split('+')[0]; - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.outlookdotcom_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - } else if (~yahoo_domains.indexOf(parts[1])) { - // Address is Yahoo - if (options.yahoo_remove_subaddress) { - var components = parts[0].split('-'); - parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0]; - } - if (!parts[0].length) { - return false; - } - if (options.all_lowercase || options.yahoo_lowercase) { - parts[0] = parts[0].toLowerCase(); - } - } else if (options.all_lowercase) { - // Any other address - parts[0] = parts[0].toLowerCase(); - } - return parts.join('@'); -} - -var version = '9.4.1'; - -var validator = { - version: version, - toDate: toDate, - toFloat: toFloat, - toInt: toInt, - toBoolean: toBoolean, - equals: equals, - contains: contains, - matches: matches, - isEmail: isEmail, - isURL: isURL, - isMACAddress: isMACAddress, - isIP: isIP, - isFQDN: isFQDN, - isBoolean: isBoolean, - isAlpha: isAlpha, - isAlphanumeric: isAlphanumeric, - isNumeric: isNumeric, - isPort: isPort, - isLowercase: isLowercase, - isUppercase: isUppercase, - isAscii: isAscii, - isFullWidth: isFullWidth, - isHalfWidth: isHalfWidth, - isVariableWidth: isVariableWidth, - isMultibyte: isMultibyte, - isSurrogatePair: isSurrogatePair, - isInt: isInt, - isFloat: isFloat, - isDecimal: isDecimal, - isHexadecimal: isHexadecimal, - isDivisibleBy: isDivisibleBy, - isHexColor: isHexColor, - isISRC: isISRC, - isMD5: isMD5, - isHash: isHash, - isJSON: isJSON, - isEmpty: isEmpty, - isLength: isLength, - isByteLength: isByteLength, - isUUID: isUUID, - isMongoId: isMongoId, - isAfter: isAfter, - isBefore: isBefore, - isIn: isIn, - isCreditCard: isCreditCard, - isISIN: isISIN, - isISBN: isISBN, - isISSN: isISSN, - isMobilePhone: isMobilePhone, - isPostalCode: isPostalCode, - isCurrency: isCurrency, - isISO8601: isISO8601, - isISO31661Alpha2: isISO31661Alpha2, - isBase64: isBase64, - isDataURI: isDataURI, - isMimeType: isMimeType, - isLatLong: isLatLong, - ltrim: ltrim, - rtrim: rtrim, - trim: trim, - escape: escape, - unescape: unescape, - stripLow: stripLow, - whitelist: whitelist, - blacklist: blacklist$1, - isWhitelisted: isWhitelisted, - normalizeEmail: normalizeEmail, - toString: toString -}; - -return validator; - -}))); diff --git a/node_modules/azure-storage/node_modules/validator/validator.min.js b/node_modules/azure-storage/node_modules/validator/validator.min.js deleted file mode 100644 index e419e04d5..000000000 --- a/node_modules/azure-storage/node_modules/validator/validator.min.js +++ /dev/null @@ -1,23 +0,0 @@ -/*! - * Copyright (c) 2016 Chris O'Hara - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.validator=t()}(this,function(){"use strict";function e(e){if(!("string"==typeof e||e instanceof String))throw new TypeError("This library (validator.js) validates strings only")}function t(t){return e(t),t=Date.parse(t),isNaN(t)?null:new Date(t)}function r(t){return e(t),parseFloat(t)}var i="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};function o(e){return"object"===(void 0===e?"undefined":i(e))&&null!==e?e="function"==typeof e.toString?e.toString():"[object Object]":(null==e||isNaN(e)&&!e.length)&&(e=""),String(e)}function n(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];for(var r in t)void 0===e[r]&&(e[r]=t[r]);return e}function a(t,r){e(t);var o=void 0,n=void 0;"object"===(void 0===r?"undefined":i(r))?(o=r.min||0,n=r.max):(o=arguments[1],n=arguments[2]);var a=encodeURI(t).split(/%..|./).length-1;return a>=o&&(void 0===n||a<=n)}var l={require_tld:!0,allow_underscores:!1,allow_trailing_dot:!1};function s(t,r){e(t),(r=n(r,l)).allow_trailing_dot&&"."===t[t.length-1]&&(t=t.substring(0,t.length-1));var i=t.split(".");if(r.require_tld){var o=i.pop();if(!i.length||!/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(o))return!1;if(/[\s\u2002-\u200B\u202F\u205F\u3000\uFEFF\uDB40\uDC20]/.test(o))return!1}for(var a,s=0;s$/i,c=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i,f=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i,g=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i,p=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i;var h=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,v=/^[0-9A-F]{1,4}$/i;function m(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(e(t),!(r=String(r)))return m(t,4)||m(t,6);if("4"===r)return!!h.test(t)&&t.split(".").sort(function(e,t){return e-t})[3]<=255;if("6"===r){var i=t.split(":"),o=!1,n=m(i[i.length-1],4),a=n?7:8;if(i.length>a)return!1;if("::"===t)return!0;"::"===t.substr(0,2)?(i.shift(),i.shift(),o=!0):"::"===t.substr(t.length-2)&&(i.pop(),i.pop(),o=!0);for(var l=0;l0&&l=1:i.length===a}return!1}var $={protocols:["http","https","ftp"],require_tld:!0,require_protocol:!1,require_host:!0,require_valid_protocol:!0,allow_underscores:!1,allow_trailing_dot:!1,allow_protocol_relative_urls:!1},_=/^\[([^\]]+)\](?::([0-9]+))?$/;function F(e,t){for(var r=0;r=r.min,n=!r.hasOwnProperty("max")||t<=r.max,a=!r.hasOwnProperty("lt")||tr.gt;return i.test(t)&&o&&n&&a&&l}var M=/^[\x00-\x7F]+$/;var G=/[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;var L=/[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;var U=/[^\x00-\x7F]/;var K=/[\uD800-\uDBFF][\uDC00-\uDFFF]/;var z={force_decimal:!1,decimal_digits:"1,",locale:"en-US"},H=["","-","+"];var j=/^[0-9A-F]+$/i;function q(t){return e(t),j.test(t)}var W=/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i;var J=/^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/;var V=/^[a-f0-9]{32}$/;var Y={md5:32,md4:32,sha1:40,sha256:64,sha384:96,sha512:128,ripemd128:32,ripemd160:40,tiger128:32,tiger160:40,tiger192:48,crc32:8,crc32b:8};var Q={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i};var X=/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|62[0-9]{14})$/;var ee=/^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;var te=/^(?:[0-9]{9}X|[0-9]{10})$/,re=/^(?:[0-9]{13})$/,ie=[1,3];var oe="^\\d{4}-?\\d{3}[\\dX]$";var ne={"ar-AE":/^((\+?971)|0)?5[024568]\d{7}$/,"ar-DZ":/^(\+?213|0)(5|6|7)\d{8}$/,"ar-EG":/^((\+?20)|0)?1[012]\d{8}$/,"ar-JO":/^(\+?962|0)?7[789]\d{7}$/,"ar-SA":/^(!?(\+?966)|0)?5\d{8}$/,"ar-SY":/^(!?(\+?963)|0)?9\d{8}$/,"be-BY":/^(\+?375)?(24|25|29|33|44)\d{7}$/,"bg-BG":/^(\+?359|0)?8[789]\d{7}$/,"cs-CZ":/^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,"da-DK":/^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/,"de-DE":/^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,"el-GR":/^(\+?30|0)?(69\d{8})$/,"en-AU":/^(\+?61|0)4\d{8}$/,"en-GB":/^(\+?44|0)7\d{9}$/,"en-HK":/^(\+?852\-?)?[456789]\d{3}\-?\d{4}$/,"en-IN":/^(\+?91|0)?[6789]\d{9}$/,"en-KE":/^(\+?254|0)?[7]\d{8}$/,"en-NG":/^(\+?234|0)?[789]\d{9}$/,"en-NZ":/^(\+?64|0)2\d{7,9}$/,"en-PK":/^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$/,"en-RW":/^(\+?250|0)?[7]\d{8}$/,"en-SG":/^(\+65)?[89]\d{7}$/,"en-TZ":/^(\+?255|0)?[67]\d{8}$/,"en-UG":/^(\+?256|0)?[7]\d{8}$/,"en-US":/^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,"en-ZA":/^(\+?27|0)\d{9}$/,"en-ZM":/^(\+?26)?09[567]\d{7}$/,"es-ES":/^(\+?34)?(6\d{1}|7[1234])\d{7}$/,"et-EE":/^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/,"fa-IR":/^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/,"fi-FI":/^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/,"fo-FO":/^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/,"fr-FR":/^(\+?33|0)[67]\d{8}$/,"he-IL":/^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}/,"hu-HU":/^(\+?36)(20|30|70)\d{7}$/,"id-ID":/^(\+?62|0[1-9])[\s|\d]+$/,"it-IT":/^(\+?39)?\s?3\d{2} ?\d{6,7}$/,"ja-JP":/^(\+?81|0)[789]0[ \-]?[1-9]\d{2}[ \-]?\d{5}$/,"kk-KZ":/^(\+?7|8)?7\d{9}$/,"kl-GL":/^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/,"ko-KR":/^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/,"lt-LT":/^(\+370|8)\d{8}$/,"ms-MY":/^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/,"nb-NO":/^(\+?47)?[49]\d{7}$/,"nl-BE":/^(\+?32|0)4?\d{8}$/,"nn-NO":/^(\+?47)?[49]\d{7}$/,"pl-PL":/^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/,"pt-BR":/^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/,"pt-PT":/^(\+?351)?9[1236]\d{7}$/,"ro-RO":/^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/,"ru-RU":/^(\+?7|8)?9\d{9}$/,"sk-SK":/^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,"sr-RS":/^(\+3816|06)[- \d]{5,9}$/,"th-TH":/^(\+66|66|0)\d{9}$/,"tr-TR":/^(\+?90|0)?5\d{9}$/,"uk-UA":/^(\+?38|8)?0\d{9}$/,"vi-VN":/^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/,"zh-CN":/^(\+?0?86\-?)?1[3456789]\d{9}$/,"zh-TW":/^(\+?886\-?|0)?9\d{8}$/};ne["en-CA"]=ne["en-US"],ne["fr-BE"]=ne["nl-BE"],ne["zh-HK"]=ne["en-HK"];var ae={symbol:"$",require_symbol:!1,allow_space_after_symbol:!1,symbol_after_digits:!1,allow_negatives:!0,parens_for_negatives:!1,negative_sign_before_digits:!1,negative_sign_after_digits:!1,allow_negative_sign_placeholder:!1,thousands_separator:",",decimal_separator:".",allow_decimal:!0,require_decimal:!1,digits_after_decimal:[2],allow_space_after_digits:!1};var le=/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var se=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","ZA","ZM","ZW"];var ue=/[^A-Z0-9+\/=]/i;var de=/^[a-z]+\/[a-z0-9\-\+]+$/i,ce=/^[a-z\-]+=[a-z0-9\-]+$/i,fe=/^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i;var ge=/^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i,pe=/^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i,he=/^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i;var ve=/^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/,me=/^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/,$e=/^\d{4}$/,_e=/^\d{5}$/,Fe=/^\d{6}$/,Ae={AT:$e,AU:$e,BE:$e,BG:$e,CA:/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i,CH:$e,CZ:/^\d{3}\s?\d{2}$/,DE:_e,DK:$e,DZ:_e,ES:_e,FI:_e,FR:/^\d{2}\s?\d{3}$/,GB:/^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i,GR:/^\d{3}\s?\d{2}$/,IL:_e,IN:Fe,IS:/^\d{3}$/,IT:_e,JP:/^\d{3}\-\d{4}$/,KE:_e,LI:/^(948[5-9]|949[0-7])$/,MX:_e,NL:/^\d{4}\s?[a-z]{2}$/i,NO:$e,PL:/^\d{2}\-\d{3}$/,PT:/^\d{4}\-\d{3}?$/,RO:Fe,RU:Fe,SA:_e,SE:/^\d{3}\s?\d{2}$/,TW:/^\d{3}(\d{2})?$/,US:/^\d{5}(-\d{4})?$/,ZA:$e,ZM:_e};function xe(t,r){e(t);var i=r?new RegExp("^["+r+"]+","g"):/^\s+/g;return t.replace(i,"")}function Se(t,r){e(t);for(var i=r?new RegExp("["+r+"]"):/\s/,o=t.length-1;o>=0&&i.test(t[o]);)o--;return o=0},matches:function(t,r,i){return e(t),"[object RegExp]"!==Object.prototype.toString.call(r)&&(r=new RegExp(r,i)),r.test(t)},isEmail:function(t,r){if(e(t),(r=n(r,u)).require_display_name||r.allow_display_name){var i=t.match(d);if(i)t=i[1];else if(r.require_display_name)return!1}var o=t.split("@"),l=o.pop(),h=o.join("@"),v=l.toLowerCase();if("gmail.com"!==v&&"googlemail.com"!==v||(h=h.replace(/\./g,"").toLowerCase()),!a(h,{max:64})||!a(l,{max:254}))return!1;if(!s(l,{require_tld:r.require_tld}))return!1;if('"'===h[0])return h=h.slice(1,h.length-1),r.allow_utf8_local_part?p.test(h):f.test(h);for(var m=r.allow_utf8_local_part?g:c,$=h.split("."),_=0;_<$.length;_++)if(!m.test($[_]))return!1;return!0},isURL:function(t,r){if(e(t),!t||t.length>=2083||/[\s<>]/.test(t))return!1;if(0===t.indexOf("mailto:"))return!1;r=n(r,$);var i=void 0,o=void 0,a=void 0,l=void 0,u=void 0,d=void 0,c=void 0,f=void 0;if((c=(t=(c=(t=(c=t.split("#")).shift()).split("?")).shift()).split("://")).length>1){if(i=c.shift(),r.require_valid_protocol&&-1===r.protocols.indexOf(i))return!1}else{if(r.require_protocol)return!1;r.allow_protocol_relative_urls&&"//"===t.substr(0,2)&&(c[0]=t.substr(2))}if(""===(t=c.join("://")))return!1;if(""===(t=(c=t.split("/")).shift())&&!r.require_host)return!0;if((c=t.split("@")).length>1&&(o=c.shift()).indexOf(":")>=0&&o.split(":").length>2)return!1;d=null,f=null;var g=(l=c.join("@")).match(_);return g?(a="",f=g[1],d=g[2]||null):(a=(c=l.split(":")).shift(),c.length&&(d=c.join(":"))),!(null!==d&&(u=parseInt(d,10),!/^[0-9]+$/.test(d)||u<=0||u>65535)||!(m(a)||s(a,r)||f&&m(f,6))||(a=a||f,r.host_whitelist&&!F(a,r.host_whitelist)||r.host_blacklist&&F(a,r.host_blacklist)))},isMACAddress:function(t){return e(t),A.test(t)},isIP:m,isFQDN:s,isBoolean:function(t){return e(t),["true","false","1","0"].indexOf(t)>=0},isAlpha:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"en-US";if(e(t),r in S)return S[r].test(t);throw new Error("Invalid locale '"+r+"'")},isAlphanumeric:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"en-US";if(e(t),r in w)return w[r].test(t);throw new Error("Invalid locale '"+r+"'")},isNumeric:function(t){return e(t),O.test(t)},isPort:function(e){return P(e,{min:0,max:65535})},isLowercase:function(t){return e(t),t===t.toLowerCase()},isUppercase:function(t){return e(t),t===t.toUpperCase()},isAscii:function(t){return e(t),M.test(t)},isFullWidth:function(t){return e(t),G.test(t)},isHalfWidth:function(t){return e(t),L.test(t)},isVariableWidth:function(t){return e(t),G.test(t)&&L.test(t)},isMultibyte:function(t){return e(t),U.test(t)},isSurrogatePair:function(t){return e(t),K.test(t)},isInt:P,isFloat:function(t,r){e(t),r=r||{};var i=new RegExp("^(?:[-+])?(?:[0-9]+)?(?:\\"+(r.locale?E[r.locale]:".")+"[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$");return""!==t&&"."!==t&&"-"!==t&&"+"!==t&&i.test(t)&&(!r.hasOwnProperty("min")||t>=r.min)&&(!r.hasOwnProperty("max")||t<=r.max)&&(!r.hasOwnProperty("lt")||tr.gt)},isDecimal:function(t,r){if(e(t),(r=n(r,z)).locale in E)return!H.includes(t.replace(/ /g,""))&&(i=r,new RegExp("^[-+]?([0-9]+)?(\\"+E[i.locale]+"[0-9]{"+i.decimal_digits+"})"+(i.force_decimal?"":"?")+"$")).test(t);var i;throw new Error("Invalid locale '"+r.locale+"'")},isHexadecimal:q,isDivisibleBy:function(t,i){return e(t),r(t)%parseInt(i,10)==0},isHexColor:function(t){return e(t),W.test(t)},isISRC:function(t){return e(t),J.test(t)},isMD5:function(t){return e(t),V.test(t)},isHash:function(t,r){return e(t),new RegExp("^[a-f0-9]{"+Y[r]+"}$").test(t)},isJSON:function(t){e(t);try{var r=JSON.parse(t);return!!r&&"object"===(void 0===r?"undefined":i(r))}catch(e){}return!1},isEmpty:function(t){return e(t),0===t.length},isLength:function(t,r){e(t);var o=void 0,n=void 0;"object"===(void 0===r?"undefined":i(r))?(o=r.min||0,n=r.max):(o=arguments[1],n=arguments[2]);var a=t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)||[],l=t.length-a.length;return l>=o&&(void 0===n||l<=n)},isByteLength:a,isUUID:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"all";e(t);var i=Q[r];return i&&i.test(t)},isMongoId:function(t){return e(t),q(t)&&24===t.length},isAfter:function(r){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:String(new Date);e(r);var o=t(i),n=t(r);return!!(n&&o&&n>o)},isBefore:function(r){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:String(new Date);e(r);var o=t(i),n=t(r);return!!(n&&o&&n=0}return"object"===(void 0===r?"undefined":i(r))?r.hasOwnProperty(t):!(!r||"function"!=typeof r.indexOf)&&r.indexOf(t)>=0},isCreditCard:function(t){e(t);var r=t.replace(/[- ]+/g,"");if(!X.test(r))return!1;for(var i=0,o=void 0,n=void 0,a=void 0,l=r.length-1;l>=0;l--)o=r.substring(l,l+1),n=parseInt(o,10),i+=a&&(n*=2)>=10?n%10+1:n,a=!a;return!(i%10!=0||!r)},isISIN:function(t){if(e(t),!ee.test(t))return!1;for(var r=t.replace(/[A-Z]/g,function(e){return parseInt(e,36)}),i=0,o=void 0,n=void 0,a=!0,l=r.length-2;l>=0;l--)o=r.substring(l,l+1),n=parseInt(o,10),i+=a&&(n*=2)>=10?n+1:n,a=!a;return parseInt(t.substr(t.length-1),10)===(1e4-i)%10},isISBN:function t(r){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(e(r),!(i=String(i)))return t(r,10)||t(r,13);var o=r.replace(/[\s-]+/g,""),n=0,a=void 0;if("10"===i){if(!te.test(o))return!1;for(a=0;a<9;a++)n+=(a+1)*o.charAt(a);if("X"===o.charAt(9)?n+=100:n+=10*o.charAt(9),n%11==0)return!!o}else if("13"===i){if(!re.test(o))return!1;for(a=0;a<12;a++)n+=ie[a%2]*o.charAt(a);if(o.charAt(12)-(10-n%10)%10==0)return!!o}return!1},isISSN:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(t);var i=oe;if(i=r.require_hyphen?i.replace("?",""):i,!(i=r.case_sensitive?new RegExp(i):new RegExp(i,"i")).test(t))return!1;var o=t.replace("-",""),n=8,a=0,l=!0,s=!1,u=void 0;try{for(var d,c=o[Symbol.iterator]();!(l=(d=c.next()).done);l=!0){var f=d.value;a+=("X"===f.toUpperCase()?10:+f)*n,--n}}catch(e){s=!0,u=e}finally{try{!l&&c.return&&c.return()}finally{if(s)throw u}}return a%11==0},isMobilePhone:function(t,r,i){if(e(t),i&&i.strictMode&&!t.startsWith("+"))return!1;if(r in ne)return ne[r].test(t);if("any"===r){for(var o in ne)if(ne.hasOwnProperty(o)&&ne[o].test(t))return!0;return!1}throw new Error("Invalid locale '"+r+"'")},isPostalCode:function(t,r){if(e(t),r in Ae)return Ae[r].test(t);if("any"===r){for(var i in Ae)if(Ae.hasOwnProperty(i)&&Ae[i].test(t))return!0;return!1}throw new Error("Invalid locale '"+r+"'")},isCurrency:function(t,r){return e(t),function(e){var t="\\d{"+e.digits_after_decimal[0]+"}";e.digits_after_decimal.forEach(function(e,r){0!==r&&(t=t+"|\\d{"+e+"}")});var r="(\\"+e.symbol.replace(/\./g,"\\.")+")"+(e.require_symbol?"":"?"),i="("+["0","[1-9]\\d*","[1-9]\\d{0,2}(\\"+e.thousands_separator+"\\d{3})*"].join("|")+")?",o="(\\"+e.decimal_separator+"("+t+"))"+(e.require_decimal?"":"?"),n=i+(e.allow_decimal||e.require_decimal?o:"");return e.allow_negatives&&!e.parens_for_negatives&&(e.negative_sign_after_digits?n+="-?":e.negative_sign_before_digits&&(n="-?"+n)),e.allow_negative_sign_placeholder?n="( (?!\\-))?"+n:e.allow_space_after_symbol?n=" ?"+n:e.allow_space_after_digits&&(n+="( (?!$))?"),e.symbol_after_digits?n+=r:n=r+n,e.allow_negatives&&(e.parens_for_negatives?n="(\\("+n+"\\)|"+n+")":e.negative_sign_before_digits||e.negative_sign_after_digits||(n="-?"+n)),new RegExp("^(?!-? )(?=.*\\d)"+n+"$")}(r=n(r,ae)).test(t)},isISO8601:function(t){return e(t),le.test(t)},isISO31661Alpha2:function(t){return e(t),se.includes(t.toUpperCase())},isBase64:function(t){e(t);var r=t.length;if(!r||r%4!=0||ue.test(t))return!1;var i=t.indexOf("=");return-1===i||i===r-1||i===r-2&&"="===t[r-1]},isDataURI:function(t){e(t);var r=t.split(",");if(r.length<2)return!1;var i=r.shift().trim().split(";"),o=i.shift();if("data:"!==o.substr(0,5))return!1;var n=o.substr(5);if(""!==n&&!de.test(n))return!1;for(var a=0;a/g,">").replace(/\//g,"/").replace(/\\/g,"\").replace(/`/g,"`")},unescape:function(t){return e(t),t.replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(///g,"/").replace(/\/g,"\\").replace(/`/g,"`")},stripLow:function(t,r){return e(t),we(t,r?"\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F":"\\x00-\\x1F\\x7F")},whitelist:function(t,r){return e(t),t.replace(new RegExp("[^"+r+"]+","g"),"")},blacklist:we,isWhitelisted:function(t,r){e(t);for(var i=t.length-1;i>=0;i--)if(-1===r.indexOf(t[i]))return!1;return!0},normalizeEmail:function(e,t){t=n(t,Ee);var r=e.split("@"),i=r.pop(),o=[r.join("@"),i];if(o[1]=o[1].toLowerCase(),"gmail.com"===o[1]||"googlemail.com"===o[1]){if(t.gmail_remove_subaddress&&(o[0]=o[0].split("+")[0]),t.gmail_remove_dots&&(o[0]=o[0].replace(/\./g,"")),!o[0].length)return!1;(t.all_lowercase||t.gmail_lowercase)&&(o[0]=o[0].toLowerCase()),o[1]=t.gmail_convert_googlemaildotcom?"gmail.com":o[1]}else if(~Ze.indexOf(o[1])){if(t.icloud_remove_subaddress&&(o[0]=o[0].split("+")[0]),!o[0].length)return!1;(t.all_lowercase||t.icloud_lowercase)&&(o[0]=o[0].toLowerCase())}else if(~be.indexOf(o[1])){if(t.outlookdotcom_remove_subaddress&&(o[0]=o[0].split("+")[0]),!o[0].length)return!1;(t.all_lowercase||t.outlookdotcom_lowercase)&&(o[0]=o[0].toLowerCase())}else if(~ye.indexOf(o[1])){if(t.yahoo_remove_subaddress){var a=o[0].split("-");o[0]=a.length>1?a.slice(0,-1).join("-"):a[0]}if(!o[0].length)return!1;(t.all_lowercase||t.yahoo_lowercase)&&(o[0]=o[0].toLowerCase())}else t.all_lowercase&&(o[0]=o[0].toLowerCase());return o.join("@")},toString:o}}); \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/xml2js/.npmignore b/node_modules/azure-storage/node_modules/xml2js/.npmignore deleted file mode 100644 index ef7b9b905..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -*.swp -.idea -node_modules -src -test -Cakefile \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/xml2js/.travis.yml b/node_modules/azure-storage/node_modules/xml2js/.travis.yml deleted file mode 100644 index 755a6b73d..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js - -node_js: - - "0.8" - - "0.10" diff --git a/node_modules/azure-storage/node_modules/xml2js/83.coffee b/node_modules/azure-storage/node_modules/xml2js/83.coffee deleted file mode 100644 index 3443540fe..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/83.coffee +++ /dev/null @@ -1,6 +0,0 @@ -xml2js = require 'xml2js' -util = require 'util' - -body = 'Character data here!' -xml2js.parseString body, (err, result) -> - console.log util.inspect result, false, null diff --git a/node_modules/azure-storage/node_modules/xml2js/LICENSE b/node_modules/azure-storage/node_modules/xml2js/LICENSE deleted file mode 100644 index e3b4222a6..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright 2010, 2011, 2012, 2013. 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/azure-storage/node_modules/xml2js/README.md b/node_modules/azure-storage/node_modules/xml2js/README.md deleted file mode 100644 index b0097240a..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/README.md +++ /dev/null @@ -1,248 +0,0 @@ -node-xml2js -=========== - -Ever had the urge to parse XML? And wanted to access the data in some sane, -easy way? Don't want to compile a C parser, for whatever reason? Then xml2js is -what you're looking for! - -Description -=========== - -Simple XML to JavaScript object converter. Uses -[sax-js](https://github.com/isaacs/sax-js/). - -Note: If you're looking for a full DOM parser, you probably want -[JSDom](https://github.com/tmpvar/jsdom). - -Installation -============ - -Simplest way to install `xml2js` is to use [npm](http://npmjs.org), just `npm -install xml2js` which will download xml2js and all dependencies. - -Usage -===== - -No extensive tutorials required because you are a smart developer! The task of -parsing XML should be an easy one, so let's make it so! Here's some examples. - -Shoot-and-forget usage ----------------------- - -You want to parse XML as simple and easy as possible? It's dangerous to go -alone, take this: - -```javascript -var parseString = require('xml2js').parseString; -var xml = "Hello xml2js!" -parseString(xml, function (err, result) { - console.dir(result); -}); -``` - -Can't get easier than this, right? This works starting with `xml2js` 0.2.3. -With CoffeeScript it looks like this: - -```coffeescript -parseString = require('xml2js').parseString -xml = "Hello xml2js!" -parseString xml, (err, result) -> - console.dir result -``` - -If you need some special options, fear not, `xml2js` supports a number of -options (see below), you can specify these as second argument: - -```javascript -parseString(xml, {trim: true}, function (err, result) { -}); -``` - -Simple as pie usage -------------------- - -That's right, if you have been using xml-simple or a home-grown -wrapper, this is was added in 0.1.11 just for you: - -```javascript -var fs = require('fs'), - xml2js = require('xml2js'); - -var parser = new xml2js.Parser(); -fs.readFile(__dirname + '/foo.xml', function(err, data) { - parser.parseString(data, function (err, result) { - console.dir(result); - console.log('Done'); - }); -}); -``` - -Look ma, no event listeners! - -You can also use `xml2js` from -[CoffeeScript](http://jashkenas.github.com/coffee-script/), further reducing -the clutter: - -```coffeescript -fs = require 'fs', -xml2js = require 'xml2js' - -parser = new xml2js.Parser() -fs.readFile __dirname + '/foo.xml', (err, data) -> - parser.parseString data, (err, result) -> - console.dir result - console.log 'Done.' -``` - -But what happens if you forget the `new` keyword to create a new `Parser`? In -the middle of a nightly coding session, it might get lost, after all. Worry -not, we got you covered! Starting with 0.2.8 you can also leave it out, in -which case `xml2js` will helpfully add it for you, no bad surprises and -inexplicable bugs! - -"Traditional" usage -------------------- - -Alternatively you can still use the traditional `addListener` variant that was -supported since forever: - -```javascript -var fs = require('fs'), - xml2js = require('xml2js'); - -var parser = new xml2js.Parser(); -parser.addListener('end', function(result) { - console.dir(result); - console.log('Done.'); -}); -fs.readFile(__dirname + '/foo.xml', function(err, data) { - parser.parseString(data); -}); -``` - -If you want to parse multiple files, you have multiple possibilites: - - * You can create one `xml2js.Parser` per file. That's the recommended one - and is promised to always *just work*. - * You can call `reset()` on your parser object. - * You can hope everything goes well anyway. This behaviour is not - guaranteed work always, if ever. Use option #1 if possible. Thanks! - -So you wanna some JSON? ------------------------ - -Just wrap the `result` object in a call to `JSON.stringify` like this -`JSON.stringify(result)`. You get a string containing the JSON representation -of the parsed object that you can feed to JSON-hungry consumers. - -Displaying results ------------------- - -You might wonder why, using `console.dir` or `console.log` the output at some -level is only `[Object]`. Don't worry, this is not because xml2js got lazy. -That's because Node uses `util.inspect` to convert the object into strings and -that function stops after `depth=2` which is a bit low for most XML. - -To display the whole deal, you can use `console.log(util.inspect(result, false, -null))`, which displays the whole result. - -So much for that, but what if you use -[eyes](https://github.com/cloudhead/eyes.js) for nice colored output and it -truncates the output with `…`? Don't fear, there's also a solution for that, -you just need to increase the `maxLength` limit by creating a custom inspector -`var inspect = require('eyes').inspector({maxLength: false})` and then you can -easily `inspect(result)`. - -Options -======= - -Apart from the default settings, there is a number of options that can be -specified for the parser. Options are specified by ``new Parser({optionName: -value})``. Possible options are: - - * `attrkey` (default: `$`): Prefix that is used to access the attributes. - Version 0.1 default was `@`. - * `charkey` (default: `_`): Prefix that is used to access the character - content. Version 0.1 default was `#`. - * `explicitCharkey` (default: `false`) - * `trim` (default: `false`): Trim the whitespace at the beginning and end of - text nodes. - * `normalizeTags` (default: `false`): Normalize all tag names to lowercase. - * `normalize` (default: `false`): Trim whitespaces inside text nodes. - * `explicitRoot` (default: `true`): Set this if you want to get the root - node in the resulting object. - * `emptyTag` (default: `undefined`): what will the value of empty nodes be. - Default is `{}`. - * `explicitArray` (default: `true`): Always put child nodes in an array if - true; otherwise an array is created only if there is more than one. - * `ignoreAttrs` (default: `false`): Ignore all XML attributes and only create - text nodes. - * `mergeAttrs` (default: `false`): Merge attributes and child elements as - properties of the parent, instead of keying attributes off a child - attribute object. This option is ignored if `ignoreAttrs` is `false`. - * `validator` (default `null`): You can specify a callable that validates - the resulting structure somehow, however you want. See unit tests - for an example. - * `xmlns` (default `false`): Give each element a field usually called '$ns' - (the first character is the same as attrkey) that contains its local name - and namespace URI. - * `explicitChildren` (default `false`): Put child elements to separate - property. Doesn't work with `mergeAttrs = true`. If element has no children - then "children" won't be created. Added in 0.2.5. - * `childkey` (default `$$`): Prefix that is used to access child elements if - `explicitChildren` is set to `true`. Added in 0.2.5. - * `charsAsChildren` (default `false`): Determines whether chars should be - considered children if `explicitChildren` is on. Added in 0.2.5. - * `async` (default `false`): Should the callbacks be async? This *might* be - an incompatible change if your code depends on sync execution of callbacks. - xml2js 0.3 might change this default, so the recommendation is to not - depend on sync execution anyway. Added in 0.2.6. - * `strict` (default `true`): Set sax-js to strict or non-strict parsing mode. - Defaults to `true` which is *highly* recommended, since parsing HTML which - is not well-formed XML might yield just about anything. Added in 0.2.7. - -Updating to new version -======================= - -Version 0.2 changed the default parsing settings, but version 0.1.14 introduced -the default settings for version 0.2, so these settings can be tried before the -migration. - -```javascript -var xml2js = require('xml2js'); -var parser = new xml2js.Parser(xml2js.defaults["0.2"]); -``` - -To get the 0.1 defaults in version 0.2 you can just use -`xml2js.defaults["0.1"]` in the same place. This provides you with enough time -to migrate to the saner way of parsing in xml2js 0.2. We try to make the -migration as simple and gentle as possible, but some breakage cannot be -avoided. - -So, what exactly did change and why? In 0.2 we changed some defaults to parse -the XML in a more universal and sane way. So we disabled `normalize` and `trim` -so xml2js does not cut out any text content. You can reenable this at will of -course. A more important change is that we return the root tag in the resulting -JavaScript structure via the `explicitRoot` setting, so you need to access the -first element. This is useful for anybody who wants to know what the root node -is and preserves more information. The last major change was to enable -`explicitArray`, so everytime it is possible that one might embed more than one -sub-tag into a tag, xml2js >= 0.2 returns an array even if the array just -includes one element. This is useful when dealing with APIs that return -variable amounts of subtags. - -Running tests, development -========================== - -[![Build Status](https://secure.travis-ci.org/Leonidas-from-XIV/node-xml2js.png?branch=master)](https://travis-ci.org/Leonidas-from-XIV/node-xml2js) - -The development requirements are handled by npm, you just need to install them. -We also have a number of unit tests, they can be run using `npm test` directly -from the project root. This runs zap to discover all the tests and execute -them. - -If you like to contribute, keep in mind that xml2js is written in CoffeeScript, -so don't develop on the JavaScript files that are checked into the repository -for convenience reasons. Also, please write some unit test to check your -behaviour and if it is some user-facing thing, add some documentation to this -README, so people will know it exists. Thanks in advance! diff --git a/node_modules/azure-storage/node_modules/xml2js/canon.xml b/node_modules/azure-storage/node_modules/xml2js/canon.xml deleted file mode 100644 index f24ddd130..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/canon.xml +++ /dev/null @@ -1,482 +0,0 @@ - - - AF485783 - 14758 - double - DNA - circular - SYN - 15-MAY-2003 - 21-MAR-2002 - Binary vector pBI121, complete sequence - AF485783 - AF485783.1 - - gb|AF485783.1| - gi|19569229 - - Binary vector pBI121 - Binary vector pBI121 - other sequences; artificial sequences; vectors - - - 1 - 1..14758 - - Chen,P.Y. - Wang,C.K. - Soong,S.C. - To,K.Y. - - Complete sequence of the binary vector pBI121 and its application in cloning T-DNA insertion from transgenic plants - Mol. Breed. 11, 287-293 (2003) - - - 2 - 1..14758 - - To,K.Y. - - Direct Submission - Submitted (20-FEB-2002) Institute of BioAgricultural Sciences, Academia Sinica, Taipei 11529, Taiwan - - - - - source - 1..14758 - - - 1 - 14758 - AF485783.1 - - - - - organism - Binary vector pBI121 - - - mol_type - genomic DNA - - - db_xref - taxon:189807 - - - note - constructed using pB221 from Clontech Laboratories and Bin19 described in GenBank Accession Number U09365 - - - - - misc_feature - complement(13..796) - - - 796 - 13 - - AF485783.1 - - - - - note - similar to traF in GenBank Accession Number X54459 - - - - - rep_origin - complement(790..1168) - - - 1168 - 790 - - AF485783.1 - - - - - note - ColE1 ori; similar to sequence in GenBank Accession Number V00268 - - - - - misc_feature - complement(1161..2344) - - - 2344 - 1161 - - AF485783.1 - - - - - note - similar to tetA in GenBank Accession Number X75761 - - - - - misc_feature - complement(2454..2478) - - - 2478 - 2454 - - AF485783.1 - - - - - note - T-DNA right border - - - - - promoter - 2519..2825 - - - 2519 - 2825 - AF485783.1 - - - - - note - NOS - - - - - gene - 2838..3632 - - - 2838 - 3632 - AF485783.1 - - - - - gene - nptII - - - - - CDS - 2838..3632 - - - 2838 - 3632 - AF485783.1 - - - - - gene - nptII - - - codon_start - 1 - - - transl_table - 1 - - - product - neomycin phosphotransferase II - - - protein_id - AAL92039.1 - - - db_xref - GI:19569230 - - - translation - MIEQDGLHAGSPAAWVERLFGYDWAQQTIGCSDAAVFRLSAQGRPVLFVKTDLSGALNELQDEAARLSWLATTGVPCAAVLDVVTEAGRDWLLLGEVPGQDLLSSHLAPAEKVSIMADAMRRLHTLDPATCPFDHQAKHRIERARTRMEAGLVDQDDLDEEHQGLAPAELFARLKARMPDGDDLVVTHGDACLPNIMVENGRFSGFIDCGRLGVADRYQDIALATRDIAEELGGEWADRFLVLYGIAAPDSQRIAFYRLLDEFF - - - - - terminator - 4022..4277 - - - 4022 - 4277 - AF485783.1 - - - - - note - NOS - - - - - promoter - 4974..5808 - - - 4974 - 5808 - AF485783.1 - - - - - note - CaMV 35S - - - - - gene - 5845..7656 - - - 5845 - 7656 - AF485783.1 - - - - - gene - gusA - - - - - CDS - 5845..7656 - - - 5845 - 7656 - AF485783.1 - - - - - gene - gusA - - - note - GUS - - - codon_start - 1 - - - transl_table - 1 - - - product - beta-glucuronidase - - - protein_id - AAL92040.1 - - - db_xref - GI:19569231 - - - translation - MLRPVETPTREIKKLDGLWAFSLDRENCGIDQRWWESALQESRAIAVPGSFNDQFADADIRNYAGNVWYQREVFIPKGWAGQRIVLRFDAVTHYGKVWVNNQEVMEHQGGYTPFEADVTPYVIAGKSVRITVCVNNELNWQTIPPGMVITDENGKKKQSYFHDFFNYAGIHRSVMLYTTPNTWVDDITVVTHVAQDCNHASVDWQVVANGDVSVELRDADQQVVATGQGTSGTLQVVNPHLWQPGEGYLYELCVTAKSQTECDIYPLRVGIRSVAVKGEQFLINHKPFYFTGFGRHEDADLRGKGFDNVLMVHDHALMDWIGANSYRTSHYPYAEEMLDWADEHGIVVIDETAAVGFNLSLGIGFEAGNKPKELYSEEAVNGETQQAHLQAIKELIARDKNHPSVVMWSIANEPDTRPQGAREYFAPLAEATRKLDPTRPITCVNVMFCDAHTDTISDLFDVLCLNRYYGWYVQSGDLETAEKVLEKELLAWQEKLHQPIIITEYGVDTLAGLHSMYTDMWSEEYQCAWLDMYHRVFDRVSAVVGEQVWNFADFATSQGILRVGGNKKGIFTRDRKPKSAAFLLQKRWTGMNFGEKPQQGGKQ - - - - - terminator - 7727..7979 - - - 7727 - 7979 - AF485783.1 - - - - - note - NOS - - - - - misc_feature - complement(8621..8646) - - - 8646 - 8621 - - AF485783.1 - - - - - note - T-DNA left border - - - - - misc_feature - complement(9156..10198) - - - 10198 - 9156 - - AF485783.1 - - - - - note - similar to tetA in GenBank Accession Number L13842 - - - - - misc_feature - complement(10199..11680) - - - 11680 - 10199 - - AF485783.1 - - - - - note - similar to trfA in GenBank Accession Number X00713 - - - - - misc_feature - complement(11681..12673) - - - 12673 - 11681 - - AF485783.1 - - - - - note - similar to NPTIII gene in GenBank Accession Number V01547 - - - - - misc_feature - complement(12674..13443) - - - 13443 - 12674 - - AF485783.1 - - - - - note - similar to transposable element IS1 in GenBank Accession Number X58999 - - - - - misc_feature - complement(13444..13794) - - - 13794 - 13444 - - AF485783.1 - - - - - note - similarity to NPT III gene in GenBank Accession Number V01547 - - - - - misc_feature - complement(13795..14066) - - - 14066 - 13795 - - AF485783.1 - - - - - note - similar to kilA in GenBank Accession Number M62846 - - - - - rep_origin - complement(14141..14758) - - - 14758 - 14141 - - AF485783.1 - - - - - note - ori V; similar to sequence in GenBank Accession Number M20134 - - - - - tgagcgtcgcaaaggcgctcggtcttgccttgctcgtcggtgatgtacttcaccagctccgcgaagtcgctcttcttgatggagcgcatggggacgtgcttggcaatcacgcgcaccccccggccgttttagcggctaaaaaagtcatggctctgccctcgggcggaccacgcccatcatgaccttgccaagctcgtcctgcttctcttcgatcttcgccagcagggcgaggatcgtggcatcaccgaaccgcgccgtgcgcgggtcgtcggtgagccagagtttcagcaggccgcccaggcggcccaggtcgccattgatgcgggccagctcgcggacgtgctcatagtccacgacgcccgtgattttgtagccctggccgacggccagcaggtaggccgacaggctcatgccggccgccgccgccttttcctcaatcgctcttcgttcgtctggaaggcagtacaccttgataggtgggctgcccttcctggttggcttggtttcatcagccatccgcttgccctcatctgttacgccggcggtagccggccagcctcgcagagcaggattcccgttgagcaccgccaggtgcgaataagggacagtgaagaaggaacacccgctcgcgggtgggcctacttcacctatcctgcccggctgacgccgttggatacaccaaggaaagtctacacgaaccctttggcaaaatcctgtatatcgtgcgaaaaaggatggatataccgaaaaaatcgctataatgaccccgaagcagggttatgcagcggaaaagcgccacgcttcccgaagggagaaaggcggacaggtatccggtaagcggcagggtcggaacaggagagcgcacgagggagcttccagggggaaacgcctggtatctttatagtcctgtcgggtttcgccacctctgacttgagcgtcgatttttgtgatgctcgtcaggggggcggagcctatggaaaaacgccagcaacgcggcctttttacggttcctggccttttgctggccttttgctcacatgttctttcctgcgttatcccctgattctgtggataaccgtattaccgcctttgagtgagctgataccgctcgccgcagccgaacgaccgagcgcagcgagtcagtgagcgaggaagcggaagagcgccagaaggccgccagagaggccgagcgcggccgtgaggcttggacgctagggcagggcatgaaaaagcccgtagcgggctgctacgggcgtctgacgcggtggaaagggggaggggatgttgtctacatggctctgctgtagtgagtgggttgcgctccggcagcggtcctgatcaatcgtcaccctttctcggtccttcaacgttcctgacaacgagcctccttttcgccaatccatcgacaatcaccgcgagtccctgctcgaacgctgcgtccggaccggcttcgtcgaaggcgtctatcgcggcccgcaacagcggcgagagcggagcctgttcaacggtgccgccgcgctcgccggcatcgctgtcgccggcctgctcctcaagcacggccccaacagtgaagtagctgattgtcatcagcgcattgacggcgtccccggccgaaaaacccgcctcgcagaggaagcgaagctgcgcgtcggccgtttccatctgcggtgcgcccggtcgcgtgccggcatggatgcgcgcgccatcgcggtaggcgagcagcgcctgcctgaagctgcgggcattcccgatcagaaatgagcgccagtcgtcgtcggctctcggcaccgaatgcgtatgattctccgccagcatggcttcggccagtgcgtcgagcagcgcccgcttgttcctgaagtgccagtaaagcgccggctgctgaacccccaaccgttccgccagtttgcgtgtcgtcagaccgtctacgccgacctcgttcaacaggtccagggcggcacggatcactgtattcggctgcaactttgtcatgcttgacactttatcactgataaacataatatgtccaccaacttatcagtgataaagaatccgcgcgttcaatcggaccagcggaggctggtccggaggccagacgtgaaacccaacatacccctgatcgtaattctgagcactgtcgcgctcgacgctgtcggcatcggcctgattatgccggtgctgccgggcctcctgcgcgatctggttcactcgaacgacgtcaccgcccactatggcattctgctggcgctgtatgcgttggtgcaatttgcctgcgcacctgtgctgggcgcgctgtcggatcgtttcgggcggcggccaatcttgctcgtctcgctggccggcgccagatctggggaaccctgtggttggcatgcacatacaaatggacgaacggataaaccttttcacgcccttttaaatatccgattattctaataaacgctcttttctcttaggtttacccgccaatatatcctgtcaaacactgatagtttaaactgaaggcgggaaacgacaatctgatcatgagcggagaattaagggagtcacgttatgacccccgccgatgacgcgggacaagccgttttacgtttggaactgacagaaccgcaacgttgaaggagccactcagccgcgggtttctggagtttaatgagctaagcacatacgtcagaaaccattattgcgcgttcaaaagtcgcctaaggtcactatcagctagcaaatatttcttgtcaaaaatgctccactgacgttccataaattcccctcggtatccaattagagtctcatattcactctcaatccaaataatctgcaccggatctggatcgtttcgcatgattgaacaagatggattgcacgcaggttctccggccgcttgggtggagaggctattcggctatgactgggcacaacagacaatcggctgctctgatgccgccgtgttccggctgtcagcgcaggggcgcccggttctttttgtcaagaccgacctgtccggtgccctgaatgaactgcaggacgaggcagcgcggctatcgtggctggccacgacgggcgttccttgcgcagctgtgctcgacgttgtcactgaagcgggaagggactggctgctattgggcgaagtgccggggcaggatctcctgtcatctcaccttgctcctgccgagaaagtatccatcatggctgatgcaatgcggcggctgcatacgcttgatccggctacctgcccattcgaccaccaagcgaaacatcgcatcgagcgagcacgtactcggatggaagccggtcttgtcgatcaggatgatctggacgaagagcatcaggggctcgcgccagccgaactgttcgccaggctcaaggcgcgcatgcccgacggcgatgatctcgtcgtgacccatggcgatgcctgcttgccgaatatcatggtggaaaatggccgcttttctggattcatcgactgtggccggctgggtgtggcggaccgctatcaggacatagcgttggctacccgtgatattgctgaagagcttggcggcgaatgggctgaccgcttcctcgtgctttacggtatcgccgctcccgattcgcagcgcatcgccttctatcgccttcttgacgagttcttctgagcgggactctggggttcgaaatgaccgaccaagcgacgcccaacctgccatcacgagatttcgattccaccgccgccttctatgaaaggttgggcttcggaatcgttttccgggacgccggctggatgatcctccagcgcggggatctcatgctggagttcttcgcccacgggatctctgcggaacaggcggtcgaaggtgccgatatcattacgacagcaacggccgacaagcacaacgccacgatcctgagcgacaatatgatcgggcccggcgtccacatcaacggcgtcggcggcgactgcccaggcaagaccgagatgcaccgcgatatcttgctgcgttcggatattttcgtggagttcccgccacagacccggatgatccccgatcgttcaaacatttggcaataaagtttcttaagattgaatcctgttgccggtcttgcgatgattatcatataatttctgttgaattacgttaagcatgtaataattaacatgtaatgcatgacgttatttatgagatgggtttttatgattagagtcccgcaattatacatttaatacgcgatagaaaacaaaatatagcgcgcaaactaggataaattatcgcgcgcggtgtcatctatgttactagatcgggcctcctgtcaatgctggcggcggctctggtggtggttctggtggcggctctgagggtggtggctctgagggtggcggttctgagggtggcggctctgagggaggcggttccggtggtggctctggttccggtgattttgattatgaaaagatggcaaacgctaataagggggctatgaccgaaaatgccgatgaaaacgcgctacagtctgacgctaaaggcaaacttgattctgtcgctactgattacggtgctgctatcgatggtttcattggtgacgtttccggccttgctaatggtaatggtgctactggtgattttgctggctctaattcccaaatggctcaagtcggtgacggtgataattcacctttaatgaataatttccgtcaatatttaccttccctccctcaatcggttgaatgtcgcccttttgtctttggcccaatacgcaaaccgcctctccccgcgcgttggccgattcattaatgcagctggcacgacaggtttcccgactggaaagcgggcagtgagcgcaacgcaattaatgtgagttagctcactcattaggcaccccaggctttacactttatgcttccggctcgtatgttgtgtggaattgtgagcggataacaatttcacacaggaaacagctatgaccatgattacgccaagcttgcatgcctgcaggtccccagattagccttttcaatttcagaaagaatgctaacccacagatggttagagaggcttacgcagcaggtctcatcaagacgatctacccgagcaataatctccaggaaatcaaataccttcccaagaaggttaaagatgcagtcaaaagattcaggactaactgcatcaagaacacagagaaagatatatttctcaagatcagaagtactattccagtatggacgattcaaggcttgcttcacaaaccaaggcaagtaatagagattggagtctctaaaaaggtagttcccactgaatcaaaggccatggagtcaaagattcaaatagaggacctaacagaactcgccgtaaagactggcgaacagttcatacagagtctcttacgactcaatgacaagaagaaaatcttcgtcaacatggtggagcacgacacacttgtctactccaaaaatatcaaagatacagtctcagaagaccaaagggcaattgagacttttcaacaaagggtaatatccggaaacctcctcggattccattgcccagctatctgtcactttattgtgaagatagtggaaaaggaaggtggctcctacaaatgccatcattgcgataaaggaaaggccatcgttgaagatgcctctgccgacagtggtcccaaagatggacccccacccacgaggagcatcgtggaaaaagaagacgttccaaccacgtcttcaaagcaagtggattgatgtgatatctccactgacgtaagggatgacgcacaatcccactatccttcgcaagacccttcctctatataaggaagttcatttcatttggagagaacacgggggactctagaggatccccgggtggtcagtcccttatgttacgtcctgtagaaaccccaacccgtgaaatcaaaaaactcgacggcctgtgggcattcagtctggatcgcgaaaactgtggaattgatcagcgttggtgggaaagcgcgttacaagaaagccgggcaattgctgtgccaggcagttttaacgatcagttcgccgatgcagatattcgtaattatgcgggcaacgtctggtatcagcgcgaagtctttataccgaaaggttgggcaggccagcgtatcgtgctgcgtttcgatgcggtcactcattacggcaaagtgtgggtcaataatcaggaagtgatggagcatcagggcggctatacgccatttgaagccgatgtcacgccgtatgttattgccgggaaaagtgtacgtatcaccgtttgtgtgaacaacgaactgaactggcagactatcccgccgggaatggtgattaccgacgaaaacggcaagaaaaagcagtcttacttccatgatttctttaactatgccggaatccatcgcagcgtaatgctctacaccacgccgaacacctgggtggacgatatcaccgtggtgacgcatgtcgcgcaagactgtaaccacgcgtctgttgactggcaggtggtggccaatggtgatgtcagcgttgaactgcgtgatgcggatcaacaggtggttgcaactggacaaggcactagcgggactttgcaagtggtgaatccgcacctctggcaaccgggtgaaggttatctctatgaactgtgcgtcacagccaaaagccagacagagtgtgatatctacccgcttcgcgtcggcatccggtcagtggcagtgaagggcgaacagttcctgattaaccacaaaccgttctactttactggctttggtcgtcatgaagatgcggacttgcgtggcaaaggattcgataacgtgctgatggtgcacgaccacgcattaatggactggattggggccaactcctaccgtacctcgcattacccttacgctgaagagatgctcgactgggcagatgaacatggcatcgtggtgattgatgaaactgctgctgtcggctttaacctctctttaggcattggtttcgaagcgggcaacaagccgaaagaactgtacagcgaagaggcagtcaacggggaaactcagcaagcgcacttacaggcgattaaagagctgatagcgcgtgacaaaaaccacccaagcgtggtgatgtggagtattgccaacgaaccggatacccgtccgcaaggtgcacgggaatatttcgcgccactggcggaagcaacgcgtaaactcgacccgacgcgtccgatcacctgcgtcaatgtaatgttctgcgacgctcacaccgataccatcagcgatctctttgatgtgctgtgcctgaaccgttattacggatggtatgtccaaagcggcgatttggaaacggcagagaaggtactggaaaaagaacttctggcctggcaggagaaactgcatcagccgattatcatcaccgaatacggcgtggatacgttagccgggctgcactcaatgtacaccgacatgtggagtgaagagtatcagtgtgcatggctggatatgtatcaccgcgtctttgatcgcgtcagcgccgtcgtcggtgaacaggtatggaatttcgccgattttgcgacctcgcaaggcatattgcgcgttggcggtaacaagaaagggatcttcactcgcgaccgcaaaccgaagtcggcggcttttctgctgcaaaaacgctggactggcatgaacttcggtgaaaaaccgcagcagggaggcaaacaatgaatcaacaactctcctggcgcaccatcgtcggctacagcctcgggaattgctaccgagctcgaatttccccgatcgttcaaacatttggcaataaagtttcttaagattgaatcctgttgccggtcttgcgatgattatcatataatttctgttgaattacgttaagcatgtaataattaacatgtaatgcatgacgttatttatgagatgggtttttatgattagagtcccgcaattatacatttaatacgcgatagaaaacaaaatatagcgcgcaaactaggataaattatcgcgcgcggtgtcatctatgttactagatcgggaattcactggccgtcgttttacaacgtcgtgactgggaaaaccctggcgttacccaacttaatcgccttgcagcacatccccctttcgccagctggcgtaatagcgaagaggcccgcaccgatcgcccttcccaacagttgcgcagcctgaatggcgcccgctcctttcgctttcttcccttcctttctcgccacgttcgccggctttccccgtcaagctctaaatcgggggctccctttagggttccgatttagtgctttacggcacctcgaccccaaaaaacttgatttgggtgatggttcacgtagtgggccatcgccctgatagacggtttttcgccctttgacgttggagtccacgttctttaatagtggactcttgttccaaactggaacaacactcaaccctatctcgggctattcttttgatttataagggattttgccgatttcggaaccaccatcaaacaggattttcgcctgctggggcaaaccagcgtggaccgcttgctgcaactctctcagggccaggcggtgaagggcaatcagctgttgcccgtctcactggtgaaaagaaaaaccaccccagtacattaaaaacgtccgcaatgtgttattaagttgtctaagcgtcaatttgtttacaccacaatatatcctgccaccagccagccaacagctccccgaccggcagctcggcacaaaatcaccactcgatacaggcagcccatcagtccgggacggcgtcagcgggagagccgttgtaaggcggcagactttgctcatgttaccgatgctattcggaagaacggcaactaagctgccgggtttgaaacacggatgatctcgcggagggtagcatgttgattgtaacgatgacagagcgttgctgcctgtgatcaaatatcatctccctcgcagagatccgaattatcagccttcttattcatttctcgcttaaccgtgacaggctgtcgatcttgagaactatgccgacataataggaaatcgctggataaagccgctgaggaagctgagtggcgctatttctttagaagtgaacgttgacgatatcaactcccctatccattgctcaccgaatggtacaggtcggggacccgaagttccgactgtcggcctgatgcatccccggctgatcgaccccagatctggggctgagaaagcccagtaaggaaacaactgtaggttcgagtcgcgagatcccccggaaccaaaggaagtaggttaaacccgctccgatcaggccgagccacgccaggccgagaacattggttcctgtaggcatcgggattggcggatcaaacactaaagctactggaacgagcagaagtcctccggccgccagttgccaggcggtaaaggtgagcagaggcacgggaggttgccacttgcgggtcagcacggttccgaacgccatggaaaccgcccccgccaggcccgctgcgacgccgacaggatctagcgctgcgtttggtgtcaacaccaacagcgccacgcccgcagttccgcaaatagcccccaggaccgccatcaatcgtatcgggctacctagcagagcggcagagatgaacacgaccatcagcggctgcacagcgcctaccgtcgccgcgaccccgcccggcaggcggtagaccgaaataaacaacaagctccagaatagcgaaatattaagtgcgccgaggatgaagatgcgcatccaccagattcccgttggaatctgtcggacgatcatcacgagcaataaacccgccggcaacgcccgcagcagcataccggcgacccctcggcctcgctgttcgggctccacgaaaacgccggacagatgcgccttgtgagcgtccttggggccgtcctcctgtttgaagaccgacagcccaatgatctcgccgtcgatgtaggcgccgaatgccacggcatctcgcaaccgttcagcgaacgcctccatgggctttttctcctcgtgctcgtaaacggacccgaacatctctggagctttcttcagggccgacaatcggatctcgcggaaatcctgcacgtcggccgctccaagccgtcgaatctgagccttaatcacaattgtcaattttaatcctctgtttatcggcagttcgtagagcgcgccgtgcgtcccgagcgatactgagcgaagcaagtgcgtcgagcagtgcccgcttgttcctgaaatgccagtaaagcgctggctgctgaacccccagccggaactgaccccacaaggccctagcgtttgcaatgcaccaggtcatcattgacccaggcgtgttccaccaggccgctgcctcgcaactcttcgcaggcttcgccgacctgctcgcgccacttcttcacgcgggtggaatccgatccgcacatgaggcggaaggtttccagcttgagcgggtacggctcccggtgcgagctgaaatagtcgaacatccgtcgggccgtcggcgacagcttgcggtacttctcccatatgaatttcgtgtagtggtcgccagcaaacagcacgacgatttcctcgtcgatcaggacctggcaacgggacgttttcttgccacggtccaggacgcggaagcggtgcagcagcgacaccgattccaggtgcccaacgcggtcggacgtgaagcccatcgccgtcgcctgtaggcgcgacaggcattcctcggccttcgtgtaataccggccattgatcgaccagcccaggtcctggcaaagctcgtagaacgtgaaggtgatcggctcgccgataggggtgcgcttcgcgtactccaacacctgctgccacaccagttcgtcatcgtcggcccgcagctcgacgccggtgtaggtgatcttcacgtccttgttgacgtggaaaatgaccttgttttgcagcgcctcgcgcgggattttcttgttgcgcgtggtgaacagggcagagcgggccgtgtcgtttggcatcgctcgcatcgtgtccggccacggcgcaatatcgaacaaggaaagctgcatttccttgatctgctgcttcgtgtgtttcagcaacgcggcctgcttggcctcgctgacctgttttgccaggtcctcgccggcggtttttcgcttcttggtcgtcatagttcctcgcgtgtcgatggtcatcgacttcgccaaacctgccgcctcctgttcgagacgacgcgaacgctccacggcggccgatggcgcgggcagggcagggggagccagttgcacgctgtcgcgctcgatcttggccgtagcttgctggaccatcgagccgacggactggaaggtttcgcggggcgcacgcatgacggtgcggcttgcgatggtttcggcatcctcggcggaaaaccccgcgtcgatcagttcttgcctgtatgccttccggtcaaacgtccgattcattcaccctccttgcgggattgccccgactcacgccggggcaatgtgcccttattcctgatttgacccgcctggtgccttggtgtccagataatccaccttatcggcaatgaagtcggtcccgtagaccgtctggccgtccttctcgtacttggtattccgaatcttgccctgcacgaataccagcgaccccttgcccaaatacttgccgtgggcctcggcctgagagccaaaacacttgatgcggaagaagtcggtgcgctcctgcttgtcgccggcatcgttgcgccacatctaggtactaaaacaattcatccagtaaaatataatattttattttctcccaatcaggcttgatccccagtaagtcaaaaaatagctcgacatactgttcttccccgatatcctccctgatcgaccggacgcagaaggcaatgtcataccacttgtccgccctgccgcttctcccaagatcaataaagccacttactttgccatctttcacaaagatgttgctgtctcccaggtcgccgtgggaaaagacaagttcctcttcgggcttttccgtctttaaaaaatcatacagctcgcgcggatctttaaatggagtgtcttcttcccagttttcgcaatccacatcggccagatcgttattcagtaagtaatccaattcggctaagcggctgtctaagctattcgtatagggacaatccgatatgtcgatggagtgaaagagcctgatgcactccgcatacagctcgataatcttttcagggctttgttcatcttcatactcttccgagcaaaggacgccatcggcctcactcatgagcagattgctccagccatcatgccgttcaaagtgcaggacctttggaacaggcagctttccttccagccatagcatcatgtccttttcccgttccacatcataggtggtccctttataccggctgtccgtcatttttaaatataggttttcattttctcccaccagcttatataccttagcaggagacattccttccgtatcttttacgcagcggtatttttcgatcagttttttcaattccggtgatattctcattttagccatttattatttccttcctcttttctacagtatttaaagataccccaagaagctaattataacaagacgaactccaattcactgttccttgcattctaaaaccttaaataccagaaaacagctttttcaaagttgttttcaaagttggcgtataacatagtatcgacggagccgattttgaaaccacaattatgggtgatgctgccaacttactgatttagtgtatgatggtgtttttgaggtgctccagtggcttctgtgtctatcagctgtccctcctgttcagctactgacggggtggtgcgtaacggcaaaagcaccgccggacatcagcgctatctctgctctcactgccgtaaaacatggcaactgcagttcacttacaccgcttctcaacccggtacgcaccagaaaatcattgatatggccatgaatggcgttggatgccgggcaacagcccgcattatgggcgttggcctcaacacgattttacgtcacttaaaaaactcaggccgcagtcggtaacctcgcgcatacagccgggcagtgacgtcatcgtctgcgcggaaatggacgaacagtggggctatgtcggggctaaatcgcgccagcgctggctgttttacgcgtatgacagtctccggaagacggttgttgcgcacgtattcggtgaacgcactatggcgacgctggggcgtcttatgagcctgctgtcaccctttgacgtggtgatatggatgacggatggctggccgctgtatgaatcccgcctgaagggaaagctgcacgtaatcagcaagcgatatacgcagcgaattgagcggcataacctgaatctgaggcagcacctggcacggctgggacggaagtcgctgtcgttctcaaaatcggtggagctgcatgacaaagtcatcgggcattatctgaacataaaacactatcaataagttggagtcattacccaattatgatagaatttacaagctataaggttattgtcctgggtttcaagcattagtccatgcaagtttttatgctttgcccattctatagatatattgataagcgcgctgcctatgccttgccccctgaaatccttacatacggcgatatcttctatataaaagatatattatcttatcagtattgtcaatatattcaaggcaatctgcctcctcatcctcttcatcctcttcgtcttggtagctttttaaatatggcgcttcatagagtaattctgtaaaggtccaattctcgttttcatacctcggtataatcttacctatcacctcaaatggttcgctgggtttatcgcacccccgaacacgagcacggcacccgcgaccactatgccaagaatgcccaaggtaaaaattgccggccccgccatgaagtccgtgaatgccccgacggccgaagtgaagggcaggccgccacccaggccgccgccctcactgcccggcacctggtcgctgaatgtcgatgccagcacctgcggcacgtcaatgcttccgggcgtcgcgctcgggctgatcgcccatcccgttactgccccgatcccggcaatggcaaggactgccagcgctgccatttttggggtgaggccgttcgcggccgaggggcgcagcccctggggggatgggaggcccgcgttagcgggccgggagggttcgagaagggggggcaccccccttcggcgtgcgcggtcacgcgcacagggcgcagccctggttaaaaacaaggtttataaatattggtttaaaagcaggttaaaagacaggttagcggtggccgaaaaacgggcggaaacccttgcaaatgctggattttctgcctgtggacagcccctcaaatgtcaataggtgcgcccctcatctgtcagcactctgcccctcaagtgtcaaggatcgcgcccctcatctgtcagtagtcgcgcccctcaagtgtcaataccgcagggcacttatccccaggcttgtccacatcatctgtgggaaactcgcgtaaaatcaggcgttttcgccgatttgcgaggctggccagctccacgtcgccggccgaaatcgagcctgcccctcatctgtcaacgccgcgccgggtgagtcggcccctcaagtgtcaacgtccgcccctcatctgtcagtgagggccaagttttccgcgaggtatccacaacgccggcggccgcggtgtctcgcacacggcttcgacggcgtttctggcgcgtttgcagggccatagacggccgccagcccagcggcgagggcaaccagcccgg - - - \ No newline at end of file diff --git a/node_modules/azure-storage/node_modules/xml2js/lib/xml2js.js b/node_modules/azure-storage/node_modules/xml2js/lib/xml2js.js deleted file mode 100644 index bec8a2108..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/lib/xml2js.js +++ /dev/null @@ -1,299 +0,0 @@ -// Generated by CoffeeScript 1.6.3 -(function() { - var events, isEmpty, sax, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; - - sax = require('sax'); - - events = require('events'); - - isEmpty = function(thing) { - return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0; - }; - - exports.defaults = { - "0.1": { - explicitCharkey: false, - trim: true, - normalize: true, - normalizeTags: false, - attrkey: "@", - charkey: "#", - explicitArray: false, - ignoreAttrs: false, - mergeAttrs: false, - explicitRoot: false, - validator: null, - xmlns: false, - explicitChildren: false, - childkey: '@@', - charsAsChildren: false, - async: false, - strict: true - }, - "0.2": { - explicitCharkey: false, - trim: false, - normalize: false, - normalizeTags: false, - attrkey: "$", - charkey: "_", - explicitArray: true, - ignoreAttrs: false, - mergeAttrs: false, - explicitRoot: true, - validator: null, - xmlns: false, - explicitChildren: false, - childkey: '$$', - charsAsChildren: false, - async: false, - strict: true - } - }; - - exports.ValidationError = (function(_super) { - __extends(ValidationError, _super); - - function ValidationError(message) { - this.message = message; - } - - return ValidationError; - - })(Error); - - exports.Parser = (function(_super) { - __extends(Parser, _super); - - function Parser(opts) { - this.parseString = __bind(this.parseString, this); - this.reset = __bind(this.reset, this); - var key, value, _ref; - if (!(this instanceof exports.Parser)) { - return new exports.Parser(opts); - } - this.options = {}; - _ref = exports.defaults["0.2"]; - for (key in _ref) { - if (!__hasProp.call(_ref, key)) continue; - value = _ref[key]; - this.options[key] = value; - } - for (key in opts) { - if (!__hasProp.call(opts, key)) continue; - value = opts[key]; - this.options[key] = value; - } - if (this.options.xmlns) { - this.options.xmlnskey = this.options.attrkey + "ns"; - } - this.reset(); - } - - Parser.prototype.reset = function() { - var attrkey, charkey, err, ontext, stack, - _this = this; - this.removeAllListeners(); - this.saxParser = sax.parser(this.options.strict, { - trim: false, - normalize: false, - xmlns: this.options.xmlns - }); - err = false; - this.saxParser.onerror = function(error) { - if (!err) { - err = true; - return _this.emit("error", error); - } - }; - this.EXPLICIT_CHARKEY = this.options.explicitCharkey; - this.resultObject = null; - stack = []; - attrkey = this.options.attrkey; - charkey = this.options.charkey; - this.saxParser.onopentag = function(node) { - var key, obj, _ref; - obj = {}; - obj[charkey] = ""; - if (!_this.options.ignoreAttrs) { - _ref = node.attributes; - for (key in _ref) { - if (!__hasProp.call(_ref, key)) continue; - if (!(attrkey in obj) && !_this.options.mergeAttrs) { - obj[attrkey] = {}; - } - if (_this.options.mergeAttrs) { - obj[key] = node.attributes[key]; - } else { - obj[attrkey][key] = node.attributes[key]; - } - } - } - obj["#name"] = _this.options.normalizeTags ? node.name.toLowerCase() : node.name; - if (_this.options.xmlns) { - obj[_this.options.xmlnskey] = { - uri: node.uri, - local: node.local - }; - } - return stack.push(obj); - }; - this.saxParser.onclosetag = function() { - var cdata, emptyStr, node, nodeName, obj, old, s, xpath; - obj = stack.pop(); - nodeName = obj["#name"]; - delete obj["#name"]; - cdata = obj.cdata; - delete obj.cdata; - s = stack[stack.length - 1]; - if (obj[charkey].match(/^\s*$/) && !cdata) { - emptyStr = obj[charkey]; - delete obj[charkey]; - } else { - if (_this.options.trim) { - obj[charkey] = obj[charkey].trim(); - } - if (_this.options.normalize) { - obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim(); - } - if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) { - obj = obj[charkey]; - } - } - if (isEmpty(obj)) { - obj = _this.options.emptyTag !== void 0 ? _this.options.emptyTag : emptyStr; - } - if (_this.options.validator != null) { - xpath = "/" + ((function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = stack.length; _i < _len; _i++) { - node = stack[_i]; - _results.push(node["#name"]); - } - return _results; - })()).concat(nodeName).join("/"); - try { - obj = _this.options.validator(xpath, s && s[nodeName], obj); - } catch (_error) { - err = _error; - _this.emit("error", err); - } - } - if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { - node = {}; - if (_this.options.attrkey in obj) { - node[_this.options.attrkey] = obj[_this.options.attrkey]; - delete obj[_this.options.attrkey]; - } - if (!_this.options.charsAsChildren && _this.options.charkey in obj) { - node[_this.options.charkey] = obj[_this.options.charkey]; - delete obj[_this.options.charkey]; - } - if (Object.getOwnPropertyNames(obj).length > 0) { - node[_this.options.childkey] = obj; - } - obj = node; - } - if (stack.length > 0) { - if (!_this.options.explicitArray) { - if (!(nodeName in s)) { - return s[nodeName] = obj; - } else if (s[nodeName] instanceof Array) { - return s[nodeName].push(obj); - } else { - old = s[nodeName]; - s[nodeName] = [old]; - return s[nodeName].push(obj); - } - } else { - if (!(s[nodeName] instanceof Array)) { - s[nodeName] = []; - } - return s[nodeName].push(obj); - } - } else { - if (_this.options.explicitRoot) { - old = obj; - obj = {}; - obj[nodeName] = old; - } - _this.resultObject = obj; - return _this.emit("end", _this.resultObject); - } - }; - ontext = function(text) { - var s; - s = stack[stack.length - 1]; - if (s) { - s[charkey] += text; - return s; - } - }; - this.saxParser.ontext = ontext; - return this.saxParser.oncdata = function(text) { - var s; - s = ontext(text); - if (s) { - return s.cdata = true; - } - }; - }; - - Parser.prototype.parseString = function(str, cb) { - if ((cb != null) && typeof cb === "function") { - this.on("end", function(result) { - this.reset(); - if (this.options.async) { - return process.nextTick(function() { - return cb(null, result); - }); - } else { - return cb(null, result); - } - }); - this.on("error", function(err) { - this.reset(); - if (this.options.async) { - return process.nextTick(function() { - return cb(err); - }); - } else { - return cb(err); - } - }); - } - if (str.toString().trim() === '') { - this.emit("end", null); - return true; - } - return this.saxParser.write(str.toString()); - }; - - return Parser; - - })(events.EventEmitter); - - exports.parseString = function(str, a, b) { - var cb, options, parser; - if (b != null) { - if (typeof b === 'function') { - cb = b; - } - if (typeof a === 'object') { - options = a; - } - } else { - if (typeof a === 'function') { - cb = a; - } - options = {}; - } - parser = new exports.Parser(options); - return parser.parseString(str, cb); - }; - -}).call(this); diff --git a/node_modules/azure-storage/node_modules/xml2js/package.json b/node_modules/azure-storage/node_modules/xml2js/package.json deleted file mode 100644 index 7b6d5e491..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/package.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "_from": "xml2js@0.2.8", - "_id": "xml2js@0.2.8", - "_inBundle": false, - "_integrity": "sha1-m4FpCTFjH/CdGVdUn69U9PmAs8I=", - "_location": "/azure-storage/xml2js", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "xml2js@0.2.8", - "name": "xml2js", - "escapedName": "xml2js", - "rawSpec": "0.2.8", - "saveSpec": null, - "fetchSpec": "0.2.8" - }, - "_requiredBy": [ - "/azure-storage" - ], - "_resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.2.8.tgz", - "_shasum": "9b81690931631ff09d1957549faf54f4f980b3c2", - "_spec": "xml2js@0.2.8", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot\\node_modules\\azure-storage", - "author": { - "name": "Marek Kubica", - "email": "marek@xivilization.net", - "url": "http://xivilization.net" - }, - "bugs": { - "url": "https://github.com/Leonidas-from-XIV/node-xml2js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "maqr", - "email": "maqr.lollerskates@gmail.com", - "url": "https://github.com/maqr" - }, - { - "name": "Ben Weaver", - "url": "http://benweaver.com/" - }, - { - "name": "Jae Kwon", - "url": "https://github.com/jaekwon" - }, - { - "name": "Jim Robert" - }, - { - "name": "Ștefan Rusu", - "url": "http://www.saltwaterc.eu/" - }, - { - "name": "Carter Cole", - "email": "carter.cole@cartercole.com", - "url": "http://cartercole.com/" - }, - { - "name": "Kurt Raschke", - "email": "kurt@kurtraschke.com", - "url": "http://www.kurtraschke.com/" - }, - { - "name": "Contra", - "email": "contra@australia.edu", - "url": "https://github.com/Contra" - }, - { - "name": "Marcelo Diniz", - "email": "marudiniz@gmail.com", - "url": "https://github.com/mdiniz" - }, - { - "name": "Michael Hart", - "url": "https://github.com/mhart" - }, - { - "name": "Zachary Scott", - "email": "zachary@zacharyscott.net", - "url": "http://zacharyscott.net/" - }, - { - "name": "Raoul Millais", - "url": "https://github.com/raoulmillais" - }, - { - "name": "Salsita Software", - "url": "http://www.salsitasoft.com/" - }, - { - "name": "Mike Schilling", - "email": "mike@emotive.com", - "url": "http://www.emotive.com/" - }, - { - "name": "Jackson Tian", - "email": "shyvo1987@gmail.com", - "url": "http://weibo.com/shyvo" - }, - { - "name": "Mikhail Zyatin", - "email": "mikhail.zyatin@gmail.com", - "url": "https://github.com/Sitin" - }, - { - "name": "Chris Tavares", - "email": "ctavares@microsoft.com", - "url": "https://github.com/christav" - }, - { - "name": "Frank Xu", - "email": "yyfrankyy@gmail.com", - "url": "http://f2e.us/" - } - ], - "dependencies": { - "sax": "0.5.x" - }, - "deprecated": false, - "description": "Simple XML to JavaScript object converter.", - "devDependencies": { - "coffee-script": ">=1.6.3", - "docco": ">=0.6.2", - "zap": ">=0.2.5" - }, - "directories": { - "lib": "./lib" - }, - "homepage": "https://github.com/Leonidas-from-XIV/node-xml2js", - "keywords": [ - "xml", - "json" - ], - "main": "./lib/xml2js", - "name": "xml2js", - "repository": { - "type": "git", - "url": "git+https://github.com/Leonidas-from-XIV/node-xml2js.git" - }, - "scripts": { - "test": "zap" - }, - "version": "0.2.8" -} diff --git a/node_modules/azure-storage/node_modules/xml2js/text.coffee b/node_modules/azure-storage/node_modules/xml2js/text.coffee deleted file mode 100644 index c5d8c66d9..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/text.coffee +++ /dev/null @@ -1,11 +0,0 @@ -fs = require 'fs' -xml2js = require 'xml2js' - -parser = new xml2js.Parser - -fs.readFile 'canon.xml', (err, data) -> - console.log err - parser.parseString (err, result) -> - console.log err - console.dir result - diff --git a/node_modules/azure-storage/node_modules/xml2js/text.xml b/node_modules/azure-storage/node_modules/xml2js/text.xml deleted file mode 100644 index bd3b482a4..000000000 --- a/node_modules/azure-storage/node_modules/xml2js/text.xml +++ /dev/null @@ -1,485 +0,0 @@ - - - - - AF485783 - 14758 - double - DNA - circular - SYN - 15-MAY-2003 - 21-MAR-2002 - Binary vector pBI121, complete sequence - AF485783 - AF485783.1 - - gb|AF485783.1| - gi|19569229 - - Binary vector pBI121 - Binary vector pBI121 - other sequences; artificial sequences; vectors - - - 1 - 1..14758 - - Chen,P.Y. - Wang,C.K. - Soong,S.C. - To,K.Y. - - Complete sequence of the binary vector pBI121 and its application in cloning T-DNA insertion from transgenic plants - Mol. Breed. 11, 287-293 (2003) - - - 2 - 1..14758 - - To,K.Y. - - Direct Submission - Submitted (20-FEB-2002) Institute of BioAgricultural Sciences, Academia Sinica, Taipei 11529, Taiwan - - - - - source - 1..14758 - - - 1 - 14758 - AF485783.1 - - - - - organism - Binary vector pBI121 - - - mol_type - genomic DNA - - - db_xref - taxon:189807 - - - note - constructed using pB221 from Clontech Laboratories and Bin19 described in GenBank Accession Number U09365 - - - - - misc_feature - complement(13..796) - - - 796 - 13 - - AF485783.1 - - - - - note - similar to traF in GenBank Accession Number X54459 - - - - - rep_origin - complement(790..1168) - - - 1168 - 790 - - AF485783.1 - - - - - note - ColE1 ori; similar to sequence in GenBank Accession Number V00268 - - - - - misc_feature - complement(1161..2344) - - - 2344 - 1161 - - AF485783.1 - - - - - note - similar to tetA in GenBank Accession Number X75761 - - - - - misc_feature - complement(2454..2478) - - - 2478 - 2454 - - AF485783.1 - - - - - note - T-DNA right border - - - - - promoter - 2519..2825 - - - 2519 - 2825 - AF485783.1 - - - - - note - NOS - - - - - gene - 2838..3632 - - - 2838 - 3632 - AF485783.1 - - - - - gene - nptII - - - - - CDS - 2838..3632 - - - 2838 - 3632 - AF485783.1 - - - - - gene - nptII - - - codon_start - 1 - - - transl_table - 1 - - - product - neomycin phosphotransferase II - - - protein_id - AAL92039.1 - - - db_xref - GI:19569230 - - - translation - MIEQDGLHAGSPAAWVERLFGYDWAQQTIGCSDAAVFRLSAQGRPVLFVKTDLSGALNELQDEAARLSWLATTGVPCAAVLDVVTEAGRDWLLLGEVPGQDLLSSHLAPAEKVSIMADAMRRLHTLDPATCPFDHQAKHRIERARTRMEAGLVDQDDLDEEHQGLAPAELFARLKARMPDGDDLVVTHGDACLPNIMVENGRFSGFIDCGRLGVADRYQDIALATRDIAEELGGEWADRFLVLYGIAAPDSQRIAFYRLLDEFF - - - - - terminator - 4022..4277 - - - 4022 - 4277 - AF485783.1 - - - - - note - NOS - - - - - promoter - 4974..5808 - - - 4974 - 5808 - AF485783.1 - - - - - note - CaMV 35S - - - - - gene - 5845..7656 - - - 5845 - 7656 - AF485783.1 - - - - - gene - gusA - - - - - CDS - 5845..7656 - - - 5845 - 7656 - AF485783.1 - - - - - gene - gusA - - - note - GUS - - - codon_start - 1 - - - transl_table - 1 - - - product - beta-glucuronidase - - - protein_id - AAL92040.1 - - - db_xref - GI:19569231 - - - translation - MLRPVETPTREIKKLDGLWAFSLDRENCGIDQRWWESALQESRAIAVPGSFNDQFADADIRNYAGNVWYQREVFIPKGWAGQRIVLRFDAVTHYGKVWVNNQEVMEHQGGYTPFEADVTPYVIAGKSVRITVCVNNELNWQTIPPGMVITDENGKKKQSYFHDFFNYAGIHRSVMLYTTPNTWVDDITVVTHVAQDCNHASVDWQVVANGDVSVELRDADQQVVATGQGTSGTLQVVNPHLWQPGEGYLYELCVTAKSQTECDIYPLRVGIRSVAVKGEQFLINHKPFYFTGFGRHEDADLRGKGFDNVLMVHDHALMDWIGANSYRTSHYPYAEEMLDWADEHGIVVIDETAAVGFNLSLGIGFEAGNKPKELYSEEAVNGETQQAHLQAIKELIARDKNHPSVVMWSIANEPDTRPQGAREYFAPLAEATRKLDPTRPITCVNVMFCDAHTDTISDLFDVLCLNRYYGWYVQSGDLETAEKVLEKELLAWQEKLHQPIIITEYGVDTLAGLHSMYTDMWSEEYQCAWLDMYHRVFDRVSAVVGEQVWNFADFATSQGILRVGGNKKGIFTRDRKPKSAAFLLQKRWTGMNFGEKPQQGGKQ - - - - - terminator - 7727..7979 - - - 7727 - 7979 - AF485783.1 - - - - - note - NOS - - - - - misc_feature - complement(8621..8646) - - - 8646 - 8621 - - AF485783.1 - - - - - note - T-DNA left border - - - - - misc_feature - complement(9156..10198) - - - 10198 - 9156 - - AF485783.1 - - - - - note - similar to tetA in GenBank Accession Number L13842 - - - - - misc_feature - complement(10199..11680) - - - 11680 - 10199 - - AF485783.1 - - - - - note - similar to trfA in GenBank Accession Number X00713 - - - - - misc_feature - complement(11681..12673) - - - 12673 - 11681 - - AF485783.1 - - - - - note - similar to NPTIII gene in GenBank Accession Number V01547 - - - - - misc_feature - complement(12674..13443) - - - 13443 - 12674 - - AF485783.1 - - - - - note - similar to transposable element IS1 in GenBank Accession Number X58999 - - - - - misc_feature - complement(13444..13794) - - - 13794 - 13444 - - AF485783.1 - - - - - note - similarity to NPT III gene in GenBank Accession Number V01547 - - - - - misc_feature - complement(13795..14066) - - - 14066 - 13795 - - AF485783.1 - - - - - note - similar to kilA in GenBank Accession Number M62846 - - - - - rep_origin - complement(14141..14758) - - - 14758 - 14141 - - AF485783.1 - - - - - note - ori V; similar to sequence in GenBank Accession Number M20134 - - - - - tgagcgtcgcaaaggcgctcggtcttgccttgctcgtcggtgatgtacttcaccagctccgcgaagtcgctcttcttgatggagcgcatggggacgtgcttggcaatcacgcgcaccccccggccgttttagcggctaaaaaagtcatggctctgccctcgggcggaccacgcccatcatgaccttgccaagctcgtcctgcttctcttcgatcttcgccagcagggcgaggatcgtggcatcaccgaaccgcgccgtgcgcgggtcgtcggtgagccagagtttcagcaggccgcccaggcggcccaggtcgccattgatgcgggccagctcgcggacgtgctcatagtccacgacgcccgtgattttgtagccctggccgacggccagcaggtaggccgacaggctcatgccggccgccgccgccttttcctcaatcgctcttcgttcgtctggaaggcagtacaccttgataggtgggctgcccttcctggttggcttggtttcatcagccatccgcttgccctcatctgttacgccggcggtagccggccagcctcgcagagcaggattcccgttgagcaccgccaggtgcgaataagggacagtgaagaaggaacacccgctcgcgggtgggcctacttcacctatcctgcccggctgacgccgttggatacaccaaggaaagtctacacgaaccctttggcaaaatcctgtatatcgtgcgaaaaaggatggatataccgaaaaaatcgctataatgaccccgaagcagggttatgcagcggaaaagcgccacgcttcccgaagggagaaaggcggacaggtatccggtaagcggcagggtcggaacaggagagcgcacgagggagcttccagggggaaacgcctggtatctttatagtcctgtcgggtttcgccacctctgacttgagcgtcgatttttgtgatgctcgtcaggggggcggagcctatggaaaaacgccagcaacgcggcctttttacggttcctggccttttgctggccttttgctcacatgttctttcctgcgttatcccctgattctgtggataaccgtattaccgcctttgagtgagctgataccgctcgccgcagccgaacgaccgagcgcagcgagtcagtgagcgaggaagcggaagagcgccagaaggccgccagagaggccgagcgcggccgtgaggcttggacgctagggcagggcatgaaaaagcccgtagcgggctgctacgggcgtctgacgcggtggaaagggggaggggatgttgtctacatggctctgctgtagtgagtgggttgcgctccggcagcggtcctgatcaatcgtcaccctttctcggtccttcaacgttcctgacaacgagcctccttttcgccaatccatcgacaatcaccgcgagtccctgctcgaacgctgcgtccggaccggcttcgtcgaaggcgtctatcgcggcccgcaacagcggcgagagcggagcctgttcaacggtgccgccgcgctcgccggcatcgctgtcgccggcctgctcctcaagcacggccccaacagtgaagtagctgattgtcatcagcgcattgacggcgtccccggccgaaaaacccgcctcgcagaggaagcgaagctgcgcgtcggccgtttccatctgcggtgcgcccggtcgcgtgccggcatggatgcgcgcgccatcgcggtaggcgagcagcgcctgcctgaagctgcgggcattcccgatcagaaatgagcgccagtcgtcgtcggctctcggcaccgaatgcgtatgattctccgccagcatggcttcggccagtgcgtcgagcagcgcccgcttgttcctgaagtgccagtaaagcgccggctgctgaacccccaaccgttccgccagtttgcgtgtcgtcagaccgtctacgccgacctcgttcaacaggtccagggcggcacggatcactgtattcggctgcaactttgtcatgcttgacactttatcactgataaacataatatgtccaccaacttatcagtgataaagaatccgcgcgttcaatcggaccagcggaggctggtccggaggccagacgtgaaacccaacatacccctgatcgtaattctgagcactgtcgcgctcgacgctgtcggcatcggcctgattatgccggtgctgccgggcctcctgcgcgatctggttcactcgaacgacgtcaccgcccactatggcattctgctggcgctgtatgcgttggtgcaatttgcctgcgcacctgtgctgggcgcgctgtcggatcgtttcgggcggcggccaatcttgctcgtctcgctggccggcgccagatctggggaaccctgtggttggcatgcacatacaaatggacgaacggataaaccttttcacgcccttttaaatatccgattattctaataaacgctcttttctcttaggtttacccgccaatatatcctgtcaaacactgatagtttaaactgaaggcgggaaacgacaatctgatcatgagcggagaattaagggagtcacgttatgacccccgccgatgacgcgggacaagccgttttacgtttggaactgacagaaccgcaacgttgaaggagccactcagccgcgggtttctggagtttaatgagctaagcacatacgtcagaaaccattattgcgcgttcaaaagtcgcctaaggtcactatcagctagcaaatatttcttgtcaaaaatgctccactgacgttccataaattcccctcggtatccaattagagtctcatattcactctcaatccaaataatctgcaccggatctggatcgtttcgcatgattgaacaagatggattgcacgcaggttctccggccgcttgggtggagaggctattcggctatgactgggcacaacagacaatcggctgctctgatgccgccgtgttccggctgtcagcgcaggggcgcccggttctttttgtcaagaccgacctgtccggtgccctgaatgaactgcaggacgaggcagcgcggctatcgtggctggccacgacgggcgttccttgcgcagctgtgctcgacgttgtcactgaagcgggaagggactggctgctattgggcgaagtgccggggcaggatctcctgtcatctcaccttgctcctgccgagaaagtatccatcatggctgatgcaatgcggcggctgcatacgcttgatccggctacctgcccattcgaccaccaagcgaaacatcgcatcgagcgagcacgtactcggatggaagccggtcttgtcgatcaggatgatctggacgaagagcatcaggggctcgcgccagccgaactgttcgccaggctcaaggcgcgcatgcccgacggcgatgatctcgtcgtgacccatggcgatgcctgcttgccgaatatcatggtggaaaatggccgcttttctggattcatcgactgtggccggctgggtgtggcggaccgctatcaggacatagcgttggctacccgtgatattgctgaagagcttggcggcgaatgggctgaccgcttcctcgtgctttacggtatcgccgctcccgattcgcagcgcatcgccttctatcgccttcttgacgagttcttctgagcgggactctggggttcgaaatgaccgaccaagcgacgcccaacctgccatcacgagatttcgattccaccgccgccttctatgaaaggttgggcttcggaatcgttttccgggacgccggctggatgatcctccagcgcggggatctcatgctggagttcttcgcccacgggatctctgcggaacaggcggtcgaaggtgccgatatcattacgacagcaacggccgacaagcacaacgccacgatcctgagcgacaatatgatcgggcccggcgtccacatcaacggcgtcggcggcgactgcccaggcaagaccgagatgcaccgcgatatcttgctgcgttcggatattttcgtggagttcccgccacagacccggatgatccccgatcgttcaaacatttggcaataaagtttcttaagattgaatcctgttgccggtcttgcgatgattatcatataatttctgttgaattacgttaagcatgtaataattaacatgtaatgcatgacgttatttatgagatgggtttttatgattagagtcccgcaattatacatttaatacgcgatagaaaacaaaatatagcgcgcaaactaggataaattatcgcgcgcggtgtcatctatgttactagatcgggcctcctgtcaatgctggcggcggctctggtggtggttctggtggcggctctgagggtggtggctctgagggtggcggttctgagggtggcggctctgagggaggcggttccggtggtggctctggttccggtgattttgattatgaaaagatggcaaacgctaataagggggctatgaccgaaaatgccgatgaaaacgcgctacagtctgacgctaaaggcaaacttgattctgtcgctactgattacggtgctgctatcgatggtttcattggtgacgtttccggccttgctaatggtaatggtgctactggtgattttgctggctctaattcccaaatggctcaagtcggtgacggtgataattcacctttaatgaataatttccgtcaatatttaccttccctccctcaatcggttgaatgtcgcccttttgtctttggcccaatacgcaaaccgcctctccccgcgcgttggccgattcattaatgcagctggcacgacaggtttcccgactggaaagcgggcagtgagcgcaacgcaattaatgtgagttagctcactcattaggcaccccaggctttacactttatgcttccggctcgtatgttgtgtggaattgtgagcggataacaatttcacacaggaaacagctatgaccatgattacgccaagcttgcatgcctgcaggtccccagattagccttttcaatttcagaaagaatgctaacccacagatggttagagaggcttacgcagcaggtctcatcaagacgatctacccgagcaataatctccaggaaatcaaataccttcccaagaaggttaaagatgcagtcaaaagattcaggactaactgcatcaagaacacagagaaagatatatttctcaagatcagaagtactattccagtatggacgattcaaggcttgcttcacaaaccaaggcaagtaatagagattggagtctctaaaaaggtagttcccactgaatcaaaggccatggagtcaaagattcaaatagaggacctaacagaactcgccgtaaagactggcgaacagttcatacagagtctcttacgactcaatgacaagaagaaaatcttcgtcaacatggtggagcacgacacacttgtctactccaaaaatatcaaagatacagtctcagaagaccaaagggcaattgagacttttcaacaaagggtaatatccggaaacctcctcggattccattgcccagctatctgtcactttattgtgaagatagtggaaaaggaaggtggctcctacaaatgccatcattgcgataaaggaaaggccatcgttgaagatgcctctgccgacagtggtcccaaagatggacccccacccacgaggagcatcgtggaaaaagaagacgttccaaccacgtcttcaaagcaagtggattgatgtgatatctccactgacgtaagggatgacgcacaatcccactatccttcgcaagacccttcctctatataaggaagttcatttcatttggagagaacacgggggactctagaggatccccgggtggtcagtcccttatgttacgtcctgtagaaaccccaacccgtgaaatcaaaaaactcgacggcctgtgggcattcagtctggatcgcgaaaactgtggaattgatcagcgttggtgggaaagcgcgttacaagaaagccgggcaattgctgtgccaggcagttttaacgatcagttcgccgatgcagatattcgtaattatgcgggcaacgtctggtatcagcgcgaagtctttataccgaaaggttgggcaggccagcgtatcgtgctgcgtttcgatgcggtcactcattacggcaaagtgtgggtcaataatcaggaagtgatggagcatcagggcggctatacgccatttgaagccgatgtcacgccgtatgttattgccgggaaaagtgtacgtatcaccgtttgtgtgaacaacgaactgaactggcagactatcccgccgggaatggtgattaccgacgaaaacggcaagaaaaagcagtcttacttccatgatttctttaactatgccggaatccatcgcagcgtaatgctctacaccacgccgaacacctgggtggacgatatcaccgtggtgacgcatgtcgcgcaagactgtaaccacgcgtctgttgactggcaggtggtggccaatggtgatgtcagcgttgaactgcgtgatgcggatcaacaggtggttgcaactggacaaggcactagcgggactttgcaagtggtgaatccgcacctctggcaaccgggtgaaggttatctctatgaactgtgcgtcacagccaaaagccagacagagtgtgatatctacccgcttcgcgtcggcatccggtcagtggcagtgaagggcgaacagttcctgattaaccacaaaccgttctactttactggctttggtcgtcatgaagatgcggacttgcgtggcaaaggattcgataacgtgctgatggtgcacgaccacgcattaatggactggattggggccaactcctaccgtacctcgcattacccttacgctgaagagatgctcgactgggcagatgaacatggcatcgtggtgattgatgaaactgctgctgtcggctttaacctctctttaggcattggtttcgaagcgggcaacaagccgaaagaactgtacagcgaagaggcagtcaacggggaaactcagcaagcgcacttacaggcgattaaagagctgatagcgcgtgacaaaaaccacccaagcgtggtgatgtggagtattgccaacgaaccggatacccgtccgcaaggtgcacgggaatatttcgcgccactggcggaagcaacgcgtaaactcgacccgacgcgtccgatcacctgcgtcaatgtaatgttctgcgacgctcacaccgataccatcagcgatctctttgatgtgctgtgcctgaaccgttattacggatggtatgtccaaagcggcgatttggaaacggcagagaaggtactggaaaaagaacttctggcctggcaggagaaactgcatcagccgattatcatcaccgaatacggcgtggatacgttagccgggctgcactcaatgtacaccgacatgtggagtgaagagtatcagtgtgcatggctggatatgtatcaccgcgtctttgatcgcgtcagcgccgtcgtcggtgaacaggtatggaatttcgccgattttgcgacctcgcaaggcatattgcgcgttggcggtaacaagaaagggatcttcactcgcgaccgcaaaccgaagtcggcggcttttctgctgcaaaaacgctggactggcatgaacttcggtgaaaaaccgcagcagggaggcaaacaatgaatcaacaactctcctggcgcaccatcgtcggctacagcctcgggaattgctaccgagctcgaatttccccgatcgttcaaacatttggcaataaagtttcttaagattgaatcctgttgccggtcttgcgatgattatcatataatttctgttgaattacgttaagcatgtaataattaacatgtaatgcatgacgttatttatgagatgggtttttatgattagagtcccgcaattatacatttaatacgcgatagaaaacaaaatatagcgcgcaaactaggataaattatcgcgcgcggtgtcatctatgttactagatcgggaattcactggccgtcgttttacaacgtcgtgactgggaaaaccctggcgttacccaacttaatcgccttgcagcacatccccctttcgccagctggcgtaatagcgaagaggcccgcaccgatcgcccttcccaacagttgcgcagcctgaatggcgcccgctcctttcgctttcttcccttcctttctcgccacgttcgccggctttccccgtcaagctctaaatcgggggctccctttagggttccgatttagtgctttacggcacctcgaccccaaaaaacttgatttgggtgatggttcacgtagtgggccatcgccctgatagacggtttttcgccctttgacgttggagtccacgttctttaatagtggactcttgttccaaactggaacaacactcaaccctatctcgggctattcttttgatttataagggattttgccgatttcggaaccaccatcaaacaggattttcgcctgctggggcaaaccagcgtggaccgcttgctgcaactctctcagggccaggcggtgaagggcaatcagctgttgcccgtctcactggtgaaaagaaaaaccaccccagtacattaaaaacgtccgcaatgtgttattaagttgtctaagcgtcaatttgtttacaccacaatatatcctgccaccagccagccaacagctccccgaccggcagctcggcacaaaatcaccactcgatacaggcagcccatcagtccgggacggcgtcagcgggagagccgttgtaaggcggcagactttgctcatgttaccgatgctattcggaagaacggcaactaagctgccgggtttgaaacacggatgatctcgcggagggtagcatgttgattgtaacgatgacagagcgttgctgcctgtgatcaaatatcatctccctcgcagagatccgaattatcagccttcttattcatttctcgcttaaccgtgacaggctgtcgatcttgagaactatgccgacataataggaaatcgctggataaagccgctgaggaagctgagtggcgctatttctttagaagtgaacgttgacgatatcaactcccctatccattgctcaccgaatggtacaggtcggggacccgaagttccgactgtcggcctgatgcatccccggctgatcgaccccagatctggggctgagaaagcccagtaaggaaacaactgtaggttcgagtcgcgagatcccccggaaccaaaggaagtaggttaaacccgctccgatcaggccgagccacgccaggccgagaacattggttcctgtaggcatcgggattggcggatcaaacactaaagctactggaacgagcagaagtcctccggccgccagttgccaggcggtaaaggtgagcagaggcacgggaggttgccacttgcgggtcagcacggttccgaacgccatggaaaccgcccccgccaggcccgctgcgacgccgacaggatctagcgctgcgtttggtgtcaacaccaacagcgccacgcccgcagttccgcaaatagcccccaggaccgccatcaatcgtatcgggctacctagcagagcggcagagatgaacacgaccatcagcggctgcacagcgcctaccgtcgccgcgaccccgcccggcaggcggtagaccgaaataaacaacaagctccagaatagcgaaatattaagtgcgccgaggatgaagatgcgcatccaccagattcccgttggaatctgtcggacgatcatcacgagcaataaacccgccggcaacgcccgcagcagcataccggcgacccctcggcctcgctgttcgggctccacgaaaacgccggacagatgcgccttgtgagcgtccttggggccgtcctcctgtttgaagaccgacagcccaatgatctcgccgtcgatgtaggcgccgaatgccacggcatctcgcaaccgttcagcgaacgcctccatgggctttttctcctcgtgctcgtaaacggacccgaacatctctggagctttcttcagggccgacaatcggatctcgcggaaatcctgcacgtcggccgctccaagccgtcgaatctgagccttaatcacaattgtcaattttaatcctctgtttatcggcagttcgtagagcgcgccgtgcgtcccgagcgatactgagcgaagcaagtgcgtcgagcagtgcccgcttgttcctgaaatgccagtaaagcgctggctgctgaacccccagccggaactgaccccacaaggccctagcgtttgcaatgcaccaggtcatcattgacccaggcgtgttccaccaggccgctgcctcgcaactcttcgcaggcttcgccgacctgctcgcgccacttcttcacgcgggtggaatccgatccgcacatgaggcggaaggtttccagcttgagcgggtacggctcccggtgcgagctgaaatagtcgaacatccgtcgggccgtcggcgacagcttgcggtacttctcccatatgaatttcgtgtagtggtcgccagcaaacagcacgacgatttcctcgtcgatcaggacctggcaacgggacgttttcttgccacggtccaggacgcggaagcggtgcagcagcgacaccgattccaggtgcccaacgcggtcggacgtgaagcccatcgccgtcgcctgtaggcgcgacaggcattcctcggccttcgtgtaataccggccattgatcgaccagcccaggtcctggcaaagctcgtagaacgtgaaggtgatcggctcgccgataggggtgcgcttcgcgtactccaacacctgctgccacaccagttcgtcatcgtcggcccgcagctcgacgccggtgtaggtgatcttcacgtccttgttgacgtggaaaatgaccttgttttgcagcgcctcgcgcgggattttcttgttgcgcgtggtgaacagggcagagcgggccgtgtcgtttggcatcgctcgcatcgtgtccggccacggcgcaatatcgaacaaggaaagctgcatttccttgatctgctgcttcgtgtgtttcagcaacgcggcctgcttggcctcgctgacctgttttgccaggtcctcgccggcggtttttcgcttcttggtcgtcatagttcctcgcgtgtcgatggtcatcgacttcgccaaacctgccgcctcctgttcgagacgacgcgaacgctccacggcggccgatggcgcgggcagggcagggggagccagttgcacgctgtcgcgctcgatcttggccgtagcttgctggaccatcgagccgacggactggaaggtttcgcggggcgcacgcatgacggtgcggcttgcgatggtttcggcatcctcggcggaaaaccccgcgtcgatcagttcttgcctgtatgccttccggtcaaacgtccgattcattcaccctccttgcgggattgccccgactcacgccggggcaatgtgcccttattcctgatttgacccgcctggtgccttggtgtccagataatccaccttatcggcaatgaagtcggtcccgtagaccgtctggccgtccttctcgtacttggtattccgaatcttgccctgcacgaataccagcgaccccttgcccaaatacttgccgtgggcctcggcctgagagccaaaacacttgatgcggaagaagtcggtgcgctcctgcttgtcgccggcatcgttgcgccacatctaggtactaaaacaattcatccagtaaaatataatattttattttctcccaatcaggcttgatccccagtaagtcaaaaaatagctcgacatactgttcttccccgatatcctccctgatcgaccggacgcagaaggcaatgtcataccacttgtccgccctgccgcttctcccaagatcaataaagccacttactttgccatctttcacaaagatgttgctgtctcccaggtcgccgtgggaaaagacaagttcctcttcgggcttttccgtctttaaaaaatcatacagctcgcgcggatctttaaatggagtgtcttcttcccagttttcgcaatccacatcggccagatcgttattcagtaagtaatccaattcggctaagcggctgtctaagctattcgtatagggacaatccgatatgtcgatggagtgaaagagcctgatgcactccgcatacagctcgataatcttttcagggctttgttcatcttcatactcttccgagcaaaggacgccatcggcctcactcatgagcagattgctccagccatcatgccgttcaaagtgcaggacctttggaacaggcagctttccttccagccatagcatcatgtccttttcccgttccacatcataggtggtccctttataccggctgtccgtcatttttaaatataggttttcattttctcccaccagcttatataccttagcaggagacattccttccgtatcttttacgcagcggtatttttcgatcagttttttcaattccggtgatattctcattttagccatttattatttccttcctcttttctacagtatttaaagataccccaagaagctaattataacaagacgaactccaattcactgttccttgcattctaaaaccttaaataccagaaaacagctttttcaaagttgttttcaaagttggcgtataacatagtatcgacggagccgattttgaaaccacaattatgggtgatgctgccaacttactgatttagtgtatgatggtgtttttgaggtgctccagtggcttctgtgtctatcagctgtccctcctgttcagctactgacggggtggtgcgtaacggcaaaagcaccgccggacatcagcgctatctctgctctcactgccgtaaaacatggcaactgcagttcacttacaccgcttctcaacccggtacgcaccagaaaatcattgatatggccatgaatggcgttggatgccgggcaacagcccgcattatgggcgttggcctcaacacgattttacgtcacttaaaaaactcaggccgcagtcggtaacctcgcgcatacagccgggcagtgacgtcatcgtctgcgcggaaatggacgaacagtggggctatgtcggggctaaatcgcgccagcgctggctgttttacgcgtatgacagtctccggaagacggttgttgcgcacgtattcggtgaacgcactatggcgacgctggggcgtcttatgagcctgctgtcaccctttgacgtggtgatatggatgacggatggctggccgctgtatgaatcccgcctgaagggaaagctgcacgtaatcagcaagcgatatacgcagcgaattgagcggcataacctgaatctgaggcagcacctggcacggctgggacggaagtcgctgtcgttctcaaaatcggtggagctgcatgacaaagtcatcgggcattatctgaacataaaacactatcaataagttggagtcattacccaattatgatagaatttacaagctataaggttattgtcctgggtttcaagcattagtccatgcaagtttttatgctttgcccattctatagatatattgataagcgcgctgcctatgccttgccccctgaaatccttacatacggcgatatcttctatataaaagatatattatcttatcagtattgtcaatatattcaaggcaatctgcctcctcatcctcttcatcctcttcgtcttggtagctttttaaatatggcgcttcatagagtaattctgtaaaggtccaattctcgttttcatacctcggtataatcttacctatcacctcaaatggttcgctgggtttatcgcacccccgaacacgagcacggcacccgcgaccactatgccaagaatgcccaaggtaaaaattgccggccccgccatgaagtccgtgaatgccccgacggccgaagtgaagggcaggccgccacccaggccgccgccctcactgcccggcacctggtcgctgaatgtcgatgccagcacctgcggcacgtcaatgcttccgggcgtcgcgctcgggctgatcgcccatcccgttactgccccgatcccggcaatggcaaggactgccagcgctgccatttttggggtgaggccgttcgcggccgaggggcgcagcccctggggggatgggaggcccgcgttagcgggccgggagggttcgagaagggggggcaccccccttcggcgtgcgcggtcacgcgcacagggcgcagccctggttaaaaacaaggtttataaatattggtttaaaagcaggttaaaagacaggttagcggtggccgaaaaacgggcggaaacccttgcaaatgctggattttctgcctgtggacagcccctcaaatgtcaataggtgcgcccctcatctgtcagcactctgcccctcaagtgtcaaggatcgcgcccctcatctgtcagtagtcgcgcccctcaagtgtcaataccgcagggcacttatccccaggcttgtccacatcatctgtgggaaactcgcgtaaaatcaggcgttttcgccgatttgcgaggctggccagctccacgtcgccggccgaaatcgagcctgcccctcatctgtcaacgccgcgccgggtgagtcggcccctcaagtgtcaacgtccgcccctcatctgtcagtgagggccaagttttccgcgaggtatccacaacgccggcggccgcggtgtctcgcacacggcttcgacggcgtttctggcgcgtttgcagggccatagacggccgccagcccagcggcgagggcaaccagcccgg - - - - diff --git a/node_modules/azure-storage/package.json b/node_modules/azure-storage/package.json deleted file mode 100644 index 9e6e68863..000000000 --- a/node_modules/azure-storage/package.json +++ /dev/null @@ -1,133 +0,0 @@ -{ - "_from": "azure-storage@2.8.2", - "_id": "azure-storage@2.8.2", - "_inBundle": false, - "_integrity": "sha1-GctjKx5WMK6uVEUaZNrBYLFlyEg=", - "_location": "/azure-storage", - "_phantomChildren": { - "aws-sign2": "0.7.0", - "aws4": "1.6.0", - "caseless": "0.12.0", - "combined-stream": "1.0.5", - "forever-agent": "0.6.1", - "form-data": "2.3.1", - "har-validator": "5.0.3", - "hawk": "6.0.2", - "http-signature": "1.2.0", - "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": "2.1.0", - "qs": "6.5.1", - "safe-buffer": "5.1.1", - "sax": "0.5.2", - "stringstream": "0.0.5", - "tough-cookie": "2.3.3", - "tunnel-agent": "0.6.0", - "uuid": "3.1.0" - }, - "_requested": { - "type": "version", - "registry": true, - "raw": "azure-storage@2.8.2", - "name": "azure-storage", - "escapedName": "azure-storage", - "rawSpec": "2.8.2", - "saveSpec": null, - "fetchSpec": "2.8.2" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/azure-storage/-/azure-storage-2.8.2.tgz", - "_shasum": "19cb632b1e5630aeae54451a64dac160b165c848", - "_spec": "azure-storage@2.8.2", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot", - "author": { - "name": "Microsoft Corporation" - }, - "bugs": { - "url": "http://github.com/Azure/azure-storage-node/issues" - }, - "bundleDependencies": false, - "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.83.0", - "underscore": "~1.8.3", - "uuid": "^3.0.0", - "validator": "~9.4.1", - "xml2js": "0.2.8", - "xmlbuilder": "0.4.3" - }, - "deprecated": false, - "description": "Microsoft Azure Storage Client Library for Node.js", - "devDependencies": { - "batchflow": "0.4.0", - "browserify": "^16.1.1", - "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", - "karma": "^2.0.0", - "karma-chrome-launcher": "^2.2.0", - "karma-edge-launcher": "^0.4.2", - "karma-env-preprocessor": "^0.1.1", - "karma-firefox-launcher": "^1.1.0", - "karma-ie-launcher": "^1.0.0", - "karma-mocha": "^1.3.0", - "karma-mocha-reporter": "^2.2.5", - "mocha": ">= 1.18.0", - "mocha-lcov-reporter": "^1.0.0", - "nock": "0.16", - "nsp": "^2.2.0", - "should": "1.2.x", - "uglify-js": "~3.3.9", - "watchify": "^3.11.0" - }, - "engines": { - "node": ">= 0.8.26" - }, - "homepage": "http://github.com/Azure/azure-storage-node", - "keywords": [ - "node", - "azure", - "storage" - ], - "license": "Apache-2.0", - "main": "./lib/azure-storage.js", - "name": "azure-storage", - "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", - "jstest": "npm run genjs && node ./browser/test/bundle.js && karma start --single-run", - "test": "jshint lib && nsp check && mocha --no-timeouts --recursive test" - }, - "tags": [ - "azure", - "storage", - "sdk" - ], - "typings": "typings/azure-storage/azure-storage.d.ts", - "version": "2.8.2" -} diff --git a/node_modules/azure-storage/tsconfig.json b/node_modules/azure-storage/tsconfig.json deleted file mode 100644 index 7141a7fa5..000000000 --- a/node_modules/azure-storage/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "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 deleted file mode 100644 index 91b516347..000000000 --- a/node_modules/azure-storage/typings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "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 deleted file mode 100644 index 6bb4dd4ad..000000000 --- a/node_modules/azure-storage/typings/azure-storage/azure-storage.d.ts +++ /dev/null @@ -1,9521 +0,0 @@ -// -// 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 {Readable} A Node.js Readable 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 {Writable} writeStream The Node.js Writable 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 {Writable} writeStream The Node.js Writable 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. - * @param {string} [snapshotId] The snapshot identifier. - * @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, snapshotId?: string): 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 {Writable} A Node.js Writable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Writable} A Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {string} [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 {Readable} A Node.js Readable 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 {Writable} writeStream The Node.js Writable 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 {Readable} readStream The Node.js Readable 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 {Writable} A Node.js Writable 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 {Writable} A Node.js Writable 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 deleted file mode 100644 index af29a7118..000000000 --- a/node_modules/azure-storage/typings/globals/node/index.d.ts +++ /dev/null @@ -1,1440 +0,0 @@ -// 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 deleted file mode 100644 index 24054ce08..000000000 --- a/node_modules/azure-storage/typings/globals/node/typings.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "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 deleted file mode 100644 index 22e4de57a..000000000 --- a/node_modules/azure-storage/typings/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// diff --git a/node_modules/bcrypt-pbkdf/README.md b/node_modules/bcrypt-pbkdf/README.md deleted file mode 100644 index 12018090b..000000000 --- a/node_modules/bcrypt-pbkdf/README.md +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index b1b5ad4b7..000000000 --- a/node_modules/bcrypt-pbkdf/index.js +++ /dev/null @@ -1,556 +0,0 @@ -'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 deleted file mode 100644 index e1dea6112..000000000 --- a/node_modules/bcrypt-pbkdf/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "_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/LICENSE b/node_modules/boom/LICENSE deleted file mode 100644 index 94b91cbf0..000000000 --- a/node_modules/boom/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2012-2017, Project contributors. -Copyright (c) 2012-2014, Walmart. -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 diff --git a/node_modules/boom/README.md b/node_modules/boom/README.md deleted file mode 100644 index 6452491b9..000000000 --- a/node_modules/boom/README.md +++ /dev/null @@ -1,760 +0,0 @@ -![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.svg)](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](#boom) - - [Helper Methods](#helper-methods) - - [`wrap(error, [statusCode], [message])`](#wraperror-statuscode-message) - - [`create(statusCode, [message], [data])`](#createstatuscode-message-data) - - [HTTP 4xx Errors](#http-4xx-errors) - - [`Boom.badRequest([message], [data])`](#boombadrequestmessage-data) - - [`Boom.unauthorized([message], [scheme], [attributes])`](#boomunauthorizedmessage-scheme-attributes) - - [`Boom.paymentRequired([message], [data])`](#boompaymentrequiredmessage-data) - - [`Boom.forbidden([message], [data])`](#boomforbiddenmessage-data) - - [`Boom.notFound([message], [data])`](#boomnotfoundmessage-data) - - [`Boom.methodNotAllowed([message], [data], [allow])`](#boommethodnotallowedmessage-data-allow) - - [`Boom.notAcceptable([message], [data])`](#boomnotacceptablemessage-data) - - [`Boom.proxyAuthRequired([message], [data])`](#boomproxyauthrequiredmessage-data) - - [`Boom.clientTimeout([message], [data])`](#boomclienttimeoutmessage-data) - - [`Boom.conflict([message], [data])`](#boomconflictmessage-data) - - [`Boom.resourceGone([message], [data])`](#boomresourcegonemessage-data) - - [`Boom.lengthRequired([message], [data])`](#boomlengthrequiredmessage-data) - - [`Boom.preconditionFailed([message], [data])`](#boompreconditionfailedmessage-data) - - [`Boom.entityTooLarge([message], [data])`](#boomentitytoolargemessage-data) - - [`Boom.uriTooLong([message], [data])`](#boomuritoolongmessage-data) - - [`Boom.unsupportedMediaType([message], [data])`](#boomunsupportedmediatypemessage-data) - - [`Boom.rangeNotSatisfiable([message], [data])`](#boomrangenotsatisfiablemessage-data) - - [`Boom.expectationFailed([message], [data])`](#boomexpectationfailedmessage-data) - - [`Boom.teapot([message], [data])`](#boomteapotmessage-data) - - [`Boom.badData([message], [data])`](#boombaddatamessage-data) - - [`Boom.locked([message], [data])`](#boomlockedmessage-data) - - [`Boom.preconditionRequired([message], [data])`](#boompreconditionrequiredmessage-data) - - [`Boom.tooManyRequests([message], [data])`](#boomtoomanyrequestsmessage-data) - - [`Boom.illegal([message], [data])`](#boomillegalmessage-data) - - [HTTP 5xx Errors](#http-5xx-errors) - - [`Boom.badImplementation([message], [data])` - (*alias: `internal`*)](#boombadimplementationmessage-data---alias-internal) - - [`Boom.notImplemented([message], [data])`](#boomnotimplementedmessage-data) - - [`Boom.badGateway([message], [data])`](#boombadgatewaymessage-data) - - [`Boom.serverUnavailable([message], [data])`](#boomserverunavailablemessage-data) - - [`Boom.gatewayTimeout([message], [data])`](#boomgatewaytimeoutmessage-data) - - [F.A.Q.](#faq) - - - -# Boom - -**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. - -## 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 `scheme` 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. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. - `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(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4='); -``` - -Generates the following response: - -```json -"payload": { - "statusCode": 401, - "error": "Unauthorized", - "attributes": "VGhpcyBpcyBhIHRlc3QgdG9rZW4=" -}, -"headers" { - "WWW-Authenticate": "Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4=" -} -``` - -```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.paymentRequired([message], [data])` - -Returns a 402 Payment Required error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.paymentRequired('bandwidth used'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 402, - "error": "Payment Required", - "message": "bandwidth used" -} -``` - -### `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], [allow])` - -Returns a 405 Method Not Allowed error where: -- `message` - optional message. -- `data` - optional additional error data. -- `allow` - optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header. - -```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.teapot([message], [data])` - -Returns a 418 I'm a Teapot error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.teapot('sorry, no coffee...'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 418, - "error": "I'm a Teapot", - "message": "Sorry, no coffee..." -} -``` - -### `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.locked([message], [data])` - -Returns a 423 Locked error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.locked('this resource has been locked'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 423, - "error": "Locked", - "message": "this resource has been locked" -} -``` - -### `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" -} -``` - -### `Boom.illegal([message], [data])` - -Returns a 451 Unavailable For Legal Reasons error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.illegal('you are not permitted to view this resource for legal reasons'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 451, - "error": "Unavailable For Legal Reasons", - "message": "you are not permitted to view this resource for legal reasons" -} -``` - -## 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])` - (*alias: `internal`*) - -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.serverUnavailable([message], [data])` - -Returns a 503 Service Unavailable error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.serverUnavailable('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. - -**Q** How do I include extra information in my responses? `output.payload` is missing `data`, what gives? - -**A** 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/lib/index.js b/node_modules/boom/lib/index.js deleted file mode 100644 index 17ed0279e..000000000 --- a/node_modules/boom/lib/index.js +++ /dev/null @@ -1,433 +0,0 @@ -'use strict'; - -// Load modules - -const Hoek = require('hoek'); - - -// Declare internals - -const internals = { - STATUS_CODES: Object.setPrototypeOf({ - '100': 'Continue', - '101': 'Switching Protocols', - '102': 'Processing', - '200': 'OK', - '201': 'Created', - '202': 'Accepted', - '203': 'Non-Authoritative Information', - '204': 'No Content', - '205': 'Reset Content', - '206': 'Partial Content', - '207': 'Multi-Status', - '300': 'Multiple Choices', - '301': 'Moved Permanently', - '302': 'Moved Temporarily', - '303': 'See Other', - '304': 'Not Modified', - '305': 'Use Proxy', - '307': 'Temporary Redirect', - '400': 'Bad Request', - '401': 'Unauthorized', - '402': 'Payment Required', - '403': 'Forbidden', - '404': 'Not Found', - '405': 'Method Not Allowed', - '406': 'Not Acceptable', - '407': 'Proxy Authentication Required', - '408': 'Request Time-out', - '409': 'Conflict', - '410': 'Gone', - '411': 'Length Required', - '412': 'Precondition Failed', - '413': 'Request Entity Too Large', - '414': 'Request-URI Too Large', - '415': 'Unsupported Media Type', - '416': 'Requested Range Not Satisfiable', - '417': 'Expectation Failed', - '418': 'I\'m a teapot', - '422': 'Unprocessable Entity', - '423': 'Locked', - '424': 'Failed Dependency', - '425': 'Unordered Collection', - '426': 'Upgrade Required', - '428': 'Precondition Required', - '429': 'Too Many Requests', - '431': 'Request Header Fields Too Large', - '451': 'Unavailable For Legal Reasons', - '500': 'Internal Server Error', - '501': 'Not Implemented', - '502': 'Bad Gateway', - '503': 'Service Unavailable', - '504': 'Gateway Time-out', - '505': 'HTTP Version Not Supported', - '506': 'Variant Also Negotiates', - '507': 'Insufficient Storage', - '509': 'Bandwidth Limit Exceeded', - '510': 'Not Extended', - '511': 'Network Authentication Required' - }, null) -}; - - -exports.wrap = function (error, statusCode, message) { - - Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object'); - Hoek.assert(!error.isBoom || (!statusCode && !message), 'Cannot provide statusCode or message with boom error'); - - return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message)); -}; - - -exports.create = function (statusCode, message, data) { - - return internals.create(statusCode, message, data, exports.create); -}; - - -internals.create = function (statusCode, message, data, ctor) { - - if (message instanceof Error) { - if (data) { - message.data = data; - } - return exports.wrap(message, statusCode); - } - - const error = new Error(message ? message : undefined); // Avoids settings null message - Error.captureStackTrace(error, ctor); // Filter the stack to our external API - error.data = data || null; - internals.initialize(error, statusCode); - return error; -}; - - -internals.initialize = function (error, statusCode, message) { - - const numberCode = parseInt(statusCode, 10); - Hoek.assert(!isNaN(numberCode) && numberCode >= 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 = internals.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[]) - - const err = internals.create(401, message, undefined, exports.unauthorized); - - if (!scheme) { - return err; - } - - let wwwAuthenticate = ''; - - if (typeof scheme === 'string') { - - // function (message, scheme, attributes) - - wwwAuthenticate = scheme; - - if (attributes || message) { - err.output.payload.attributes = {}; - } - - if (attributes) { - if (typeof attributes === 'string') { - wwwAuthenticate = wwwAuthenticate + ' ' + Hoek.escapeHeaderAttribute(attributes); - err.output.payload.attributes = attributes; - } - else { - const names = Object.keys(attributes); - for (let i = 0; i < names.length; ++i) { - const name = names[i]; - if (i) { - wwwAuthenticate = wwwAuthenticate + ','; - } - - let value = attributes[name]; - if (value === null || - value === undefined) { // Value can be zero - - value = ''; - } - wwwAuthenticate = wwwAuthenticate + ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"'; - err.output.payload.attributes[name] = value; - } - } - } - - - if (message) { - if (attributes) { - wwwAuthenticate = wwwAuthenticate + ','; - } - wwwAuthenticate = wwwAuthenticate + ' error="' + Hoek.escapeHeaderAttribute(message) + '"'; - err.output.payload.attributes.error = message; - } - else { - err.isMissing = true; - } - } - else { - - // function (message, wwwAuthenticate[]) - - const wwwArray = scheme; - for (let i = 0; i < wwwArray.length; ++i) { - if (i) { - wwwAuthenticate = wwwAuthenticate + ', '; - } - - wwwAuthenticate = wwwAuthenticate + wwwArray[i]; - } - } - - err.output.headers['WWW-Authenticate'] = wwwAuthenticate; - - return err; -}; - - -exports.paymentRequired = function (message, data) { - - return internals.create(402, message, data, exports.paymentRequired); -}; - - -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, allow) { - - const err = internals.create(405, message, data, exports.methodNotAllowed); - - if (typeof allow === 'string') { - allow = [allow]; - } - - if (Array.isArray(allow)) { - err.output.headers.Allow = allow.join(', '); - } - - return err; -}; - - -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.teapot = function (message, data) { - - return internals.create(418, message, data, exports.teapot); -}; - - -exports.badData = function (message, data) { - - return internals.create(422, message, data, exports.badData); -}; - - -exports.locked = function (message, data) { - - return internals.create(423, message, data, exports.locked); -}; - - -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); -}; - - -exports.illegal = function (message, data) { - - return internals.create(451, message, data, exports.illegal); -}; - - -// 5xx Server Errors - -exports.internal = function (message, data, statusCode) { - - return internals.serverError(message, data, statusCode, exports.internal); -}; - - -internals.serverError = function (message, data, statusCode, ctor) { - - let 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.serverUnavailable = function (message, data) { - - return internals.serverError(message, data, 503, exports.serverUnavailable); -}; - - -exports.gatewayTimeout = function (message, data) { - - return internals.serverError(message, data, 504, exports.gatewayTimeout); -}; - - -exports.badImplementation = function (message, data) { - - const 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 deleted file mode 100644 index f24a637e7..000000000 --- a/node_modules/boom/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "_args": [ - [ - "boom@4.3.1", - "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot" - ] - ], - "_from": "boom@4.3.1", - "_id": "boom@4.3.1", - "_inBundle": false, - "_integrity": "sha1-T4owBctKfjiJ90kDD9JbluAdLjE=", - "_location": "/boom", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "boom@4.3.1", - "name": "boom", - "escapedName": "boom", - "rawSpec": "4.3.1", - "saveSpec": null, - "fetchSpec": "4.3.1" - }, - "_requiredBy": [ - "/hawk" - ], - "_resolved": "https://registry.npmjs.org/boom/-/boom-4.3.1.tgz", - "_spec": "4.3.1", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot", - "bugs": { - "url": "https://github.com/hapijs/boom/issues" - }, - "dependencies": { - "hoek": "4.x.x" - }, - "description": "HTTP-friendly error objects", - "devDependencies": { - "code": "4.x.x", - "lab": "13.x.x", - "markdown-toc": "0.12.x" - }, - "engines": { - "node": ">=4.0.0" - }, - "homepage": "https://github.com/hapijs/boom#readme", - "keywords": [ - "error", - "http" - ], - "license": "BSD-3-Clause", - "main": "lib/index.js", - "name": "boom", - "repository": { - "type": "git", - "url": "git://github.com/hapijs/boom.git" - }, - "scripts": { - "test": "lab -a code -t 100 -L -v", - "test-cov-html": "lab -a code -r html -o coverage.html -L", - "toc": "node generate-toc.js", - "version": "npm run toc && git add README.md" - }, - "version": "4.3.1" -} diff --git a/node_modules/browserify-mime/.npmignore b/node_modules/browserify-mime/.npmignore deleted file mode 100644 index e2385fa8b..000000000 --- a/node_modules/browserify-mime/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -types -generate.js -main.js diff --git a/node_modules/browserify-mime/LICENSE b/node_modules/browserify-mime/LICENSE deleted file mode 100644 index 451fc4550..000000000 --- a/node_modules/browserify-mime/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index b90552a3b..000000000 --- a/node_modules/browserify-mime/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# mime - -Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. - -## Install - -Install with [npm](http://github.com/isaacs/npm): - - npm install mime - -## API - Queries - -### mime.lookup(path) -Get the mime type associated with a file. 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 deleted file mode 100644 index d24bdbe03..000000000 --- a/node_modules/browserify-mime/browserify-mime.js +++ /dev/null @@ -1,1813 +0,0 @@ -//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 deleted file mode 100644 index 8a7eb093f..000000000 --- a/node_modules/browserify-mime/mime.js +++ /dev/null @@ -1,114 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); - - // Map of mime type -> extension - this.extensions = Object.create(null); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - - for (var i = 0; i < exts.length; i++) { - if (process.env.DEBUG_MIME && this.types[exts]) { - console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + - this.types[exts] + ' to ' + type); - } - - this.types[exts[i]] = type; - } - - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; - -/** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ -Mime.prototype.load = function(file) { - - this._loading = file; - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - this.define(map); - - this._loading = null; -}; - -/** - * Lookup a mime type based on extension - */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/.*[\.\/]/, '').toLowerCase(); - - return this.types[ext] || fallback || this.default_type; -}; - -/** - * Return file extension associated with a mime type - */ -Mime.prototype.extension = function(mimeType) { - var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); - return this.extensions[type]; -}; - -// Default instance -var mime = new Mime(); - -// Load local copy of -// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); - -// Load additional types from node.js community -mime.load(path.join(__dirname, 'types/node.types')); - -// Default type -mime.default_type = mime.lookup('bin'); - -// -// Additional API specific to the default instance -// - -mime.Mime = Mime; - -/** - * Lookup a charset based on mime type. - */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; - } -}; - -module.exports = mime; diff --git a/node_modules/browserify-mime/package.json b/node_modules/browserify-mime/package.json deleted file mode 100644 index b598f77c8..000000000 --- a/node_modules/browserify-mime/package.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "_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 deleted file mode 100644 index 1932ce74f..000000000 --- a/node_modules/browserify-mime/test.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 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 deleted file mode 100644 index 61789f4a4..000000000 --- a/node_modules/caseless/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -1. Definitions. -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: -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 deleted file mode 100644 index e5077a216..000000000 --- a/node_modules/caseless/README.md +++ /dev/null @@ -1,45 +0,0 @@ -## 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 deleted file mode 100644 index b194734ee..000000000 --- a/node_modules/caseless/index.js +++ /dev/null @@ -1,67 +0,0 @@ -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 deleted file mode 100644 index f55196cc0..000000000 --- a/node_modules/caseless/test.js +++ /dev/null @@ -1,67 +0,0 @@ -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 deleted file mode 100644 index 68fbb154d..000000000 --- a/node_modules/co/History.md +++ /dev/null @@ -1,172 +0,0 @@ -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 deleted file mode 100644 index 92faba5db..000000000 --- a/node_modules/co/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(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 deleted file mode 100644 index c1d4882a1..000000000 --- a/node_modules/co/Readme.md +++ /dev/null @@ -1,212 +0,0 @@ -# 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 deleted file mode 100644 index 87ba8ba8b..000000000 --- a/node_modules/co/index.js +++ /dev/null @@ -1,237 +0,0 @@ - -/** - * 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 deleted file mode 100644 index b8e97f5db..000000000 --- a/node_modules/co/package.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "_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 deleted file mode 100644 index 4804b7ab4..000000000 --- a/node_modules/combined-stream/License +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 3a9e025fb..000000000 --- a/node_modules/combined-stream/Readme.md +++ /dev/null @@ -1,138 +0,0 @@ -# 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 deleted file mode 100644 index 6b5c21b6b..000000000 --- a/node_modules/combined-stream/lib/combined_stream.js +++ /dev/null @@ -1,188 +0,0 @@ -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 deleted file mode 100644 index bfdf8aa04..000000000 --- a/node_modules/combined-stream/package.json +++ /dev/null @@ -1,94 +0,0 @@ -{ - "_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 deleted file mode 100644 index d8d7f9437..000000000 --- a/node_modules/core-util-is/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b4149..000000000 --- a/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c05f..000000000 --- a/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js deleted file mode 100644 index ff4c851c0..000000000 --- a/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json deleted file mode 100644 index 9ed0a5bd0..000000000 --- a/node_modules/core-util-is/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_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 deleted file mode 100644 index 1a490c65a..000000000 --- a/node_modules/core-util-is/test.js +++ /dev/null @@ -1,68 +0,0 @@ -var assert = require('tap'); - -var t = require('./lib/util'); - -assert.equal(t.isArray([]), true); -assert.equal(t.isArray({}), false); - -assert.equal(t.isBoolean(null), false); -assert.equal(t.isBoolean(true), true); -assert.equal(t.isBoolean(false), true); - -assert.equal(t.isNull(null), true); -assert.equal(t.isNull(undefined), false); -assert.equal(t.isNull(false), false); -assert.equal(t.isNull(), false); - -assert.equal(t.isNullOrUndefined(null), true); -assert.equal(t.isNullOrUndefined(undefined), true); -assert.equal(t.isNullOrUndefined(false), false); -assert.equal(t.isNullOrUndefined(), true); - -assert.equal(t.isNumber(null), false); -assert.equal(t.isNumber('1'), false); -assert.equal(t.isNumber(1), true); - -assert.equal(t.isString(null), false); -assert.equal(t.isString('1'), true); -assert.equal(t.isString(1), false); - -assert.equal(t.isSymbol(null), false); -assert.equal(t.isSymbol('1'), false); -assert.equal(t.isSymbol(1), false); -assert.equal(t.isSymbol(Symbol()), true); - -assert.equal(t.isUndefined(null), false); -assert.equal(t.isUndefined(undefined), true); -assert.equal(t.isUndefined(false), false); -assert.equal(t.isUndefined(), true); - -assert.equal(t.isRegExp(null), false); -assert.equal(t.isRegExp('1'), false); -assert.equal(t.isRegExp(new RegExp()), true); - -assert.equal(t.isObject({}), true); -assert.equal(t.isObject([]), true); -assert.equal(t.isObject(new RegExp()), true); -assert.equal(t.isObject(new Date()), true); - -assert.equal(t.isDate(null), false); -assert.equal(t.isDate('1'), false); -assert.equal(t.isDate(new Date()), true); - -assert.equal(t.isError(null), false); -assert.equal(t.isError({ err: true }), false); -assert.equal(t.isError(new Error()), true); - -assert.equal(t.isFunction(null), false); -assert.equal(t.isFunction({ }), false); -assert.equal(t.isFunction(function() {}), true); - -assert.equal(t.isPrimitive(null), true); -assert.equal(t.isPrimitive(''), true); -assert.equal(t.isPrimitive(0), true); -assert.equal(t.isPrimitive(new Date()), false); - -assert.equal(t.isBuffer(null), false); -assert.equal(t.isBuffer({}), false); -assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/cryptiles/.npmignore b/node_modules/cryptiles/.npmignore deleted file mode 100644 index adac8ad9c..000000000 --- a/node_modules/cryptiles/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!lib/** -!.npmignore diff --git a/node_modules/cryptiles/LICENSE b/node_modules/cryptiles/LICENSE deleted file mode 100644 index 4028ccd3f..000000000 --- a/node_modules/cryptiles/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2014-2017, Eran Hammer and Project 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 deleted file mode 100644 index b3df9e67f..000000000 --- a/node_modules/cryptiles/README.md +++ /dev/null @@ -1,19 +0,0 @@ -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. - -### `randomDigits( size)` -Returns a cryptographically strong pseudo-random data string consisting of only numerical digits (0-9). 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 deleted file mode 100644 index 511eab66d..000000000 --- a/node_modules/cryptiles/lib/index.js +++ /dev/null @@ -1,88 +0,0 @@ -'use strict'; - -// Load modules - -const Crypto = require('crypto'); -const Boom = require('boom'); - - -// Declare internals - -const internals = {}; - - -// Generate a cryptographically strong pseudo-random data - -exports.randomString = function (size) { - - const buffer = exports.randomBits((size + 1) * 6); - if (buffer instanceof Error) { - return buffer; - } - - const string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); - return string.slice(0, size); -}; - - -// Return a random string of digits - -exports.randomDigits = function (size) { - - const buffer = exports.randomBits(size * 8); - if (buffer instanceof Error) { - return buffer; - } - - const digits = []; - for (let i = 0; i < buffer.length; ++i) { - digits.push(Math.floor(buffer[i] / 25.6)); - } - - return digits.join(''); -}; - - -// Generate a buffer of random bits - -exports.randomBits = function (bits) { - - if (!bits || - bits < 0) { - - return Boom.internal('Invalid random bits count'); - } - - const 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; - } - - let mismatch = (a.length === b.length ? 0 : 1); - if (mismatch) { - b = a; - } - - for (let i = 0; i < a.length; ++i) { - const ac = a.charCodeAt(i); - const bc = b.charCodeAt(i); - mismatch |= (ac ^ bc); - } - - return (mismatch === 0); -}; diff --git a/node_modules/cryptiles/node_modules/boom/LICENSE b/node_modules/cryptiles/node_modules/boom/LICENSE deleted file mode 100644 index 94b91cbf0..000000000 --- a/node_modules/cryptiles/node_modules/boom/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2012-2017, Project contributors. -Copyright (c) 2012-2014, Walmart. -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 diff --git a/node_modules/cryptiles/node_modules/boom/README.md b/node_modules/cryptiles/node_modules/boom/README.md deleted file mode 100644 index 50d5b0d7d..000000000 --- a/node_modules/cryptiles/node_modules/boom/README.md +++ /dev/null @@ -1,784 +0,0 @@ -![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.svg)](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](#boom) - - [Helper Methods](#helper-methods) - - [`boomify(error, [options])`](#boomifyerror-options) - - [`wrap(error, [statusCode], [message])`](#wraperror-statuscode-message) - - [`create(statusCode, [message], [data])`](#createstatuscode-message-data) - - [HTTP 4xx Errors](#http-4xx-errors) - - [`Boom.badRequest([message], [data])`](#boombadrequestmessage-data) - - [`Boom.unauthorized([message], [scheme], [attributes])`](#boomunauthorizedmessage-scheme-attributes) - - [`Boom.paymentRequired([message], [data])`](#boompaymentrequiredmessage-data) - - [`Boom.forbidden([message], [data])`](#boomforbiddenmessage-data) - - [`Boom.notFound([message], [data])`](#boomnotfoundmessage-data) - - [`Boom.methodNotAllowed([message], [data], [allow])`](#boommethodnotallowedmessage-data-allow) - - [`Boom.notAcceptable([message], [data])`](#boomnotacceptablemessage-data) - - [`Boom.proxyAuthRequired([message], [data])`](#boomproxyauthrequiredmessage-data) - - [`Boom.clientTimeout([message], [data])`](#boomclienttimeoutmessage-data) - - [`Boom.conflict([message], [data])`](#boomconflictmessage-data) - - [`Boom.resourceGone([message], [data])`](#boomresourcegonemessage-data) - - [`Boom.lengthRequired([message], [data])`](#boomlengthrequiredmessage-data) - - [`Boom.preconditionFailed([message], [data])`](#boompreconditionfailedmessage-data) - - [`Boom.entityTooLarge([message], [data])`](#boomentitytoolargemessage-data) - - [`Boom.uriTooLong([message], [data])`](#boomuritoolongmessage-data) - - [`Boom.unsupportedMediaType([message], [data])`](#boomunsupportedmediatypemessage-data) - - [`Boom.rangeNotSatisfiable([message], [data])`](#boomrangenotsatisfiablemessage-data) - - [`Boom.expectationFailed([message], [data])`](#boomexpectationfailedmessage-data) - - [`Boom.teapot([message], [data])`](#boomteapotmessage-data) - - [`Boom.badData([message], [data])`](#boombaddatamessage-data) - - [`Boom.locked([message], [data])`](#boomlockedmessage-data) - - [`Boom.preconditionRequired([message], [data])`](#boompreconditionrequiredmessage-data) - - [`Boom.tooManyRequests([message], [data])`](#boomtoomanyrequestsmessage-data) - - [`Boom.illegal([message], [data])`](#boomillegalmessage-data) - - [HTTP 5xx Errors](#http-5xx-errors) - - [`Boom.badImplementation([message], [data])` - (*alias: `internal`*)](#boombadimplementationmessage-data---alias-internal) - - [`Boom.notImplemented([message], [data])`](#boomnotimplementedmessage-data) - - [`Boom.badGateway([message], [data])`](#boombadgatewaymessage-data) - - [`Boom.serverUnavailable([message], [data])`](#boomserverunavailablemessage-data) - - [`Boom.gatewayTimeout([message], [data])`](#boomgatewaytimeoutmessage-data) - - [F.A.Q.](#faq) - - - -# Boom - -**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. -- `typeof` - the contructor used to create the error (e.g. `Boom.badRequest`). -- `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. - -## Helper Methods - -### `boomify(error, [options])` - -Decorates an error with the **boom** properties where: -- `error` - the `Error` object to decorate. -- `options` - optional object with the following optional settings: - - `statusCode` - the HTTP status code. Defaults to `500` if no status code is already set. - - `message` - error message string. If the error already has a message, the provided `message` is added as a prefix. - Defaults to no message. - - `override` - if `false`, the `error` provided is a **boom** object, and a `statusCode` or `message` are provided, - the values are ignored. Defaults to `true` (apply the provided `statusCode` and `message` options to the error - regardless of its type, `Error` or **boom** object). - -Note: This method replaces the [`wrap()`](#wraperror-statuscode-message) and changes the default behavior to override -existing **boom** objects with the provided status code and message. - -```js -var error = new Error('Unexpected input'); -Boom.boomify(error, { statusCode: 400 }); -``` - -### `wrap(error, [statusCode], [message])` - -Note: This method is deprecated. - -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 `scheme` 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. Alternatively value can be a string which is use to set the value of the scheme, for example setting the token value for negotiate header. If string is used message parameter must be null. - `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(null, 'Negotiate', 'VGhpcyBpcyBhIHRlc3QgdG9rZW4='); -``` - -Generates the following response: - -```json -"payload": { - "statusCode": 401, - "error": "Unauthorized", - "attributes": "VGhpcyBpcyBhIHRlc3QgdG9rZW4=" -}, -"headers" { - "WWW-Authenticate": "Negotiate VGhpcyBpcyBhIHRlc3QgdG9rZW4=" -} -``` - -```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.paymentRequired([message], [data])` - -Returns a 402 Payment Required error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.paymentRequired('bandwidth used'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 402, - "error": "Payment Required", - "message": "bandwidth used" -} -``` - -### `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], [allow])` - -Returns a 405 Method Not Allowed error where: -- `message` - optional message. -- `data` - optional additional error data. -- `allow` - optional string or array of strings (to be combined and separated by ', ') which is set to the 'Allow' header. - -```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.teapot([message], [data])` - -Returns a 418 I'm a Teapot error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.teapot('sorry, no coffee...'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 418, - "error": "I'm a Teapot", - "message": "Sorry, no coffee..." -} -``` - -### `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.locked([message], [data])` - -Returns a 423 Locked error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.locked('this resource has been locked'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 423, - "error": "Locked", - "message": "this resource has been locked" -} -``` - -### `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" -} -``` - -### `Boom.illegal([message], [data])` - -Returns a 451 Unavailable For Legal Reasons error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.illegal('you are not permitted to view this resource for legal reasons'); -``` - -Generates the following response payload: - -```json -{ - "statusCode": 451, - "error": "Unavailable For Legal Reasons", - "message": "you are not permitted to view this resource for legal reasons" -} -``` - -## 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])` - (*alias: `internal`*) - -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.serverUnavailable([message], [data])` - -Returns a 503 Service Unavailable error where: -- `message` - optional message. -- `data` - optional additional error data. - -```js -Boom.serverUnavailable('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. - -**Q** How do I include extra information in my responses? `output.payload` is missing `data`, what gives? - -**A** 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/cryptiles/node_modules/boom/lib/index.js b/node_modules/cryptiles/node_modules/boom/lib/index.js deleted file mode 100644 index c57c79d43..000000000 --- a/node_modules/cryptiles/node_modules/boom/lib/index.js +++ /dev/null @@ -1,457 +0,0 @@ -'use strict'; - -// Load modules - -const Hoek = require('hoek'); - - -// Declare internals - -const internals = { - STATUS_CODES: Object.setPrototypeOf({ - '100': 'Continue', - '101': 'Switching Protocols', - '102': 'Processing', - '200': 'OK', - '201': 'Created', - '202': 'Accepted', - '203': 'Non-Authoritative Information', - '204': 'No Content', - '205': 'Reset Content', - '206': 'Partial Content', - '207': 'Multi-Status', - '300': 'Multiple Choices', - '301': 'Moved Permanently', - '302': 'Moved Temporarily', - '303': 'See Other', - '304': 'Not Modified', - '305': 'Use Proxy', - '307': 'Temporary Redirect', - '400': 'Bad Request', - '401': 'Unauthorized', - '402': 'Payment Required', - '403': 'Forbidden', - '404': 'Not Found', - '405': 'Method Not Allowed', - '406': 'Not Acceptable', - '407': 'Proxy Authentication Required', - '408': 'Request Time-out', - '409': 'Conflict', - '410': 'Gone', - '411': 'Length Required', - '412': 'Precondition Failed', - '413': 'Request Entity Too Large', - '414': 'Request-URI Too Large', - '415': 'Unsupported Media Type', - '416': 'Requested Range Not Satisfiable', - '417': 'Expectation Failed', - '418': 'I\'m a teapot', - '422': 'Unprocessable Entity', - '423': 'Locked', - '424': 'Failed Dependency', - '425': 'Unordered Collection', - '426': 'Upgrade Required', - '428': 'Precondition Required', - '429': 'Too Many Requests', - '431': 'Request Header Fields Too Large', - '451': 'Unavailable For Legal Reasons', - '500': 'Internal Server Error', - '501': 'Not Implemented', - '502': 'Bad Gateway', - '503': 'Service Unavailable', - '504': 'Gateway Time-out', - '505': 'HTTP Version Not Supported', - '506': 'Variant Also Negotiates', - '507': 'Insufficient Storage', - '509': 'Bandwidth Limit Exceeded', - '510': 'Not Extended', - '511': 'Network Authentication Required' - }, null) -}; - - -exports.boomify = function (error, options) { - - Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object'); - - options = options || {}; - - if (!error.isBoom) { - return internals.initialize(error, options.statusCode || 500, options.message); - } - - if (options.override === false || // Defaults to true - (!options.statusCode && !options.message)) { - - return error; - } - - return internals.initialize(error, options.statusCode || error.output.statusCode, options.message); -}; - - -exports.wrap = function (error, statusCode, message) { - - Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object'); - Hoek.assert(!error.isBoom || (!statusCode && !message), 'Cannot provide statusCode or message with boom error'); - - return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message)); -}; - - -exports.create = function (statusCode, message, data) { - - return internals.create(statusCode, message, data, exports.create); -}; - - -internals.create = function (statusCode, message, data, ctor) { - - if (message instanceof Error) { - if (data) { - message.data = data; - } - - return exports.wrap(message, statusCode); - } - - const error = new Error(message ? message : undefined); // Avoids settings null message - Error.captureStackTrace(error, ctor); // Filter the stack to our external API - error.data = data || null; - internals.initialize(error, statusCode); - error.typeof = ctor; - - return error; -}; - - -internals.initialize = function (error, statusCode, message) { - - const numberCode = parseInt(statusCode, 10); - Hoek.assert(!isNaN(numberCode) && numberCode >= 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; - - if (!message && - !error.message) { - - error.reformat(); - message = error.output.payload.error; - } - - if (message) { - error.message = (message + (error.message ? ': ' + error.message : '')); - error.output.payload.message = error.message; - } - - error.reformat(); - return error; -}; - - -internals.reformat = function () { - - this.output.payload.statusCode = this.output.statusCode; - this.output.payload.error = internals.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[]) - - const err = internals.create(401, message, undefined, exports.unauthorized); - - if (!scheme) { - return err; - } - - let wwwAuthenticate = ''; - - if (typeof scheme === 'string') { - - // function (message, scheme, attributes) - - wwwAuthenticate = scheme; - - if (attributes || message) { - err.output.payload.attributes = {}; - } - - if (attributes) { - if (typeof attributes === 'string') { - wwwAuthenticate = wwwAuthenticate + ' ' + Hoek.escapeHeaderAttribute(attributes); - err.output.payload.attributes = attributes; - } - else { - const names = Object.keys(attributes); - for (let i = 0; i < names.length; ++i) { - const name = names[i]; - if (i) { - wwwAuthenticate = wwwAuthenticate + ','; - } - - let value = attributes[name]; - if (value === null || - value === undefined) { // Value can be zero - - value = ''; - } - wwwAuthenticate = wwwAuthenticate + ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"'; - err.output.payload.attributes[name] = value; - } - } - } - - - if (message) { - if (attributes) { - wwwAuthenticate = wwwAuthenticate + ','; - } - wwwAuthenticate = wwwAuthenticate + ' error="' + Hoek.escapeHeaderAttribute(message) + '"'; - err.output.payload.attributes.error = message; - } - else { - err.isMissing = true; - } - } - else { - - // function (message, wwwAuthenticate[]) - - const wwwArray = scheme; - for (let i = 0; i < wwwArray.length; ++i) { - if (i) { - wwwAuthenticate = wwwAuthenticate + ', '; - } - - wwwAuthenticate = wwwAuthenticate + wwwArray[i]; - } - } - - err.output.headers['WWW-Authenticate'] = wwwAuthenticate; - - return err; -}; - - -exports.paymentRequired = function (message, data) { - - return internals.create(402, message, data, exports.paymentRequired); -}; - - -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, allow) { - - const err = internals.create(405, message, data, exports.methodNotAllowed); - - if (typeof allow === 'string') { - allow = [allow]; - } - - if (Array.isArray(allow)) { - err.output.headers.Allow = allow.join(', '); - } - - return err; -}; - - -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.teapot = function (message, data) { - - return internals.create(418, message, data, exports.teapot); -}; - - -exports.badData = function (message, data) { - - return internals.create(422, message, data, exports.badData); -}; - - -exports.locked = function (message, data) { - - return internals.create(423, message, data, exports.locked); -}; - - -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); -}; - - -exports.illegal = function (message, data) { - - return internals.create(451, message, data, exports.illegal); -}; - - -// 5xx Server Errors - -exports.internal = function (message, data, statusCode) { - - return internals.serverError(message, data, statusCode, exports.internal); -}; - - -internals.serverError = function (message, data, statusCode, ctor) { - - if (data instanceof Error && - !data.isBoom) { - - return exports.wrap(data, statusCode, message); - } - - const 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.serverUnavailable = function (message, data) { - - return internals.serverError(message, data, 503, exports.serverUnavailable); -}; - - -exports.gatewayTimeout = function (message, data) { - - return internals.serverError(message, data, 504, exports.gatewayTimeout); -}; - - -exports.badImplementation = function (message, data) { - - const err = internals.serverError(message, data, 500, exports.badImplementation); - err.isDeveloperError = true; - return err; -}; diff --git a/node_modules/cryptiles/node_modules/boom/package.json b/node_modules/cryptiles/node_modules/boom/package.json deleted file mode 100644 index 4dba2bc17..000000000 --- a/node_modules/cryptiles/node_modules/boom/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "_args": [ - [ - "boom@5.2.0", - "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot" - ] - ], - "_from": "boom@5.2.0", - "_id": "boom@5.2.0", - "_inBundle": false, - "_integrity": "sha512-Z5BTk6ZRe4tXXQlkqftmsAUANpXmuwlsF5Oov8ThoMbQRzdGTA1ngYRW160GexgOgjsFOKJz0LYhoNi+2AMBUw==", - "_location": "/cryptiles/boom", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "boom@5.2.0", - "name": "boom", - "escapedName": "boom", - "rawSpec": "5.2.0", - "saveSpec": null, - "fetchSpec": "5.2.0" - }, - "_requiredBy": [ - "/cryptiles" - ], - "_resolved": "https://registry.npmjs.org/boom/-/boom-5.2.0.tgz", - "_spec": "5.2.0", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot", - "bugs": { - "url": "https://github.com/hapijs/boom/issues" - }, - "dependencies": { - "hoek": "4.x.x" - }, - "description": "HTTP-friendly error objects", - "devDependencies": { - "code": "4.x.x", - "lab": "14.x.x", - "markdown-toc": "0.12.x" - }, - "engines": { - "node": ">=4.0.0" - }, - "homepage": "https://github.com/hapijs/boom#readme", - "keywords": [ - "error", - "http" - ], - "license": "BSD-3-Clause", - "main": "lib/index.js", - "name": "boom", - "repository": { - "type": "git", - "url": "git://github.com/hapijs/boom.git" - }, - "scripts": { - "test": "lab -a code -t 100 -L -v", - "test-cov-html": "lab -a code -r html -o coverage.html -L", - "toc": "node generate-toc.js", - "version": "npm run toc && git add README.md" - }, - "version": "5.2.0" -} diff --git a/node_modules/cryptiles/package.json b/node_modules/cryptiles/package.json deleted file mode 100644 index fd5fbcf80..000000000 --- a/node_modules/cryptiles/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "_args": [ - [ - "cryptiles@3.1.2", - "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot" - ] - ], - "_from": "cryptiles@3.1.2", - "_id": "cryptiles@3.1.2", - "_inBundle": false, - "_integrity": "sha1-qJ+7Ig9c4l7FboxKqKT9e1sNKf4=", - "_location": "/cryptiles", - "_phantomChildren": { - "hoek": "4.2.0" - }, - "_requested": { - "type": "version", - "registry": true, - "raw": "cryptiles@3.1.2", - "name": "cryptiles", - "escapedName": "cryptiles", - "rawSpec": "3.1.2", - "saveSpec": null, - "fetchSpec": "3.1.2" - }, - "_requiredBy": [ - "/hawk" - ], - "_resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-3.1.2.tgz", - "_spec": "3.1.2", - "_where": "C:\\Users\\Luis\\source\\repos\\Bots\\AAMasters\\AAOlivia-Indicator-Bot", - "bugs": { - "url": "https://github.com/hapijs/cryptiles/issues" - }, - "dependencies": { - "boom": "5.x.x" - }, - "description": "General purpose crypto utilities", - "devDependencies": { - "code": "4.x.x", - "lab": "13.x.x" - }, - "engines": { - "node": ">=4.0.0" - }, - "homepage": "https://github.com/hapijs/cryptiles#readme", - "keywords": [ - "cryptography", - "security", - "utilites" - ], - "license": "BSD-3-Clause", - "main": "lib/index.js", - "name": "cryptiles", - "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": "3.1.2" -} diff --git a/node_modules/dashdash/CHANGES.md b/node_modules/dashdash/CHANGES.md deleted file mode 100644 index d7c8f4ebe..000000000 --- a/node_modules/dashdash/CHANGES.md +++ /dev/null @@ -1,364 +0,0 @@ -# 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(