This commit is contained in:
Amar Zavery 2017-09-13 12:30:50 -07:00
Родитель b4bcc337c8
Коммит 6b1866d102
44 изменённых файлов: 6520 добавлений и 59 удалений

37
.gitattributes поставляемый Normal file
Просмотреть файл

@ -0,0 +1,37 @@
*.bmp binary
*.dll binary
*.gif binary
*.jpg binary
*.png binary
*.snk binary
*.exe binary
*.wmv binary
*.mp4 binary
*.ismv binary
*.isma binary
*.ascx text
*.cmd text
*.config text
*.cs text diff=csharp
*.csproj text merge=union
*.edmx text
*.htm text
*.html text
*.json text eol=lf
*.ts text eol=lf
*.js text eol=lf
*.msbuild text
*.nuspec text
*.resx text
*.ruleset text
*.StyleCop text
*.targets text
*.txt text
*.xml text
*.sln text eol=crlf merge=union

111
.gitignore поставляемый
Просмотреть файл

@ -1,59 +1,86 @@
# Logs #### linux gitignore
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data *~
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover # KDE directory preferences
lib-cov .directory
# Coverage directory used by tools like istanbul # Linux trash folder which might appear on any partition or disk
coverage .Trash-*
# nyc test coverage /obj/*
.nyc_output /node_modules
.ntvs_analysis.dat
.ntvs_analysis.*
npm-debug.log
tmp/*
packages/*
*.njsperf
.vs/
bin/*
/.vscode/*
ValidationTool.njsproj
ValidationTool.sln
.vscode/launch.json
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) #### win gitignore
.grunt
# Bower dependency directory (https://bower.io/) # Windows image file caches
bower_components Thumbs.db
ehthumbs.db
# node-waf configuration # Folder config file
.lock-wscript Desktop.ini
# Compiled binary addons (http://nodejs.org/api/addons.html) # Recycle Bin used on file shares
build/Release $RECYCLE.BIN/
# Dependency directories # Windows Installer files
node_modules/ *.cab
jspm_packages/ *.msi
*.msm
*.msp
# Typescript v1 declaration files # Windows shortcuts
typings/ *.lnk
# Optional npm cache directory
.npm
# Optional eslint cache #### osx gitignore
.eslintcache
# Optional REPL history .DS_Store
.node_repl_history .AppleDouble
.LSOverride
# Output of 'npm pack' # Icon must end with two \r
*.tgz Icon
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file # Thumbnails
.env ._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
node_modules
#### JetBrains
.idea
# ignore code gen virtual env folder
SdkCodeGen
output/*
# Typescript output
dist/ms-rest/*

7
.npmignore Normal file
Просмотреть файл

@ -0,0 +1,7 @@
.vscode/
node_modules/
samples/
test/
.travis.yml
gulpfile.js
.gitignore

5
.travis.yml Normal file
Просмотреть файл

@ -0,0 +1,5 @@
language: node_js
sudo: false
node_js:
- "6"
- "8"

34
LICENSE
Просмотреть файл

@ -1,21 +1,21 @@
MIT License MIT License
Copyright (c) Microsoft Corporation. All rights reserved. Copyright (c) 2017 MIT
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE SOFTWARE.

Просмотреть файл

@ -1,3 +1,23 @@
# ms-rest-azure-js
Azure Runtime for isomorphic javascript libraries (that work in the browser and node.js environemnt) generated via [Autorest](https://github.com/Azure/Autorest).
## Requirements
- node.js version > 6.x
- npm install -g typescript
## Installation
- After cloning the repo, execute `npm install`
## Execution
### node.js
- Set the subscriptionId and token
- Run `node samples/node-sample.js`
### In the browser
- Set the subscriptionId and token and then run
- Open index.html file in the browser. It should show the response from GET request on the storage account. From Chrome type Ctrl + Shift + I and you can see the logs in console.
# Contributing # Contributing

306
dist/lib/azureServiceClient.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,306 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const msRest = require("ms-rest-js");
const constants_1 = require("./util/constants");
const pollingState_1 = require("./pollingState");
const LroStates = constants_1.default.LongRunningOperationStates;
/**
* @class
* Initializes a new instance of the AzureServiceClient class.
* @constructor
*
* @param {msRest.ServiceClientCredentilas} credentials - ApplicationTokenCredentials or
* UserTokenCredentials object used for authentication.
* @param {AzureServiceClientOptions} options - The parameter options used by AzureServiceClient
*/
class AzureServiceClient extends msRest.ServiceClient {
constructor(credentials, options) {
super(credentials, options);
this.acceptLanguage = constants_1.default.DEFAULT_LANGUAGE;
this.generateClientRequestId = true;
this.longRunningOperationRetryTimeout = 30;
this.rpRegistrationRetryTimeout = 30;
this.acceptLanguage = constants_1.default.DEFAULT_LANGUAGE;
this.generateClientRequestId = true;
this.longRunningOperationRetryTimeout = 30;
if (!options)
options = {};
if (options.acceptLanguage !== null && options.acceptLanguage !== undefined) {
this.acceptLanguage = options.acceptLanguage;
}
if (options.generateClientRequestId !== null && options.generateClientRequestId !== undefined) {
this.generateClientRequestId = options.generateClientRequestId;
}
if (options.longRunningOperationRetryTimeout !== null && options.longRunningOperationRetryTimeout !== undefined) {
this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;
}
if (options.rpRegistrationRetryTimeout !== null && options.rpRegistrationRetryTimeout !== undefined) {
this.rpRegistrationRetryTimeout = options.rpRegistrationRetryTimeout;
}
try {
const moduleName = "ms-rest-azure";
const moduleVersion = constants_1.default.msRestAzureVersion;
this.addUserAgentInfo(`${moduleName}/${moduleVersion}`);
}
catch (err) {
// do nothing
}
}
/**
* Provides a mechanism to make a request that will poll and provide the final result.
* @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object
* @param {msRest.RequestOptionsBase} [options] Additional options to be sent while making the request
* @returns {Promise<msRest.HttpOperationResponse>} The HttpOperationResponse containing the final polling request, response and the responseBody.
*/
sendLongRunningRequest(request, options) {
return __awaiter(this, void 0, void 0, function* () {
const self = this;
let initialResponse;
try {
initialResponse = yield self.sendRequest(request);
}
catch (err) {
return Promise.reject(err);
}
let finalResponse;
try {
finalResponse = yield self.getLongRunningOperationResult(initialResponse, options);
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(finalResponse);
});
}
/**
* Verified whether an unexpected polling status code for long running operation was received for the response of the initial request.
* @param {msRest.HttpOperationResponse} initialResponse - Response to the initial request that was sent as a part of the asynchronous operation.
*/
checkResponseStatusCodeFailed(initialResponse) {
const statusCode = initialResponse.response.status;
const method = initialResponse.request.method;
if (statusCode === 200 || statusCode === 202 ||
(statusCode === 201 && method === "PUT") ||
(statusCode === 204 && (method === "DELETE" || method === "POST"))) {
return false;
}
else {
return true;
}
}
/**
* Poll Azure long running PUT, PATCH, POST or DELETE operations.
* @param {msRest.HttpOperationResponse} resultOfInitialRequest - result/response of the initial request which is a part of the asynchronous polling operation.
* @param {msRest.RequestOptionsBase} [options] - custom request options.
* @returns {Promise<msRest.HttpOperationResponse>} result - The final response after polling is complete.
*/
getLongRunningOperationResult(resultOfInitialRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const self = this;
const initialRequestMethod = resultOfInitialRequest.request.method;
if (self.checkResponseStatusCodeFailed(resultOfInitialRequest)) {
return Promise.reject(`Unexpected polling status code from long running operation ` +
`"${resultOfInitialRequest.response.status}" for method "${initialRequestMethod}".`);
}
let pollingState;
try {
pollingState = new pollingState_1.default(resultOfInitialRequest, self.longRunningOperationRetryTimeout);
pollingState.optionsOfInitialRequest = options;
}
catch (error) {
return Promise.reject(error);
}
const resourceUrl = resultOfInitialRequest.request.url;
while (![LroStates.Succeeded, LroStates.Failed, LroStates.Canceled].some((e) => { return e === pollingState.status; })) {
yield msRest.delay(pollingState.getTimeout());
if (pollingState.azureAsyncOperationHeaderLink) {
yield self.updateStateFromAzureAsyncOperationHeader(pollingState, true);
}
else if (pollingState.locationHeaderLink) {
yield self.updateStateFromLocationHeader(initialRequestMethod, pollingState);
}
else if (initialRequestMethod === "PUT") {
yield self.updateStateFromGetResourceOperation(resourceUrl, pollingState);
}
else {
return Promise.reject(new Error("Location header is missing from long running operation."));
}
}
if (pollingState.status === LroStates.Succeeded) {
if ((pollingState.azureAsyncOperationHeaderLink || !pollingState.resource) &&
(initialRequestMethod === "PUT" || initialRequestMethod === "PATCH")) {
yield self.updateStateFromGetResourceOperation(resourceUrl, pollingState);
return Promise.resolve(pollingState.getOperationResponse());
}
else {
return Promise.resolve(pollingState.getOperationResponse());
}
}
else {
return Promise.reject(pollingState.getRestError());
}
});
}
/**
* Retrieve operation status by polling from "azure-asyncoperation" header.
* @param {PollingState} pollingState - The object to persist current operation state.
* @param {boolean} inPostOrDelete - Invoked by Post Or Delete operation.
*/
updateStateFromAzureAsyncOperationHeader(pollingState, inPostOrDelete = false) {
return __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield this.getStatus(pollingState.azureAsyncOperationHeaderLink, pollingState.optionsOfInitialRequest);
}
catch (err) {
return Promise.reject(err);
}
const parsedResponse = result.bodyAsJson;
if (!parsedResponse) {
return Promise.reject(new Error("The response from long running operation does not contain a body."));
}
else if (parsedResponse && !parsedResponse.status) {
return Promise.reject(new Error(`The response "${result.bodyAsText}" from long running operation does not contain the status property.`));
}
pollingState.status = parsedResponse.status;
pollingState.error = parsedResponse.error;
pollingState.updateResponse(result.response);
pollingState.request = result.request;
pollingState.resource = undefined;
if (inPostOrDelete) {
pollingState.resource = result.bodyAsJson;
}
return Promise.resolve();
});
}
/**
* Retrieve PUT operation status by polling from "location" header.
* @param {string} method - The HTTP method.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
updateStateFromLocationHeader(method, pollingState) {
return __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield this.getStatus(pollingState.locationHeaderLink, pollingState.optionsOfInitialRequest);
}
catch (err) {
return Promise.reject(err);
}
const parsedResponse = result.bodyAsJson;
pollingState.updateResponse(result.response);
pollingState.request = result.request;
const statusCode = result.response.status;
if (statusCode === 202) {
pollingState.status = LroStates.InProgress;
}
else if (statusCode === 200 ||
(statusCode === 201 && (method === "PUT" || method === "PATCH")) ||
(statusCode === 204 && (method === "DELETE" || method === "POST"))) {
pollingState.status = LroStates.Succeeded;
pollingState.resource = parsedResponse;
// we might not throw an error, but initialize here just in case.
pollingState.error = new msRest.RestError(`Long running operation failed with status "${pollingState.status}".`);
pollingState.error.code = pollingState.status;
}
else {
return Promise.reject(new Error(`The response with status code ${statusCode} from polling for ` +
`long running operation url "${pollingState.locationHeaderLink}" is not valid.`));
}
});
}
/**
* Polling for resource status.
* @param {string} resourceUrl - The url of resource.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
updateStateFromGetResourceOperation(resourceUrl, pollingState) {
return __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield this.getStatus(resourceUrl, pollingState.optionsOfInitialRequest);
}
catch (err) {
return Promise.reject(err);
}
if (!result.bodyAsJson) {
return Promise.reject(new Error("The response from long running operation does not contain a body."));
}
const parsedResponse = result.bodyAsJson;
pollingState.status = LroStates.Succeeded;
if (parsedResponse && parsedResponse.properties && parsedResponse.properties.provisioningState) {
pollingState.status = parsedResponse.properties.provisioningState;
}
pollingState.updateResponse(result.response);
pollingState.request = result.request;
pollingState.resource = parsedResponse;
// we might not throw an error, but initialize here just in case.
pollingState.error = new msRest.RestError(`Long running operation failed with status "${pollingState.status}".`);
pollingState.error.code = pollingState.status;
return Promise.resolve();
});
}
/**
* Retrieves operation status by querying the operation URL.
* @param {string} operationUrl - URL used to poll operation result.
* @param {object} options - Options that can be set on the request object
*/
getStatus(operationUrl, options) {
return __awaiter(this, void 0, void 0, function* () {
const self = this;
// Construct URL
const requestUrl = operationUrl.replace(" ", "%20");
// Create HTTP request object
const httpRequest = {
method: "GET",
url: requestUrl,
headers: {}
};
if (options) {
const customHeaders = options.customHeaders;
for (const headerName in customHeaders) {
if (customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = customHeaders[headerName];
}
}
}
let operationResponse;
try {
operationResponse = yield self.sendRequest(httpRequest);
}
catch (err) {
return Promise.reject(err);
}
const statusCode = operationResponse.response.status;
const responseBody = operationResponse.bodyAsJson;
if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {
const error = new msRest.RestError(`Invalid status code with response body "${operationResponse.bodyAsText}" occurred ` +
`when polling for operation status.`);
error.statusCode = statusCode;
error.request = msRest.stripRequest(operationResponse.request);
error.response = operationResponse.response;
try {
error.body = responseBody;
}
catch (badResponse) {
error.message += ` Error "${badResponse}" occured while deserializing the response body - "${operationResponse.bodyAsText}".`;
error.body = operationResponse.bodyAsText;
}
return Promise.reject(error);
}
return Promise.resolve(operationResponse);
});
}
}
exports.AzureServiceClient = AzureServiceClient;
//# sourceMappingURL=azureServiceClient.js.map

1
dist/lib/azureServiceClient.js.map поставляемый Normal file

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

14
dist/lib/baseResource.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,14 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseResourceMapper = {
required: false,
serializedName: "BaseResource",
type: {
name: "Composite",
className: "BaseResource",
modelProperties: {}
}
};
//# sourceMappingURL=baseResource.js.map

1
dist/lib/baseResource.js.map поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"baseResource.js","sourceRoot":"","sources":["../../lib/baseResource.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;AAQlF,QAAA,kBAAkB,GAAG;IAChC,QAAQ,EAAE,KAAK;IACf,cAAc,EAAE,cAAc;IAC9B,IAAI,EAAE;QACJ,IAAI,EAAE,WAAW;QACjB,SAAS,EAAE,cAAc;QACzB,eAAe,EAAE,EAChB;KACF;CACF,CAAC"}

51
dist/lib/cloudError.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,51 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloudErrorMapper = {
required: false,
serializedName: "CloudError",
type: {
name: "Composite",
className: "CloudError",
modelProperties: {
code: {
required: true,
serializedName: "code",
type: {
name: "String"
}
},
message: {
required: true,
serializedName: "message",
type: {
name: "String"
}
},
target: {
required: false,
serializedName: "target",
type: {
name: "String"
}
},
details: {
required: false,
serializedName: "details",
type: {
name: "Sequence",
element: {
required: false,
serializedName: "CloudErrorElementType",
type: {
name: "Composite",
className: "CloudError"
}
}
}
}
}
}
};
//# sourceMappingURL=cloudError.js.map

1
dist/lib/cloudError.js.map поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"cloudError.js","sourceRoot":"","sources":["../../lib/cloudError.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;AAyBlF,QAAA,gBAAgB,GAAG;IAC9B,QAAQ,EAAE,KAAK;IACf,cAAc,EAAE,YAAY;IAC5B,IAAI,EAAE;QACJ,IAAI,EAAE,WAAW;QACjB,SAAS,EAAE,YAAY;QACvB,eAAe,EAAE;YACf,IAAI,EAAE;gBACJ,QAAQ,EAAE,IAAI;gBACd,cAAc,EAAE,MAAM;gBACtB,IAAI,EAAE;oBACJ,IAAI,EAAE,QAAQ;iBACf;aACF;YACD,OAAO,EAAE;gBACP,QAAQ,EAAE,IAAI;gBACd,cAAc,EAAE,SAAS;gBACzB,IAAI,EAAE;oBACJ,IAAI,EAAE,QAAQ;iBACf;aACF;YACD,MAAM,EAAE;gBACN,QAAQ,EAAE,KAAK;gBACf,cAAc,EAAE,QAAQ;gBACxB,IAAI,EAAE;oBACJ,IAAI,EAAE,QAAQ;iBACf;aACF;YACD,OAAO,EAAE;gBACP,QAAQ,EAAE,KAAK;gBACf,cAAc,EAAE,SAAS;gBACzB,IAAI,EAAE;oBACJ,IAAI,EAAE,UAAU;oBAChB,OAAO,EAAE;wBACP,QAAQ,EAAE,KAAK;wBACf,cAAc,EAAE,uBAAuB;wBACvC,IAAI,EAAE;4BACJ,IAAI,EAAE,WAAW;4BACjB,SAAS,EAAE,YAAY;yBACxB;qBACF;iBACF;aACF;SACF;KACF;CACF,CAAC"}

13
dist/lib/msRestAzure.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,13 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const azureServiceClient_1 = require("./azureServiceClient");
exports.AzureServiceClient = azureServiceClient_1.AzureServiceClient;
const constants_1 = require("./util/constants");
exports.Constants = constants_1.default;
const cloudError_1 = require("./cloudError");
exports.CloudErrorMapper = cloudError_1.CloudErrorMapper;
const baseResource_1 = require("./baseResource");
exports.BaseResourceMapper = baseResource_1.BaseResourceMapper;
//# sourceMappingURL=msRestAzure.js.map

1
dist/lib/msRestAzure.js.map поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"msRestAzure.js","sourceRoot":"","sources":["../../lib/msRestAzure.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;AAE/F,6DAAqF;AAI5E,6BAJ2B,uCAAkB,CAI3B;AAH3B,gDAAyC;AAGe,oBAHjD,mBAAS,CAGiD;AAFjE,6CAA4D;AAEmB,2BAF1D,6BAAgB,CAE0D;AAD/F,iDAAkE;AAC6C,6BADxF,iCAAkB,CACwF"}

149
dist/lib/pollingState.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,149 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = require("./util/constants");
const msRest = require("ms-rest-js");
const LroStates = constants_1.default.LongRunningOperationStates;
/**
* @class
* Initializes a new instance of the PollingState class.
*/
class PollingState {
constructor(resultOfInitialRequest, retryTimeout = 30) {
/**
* @param {number} [retryTimeout] - The timeout in seconds to retry on intermediate operation results. Default Value is 30.
*/
this.retryTimeout = 30;
this.resultOfInitialRequest = resultOfInitialRequest;
this.retryTimeout = retryTimeout;
this.updateResponse(resultOfInitialRequest.response);
this.request = resultOfInitialRequest.request;
// Parse response.body & assign it as the resource.
try {
if (resultOfInitialRequest.bodyAsText && resultOfInitialRequest.bodyAsText.length > 0) {
this.resource = JSON.parse(resultOfInitialRequest.bodyAsText);
}
else {
this.resource = resultOfInitialRequest.bodyAsJson;
}
}
catch (error) {
const deserializationError = new msRest.RestError(`Error "${error}" occurred in parsing the responseBody " +
"while creating the PollingState for Long Running Operation- "${resultOfInitialRequest.bodyAsText}"`);
deserializationError.request = resultOfInitialRequest.request;
deserializationError.response = resultOfInitialRequest.response;
throw deserializationError;
}
switch (this.response.status) {
case 202:
this.status = LroStates.InProgress;
break;
case 204:
this.status = LroStates.Succeeded;
break;
case 201:
if (this.resource && this.resource.properties && this.resource.properties.provisioningState) {
this.status = this.resource.properties.provisioningState;
}
else {
this.status = LroStates.InProgress;
}
break;
case 200:
if (this.resource && this.resource.properties && this.resource.properties.provisioningState) {
this.status = this.resource.properties.provisioningState;
}
else {
this.status = LroStates.Succeeded;
}
break;
default:
this.status = LroStates.Failed;
break;
}
}
/**
* Update cached data using the provided response object
* @param {Response} [response] - provider response object.
*/
updateResponse(response) {
this.response = response;
if (response && response.headers) {
const asyncOperationHeader = response.headers.get("azure-asyncoperation");
const locationHeader = response.headers.get("location");
if (asyncOperationHeader) {
this.azureAsyncOperationHeaderLink = asyncOperationHeader;
}
if (locationHeader) {
this.locationHeaderLink = locationHeader;
}
}
}
/**
* Gets timeout in milliseconds.
* @returns {number} timeout
*/
getTimeout() {
if (this.retryTimeout || this.retryTimeout === 0) {
return this.retryTimeout * 1000;
}
if (this.response) {
const retryAfter = this.response.headers.get("retry-after");
if (retryAfter) {
return parseInt(retryAfter) * 1000;
}
}
return 30 * 1000;
}
/**
* Returns long running operation result.
* @returns {msRest.HttpOperationResponse} HttpOperationResponse
*/
getOperationResponse() {
const result = new msRest.HttpOperationResponse(this.request, this.response, this.response.body);
if (this.resource && typeof this.resource.valueOf() === "string") {
result.bodyAsText = this.resource;
result.bodyAsJson = JSON.parse(this.resource);
}
else {
result.bodyAsJson = this.resource;
result.bodyAsText = JSON.stringify(this.resource);
}
return result;
}
/**
* Returns an Error on operation failure.
* @param {Error} err - The error object.
* @returns {msRest.RestError} The RestError defined in the runtime.
*/
getRestError(err) {
let errMsg;
let errCode = undefined;
const error = new msRest.RestError("");
error.request = msRest.stripRequest(this.request);
error.response = this.response;
const parsedResponse = this.resource;
if (err && err.message) {
errMsg = `Long running operation failed with error: "${err.message}".`;
}
else {
errMsg = `Long running operation failed with status: "${this.status}".`;
}
if (parsedResponse) {
if (parsedResponse.error && parsedResponse.error.message) {
errMsg = `Long running operation failed with error: "${parsedResponse.error.message}".`;
}
if (parsedResponse.error && parsedResponse.error.code) {
errCode = parsedResponse.error.code;
}
}
error.message = errMsg;
if (errCode)
error.code = errCode;
error.body = parsedResponse;
return error;
}
}
exports.default = PollingState;
//# sourceMappingURL=pollingState.js.map

1
dist/lib/pollingState.js.map поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"pollingState.js","sourceRoot":"","sources":["../../lib/pollingState.ts"],"names":[],"mappings":"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"}

33
dist/lib/util/constants.js поставляемый Normal file
Просмотреть файл

@ -0,0 +1,33 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const Constants = {
/**
* Defines constants for long running operation states.
*
* @const
* @type {string}
*/
LongRunningOperationStates: {
InProgress: "InProgress",
Succeeded: "Succeeded",
Failed: "Failed",
Canceled: "Canceled"
},
/**
* The default language in the request header.
*
* @const
* @type {string}
*/
DEFAULT_LANGUAGE: "en-us",
/**
* The ms-rest-azure version.
* @const
* @type {string}
*/
msRestAzureVersion: "0.1.0"
};
exports.default = Constants;
//# sourceMappingURL=constants.js.map

1
dist/lib/util/constants.js.map поставляемый Normal file
Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../lib/util/constants.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,+FAA+F;;AAE/F,MAAM,SAAS,GAAG;IAChB;;;;;OAKG;IACH,0BAA0B,EAAE;QAC1B,UAAU,EAAE,YAAY;QACxB,SAAS,EAAE,WAAW;QACtB,MAAM,EAAE,QAAQ;QAChB,QAAQ,EAAE,UAAU;KACrB;IAED;;;;;OAKG;IACH,gBAAgB,EAAE,OAAO;IAEzB;;;;OAIG;IACH,kBAAkB,EAAE,OAAO;CAC5B,CAAC;AAEF,kBAAe,SAAS,CAAC"}

30
gulpfile.js Normal file
Просмотреть файл

@ -0,0 +1,30 @@
var gulp = require("gulp"),
tslint = require("gulp-tslint"),
tsc = require("gulp-typescript"),
sourcemaps = require("gulp-sourcemaps"),
runSequence = require("run-sequence"),
mocha = require("gulp-mocha");
gulp.task('default', function () {
console.log("run gulp -T to see all available tasks.\n");
});
gulp.task("lint", () =>
gulp.src([
"lib/**/**.ts",
"test/**/**.ts"
])
.pipe(tslint({
formatter: "verbose"
}))
.pipe(tslint.report())
);
// TODO: Doesn't yet confirm to folder structure
gulp.task("build", () =>
gulp.src([
"lib/**/**.ts"
])
.pipe(tsc(tsc.createProject("tsconfig.json")))
.js.pipe(gulp.dest("dist/lib/"))
);

314
lib/azureServiceClient.ts Normal file
Просмотреть файл

@ -0,0 +1,314 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import * as msRest from "ms-rest-js";
import Constants from "./util/constants";
import PollingState from "./pollingState";
const LroStates = Constants.LongRunningOperationStates;
/**
* Options to be provided while creating the client.
*/
export interface AzureServiceClientOptions extends msRest.ServiceClientOptions {
/**
* @property {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. Default value is: "en-US".
*/
acceptLanguage?: string;
/**
* @property {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value
* is generated and included in each request. Default is true.
*/
generateClientRequestId?: boolean;
/**
* @property {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for
* Long Running Operations. Default value is 30.
*/
longRunningOperationRetryTimeout?: number;
/**
* @property {number} [rpRegistrationRetryTimeout] - Gets or sets the retry timeout in seconds for
* AutomaticRPRegistration. Default value is 30 seconds.
*/
rpRegistrationRetryTimeout?: number;
}
/**
* @class
* Initializes a new instance of the AzureServiceClient class.
* @constructor
*
* @param {msRest.ServiceClientCredentilas} credentials - ApplicationTokenCredentials or
* UserTokenCredentials object used for authentication.
* @param {AzureServiceClientOptions} options - The parameter options used by AzureServiceClient
*/
export class AzureServiceClient extends msRest.ServiceClient {
acceptLanguage: string = Constants.DEFAULT_LANGUAGE;
generateClientRequestId = true;
longRunningOperationRetryTimeout = 30;
rpRegistrationRetryTimeout = 30;
constructor(credentials: msRest.ServiceClientCredentials, options?: AzureServiceClientOptions) {
super(credentials, options);
this.acceptLanguage = Constants.DEFAULT_LANGUAGE;
this.generateClientRequestId = true;
this.longRunningOperationRetryTimeout = 30;
if (!options) options = {};
if (options.acceptLanguage !== null && options.acceptLanguage !== undefined) {
this.acceptLanguage = options.acceptLanguage;
}
if (options.generateClientRequestId !== null && options.generateClientRequestId !== undefined) {
this.generateClientRequestId = options.generateClientRequestId;
}
if (options.longRunningOperationRetryTimeout !== null && options.longRunningOperationRetryTimeout !== undefined) {
this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;
}
if (options.rpRegistrationRetryTimeout !== null && options.rpRegistrationRetryTimeout !== undefined) {
this.rpRegistrationRetryTimeout = options.rpRegistrationRetryTimeout;
}
try {
const moduleName = "ms-rest-azure";
const moduleVersion = Constants.msRestAzureVersion;
this.addUserAgentInfo(`${moduleName}/${moduleVersion}`);
} catch (err) {
// do nothing
}
}
/**
* Provides a mechanism to make a request that will poll and provide the final result.
* @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object
* @param {msRest.RequestOptionsBase} [options] Additional options to be sent while making the request
* @returns {Promise<msRest.HttpOperationResponse>} The HttpOperationResponse containing the final polling request, response and the responseBody.
*/
async sendLongRunningRequest(request: msRest.RequestPrepareOptions | msRest.WebResource, options?: msRest.RequestOptionsBase): Promise<msRest.HttpOperationResponse> {
const self = this;
let initialResponse: msRest.HttpOperationResponse;
try {
initialResponse = await self.sendRequest(request);
} catch (err) {
return Promise.reject(err);
}
let finalResponse: msRest.HttpOperationResponse;
try {
finalResponse = await self.getLongRunningOperationResult(initialResponse, options);
} catch (err) {
return Promise.reject(err);
}
return Promise.resolve(finalResponse);
}
/**
* Verified whether an unexpected polling status code for long running operation was received for the response of the initial request.
* @param {msRest.HttpOperationResponse} initialResponse - Response to the initial request that was sent as a part of the asynchronous operation.
*/
private checkResponseStatusCodeFailed(initialResponse: msRest.HttpOperationResponse): boolean {
const statusCode = initialResponse.response.status;
const method = initialResponse.request.method;
if (statusCode === 200 || statusCode === 202 ||
(statusCode === 201 && method === "PUT") ||
(statusCode === 204 && (method === "DELETE" || method === "POST"))) {
return false;
} else {
return true;
}
}
/**
* Poll Azure long running PUT, PATCH, POST or DELETE operations.
* @param {msRest.HttpOperationResponse} resultOfInitialRequest - result/response of the initial request which is a part of the asynchronous polling operation.
* @param {msRest.RequestOptionsBase} [options] - custom request options.
* @returns {Promise<msRest.HttpOperationResponse>} result - The final response after polling is complete.
*/
async getLongRunningOperationResult(resultOfInitialRequest: msRest.HttpOperationResponse, options?: msRest.RequestOptionsBase): Promise<msRest.HttpOperationResponse> {
const self = this;
const initialRequestMethod: string = resultOfInitialRequest.request.method as msRest.HttpMethods;
if (self.checkResponseStatusCodeFailed(resultOfInitialRequest)) {
return Promise.reject(`Unexpected polling status code from long running operation ` +
`"${resultOfInitialRequest.response.status}" for method "${initialRequestMethod}".`);
}
let pollingState: PollingState;
try {
pollingState = new PollingState(resultOfInitialRequest, self.longRunningOperationRetryTimeout);
pollingState.optionsOfInitialRequest = options as msRest.RequestOptionsBase;
} catch (error) {
return Promise.reject(error);
}
const resourceUrl: string = resultOfInitialRequest.request.url;
while (![LroStates.Succeeded, LroStates.Failed, LroStates.Canceled].some((e) => { return e === pollingState.status; })) {
await msRest.delay(pollingState.getTimeout());
if (pollingState.azureAsyncOperationHeaderLink) {
await self.updateStateFromAzureAsyncOperationHeader(pollingState, true);
} else if (pollingState.locationHeaderLink) {
await self.updateStateFromLocationHeader(initialRequestMethod, pollingState);
} else if (initialRequestMethod === "PUT") {
await self.updateStateFromGetResourceOperation(resourceUrl, pollingState);
} else {
return Promise.reject(new Error("Location header is missing from long running operation."));
}
}
if (pollingState.status === LroStates.Succeeded) {
if ((pollingState.azureAsyncOperationHeaderLink || !pollingState.resource) &&
(initialRequestMethod === "PUT" || initialRequestMethod === "PATCH")) {
await self.updateStateFromGetResourceOperation(resourceUrl, pollingState);
return Promise.resolve(pollingState.getOperationResponse());
} else {
return Promise.resolve(pollingState.getOperationResponse());
}
} else {
return Promise.reject(pollingState.getRestError());
}
}
/**
* Retrieve operation status by polling from "azure-asyncoperation" header.
* @param {PollingState} pollingState - The object to persist current operation state.
* @param {boolean} inPostOrDelete - Invoked by Post Or Delete operation.
*/
private async updateStateFromAzureAsyncOperationHeader(pollingState: PollingState, inPostOrDelete = false): Promise<void> {
let result: msRest.HttpOperationResponse;
try {
result = await this.getStatus(pollingState.azureAsyncOperationHeaderLink as string, pollingState.optionsOfInitialRequest);
} catch (err) {
return Promise.reject(err);
}
const parsedResponse = result.bodyAsJson as { [key: string]: any };
if (!parsedResponse) {
return Promise.reject(new Error("The response from long running operation does not contain a body."));
} else if (parsedResponse && !parsedResponse.status) {
return Promise.reject(new Error(`The response "${result.bodyAsText}" from long running operation does not contain the status property.`));
}
pollingState.status = parsedResponse.status;
pollingState.error = parsedResponse.error;
pollingState.updateResponse(result.response);
pollingState.request = result.request;
pollingState.resource = undefined;
if (inPostOrDelete) {
pollingState.resource = result.bodyAsJson;
}
return Promise.resolve();
}
/**
* Retrieve PUT operation status by polling from "location" header.
* @param {string} method - The HTTP method.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
private async updateStateFromLocationHeader(method: string, pollingState: PollingState): Promise<void> {
let result: msRest.HttpOperationResponse;
try {
result = await this.getStatus(pollingState.locationHeaderLink as string, pollingState.optionsOfInitialRequest);
} catch (err) {
return Promise.reject(err);
}
const parsedResponse = result.bodyAsJson as { [key: string]: any };
pollingState.updateResponse(result.response);
pollingState.request = result.request;
const statusCode = result.response.status;
if (statusCode === 202) {
pollingState.status = LroStates.InProgress;
} else if (statusCode === 200 ||
(statusCode === 201 && (method === "PUT" || method === "PATCH")) ||
(statusCode === 204 && (method === "DELETE" || method === "POST"))) {
pollingState.status = LroStates.Succeeded;
pollingState.resource = parsedResponse;
// we might not throw an error, but initialize here just in case.
pollingState.error = new msRest.RestError(`Long running operation failed with status "${pollingState.status}".`);
pollingState.error.code = pollingState.status;
} else {
return Promise.reject(new Error(`The response with status code ${statusCode} from polling for ` +
`long running operation url "${pollingState.locationHeaderLink}" is not valid.`));
}
}
/**
* Polling for resource status.
* @param {string} resourceUrl - The url of resource.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
private async updateStateFromGetResourceOperation(resourceUrl: string, pollingState: PollingState): Promise<void> {
let result: msRest.HttpOperationResponse;
try {
result = await this.getStatus(resourceUrl, pollingState.optionsOfInitialRequest);
} catch (err) {
return Promise.reject(err);
}
if (!result.bodyAsJson) {
return Promise.reject(new Error("The response from long running operation does not contain a body."));
}
const parsedResponse = result.bodyAsJson as { [key: string]: any };
pollingState.status = LroStates.Succeeded;
if (parsedResponse && parsedResponse.properties && parsedResponse.properties.provisioningState) {
pollingState.status = parsedResponse.properties.provisioningState;
}
pollingState.updateResponse(result.response);
pollingState.request = result.request;
pollingState.resource = parsedResponse;
// we might not throw an error, but initialize here just in case.
pollingState.error = new msRest.RestError(`Long running operation failed with status "${pollingState.status}".`);
pollingState.error.code = pollingState.status;
return Promise.resolve();
}
/**
* Retrieves operation status by querying the operation URL.
* @param {string} operationUrl - URL used to poll operation result.
* @param {object} options - Options that can be set on the request object
*/
private async getStatus(operationUrl: string, options?: msRest.RequestOptionsBase): Promise<msRest.HttpOperationResponse> {
const self = this;
// Construct URL
const requestUrl = operationUrl.replace(" ", "%20");
// Create HTTP request object
const httpRequest: msRest.RequestPrepareOptions = {
method: "GET",
url: requestUrl,
headers: {}
};
if (options) {
const customHeaders: { [key: string]: string } = (options.customHeaders as { [key: string]: string });
for (const headerName in customHeaders) {
if (customHeaders.hasOwnProperty(headerName)) {
(httpRequest.headers as { [key: string]: string })[headerName] = customHeaders[headerName];
}
}
}
let operationResponse: msRest.HttpOperationResponse;
try {
operationResponse = await self.sendRequest(httpRequest);
} catch (err) {
return Promise.reject(err);
}
const statusCode = operationResponse.response.status;
const responseBody = operationResponse.bodyAsJson;
if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {
const error = new msRest.RestError(`Invalid status code with response body "${operationResponse.bodyAsText}" occurred ` +
`when polling for operation status.`);
error.statusCode = statusCode;
error.request = msRest.stripRequest(operationResponse.request);
error.response = operationResponse.response;
try {
error.body = responseBody;
} catch (badResponse) {
error.message += ` Error "${badResponse}" occured while deserializing the response body - "${operationResponse.bodyAsText}".`;
error.body = operationResponse.bodyAsText;
}
return Promise.reject(error);
}
return Promise.resolve(operationResponse);
}
}

19
lib/baseResource.ts Normal file
Просмотреть файл

@ -0,0 +1,19 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
/**
* @class
* An empty interface.
*/
export interface BaseResource { }
export const BaseResourceMapper = {
required: false,
serializedName: "BaseResource",
type: {
name: "Composite",
className: "BaseResource",
modelProperties: {
}
}
};

72
lib/cloudError.ts Normal file
Просмотреть файл

@ -0,0 +1,72 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
/**
* @class
* Provides additional information about an http error response returned from a Microsoft Azure service.
*/
export interface CloudError extends Error {
/**
* @property {string} code The error code parsed from the body of the http error response.
*/
code: string;
/**
* @property {string} message The error message parsed from the body of the http error response.
*/
message: string;
/**
* @property {string} [target] The target of the error.
*/
target?: string;
/**
* @property {Array<CloudError>} [details] An array of CloudError objects specifying the details.
*/
details?: Array<CloudError>;
}
export const CloudErrorMapper = {
required: false,
serializedName: "CloudError",
type: {
name: "Composite",
className: "CloudError",
modelProperties: {
code: {
required: true,
serializedName: "code",
type: {
name: "String"
}
},
message: {
required: true,
serializedName: "message",
type: {
name: "String"
}
},
target: {
required: false,
serializedName: "target",
type: {
name: "String"
}
},
details: {
required: false,
serializedName: "details",
type: {
name: "Sequence",
element: {
required: false,
serializedName: "CloudErrorElementType",
type: {
name: "Composite",
className: "CloudError"
}
}
}
}
}
}
};

8
lib/msRestAzure.ts Normal file
Просмотреть файл

@ -0,0 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import { AzureServiceClientOptions, AzureServiceClient } from "./azureServiceClient";
import Constants from "./util/constants";
import { CloudError, CloudErrorMapper } from "./cloudError";
import { BaseResource, BaseResourceMapper } from "./baseResource";
export { AzureServiceClient, AzureServiceClientOptions, Constants, CloudError, CloudErrorMapper, BaseResource, BaseResourceMapper };

190
lib/pollingState.ts Normal file
Просмотреть файл

@ -0,0 +1,190 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
import Constants from "./util/constants";
import * as msRest from "ms-rest-js";
const LroStates = Constants.LongRunningOperationStates;
/**
* @class
* Initializes a new instance of the PollingState class.
*/
export default class PollingState {
/**
* @param {msRest.HttpOperationResponse} [response] - Response of the initial request that was made as a part of the asynchronous operation.
*/
resultOfInitialRequest: msRest.HttpOperationResponse;
/**
* @param {msRest.RequestOptionsBase} [optionsOfInitialRequest] - Request options that were provided as a part of the initial request.
*/
optionsOfInitialRequest: msRest.RequestOptionsBase;
/**
* @param {msRest.WebResource} [request] - provides information about the request made for polling.
*/
request: msRest.WebResource;
/**
* @param {Response} [response] - The response object to extract longrunning operation status.
*/
response: Response;
/**
* @param {any} [resource] - Provides information about the response body received in the polling request. Particularly useful when polling via provisioningState.
*/
resource: any;
/**
* @param {number} [retryTimeout] - The timeout in seconds to retry on intermediate operation results. Default Value is 30.
*/
retryTimeout = 30;
/**
* @param {string} [azureAsyncOperationHeaderLink] - The url that is present in "azure-asyncoperation" response header.
*/
azureAsyncOperationHeaderLink?: string;
/**
* @param {string} [locationHeaderLink] - The url that is present in "Location" response header.
*/
locationHeaderLink?: string;
/**
* @param {string} [status] - The status of polling. "Succeeded, Failed, Cancelled, Updating, Creating, etc."
*/
status?: string;
/**
* @param {msRest.RestError} [error] - Provides information about the error that happened while polling.
*/
error?: msRest.RestError;
constructor(resultOfInitialRequest: msRest.HttpOperationResponse, retryTimeout = 30) {
this.resultOfInitialRequest = resultOfInitialRequest;
this.retryTimeout = retryTimeout;
this.updateResponse(resultOfInitialRequest.response);
this.request = resultOfInitialRequest.request;
// Parse response.body & assign it as the resource.
try {
if (resultOfInitialRequest.bodyAsText && resultOfInitialRequest.bodyAsText.length > 0) {
this.resource = JSON.parse(resultOfInitialRequest.bodyAsText);
} else {
this.resource = resultOfInitialRequest.bodyAsJson;
}
} catch (error) {
const deserializationError = new msRest.RestError(`Error "${error}" occurred in parsing the responseBody " +
"while creating the PollingState for Long Running Operation- "${resultOfInitialRequest.bodyAsText}"`);
deserializationError.request = resultOfInitialRequest.request;
deserializationError.response = resultOfInitialRequest.response;
throw deserializationError;
}
switch (this.response.status) {
case 202:
this.status = LroStates.InProgress;
break;
case 204:
this.status = LroStates.Succeeded;
break;
case 201:
if (this.resource && this.resource.properties && this.resource.properties.provisioningState) {
this.status = this.resource.properties.provisioningState;
} else {
this.status = LroStates.InProgress;
}
break;
case 200:
if (this.resource && this.resource.properties && this.resource.properties.provisioningState) {
this.status = this.resource.properties.provisioningState;
} else {
this.status = LroStates.Succeeded;
}
break;
default:
this.status = LroStates.Failed;
break;
}
}
/**
* Update cached data using the provided response object
* @param {Response} [response] - provider response object.
*/
updateResponse(response: Response) {
this.response = response;
if (response && response.headers) {
const asyncOperationHeader: string | null | undefined = response.headers.get("azure-asyncoperation");
const locationHeader: string | null | undefined = response.headers.get("location");
if (asyncOperationHeader) {
this.azureAsyncOperationHeaderLink = asyncOperationHeader;
}
if (locationHeader) {
this.locationHeaderLink = locationHeader;
}
}
}
/**
* Gets timeout in milliseconds.
* @returns {number} timeout
*/
getTimeout() {
if (this.retryTimeout || this.retryTimeout === 0) {
return this.retryTimeout * 1000;
}
if (this.response) {
const retryAfter: string | null | undefined = this.response.headers.get("retry-after");
if (retryAfter) {
return parseInt(retryAfter) * 1000;
}
}
return 30 * 1000;
}
/**
* Returns long running operation result.
* @returns {msRest.HttpOperationResponse} HttpOperationResponse
*/
getOperationResponse(): msRest.HttpOperationResponse {
const result = new msRest.HttpOperationResponse(this.request, this.response, this.response.body);
if (this.resource && typeof this.resource.valueOf() === "string") {
result.bodyAsText = this.resource;
result.bodyAsJson = JSON.parse(this.resource);
} else {
result.bodyAsJson = this.resource;
result.bodyAsText = JSON.stringify(this.resource);
}
return result;
}
/**
* Returns an Error on operation failure.
* @param {Error} err - The error object.
* @returns {msRest.RestError} The RestError defined in the runtime.
*/
getRestError(err?: Error): msRest.RestError {
let errMsg: string;
let errCode: string | undefined = undefined;
const error = new msRest.RestError("");
error.request = msRest.stripRequest(this.request);
error.response = this.response;
const parsedResponse = this.resource as { [key: string]: any };
if (err && err.message) {
errMsg = `Long running operation failed with error: "${err.message}".`;
} else {
errMsg = `Long running operation failed with status: "${this.status}".`;
}
if (parsedResponse) {
if (parsedResponse.error && parsedResponse.error.message) {
errMsg = `Long running operation failed with error: "${parsedResponse.error.message}".`;
}
if (parsedResponse.error && parsedResponse.error.code) {
errCode = parsedResponse.error.code as string;
}
}
error.message = errMsg;
if (errCode) error.code = errCode;
error.body = parsedResponse;
return error;
}
}

34
lib/util/constants.ts Normal file
Просмотреть файл

@ -0,0 +1,34 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
const Constants = {
/**
* Defines constants for long running operation states.
*
* @const
* @type {string}
*/
LongRunningOperationStates: {
InProgress: "InProgress",
Succeeded: "Succeeded",
Failed: "Failed",
Canceled: "Canceled"
},
/**
* The default language in the request header.
*
* @const
* @type {string}
*/
DEFAULT_LANGUAGE: "en-us",
/**
* The ms-rest-azure version.
* @const
* @type {string}
*/
msRestAzureVersion: "0.1.0"
};
export default Constants;

677
msRestAzureBundle.js Normal file
Просмотреть файл

@ -0,0 +1,677 @@
var msRestAzure =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const Constants = {
/**
* Defines constants for long running operation states.
*
* @const
* @type {string}
*/
LongRunningOperationStates: {
InProgress: "InProgress",
Succeeded: "Succeeded",
Failed: "Failed",
Canceled: "Canceled"
},
/**
* The default language in the request header.
*
* @const
* @type {string}
*/
DEFAULT_LANGUAGE: "en-us",
/**
* The ms-rest-azure version.
* @const
* @type {string}
*/
msRestAzureVersion: "0.1.0"
};
exports.default = Constants;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = msRest;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const azureServiceClient_1 = __webpack_require__(3);
exports.AzureServiceClient = azureServiceClient_1.AzureServiceClient;
const constants_1 = __webpack_require__(0);
exports.Constants = constants_1.default;
const cloudError_1 = __webpack_require__(5);
exports.CloudErrorMapper = cloudError_1.CloudErrorMapper;
const baseResource_1 = __webpack_require__(6);
exports.BaseResourceMapper = baseResource_1.BaseResourceMapper;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const msRest = __webpack_require__(1);
const constants_1 = __webpack_require__(0);
const pollingState_1 = __webpack_require__(4);
const LroStates = constants_1.default.LongRunningOperationStates;
/**
* @class
* Initializes a new instance of the AzureServiceClient class.
* @constructor
*
* @param {msRest.ServiceClientCredentilas} credentials - ApplicationTokenCredentials or
* UserTokenCredentials object used for authentication.
* @param {AzureServiceClientOptions} options - The parameter options used by AzureServiceClient
*/
class AzureServiceClient extends msRest.ServiceClient {
constructor(credentials, options) {
super(credentials, options);
this.acceptLanguage = constants_1.default.DEFAULT_LANGUAGE;
this.generateClientRequestId = true;
this.longRunningOperationRetryTimeout = 30;
this.rpRegistrationRetryTimeout = 30;
this.acceptLanguage = constants_1.default.DEFAULT_LANGUAGE;
this.generateClientRequestId = true;
this.longRunningOperationRetryTimeout = 30;
if (!options)
options = {};
if (options.acceptLanguage !== null && options.acceptLanguage !== undefined) {
this.acceptLanguage = options.acceptLanguage;
}
if (options.generateClientRequestId !== null && options.generateClientRequestId !== undefined) {
this.generateClientRequestId = options.generateClientRequestId;
}
if (options.longRunningOperationRetryTimeout !== null && options.longRunningOperationRetryTimeout !== undefined) {
this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;
}
if (options.rpRegistrationRetryTimeout !== null && options.rpRegistrationRetryTimeout !== undefined) {
this.rpRegistrationRetryTimeout = options.rpRegistrationRetryTimeout;
}
try {
const moduleName = "ms-rest-azure";
const moduleVersion = constants_1.default.msRestAzureVersion;
this.addUserAgentInfo(`${moduleName}/${moduleVersion}`);
}
catch (err) {
// do nothing
}
}
/**
* Provides a mechanism to make a request that will poll and provide the final result.
* @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object
* @param {msRest.RequestOptionsBase} [options] Additional options to be sent while making the request
* @returns {Promise<msRest.HttpOperationResponse>} The HttpOperationResponse containing the final polling request, response and the responseBody.
*/
sendLongRunningRequest(request, options) {
return __awaiter(this, void 0, void 0, function* () {
const self = this;
let initialResponse;
try {
initialResponse = yield self.sendRequest(request);
}
catch (err) {
return Promise.reject(err);
}
let finalResponse;
try {
finalResponse = yield self.getLongRunningOperationResult(initialResponse, options);
}
catch (err) {
return Promise.reject(err);
}
return Promise.resolve(finalResponse);
});
}
/**
* Verified whether an unexpected polling status code for long running operation was received for the response of the initial request.
* @param {msRest.HttpOperationResponse} initialResponse - Response to the initial request that was sent as a part of the asynchronous operation.
*/
checkResponseStatusCodeFailed(initialResponse) {
const statusCode = initialResponse.response.status;
const method = initialResponse.request.method;
if (statusCode === 200 || statusCode === 202 ||
(statusCode === 201 && method === "PUT") ||
(statusCode === 204 && (method === "DELETE" || method === "POST"))) {
return false;
}
else {
return true;
}
}
/**
* Poll Azure long running PUT, PATCH, POST or DELETE operations.
* @param {msRest.HttpOperationResponse} resultOfInitialRequest - result/response of the initial request which is a part of the asynchronous polling operation.
* @param {msRest.RequestOptionsBase} [options] - custom request options.
* @returns {Promise<msRest.HttpOperationResponse>} result - The final response after polling is complete.
*/
getLongRunningOperationResult(resultOfInitialRequest, options) {
return __awaiter(this, void 0, void 0, function* () {
const self = this;
const initialRequestMethod = resultOfInitialRequest.request.method;
if (self.checkResponseStatusCodeFailed(resultOfInitialRequest)) {
return Promise.reject(`Unexpected polling status code from long running operation ` +
`"${resultOfInitialRequest.response.status}" for method "${initialRequestMethod}".`);
}
let pollingState;
try {
pollingState = new pollingState_1.default(resultOfInitialRequest, self.longRunningOperationRetryTimeout);
pollingState.optionsOfInitialRequest = options;
}
catch (error) {
return Promise.reject(error);
}
const resourceUrl = resultOfInitialRequest.request.url;
while (![LroStates.Succeeded, LroStates.Failed, LroStates.Canceled].some((e) => { return e === pollingState.status; })) {
yield msRest.delay(pollingState.getTimeout());
if (pollingState.azureAsyncOperationHeaderLink) {
yield self.updateStateFromAzureAsyncOperationHeader(pollingState, true);
}
else if (pollingState.locationHeaderLink) {
yield self.updateStateFromLocationHeader(initialRequestMethod, pollingState);
}
else if (initialRequestMethod === "PUT") {
yield self.updateStateFromGetResourceOperation(resourceUrl, pollingState);
}
else {
return Promise.reject(new Error("Location header is missing from long running operation."));
}
}
if (pollingState.status === LroStates.Succeeded) {
if ((pollingState.azureAsyncOperationHeaderLink || !pollingState.resource) &&
(initialRequestMethod === "PUT" || initialRequestMethod === "PATCH")) {
yield self.updateStateFromGetResourceOperation(resourceUrl, pollingState);
return Promise.resolve(pollingState.getOperationResponse());
}
else {
return Promise.resolve(pollingState.getOperationResponse());
}
}
else {
return Promise.reject(pollingState.getRestError());
}
});
}
/**
* Retrieve operation status by polling from "azure-asyncoperation" header.
* @param {PollingState} pollingState - The object to persist current operation state.
* @param {boolean} inPostOrDelete - Invoked by Post Or Delete operation.
*/
updateStateFromAzureAsyncOperationHeader(pollingState, inPostOrDelete = false) {
return __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield this.getStatus(pollingState.azureAsyncOperationHeaderLink, pollingState.optionsOfInitialRequest);
}
catch (err) {
return Promise.reject(err);
}
const parsedResponse = result.bodyAsJson;
if (!parsedResponse) {
return Promise.reject(new Error("The response from long running operation does not contain a body."));
}
else if (parsedResponse && !parsedResponse.status) {
return Promise.reject(new Error(`The response "${result.bodyAsText}" from long running operation does not contain the status property.`));
}
pollingState.status = parsedResponse.status;
pollingState.error = parsedResponse.error;
pollingState.updateResponse(result.response);
pollingState.request = result.request;
pollingState.resource = undefined;
if (inPostOrDelete) {
pollingState.resource = result.bodyAsJson;
}
return Promise.resolve();
});
}
/**
* Retrieve PUT operation status by polling from "location" header.
* @param {string} method - The HTTP method.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
updateStateFromLocationHeader(method, pollingState) {
return __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield this.getStatus(pollingState.locationHeaderLink, pollingState.optionsOfInitialRequest);
}
catch (err) {
return Promise.reject(err);
}
const parsedResponse = result.bodyAsJson;
pollingState.updateResponse(result.response);
pollingState.request = result.request;
const statusCode = result.response.status;
if (statusCode === 202) {
pollingState.status = LroStates.InProgress;
}
else if (statusCode === 200 ||
(statusCode === 201 && (method === "PUT" || method === "PATCH")) ||
(statusCode === 204 && (method === "DELETE" || method === "POST"))) {
pollingState.status = LroStates.Succeeded;
pollingState.resource = parsedResponse;
// we might not throw an error, but initialize here just in case.
pollingState.error = new msRest.RestError(`Long running operation failed with status "${pollingState.status}".`);
pollingState.error.code = pollingState.status;
}
else {
return Promise.reject(new Error(`The response with status code ${statusCode} from polling for ` +
`long running operation url "${pollingState.locationHeaderLink}" is not valid.`));
}
});
}
/**
* Polling for resource status.
* @param {string} resourceUrl - The url of resource.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
updateStateFromGetResourceOperation(resourceUrl, pollingState) {
return __awaiter(this, void 0, void 0, function* () {
let result;
try {
result = yield this.getStatus(resourceUrl, pollingState.optionsOfInitialRequest);
}
catch (err) {
return Promise.reject(err);
}
if (!result.bodyAsJson) {
return Promise.reject(new Error("The response from long running operation does not contain a body."));
}
const parsedResponse = result.bodyAsJson;
pollingState.status = LroStates.Succeeded;
if (parsedResponse && parsedResponse.properties && parsedResponse.properties.provisioningState) {
pollingState.status = parsedResponse.properties.provisioningState;
}
pollingState.updateResponse(result.response);
pollingState.request = result.request;
pollingState.resource = parsedResponse;
// we might not throw an error, but initialize here just in case.
pollingState.error = new msRest.RestError(`Long running operation failed with status "${pollingState.status}".`);
pollingState.error.code = pollingState.status;
return Promise.resolve();
});
}
/**
* Retrieves operation status by querying the operation URL.
* @param {string} operationUrl - URL used to poll operation result.
* @param {object} options - Options that can be set on the request object
*/
getStatus(operationUrl, options) {
return __awaiter(this, void 0, void 0, function* () {
const self = this;
// Construct URL
const requestUrl = operationUrl.replace(" ", "%20");
// Create HTTP request object
const httpRequest = {
method: "GET",
url: requestUrl,
headers: {}
};
if (options) {
const customHeaders = options.customHeaders;
for (const headerName in customHeaders) {
if (customHeaders.hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = customHeaders[headerName];
}
}
}
let operationResponse;
try {
operationResponse = yield self.sendRequest(httpRequest);
}
catch (err) {
return Promise.reject(err);
}
const statusCode = operationResponse.response.status;
const responseBody = operationResponse.bodyAsJson;
if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {
const error = new msRest.RestError(`Invalid status code with response body "${operationResponse.bodyAsText}" occurred ` +
`when polling for operation status.`);
error.statusCode = statusCode;
error.request = msRest.stripRequest(operationResponse.request);
error.response = operationResponse.response;
try {
error.body = responseBody;
}
catch (badResponse) {
error.message += ` Error "${badResponse}" occured while deserializing the response body - "${operationResponse.bodyAsText}".`;
error.body = operationResponse.bodyAsText;
}
return Promise.reject(error);
}
return Promise.resolve(operationResponse);
});
}
}
exports.AzureServiceClient = AzureServiceClient;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const constants_1 = __webpack_require__(0);
const msRest = __webpack_require__(1);
const LroStates = constants_1.default.LongRunningOperationStates;
/**
* @class
* Initializes a new instance of the PollingState class.
*/
class PollingState {
constructor(resultOfInitialRequest, retryTimeout = 30) {
/**
* @param {number} [retryTimeout] - The timeout in seconds to retry on intermediate operation results. Default Value is 30.
*/
this.retryTimeout = 30;
this.resultOfInitialRequest = resultOfInitialRequest;
this.retryTimeout = retryTimeout;
this.updateResponse(resultOfInitialRequest.response);
this.request = resultOfInitialRequest.request;
// Parse response.body & assign it as the resource.
try {
if (resultOfInitialRequest.bodyAsText && resultOfInitialRequest.bodyAsText.length > 0) {
this.resource = JSON.parse(resultOfInitialRequest.bodyAsText);
}
else {
this.resource = resultOfInitialRequest.bodyAsJson;
}
}
catch (error) {
const deserializationError = new msRest.RestError(`Error "${error}" occurred in parsing the responseBody " +
"while creating the PollingState for Long Running Operation- "${resultOfInitialRequest.bodyAsText}"`);
deserializationError.request = resultOfInitialRequest.request;
deserializationError.response = resultOfInitialRequest.response;
throw deserializationError;
}
switch (this.response.status) {
case 202:
this.status = LroStates.InProgress;
break;
case 204:
this.status = LroStates.Succeeded;
break;
case 201:
if (this.resource && this.resource.properties && this.resource.properties.provisioningState) {
this.status = this.resource.properties.provisioningState;
}
else {
this.status = LroStates.InProgress;
}
break;
case 200:
if (this.resource && this.resource.properties && this.resource.properties.provisioningState) {
this.status = this.resource.properties.provisioningState;
}
else {
this.status = LroStates.Succeeded;
}
break;
default:
this.status = LroStates.Failed;
break;
}
}
/**
* Update cached data using the provided response object
* @param {Response} [response] - provider response object.
*/
updateResponse(response) {
this.response = response;
if (response && response.headers) {
const asyncOperationHeader = response.headers.get("azure-asyncoperation");
const locationHeader = response.headers.get("location");
if (asyncOperationHeader) {
this.azureAsyncOperationHeaderLink = asyncOperationHeader;
}
if (locationHeader) {
this.locationHeaderLink = locationHeader;
}
}
}
/**
* Gets timeout in milliseconds.
* @returns {number} timeout
*/
getTimeout() {
if (this.retryTimeout || this.retryTimeout === 0) {
return this.retryTimeout * 1000;
}
if (this.response) {
const retryAfter = this.response.headers.get("retry-after");
if (retryAfter) {
return parseInt(retryAfter) * 1000;
}
}
return 30 * 1000;
}
/**
* Returns long running operation result.
* @returns {msRest.HttpOperationResponse} HttpOperationResponse
*/
getOperationResponse() {
const result = new msRest.HttpOperationResponse(this.request, this.response, this.response.body);
if (this.resource && typeof this.resource.valueOf() === "string") {
result.bodyAsText = this.resource;
result.bodyAsJson = JSON.parse(this.resource);
}
else {
result.bodyAsJson = this.resource;
result.bodyAsText = JSON.stringify(this.resource);
}
return result;
}
/**
* Returns an Error on operation failure.
* @param {Error} err - The error object.
* @returns {msRest.RestError} The RestError defined in the runtime.
*/
getRestError(err) {
let errMsg;
let errCode = undefined;
const error = new msRest.RestError("");
error.request = msRest.stripRequest(this.request);
error.response = this.response;
const parsedResponse = this.resource;
if (err && err.message) {
errMsg = `Long running operation failed with error: "${err.message}".`;
}
else {
errMsg = `Long running operation failed with status: "${this.status}".`;
}
if (parsedResponse) {
if (parsedResponse.error && parsedResponse.error.message) {
errMsg = `Long running operation failed with error: "${parsedResponse.error.message}".`;
}
if (parsedResponse.error && parsedResponse.error.code) {
errCode = parsedResponse.error.code;
}
}
error.message = errMsg;
if (errCode)
error.code = errCode;
error.body = parsedResponse;
return error;
}
}
exports.default = PollingState;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CloudErrorMapper = {
required: false,
serializedName: "CloudError",
type: {
name: "Composite",
className: "CloudError",
modelProperties: {
code: {
required: true,
serializedName: "code",
type: {
name: "String"
}
},
message: {
required: true,
serializedName: "message",
type: {
name: "String"
}
},
target: {
required: false,
serializedName: "target",
type: {
name: "String"
}
},
details: {
required: false,
serializedName: "details",
type: {
name: "Sequence",
element: {
required: false,
serializedName: "CloudErrorElementType",
type: {
name: "Composite",
className: "CloudError"
}
}
}
}
}
}
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseResourceMapper = {
required: false,
serializedName: "BaseResource",
type: {
name: "Composite",
className: "BaseResource",
modelProperties: {}
}
};
/***/ })
/******/ ]);
//# sourceMappingURL=msRestAzureBundle.js.map

1
msRestAzureBundle.js.map Normal file

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

1
msRestAzureBundle.min.js поставляемый Normal file

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

3837
package-lock.json сгенерированный Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

54
package.json Normal file
Просмотреть файл

@ -0,0 +1,54 @@
{
"name": "ms-rest-azure-js",
"author": {
"name": "Microsoft Corporation",
"email": "azsdkteam@microsoft.com",
"url": "https://github.com/Azure/azure-sdk-for-node"
},
"version": "0.1.0",
"description": "Client Runtime for Node.js client libraries generated using AutoRest",
"tags": [
"node",
"microsoft",
"autorest",
"clientruntime"
],
"keywords": [
"node",
"microsoft",
"autorest",
"clientruntime"
],
"main": "./dist/lib/msRestAzure.js",
"types": "./typings/lib/msRestAzure.d.ts",
"license": "MIT",
"dependencies": {
"ms-rest-js": "azure/ms-rest-js#master"
},
"devDependencies": {
"@types/mocha": "^2.2.40",
"@types/should": "^8.1.30",
"mocha": "^3.2.0",
"should": "5.2.0",
"ts-loader": "^2.3.7",
"tslint": "^5.7.0",
"typescript": "^2.5.2",
"webpack": "^3.5.6",
"uglify-es": "^3.0.28"
},
"homepage": "https://github.com/Azure/azure-sdk-for-node/runtime/ms-rest",
"repository": {
"type": "git",
"url": "git@github.com:Azure/azure-sdk-for-node.git"
},
"bugs": {
"url": "http://github.com/Azure/azure-sdk-for-node/issues"
},
"scripts": {
"tsc": "tsc -p tsconfig.json",
"test": "npm install && npm -s run-script unit",
"unit": "mocha -t 50000 dist/test",
"build": "npm -s run-script tsc && webpack && node node_modules/uglify-es/bin/uglifyjs --source-map -c -m -o msRestAzureBundle.min.js msRestAzureBundle.js",
"tsLint": "tslint -p . -c tslint.json --exclude test/**/*.ts"
}
}

26
samples/index.html Normal file
Просмотреть файл

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Todos</title>
<script type="text/javascript" src="../node_modules/ms-rest-ts/msRestBundle.js"></script>
<script type="text/javascript" src="../msRestAzureBundle.js"></script>
<script type="text/javascript">
document.write("hello world");
const subscriptionId = "subscriptionId";
const token = "token";
const creds = new msRest.TokenCredentials(token);
const client = new msRestAzure.AzureServiceClient(creds);
const req = {
url: `https://management.azure.com/subscriptions/${subscriptionId}/providers/Microsoft.Storage/storageAccounts?api-version=2015-06-15`,
method: "GET"
};
client.sendRequest(req).then((res) => { document.write(res.bodyAsText); }).catch((err) => { console.log(err); });
</script>
</head>
<body>
</body>
</html>

73
samples/node-sample.js Normal file
Просмотреть файл

@ -0,0 +1,73 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const msRest = require("ms-rest-js");
const msRestAzure = require("../lib/msRestAzure");
const clientOptions = {
filters: [new msRest.LogFilter()]
};
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"] || "00977cdb-163f-435f-9c32-39ec8ae61f4d";
const resourceGroupName = "foozap002";
const accountName = "foozy894";
const location = "westus";
const apiVersion = "2017-06-01";
// An easy way to get the token
// 1. Go to this test drive link https://azure.github.io/projects/apis and authenticate by clicking on Authorize. Check the user impersoantion checkbox in the popup.
// 1.1 select a subscription of your choice
// 1.2 select the storage-2015-06-15 option from the first drop down list
// 1.3 expand the url to list storage accounts in a subscription
// 1.4 click on try it out button.
// 1.5 in the curl tab you will see the actual curl request that has the bearer token in it
// 1.6 copy paste that token here. That token is valid for 1 hour
const token = "token";
const creds = new msRest.TokenCredentials(token);
const client = new msRestAzure.AzureServiceClient(creds, clientOptions);
const req = {
url: `https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.Storage/storageAccounts/${accountName}?api-version=${apiVersion}`,
method: "PUT",
body: {
location: location,
sku: {
name: "Standard_GRS"
},
kind: "Storage",
tags: {
key1: "value1",
key2: "value2"
}
}
};
function execute(req) {
return __awaiter(this, void 0, void 0, function* () {
let res;
try {
res = yield client.sendLongRunningRequest(req);
console.dir(res);
document.write(JSON.stringify(res));
return Promise.resolve(res);
}
catch (err) {
return Promise.reject(err);
}
});
}
console.log("Hi There!!");
// client.sendLongRunningRequest(req).then((res: msRest.HttpOperationResponse) => {
// console.log(res.body as string);
// }).catch((err) => {
// console.dir(err);
// });
execute(req).catch((err) => { console.dir(err); });
for (var i = 1; i <= 20; i++) {
console.log("Hello World " + i);
setTimeout(function (x) { return function () { console.log(x); }; }(i), 1000 * i);
// 1 2 3 4 5
}
//# sourceMappingURL=sample.js.map

Просмотреть файл

@ -0,0 +1 @@
{"version":3,"file":"sample.js","sourceRoot":"","sources":["../../samples/sample.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;AAEb,qCAAqC;AACrC,kDAAkD;AAClD,MAAM,aAAa,GAA0C;IAC3D,OAAO,EAAE,CAAC,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;CAClC,CAAC;AAEF,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,IAAI,sCAAsC,CAAC;AACtG,MAAM,iBAAiB,GAAG,WAAW,CAAC;AACtC,MAAM,WAAW,GAAG,UAAU,CAAC;AAC/B,MAAM,QAAQ,GAAG,QAAQ,CAAC;AAC1B,MAAM,UAAU,GAAG,YAAY,CAAC;AAChC,+BAA+B;AAC/B,qKAAqK;AACrK,2CAA2C;AAC3C,yEAAyE;AACzE,gEAAgE;AAChE,kCAAkC;AAClC,2FAA2F;AAC3F,iEAAiE;AACjE,MAAM,KAAK,GAAG,OAAO,CAAC;AACtB,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;AACjD,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,kBAAkB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;AACxE,MAAM,GAAG,GAAiC;IACxC,GAAG,EAAE,8CAA8C,cAAc,mBAAmB,iBAAiB,gDAAgD,WAAW,gBAAgB,UAAU,EAAE;IAC5L,MAAM,EAAE,KAAK;IACb,IAAI,EAAE;QACJ,QAAQ,EAAE,QAAQ;QAClB,GAAG,EAAE;YACH,IAAI,EAAE,cAAc;SACrB;QACD,IAAI,EAAE,SAAS;QACf,IAAI,EAAE;YACJ,IAAI,EAAE,QAAQ;YACd,IAAI,EAAE,QAAQ;SACf;KACF;CACF,CAAC;AAEF,iBAAuB,GAAiC;;QACtD,IAAI,GAAiC,CAAC;QACtC,IAAI,CAAC;YACH,GAAG,GAAG,MAAM,MAAM,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC;YAC/C,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACjB,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACpC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC9B,CAAC;QAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACb,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7B,CAAC;IACH,CAAC;CAAA;AACD,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;AAC1B,mFAAmF;AACnF,qCAAqC;AACrC,sBAAsB;AACtB,sBAAsB;AACtB,MAAM;AACN,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAEnD,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;IAC7B,OAAO,CAAC,GAAG,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC;IAChC,UAAU,CAAC,UAAU,CAAC,IAAI,MAAM,CAAC,cAAc,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC;IAClF,YAAY;AACd,CAAC"}

64
samples/node-sample.ts Normal file
Просмотреть файл

@ -0,0 +1,64 @@
"use strict";
import * as msRest from "ms-rest-js";
import * as msRestAzure from "../lib/msRestAzure";
const clientOptions: msRestAzure.AzureServiceClientOptions = {
filters: [new msRest.LogFilter()]
};
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"] || "00977cdb-163f-435f-9c32-39ec8ae61f4d";
const resourceGroupName = "foozap002";
const accountName = "foozy894";
const location = "westus";
const apiVersion = "2017-06-01";
// An easy way to get the token
// 1. Go to this test drive link https://azure.github.io/projects/apis and authenticate by clicking on Authorize. Check the user impersoantion checkbox in the popup.
// 1.1 select a subscription of your choice
// 1.2 select the storage-2015-06-15 option from the first drop down list
// 1.3 expand the url to list storage accounts in a subscription
// 1.4 click on try it out button.
// 1.5 in the curl tab you will see the actual curl request that has the bearer token in it
// 1.6 copy paste that token here. That token is valid for 1 hour
const token = "token";
const creds = new msRest.TokenCredentials(token);
const client = new msRestAzure.AzureServiceClient(creds, clientOptions);
const req: msRest.RequestPrepareOptions = {
url: `https://management.azure.com/subscriptions/${subscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.Storage/storageAccounts/${accountName}?api-version=${apiVersion}`,
method: "PUT",
body: {
location: location,
sku: {
name: "Standard_GRS"
},
kind: "Storage",
tags: {
key1: "value1",
key2: "value2"
}
}
};
async function execute(req: msRest.RequestPrepareOptions): Promise<msRest.HttpOperationResponse> {
let res: msRest.HttpOperationResponse;
try {
res = await client.sendLongRunningRequest(req);
console.dir(res);
document.write(JSON.stringify(res));
return Promise.resolve(res);
} catch (err) {
return Promise.reject(err);
}
}
console.log("Hi There!!");
// client.sendLongRunningRequest(req).then((res: msRest.HttpOperationResponse) => {
// console.log(res.body as string);
// }).catch((err) => {
// console.dir(err);
// });
execute(req).catch((err) => { console.dir(err); });
for (var i = 1; i <= 20; i++) {
console.log("Hello World " + i);
setTimeout(function (x) { return function () { console.log(x); }; }(i), 1000 * i);
// 1 2 3 4 5
}

40
tsconfig.json Normal file
Просмотреть файл

@ -0,0 +1,40 @@
{
"compilerOptions": {
"alwaysStrict": true,
"module": "commonjs",
"noImplicitAny": true,
"preserveConstEnums": true,
"sourceMap": true,
"newLine": "LF",
"target": "es6",
"moduleResolution": "node",
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"outDir": "dist/lib",
"declaration": true,
"declarationDir": "typings/lib",
"allowJs": false,
"strict": true,
"strictNullChecks": true,
"lib": [
"dom",
"dom.iterable",
"es5",
"es6",
"es7",
"esnext",
"esnext.asynciterable",
"es2015.iterable"
]
},
"compileOnSave": true,
"exclude": [
"node_modules"
],
"include": [
"./lib/**/*.ts",
"./test/**/*.ts"
]
}

55
tslint.json Normal file
Просмотреть файл

@ -0,0 +1,55 @@
{
"rules": {
"class-name": true,
"comment-format": [true,
"check-space"
],
"indent": [true,
"spaces"
],
"linebreak-style": [true, "LF"],
"one-line": [true,
"check-open-brace",
"check-whitespace"
],
"no-var-keyword": true,
"quotemark": [true,
"double",
"avoid-escape"
],
"semicolon": [true, "always", "ignore-bound-class-methods"],
"whitespace": [true,
"check-branch",
"check-decl",
"check-operator",
"check-module",
"check-separator",
"check-type"
],
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
},
{
"call-signature": "onespace",
"index-signature": "onespace",
"parameter": "onespace",
"property-declaration": "onespace",
"variable-declaration": "onespace"
}
],
"no-internal-module": true,
"no-trailing-whitespace": true,
"no-inferrable-types": [true],
"no-null-keyword": true,
"prefer-const": true,
"no-switch-case-fall-through": true,
"triple-equals": true,
"jsdoc-format": true
}
}

84
typings/lib/azureServiceClient.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,84 @@
import * as msRest from "ms-rest-js";
/**
* Options to be provided while creating the client.
*/
export interface AzureServiceClientOptions extends msRest.ServiceClientOptions {
/**
* @property {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. Default value is: "en-US".
*/
acceptLanguage?: string;
/**
* @property {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value
* is generated and included in each request. Default is true.
*/
generateClientRequestId?: boolean;
/**
* @property {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for
* Long Running Operations. Default value is 30.
*/
longRunningOperationRetryTimeout?: number;
/**
* @property {number} [rpRegistrationRetryTimeout] - Gets or sets the retry timeout in seconds for
* AutomaticRPRegistration. Default value is 30 seconds.
*/
rpRegistrationRetryTimeout?: number;
}
/**
* @class
* Initializes a new instance of the AzureServiceClient class.
* @constructor
*
* @param {msRest.ServiceClientCredentilas} credentials - ApplicationTokenCredentials or
* UserTokenCredentials object used for authentication.
* @param {AzureServiceClientOptions} options - The parameter options used by AzureServiceClient
*/
export declare class AzureServiceClient extends msRest.ServiceClient {
acceptLanguage: string;
generateClientRequestId: boolean;
longRunningOperationRetryTimeout: number;
rpRegistrationRetryTimeout: number;
constructor(credentials: msRest.ServiceClientCredentials, options?: AzureServiceClientOptions);
/**
* Provides a mechanism to make a request that will poll and provide the final result.
* @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object
* @param {msRest.RequestOptionsBase} [options] Additional options to be sent while making the request
* @returns {Promise<msRest.HttpOperationResponse>} The HttpOperationResponse containing the final polling request, response and the responseBody.
*/
sendLongRunningRequest(request: msRest.RequestPrepareOptions | msRest.WebResource, options?: msRest.RequestOptionsBase): Promise<msRest.HttpOperationResponse>;
/**
* Verified whether an unexpected polling status code for long running operation was received for the response of the initial request.
* @param {msRest.HttpOperationResponse} initialResponse - Response to the initial request that was sent as a part of the asynchronous operation.
*/
private checkResponseStatusCodeFailed(initialResponse);
/**
* Poll Azure long running PUT, PATCH, POST or DELETE operations.
* @param {msRest.HttpOperationResponse} resultOfInitialRequest - result/response of the initial request which is a part of the asynchronous polling operation.
* @param {msRest.RequestOptionsBase} [options] - custom request options.
* @returns {Promise<msRest.HttpOperationResponse>} result - The final response after polling is complete.
*/
getLongRunningOperationResult(resultOfInitialRequest: msRest.HttpOperationResponse, options?: msRest.RequestOptionsBase): Promise<msRest.HttpOperationResponse>;
/**
* Retrieve operation status by polling from "azure-asyncoperation" header.
* @param {PollingState} pollingState - The object to persist current operation state.
* @param {boolean} inPostOrDelete - Invoked by Post Or Delete operation.
*/
private updateStateFromAzureAsyncOperationHeader(pollingState, inPostOrDelete?);
/**
* Retrieve PUT operation status by polling from "location" header.
* @param {string} method - The HTTP method.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
private updateStateFromLocationHeader(method, pollingState);
/**
* Polling for resource status.
* @param {string} resourceUrl - The url of resource.
* @param {PollingState} pollingState - The object to persist current operation state.
*/
private updateStateFromGetResourceOperation(resourceUrl, pollingState);
/**
* Retrieves operation status by querying the operation URL.
* @param {string} operationUrl - URL used to poll operation result.
* @param {object} options - Options that can be set on the request object
*/
private getStatus(operationUrl, options?);
}

15
typings/lib/baseResource.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,15 @@
/**
* @class
* An empty interface.
*/
export interface BaseResource {
}
export declare const BaseResourceMapper: {
required: boolean;
serializedName: string;
type: {
name: string;
className: string;
modelProperties: {};
};
};

68
typings/lib/cloudError.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,68 @@
/**
* @class
* Provides additional information about an http error response returned from a Microsoft Azure service.
*/
export interface CloudError extends Error {
/**
* @property {string} code The error code parsed from the body of the http error response.
*/
code: string;
/**
* @property {string} message The error message parsed from the body of the http error response.
*/
message: string;
/**
* @property {string} [target] The target of the error.
*/
target?: string;
/**
* @property {Array<CloudError>} [details] An array of CloudError objects specifying the details.
*/
details?: Array<CloudError>;
}
export declare const CloudErrorMapper: {
required: boolean;
serializedName: string;
type: {
name: string;
className: string;
modelProperties: {
code: {
required: boolean;
serializedName: string;
type: {
name: string;
};
};
message: {
required: boolean;
serializedName: string;
type: {
name: string;
};
};
target: {
required: boolean;
serializedName: string;
type: {
name: string;
};
};
details: {
required: boolean;
serializedName: string;
type: {
name: string;
element: {
required: boolean;
serializedName: string;
type: {
name: string;
className: string;
};
};
};
};
};
};
};

5
typings/lib/msRestAzure.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,5 @@
import { AzureServiceClientOptions, AzureServiceClient } from "./azureServiceClient";
import Constants from "./util/constants";
import { CloudError, CloudErrorMapper } from "./cloudError";
import { BaseResource, BaseResourceMapper } from "./baseResource";
export { AzureServiceClient, AzureServiceClientOptions, Constants, CloudError, CloudErrorMapper, BaseResource, BaseResourceMapper };

69
typings/lib/pollingState.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,69 @@
import * as msRest from "ms-rest-js";
/**
* @class
* Initializes a new instance of the PollingState class.
*/
export default class PollingState {
/**
* @param {msRest.HttpOperationResponse} [response] - Response of the initial request that was made as a part of the asynchronous operation.
*/
resultOfInitialRequest: msRest.HttpOperationResponse;
/**
* @param {msRest.RequestOptionsBase} [optionsOfInitialRequest] - Request options that were provided as a part of the initial request.
*/
optionsOfInitialRequest: msRest.RequestOptionsBase;
/**
* @param {msRest.WebResource} [request] - provides information about the request made for polling.
*/
request: msRest.WebResource;
/**
* @param {Response} [response] - The response object to extract longrunning operation status.
*/
response: Response;
/**
* @param {any} [resource] - Provides information about the response body received in the polling request. Particularly useful when polling via provisioningState.
*/
resource: any;
/**
* @param {number} [retryTimeout] - The timeout in seconds to retry on intermediate operation results. Default Value is 30.
*/
retryTimeout: number;
/**
* @param {string} [azureAsyncOperationHeaderLink] - The url that is present in "azure-asyncoperation" response header.
*/
azureAsyncOperationHeaderLink?: string;
/**
* @param {string} [locationHeaderLink] - The url that is present in "Location" response header.
*/
locationHeaderLink?: string;
/**
* @param {string} [status] - The status of polling. "Succeeded, Failed, Cancelled, Updating, Creating, etc."
*/
status?: string;
/**
* @param {msRest.RestError} [error] - Provides information about the error that happened while polling.
*/
error?: msRest.RestError;
constructor(resultOfInitialRequest: msRest.HttpOperationResponse, retryTimeout?: number);
/**
* Update cached data using the provided response object
* @param {Response} [response] - provider response object.
*/
updateResponse(response: Response): void;
/**
* Gets timeout in milliseconds.
* @returns {number} timeout
*/
getTimeout(): number;
/**
* Returns long running operation result.
* @returns {msRest.HttpOperationResponse} HttpOperationResponse
*/
getOperationResponse(): msRest.HttpOperationResponse;
/**
* Returns an Error on operation failure.
* @param {Error} err - The error object.
* @returns {msRest.RestError} The RestError defined in the runtime.
*/
getRestError(err?: Error): msRest.RestError;
}

11
typings/lib/util/constants.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,11 @@
declare const Constants: {
LongRunningOperationStates: {
InProgress: string;
Succeeded: string;
Failed: string;
Canceled: string;
};
DEFAULT_LANGUAGE: string;
msRestAzureVersion: string;
};
export default Constants;

44
webpack.config.js Normal file
Просмотреть файл

@ -0,0 +1,44 @@
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: './lib/msRestAzure.ts',
devtool: 'source-map',
output: {
filename: 'msRestAzureBundle.js',
path: __dirname,
libraryTarget: 'var',
library: 'msRestAzure'
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /(node_modules|test)/
}
]
},
// ms-rest-js is a dependency of this project. Customer is expected to manually import/include
// this for browser javascript in a script tag. More info over here
// https://webpack.js.org/configuration/externals/ and https://webpack.js.org/guides/author-libraries/#add-externals.
externals: {
"ms-rest-js": "msRest"
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
node: {
fs: false,
net: false,
path: false,
dns: false,
tls: false,
tty: false,
v8: false,
Buffer: false
}
};