@azure/ms-rest-azure-js
Version:
Isomorphic Azure client runtime for Typescript/node.js/browser javascript client libraries generated using AutoRest
1,020 lines (1,004 loc) • 51.4 kB
JavaScript
/** @license ms-rest-azure-js
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@azure/ms-rest-js')) :
typeof define === 'function' && define.amd ? define(['exports', '@azure/ms-rest-js'], factory) :
(global = global || self, factory(global.msRestAzure = {}, global.msRest));
}(this, (function (exports, msRestJs) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
// Copyright (c) Microsoft Corporation. All rights reserved.
/**
* A long-running operation polling strategy base class that other polling strategies should extend.
*/
var LROPollStrategy = /** @class */ (function () {
function LROPollStrategy(_azureServiceClient, _pollState) {
this._azureServiceClient = _azureServiceClient;
this._pollState = _pollState;
}
LROPollStrategy.prototype.getOperationStatus = function () {
return this._pollState.state;
};
/**
* Get whether or not this poll strategy's LRO is finished.
* @returns Whether or not this poll strategy's LRO is finished.
*/
LROPollStrategy.prototype.isFinished = function () {
return isFinished(this._pollState.state);
};
/**
* Send poll requests that check the LRO's status until it is determined that the LRO is finished.
* @returns Whether or not the LRO succeeded.
*/
LROPollStrategy.prototype.pollUntilFinished = function () {
return __awaiter(this, void 0, void 0, function () {
var delayInSeconds;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!!this.isFinished()) return [3 /*break*/, 3];
delayInSeconds = getDelayInSeconds(this._azureServiceClient, this._pollState.mostRecentResponse);
return [4 /*yield*/, msRestJs.delay(delayInSeconds * 1000)];
case 1:
_a.sent();
return [4 /*yield*/, this.sendPollRequest()];
case 2:
_a.sent();
return [3 /*break*/, 0];
case 3: return [2 /*return*/, this.isFinalStatusAcceptable()];
}
});
});
};
LROPollStrategy.prototype.shouldDoFinalGetResourceRequest = function () {
var initialRequestMethod = this._pollState.initialResponse.request.method;
return !this._pollState.resource && (initialRequestMethod === "PUT" || initialRequestMethod === "PATCH" || initialRequestMethod === "POST");
};
LROPollStrategy.prototype.getMostRecentResponse = function () {
return this._pollState.mostRecentResponse;
};
LROPollStrategy.prototype.getOperationResponse = function () {
return __awaiter(this, void 0, void 0, function () {
var response, result, resource;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.shouldDoFinalGetResourceRequest()) return [3 /*break*/, 2];
return [4 /*yield*/, this.doFinalGetResourceRequest()];
case 1:
_a.sent();
_a.label = 2;
case 2:
response = this._pollState.mostRecentResponse;
result = __assign(__assign({}, response), { headers: response.headers.clone() });
resource = this._pollState.resource;
if (!resource) {
result.bodyAsText = response.bodyAsText;
result.parsedBody = response.parsedBody;
}
else if (typeof resource.valueOf() === "string") {
result.bodyAsText = resource;
try {
result.parsedBody = JSON.parse(resource);
}
catch (err) {
// There was an error parsing the JSON. Hence we set the resource as-is. Most likely, the
// resource is a string that was already parsed.
result.parsedBody = resource;
}
}
else {
result.bodyAsText = JSON.stringify(resource);
result.parsedBody = resource;
}
return [2 /*return*/, result];
}
});
});
};
LROPollStrategy.prototype.getRestError = function () {
var error = new msRestJs.RestError("");
error.request = msRestJs.stripRequest(this._pollState.mostRecentRequest);
error.response = this._pollState.mostRecentResponse;
error.message = "Long running operation failed with status: \"" + this._pollState.state + "\".";
error.body = this._pollState.resource;
if (error.body) {
var innerError = error.body.error;
if (innerError) {
if (innerError.message) {
error.message = "Long running operation failed with error: \"" + innerError.message + "\".";
}
if (innerError.code) {
error.code = innerError.code;
}
}
}
return error;
};
LROPollStrategy.prototype.updateState = function (url, shouldDeserialize) {
var _this = this;
return this.updateOperationStatus(url, shouldDeserialize).then(function (result) {
_this._pollState.state = getProvisioningState(result.parsedBody) || "Succeeded";
_this._pollState.mostRecentResponse = result;
_this._pollState.mostRecentRequest = result.request;
_this._pollState.resource = getResponseBody(result);
}).catch(function (error) {
var resultStatus;
if (error.response && error.response.status) {
resultStatus = error.response.status;
if (_this._pollState.initialResponse.request.method !== "DELETE" || resultStatus < 400 || 499 < resultStatus) {
throw error;
}
}
else {
throw error;
}
});
};
/**
* Retrieves operation status by querying the operation URL.
* @param {string} statusUrl URL used to poll operation result.
*/
LROPollStrategy.prototype.updateOperationStatus = function (statusUrl, shouldDeserialize) {
var requestUrl = statusUrl.replace(" ", "%20");
var httpRequest = new msRestJs.WebResource(requestUrl, "GET");
var pollState = this._pollState;
httpRequest.operationSpec = pollState.mostRecentRequest.operationSpec;
httpRequest.shouldDeserialize = shouldDeserialize;
httpRequest.operationResponseGetter = getOperationResponse;
var options = pollState.options;
if (options && options.customHeaders) {
var customHeaders = options.customHeaders;
for (var _i = 0, _a = Object.keys(customHeaders); _i < _a.length; _i++) {
var headerName = _a[_i];
httpRequest.headers.set(headerName, customHeaders[headerName]);
}
}
return this._azureServiceClient.sendRequest(httpRequest);
};
LROPollStrategy.prototype.getPollState = function () {
return this._pollState;
};
return LROPollStrategy;
}());
function getOperationResponse(operationSpec, response) {
var statusCode = response.status;
var operationResponses = operationSpec.responses;
var result = operationResponses[statusCode];
if (!result) {
if (statusCode === 200) {
result = operationResponses[201] || operationResponses[202];
}
else if (201 <= statusCode && statusCode <= 299) {
result = {};
}
}
return result;
}
function getDelayInSeconds(azureServiceClient, previousResponse) {
var delayInSeconds = 30;
if (azureServiceClient.longRunningOperationRetryTimeout != undefined) {
delayInSeconds = azureServiceClient.longRunningOperationRetryTimeout;
}
else {
var retryAfterHeaderValue = previousResponse.headers.get("retry-after");
if (retryAfterHeaderValue) {
var retryAfterDelayInSeconds = parseInt(retryAfterHeaderValue);
if (!Number.isNaN(retryAfterDelayInSeconds)) {
delayInSeconds = retryAfterDelayInSeconds;
}
}
}
return delayInSeconds;
}
function getProvisioningState(responseBody) {
var result;
if (responseBody) {
if (responseBody.provisioningState) {
result = responseBody.provisioningState;
}
else if (responseBody.properties) {
result = responseBody.properties.provisioningState;
}
}
return result;
}
function getResponseBody(response) {
var result;
try {
if (response.parsedBody) {
result = response.parsedBody;
}
else if (response.bodyAsText && response.bodyAsText.length > 0) {
result = JSON.parse(response.bodyAsText);
}
}
catch (error) {
var deserializationError = new msRestJs.RestError("Error \"" + error + "\" occurred in parsing the responseBody \" +\n \"while creating the PollingState for Long Running Operation- \"" + response.bodyAsText + "\"");
deserializationError.request = response.request;
deserializationError.response = response;
throw deserializationError;
}
return result;
}
function getStatusFromResponse(response, responseBody) {
if (responseBody == undefined) {
responseBody = getResponseBody(response);
}
var result;
switch (response.status) {
case 202:
result = "InProgress";
break;
case 204:
result = "Succeeded";
break;
case 201:
result = getProvisioningState(responseBody) || "InProgress";
break;
case 200:
var provisioningState = getProvisioningState(responseBody);
if (provisioningState) {
result = provisioningState;
}
else if (getAzureAsyncOperationHeaderValue(response) || getLocationHeaderValue(response)) {
result = "InProgress";
}
else {
result = "Succeeded";
}
break;
default:
result = "Failed";
break;
}
return result;
}
var terminalStates = ["Succeeded", "Failed", "Canceled", "Cancelled"];
/**
* Get whether or not a long-running operation with the provided status is finished.
* @param status The current status of a long-running operation.
* @returns Whether or not a long-running operation with the provided status is finished.
*/
function isFinished(status) {
var result = false;
for (var _i = 0, terminalStates_1 = terminalStates; _i < terminalStates_1.length; _i++) {
var terminalState = terminalStates_1[_i];
if (longRunningOperationStatesEqual(status, terminalState)) {
result = true;
break;
}
}
return result;
}
function longRunningOperationStatesEqual(lhs, rhs) {
var lhsLowerCased = lhs && lhs.toLowerCase();
var rhsLowerCased = rhs && rhs.toLowerCase();
return lhsLowerCased === rhsLowerCased;
}
/**
* Create a new long-running operation polling strategy based on the provided initial response.
* @param initialResponse The initial response to the long-running operation's initial request.
* @param azureServiceClient The AzureServiceClient that was used to send the initial request.
* @param options Any options that were provided to the initial request.
*/
function createLROPollStrategyFromInitialResponse(initialResponse, azureServiceClient, options) {
var initialRequestMethod = initialResponse.request.method;
var initialResponseStatus = initialResponse.status;
var lroPollStrategyType;
if (getAzureAsyncOperationHeaderValue(initialResponse)) {
lroPollStrategyType = "AzureAsyncOperation";
}
else if (getLocationHeaderValue(initialResponse)) {
lroPollStrategyType = "Location";
}
else if (initialRequestMethod === "PUT" || initialRequestMethod === "PATCH") {
lroPollStrategyType = "GetResource";
}
else if (initialResponseStatus !== 201 && initialResponseStatus !== 202 && !isFinished(getStatusFromResponse(initialResponse))) {
throw new Error("Can't determine long running operation polling strategy.");
}
var result;
if (lroPollStrategyType) {
var resource = getResponseBody(initialResponse);
var lroPollState = {
pollStrategyType: lroPollStrategyType,
options: options,
initialResponse: initialResponse,
mostRecentResponse: initialResponse,
mostRecentRequest: initialResponse.request,
azureAsyncOperationHeaderValue: getAzureAsyncOperationHeaderValue(initialResponse),
locationHeaderValue: getLocationHeaderValue(initialResponse),
resource: resource,
state: getStatusFromResponse(initialResponse, resource)
};
result = createLROPollStrategyFromPollState(azureServiceClient, lroPollState);
}
else {
result = undefined;
}
return result;
}
function createLROPollStrategyFromPollState(azureServiceClient, lroPollState) {
var result;
switch (lroPollState.pollStrategyType) {
case "AzureAsyncOperation":
result = new AzureAsyncOperationLROPollStrategy(azureServiceClient, lroPollState);
break;
case "Location":
result = new LocationLROPollStrategy(azureServiceClient, lroPollState);
break;
case "GetResource":
result = new GetResourceLROPollStrategy(azureServiceClient, lroPollState);
break;
default:
throw new Error("Unrecognized LRO poll strategy type: \"" + lroPollState.pollStrategyType + "\"");
}
return result;
}
function getLocationHeaderValue(response) {
return response.headers.get("location");
}
/**
* A long-running operation polling strategy that is based on the location header.
*/
var LocationLROPollStrategy = /** @class */ (function (_super) {
__extends(LocationLROPollStrategy, _super);
function LocationLROPollStrategy() {
return _super !== null && _super.apply(this, arguments) || this;
}
LocationLROPollStrategy.prototype.locationStrategyShouldDeserialize = function (parsedResponse) {
var shouldDeserialize = false;
var initialResponse = this._pollState.initialResponse;
var initialRequestMethod = initialResponse.request.method;
var statusCode = parsedResponse.status;
if (statusCode === 200 ||
(statusCode === 201 && (initialRequestMethod === "PUT" || initialRequestMethod === "PATCH")) ||
(statusCode === 204 && (initialRequestMethod === "DELETE" || initialRequestMethod === "POST"))) {
shouldDeserialize = true;
}
return shouldDeserialize;
};
/**
* 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.
*/
LocationLROPollStrategy.prototype.sendPollRequest = function () {
var lroPollState = this._pollState;
return this.updateOperationStatus(lroPollState.locationHeaderValue, this.locationStrategyShouldDeserialize.bind(this)).then(function (result) {
var locationHeaderValue = getLocationHeaderValue(result);
if (locationHeaderValue) {
lroPollState.locationHeaderValue = locationHeaderValue;
}
lroPollState.mostRecentResponse = result;
lroPollState.mostRecentRequest = result.request;
var initialResponse = lroPollState.initialResponse;
var initialRequestMethod = initialResponse.request.method;
var initialResponseStatusCode = initialResponse.status;
var statusCode = result.status;
if (statusCode === 202) {
lroPollState.state = "InProgress";
}
else if (statusCode === 200 ||
(statusCode === 201 && (initialRequestMethod === "PUT" || initialRequestMethod === "PATCH")) ||
(statusCode === 204 && (initialRequestMethod === "DELETE" || initialRequestMethod === "POST"))) {
lroPollState.state = "Succeeded";
lroPollState.resource = getResponseBody(result);
}
else if (statusCode === 404 && initialRequestMethod === "POST" &&
(initialResponseStatusCode === 200 || initialResponseStatusCode === 201 || initialResponseStatusCode === 202)) {
lroPollState.state = "Failed";
lroPollState.resource = getResponseBody(result);
}
else if (400 <= statusCode && statusCode <= 499) {
var resultBody = result.bodyAsText;
var errorMessage = resultBody;
try {
var resultObject = JSON.parse(resultBody);
errorMessage = resultObject.message;
}
catch (parseError) {
// Ignore the exception, use resultBody as the error message
}
throw new msRestJs.RestError(errorMessage, undefined, statusCode, msRestJs.stripRequest(result.request), result, resultBody);
}
else {
throw new Error("The response with status code " + statusCode + " from polling for long running operation url \"" + lroPollState.locationHeaderValue + "\" is not valid.");
}
});
};
LocationLROPollStrategy.prototype.isFinalStatusAcceptable = function () {
var lroPollState = this._pollState;
var initialResponse = lroPollState.initialResponse;
var initialResponseStatusCode = initialResponse.status;
return longRunningOperationStatesEqual(lroPollState.state, "Succeeded") ||
(initialResponse.request.method === "POST" && lroPollState.mostRecentResponse.status === 404 &&
(initialResponseStatusCode === 200 ||
initialResponseStatusCode === 201 ||
initialResponseStatusCode === 202));
};
LocationLROPollStrategy.prototype.shouldDoFinalGetResourceRequest = function () {
var lroPollState = this._pollState;
var initialResponse = lroPollState.initialResponse;
var result;
var initialRequestMethod = initialResponse.request.method;
var initialResponseStatusCode = initialResponse.status;
if (initialRequestMethod === "POST" && lroPollState.mostRecentResponse.status === 404 &&
(initialResponseStatusCode === 200 ||
initialResponseStatusCode === 201 ||
initialResponseStatusCode === 202)) {
result = false;
}
else {
result = _super.prototype.shouldDoFinalGetResourceRequest.call(this) ||
(initialRequestMethod === "POST" && initialResponseStatusCode === 201);
}
return result;
};
LocationLROPollStrategy.prototype.doFinalGetResourceRequest = function () {
var lroPollState = this._pollState;
var initialResponse = lroPollState.initialResponse;
var getResourceRequestUrl;
var initialResponseStatusCode = initialResponse.status;
var initialRequest = initialResponse.request;
if (initialRequest.method === "POST" &&
(initialResponseStatusCode === 200 ||
initialResponseStatusCode === 201 ||
initialResponseStatusCode === 202)) {
getResourceRequestUrl = lroPollState.locationHeaderValue;
}
else {
getResourceRequestUrl = initialRequest.url;
}
return this.updateState(getResourceRequestUrl, true);
};
return LocationLROPollStrategy;
}(LROPollStrategy));
function getAzureAsyncOperationHeaderValue(response) {
return response.headers.get("azure-asyncoperation");
}
/**
* A long-running operation polling strategy that is based on the azure-asyncoperation header.
*/
var AzureAsyncOperationLROPollStrategy = /** @class */ (function (_super) {
__extends(AzureAsyncOperationLROPollStrategy, _super);
function AzureAsyncOperationLROPollStrategy() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* 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.
*/
AzureAsyncOperationLROPollStrategy.prototype.sendPollRequest = function () {
var lroPollState = this._pollState;
return this.updateOperationStatus(lroPollState.azureAsyncOperationHeaderValue, false).then(function (response) {
var statusCode = response.status;
var parsedResponse = response.parsedBody;
if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {
var error = new msRestJs.RestError("Invalid status code (" + statusCode + ") with response body \"" + response.bodyAsText + "\" occurred when polling for operation status.");
error.statusCode = statusCode;
error.request = msRestJs.stripRequest(response.request);
error.response = response;
error.body = parsedResponse;
throw error;
}
if (!parsedResponse) {
throw new Error("The response from long running operation does not contain a body.");
}
else if (!parsedResponse.status) {
throw new Error("The response \"" + response.bodyAsText + "\" from long running operation does not contain the status property.");
}
var azureAsyncOperationHeaderValue = getAzureAsyncOperationHeaderValue(response);
if (azureAsyncOperationHeaderValue) {
lroPollState.azureAsyncOperationHeaderValue = azureAsyncOperationHeaderValue;
}
lroPollState.state = parsedResponse.status;
lroPollState.mostRecentResponse = response;
lroPollState.mostRecentRequest = response.request;
lroPollState.resource = getResponseBody(response);
});
};
AzureAsyncOperationLROPollStrategy.prototype.shouldDoFinalGetResourceRequest = function () {
var lroPollState = this._pollState;
var initialResponse = lroPollState.initialResponse;
var initialRequestMethod = initialResponse.request.method;
var result = false;
if (initialRequestMethod === "PUT" || initialRequestMethod === "PATCH") {
result = true;
}
else {
if (lroPollState.locationHeaderValue) {
var initialResponseStatusCode = initialResponse.status;
if (initialRequestMethod === "POST") {
result = initialResponseStatusCode === 200 || initialResponseStatusCode === 201;
}
else if (initialRequestMethod === "DELETE") {
result = initialResponseStatusCode === 200 || initialResponseStatusCode === 202;
}
}
}
return result;
};
AzureAsyncOperationLROPollStrategy.prototype.doFinalGetResourceRequest = function () {
var lroPollState = this._pollState;
var locationHeaderValue = lroPollState.locationHeaderValue;
var initialResponse = lroPollState.initialResponse;
var initialRequest = initialResponse.request;
var getResourceRequestUrl = initialRequest.url;
if (locationHeaderValue) {
var initialRequestMethod = initialRequest.method;
var initialResponseStatusCode = initialResponse.status;
if (initialRequestMethod === "POST" && (initialResponseStatusCode === 200 || initialResponseStatusCode === 201 || initialResponseStatusCode === 202)) {
getResourceRequestUrl = locationHeaderValue;
}
else if (initialRequestMethod === "DELETE" && (initialResponseStatusCode === 200 || initialResponseStatusCode === 202)) {
getResourceRequestUrl = locationHeaderValue;
}
}
return this.updateState(getResourceRequestUrl, true);
};
AzureAsyncOperationLROPollStrategy.prototype.isFinalStatusAcceptable = function () {
var lroPollState = this._pollState;
var initialResponse = lroPollState.initialResponse;
var initialResponseStatusCode = initialResponse.status;
return longRunningOperationStatesEqual(lroPollState.state, "Succeeded") ||
(initialResponse.request.method === "POST" && (initialResponseStatusCode === 200 || initialResponseStatusCode === 201));
};
return AzureAsyncOperationLROPollStrategy;
}(LROPollStrategy));
/**
* A long-running operation polling strategy that is based on the resource's provisioning state.
*/
var GetResourceLROPollStrategy = /** @class */ (function (_super) {
__extends(GetResourceLROPollStrategy, _super);
function GetResourceLROPollStrategy() {
return _super !== null && _super.apply(this, arguments) || this;
}
GetResourceLROPollStrategy.prototype.sendPollRequest = function () {
var lroPollState = this._pollState;
return this.updateOperationStatus(lroPollState.initialResponse.request.url, false).then(function (result) {
var statusCode = result.status;
var responseBody = result.parsedBody;
if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {
var error = new msRestJs.RestError("Invalid status code with response body \"" + result.bodyAsText + "\" occurred when polling for operation status.");
error.statusCode = statusCode;
error.request = msRestJs.stripRequest(result.request);
error.response = result;
error.body = responseBody;
throw error;
}
if (!result.parsedBody) {
throw new Error("The response from long running operation does not contain a body.");
}
lroPollState.state = getProvisioningState(result.parsedBody) || "Succeeded";
lroPollState.mostRecentResponse = result;
lroPollState.mostRecentRequest = result.request;
lroPollState.resource = getResponseBody(result);
});
};
GetResourceLROPollStrategy.prototype.isFinalStatusAcceptable = function () {
return longRunningOperationStatesEqual(this._pollState.state, "Succeeded");
};
GetResourceLROPollStrategy.prototype.doFinalGetResourceRequest = function () {
return this.sendPollRequest();
};
return GetResourceLROPollStrategy;
}(LROPollStrategy));
// Copyright (c) Microsoft Corporation. All rights reserved.
/**
* An HTTP operation response that provides special methods for interacting with LROs (long running
* operations).
*/
var LROPoller = /** @class */ (function () {
/**
* Create a new HttpLongRunningOperationResponse.
* @param _lroPollStrategy The LROPollStrategy that this HttpLongRunningOperationResponse will
* use to interact with the LRO.
*/
function LROPoller(_lroPollStrategy, _initialResponse) {
this._lroPollStrategy = _lroPollStrategy;
this._initialResponse = _initialResponse;
}
/**
* Get the first response that the service sent back when the LRO was initiated.
*/
LROPoller.prototype.getInitialResponse = function () {
return this._initialResponse;
};
/**
* Get the most recent response that the service sent back during this LRO.
*/
LROPoller.prototype.getMostRecentResponse = function () {
var lroPollStrategy = this._lroPollStrategy;
return !lroPollStrategy ? this._initialResponse : lroPollStrategy.getMostRecentResponse();
};
/**
* Get whether or not the LRO is finished.
*/
LROPoller.prototype.isFinished = function () {
var lroPollStrategy = this._lroPollStrategy;
return !lroPollStrategy ? true : lroPollStrategy.isFinished();
};
/**
* Get whether or not the LRO is finished and its final state is acceptable. If the LRO has not
* finished yet, then undefined will be returned. An "acceptable" final state is determined by the
* LRO strategy that the Azure service uses to perform long running operations.
*/
LROPoller.prototype.isFinalStatusAcceptable = function () {
var result;
var lroPollStrategy = this._lroPollStrategy;
if (!lroPollStrategy) {
result = true;
}
else if (lroPollStrategy.isFinished()) {
result = lroPollStrategy.isFinalStatusAcceptable();
}
return result;
};
/**
* Get the current status of the LRO.
*/
LROPoller.prototype.getOperationStatus = function () {
var lroPollStrategy = this._lroPollStrategy;
return !lroPollStrategy ? "Succeeded" : lroPollStrategy.getOperationStatus();
};
/**
* If the LRO is finished and in an acceptable state, then return the HttpOperationResponse. If
* the LRO is finished and not in an acceptable state, then throw the error that the LRO produced.
* If the LRO is not finished, then return undefined.
*/
LROPoller.prototype.getOperationResponse = function () {
var result;
var lroPollStrategy = this._lroPollStrategy;
if (!lroPollStrategy) {
result = Promise.resolve(this._initialResponse);
}
else if (!lroPollStrategy.isFinished()) {
result = Promise.resolve(undefined);
}
else if (lroPollStrategy.isFinalStatusAcceptable()) {
result = lroPollStrategy.getOperationResponse();
}
else {
throw lroPollStrategy.getRestError();
}
return result;
};
/**
* Send a single poll request and return the LRO's state.
*/
LROPoller.prototype.poll = function () {
var result;
var lroPollStrategy = this._lroPollStrategy;
if (!lroPollStrategy) {
result = Promise.resolve("Succeeded");
}
else {
result = lroPollStrategy.sendPollRequest().then(function () {
return lroPollStrategy.getOperationStatus();
});
}
return result;
};
/**
* Send poll requests that check the LRO's status until it is determined that the LRO is finished.
*/
LROPoller.prototype.pollUntilFinished = function () {
return __awaiter(this, void 0, void 0, function () {
var result, lroPollStrategy;
return __generator(this, function (_a) {
lroPollStrategy = this._lroPollStrategy;
if (!lroPollStrategy) {
result = Promise.resolve(flattenAzureResponse(this._initialResponse));
}
else {
result = lroPollStrategy.pollUntilFinished().then(function (succeeded) {
if (succeeded) {
return lroPollStrategy.getOperationResponse().then(flattenAzureResponse);
}
else {
throw lroPollStrategy.getRestError();
}
});
}
return [2 /*return*/, result];
});
});
};
/**
* Get an LROPollState object that can be used to poll this LRO in a different context (such as on
* a different process or a different machine). If the LRO couldn't produce an LRO polling
* strategy, then this will return undefined.
*/
LROPoller.prototype.getPollState = function () {
var lroPollStrategy = this._lroPollStrategy;
return !lroPollStrategy ? undefined : lroPollStrategy.getPollState();
};
return LROPoller;
}());
function createLROPollerFromInitialResponse(azureServiceClient, initialResponse, options) {
var lroPollStrategy = createLROPollStrategyFromInitialResponse(initialResponse, azureServiceClient, options);
return new LROPoller(lroPollStrategy, initialResponse);
}
function createLROPollerFromPollState(azureServiceClient, lroMemento) {
var lroPollStrategy = createLROPollStrategyFromPollState(azureServiceClient, lroMemento);
return new LROPoller(lroPollStrategy, lroMemento.initialResponse);
}
function flattenAzureResponse(response) {
var _a = response.request, operationResponseGetter = _a.operationResponseGetter, operationSpec = _a.operationSpec;
return msRestJs.flattenResponse(response, operationResponseGetter && operationSpec && operationResponseGetter(operationSpec, response));
}
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
/**
* The default language in the request header.
*
* @const
* @type {string}
*/
var DEFAULT_LANGUAGE = "en-us";
/**
* The ms-rest-azure version.
* @const
* @type {string}
*/
var msRestAzureVersion = "2.1.0";
// Copyright (c) Microsoft Corporation. All rights reserved.
/**
* @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
*/
var AzureServiceClient = /** @class */ (function (_super) {
__extends(AzureServiceClient, _super);
function AzureServiceClient(credentials, options) {
var _a;
var _this = _super.call(this, credentials, options = updateOptionsWithDefaultValues(options)) || this;
_this.acceptLanguage = DEFAULT_LANGUAGE;
// For convenience, if the credentials have an associated AzureEnvironment,
// automatically use the baseUri from that environment.
var env = (_a = credentials) === null || _a === void 0 ? void 0 : _a.environment;
if (env && !_this.baseUri) {
_this.baseUri = env.resourceManagerEndpointUrl;
}
if (options.acceptLanguage != undefined) {
_this.acceptLanguage = options.acceptLanguage;
}
if (options.longRunningOperationRetryTimeout != undefined) {
_this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;
}
return _this;
}
/**
* Send the initial request of a LRO (long running operation) and get back an
* LROPoller that provides methods for polling the LRO and checking if the LRO is finished.
* @param operationArguments The arguments to the operation.
* @param operationSpec The specification for the operation.
* @param options Additional options to be sent while making the request.
* @returns The LROPoller object that provides methods for interacting with the LRO.
*/
AzureServiceClient.prototype.sendLRORequest = function (operationArguments, operationSpec, options) {
var _this = this;
return this.sendOperationRequest(operationArguments, operationSpec)
.then(function (initialResponse) { return createLROPollerFromInitialResponse(_this, initialResponse._response, options); });
};
/**
* 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 {AzureRequestOptionsBase} [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.
*/
AzureServiceClient.prototype.sendLongRunningRequest = function (request, options) {
return this.beginLongRunningRequest(request, options)
.then(function (lroResponse) { return lroResponse.pollUntilFinished(); })
.then(function (res) { return res._response; });
};
/**
* Send the initial request of a LRO (long running operation) and get back an
* HttpLongRunningOperationResponse that provides methods for polling the LRO and checking if the
* LRO is finished.
* @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object
* @param {AzureRequestOptionsBase} [options] Additional options to be sent while making the request
* @returns {Promise<LROPoller>} The HttpLongRunningOperationResponse
* that provides methods for interacting with the LRO.
*/
AzureServiceClient.prototype.beginLongRunningRequest = function (request, options) {
var _this = this;
return this.sendRequest(request)
.then(function (initialResponse) { return createLROPollerFromInitialResponse(_this, initialResponse, options); });
};
/**
* Restore an LROPoller from the provided LROPollState. This method can be used to recreate an
* LROPoller on a different process or machine.
*/
AzureServiceClient.prototype.restoreLROPoller = function (lroPollState) {
return createLROPollerFromPollState(this, lroPollState);
};
return AzureServiceClient;
}(msRestJs.ServiceClient));
function getDefaultUserAgentValue() {
var defaultUserAgent = msRestJs.getDefaultUserAgentValue();
return "ms-rest-azure-js/" + msRestAzureVersion + " " + defaultUserAgent;
}
function updateOptionsWithDefaultValues(options) {
if (!options) {
options = {};
}
if (options.generateClientRequestIdHeader == undefined) {
options.generateClientRequestIdHeader = true;
}
if (!options.userAgent) {
options.userAgent = getDefaultUserAgentValue();
}
return options;
}
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
var BaseResourceMapper = {
serializedName: "BaseResource",
type: {
name: "Composite",
className: "BaseResource",
modelProperties: {}
}
};
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
var CloudErrorMapper = {
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: {
serializedName: "target",
type: {
name: "String"
}
},
details: {
serializedName: "details",
type: {
name: "Sequence",
element: {
serializedName: "CloudErrorElementType",
type: {
name: "Composite",
className: "CloudError"
}
}
}
},
innerError: {
required: false,
serializedName: "innererror",
type: {
name: "Object"
}
},
additionalInfo: {
required: false,
serializedName: "additionalInfo",
type: {
name: "Composite",
className: "AdditionalInfoElement",
modelProperties: {
type: {
required: true,
serializedName: "type",
type: {
name: "String"
}
},
info: {
required: false,
serializedName: "info",
type: {
name: "Object"
}
}
}
}
}
}
}
};
// Copyright (c) Microsoft Corporation. All rights reserved.
/**
* Creates a new CognitiveServicesCredentials object.
*
* @constructor
* @param {string} subscriptionKey The CognitiveServices subscription key
*/
var CognitiveServicesCredentials = /** @class */ (function (_super) {
__extends(CognitiveServicesCredentials, _super);