UNPKG

@azure/ms-rest-azure-js

Version:

Isomorphic Azure client runtime for Typescript/node.js/browser javascript client libraries generated using AutoRest

1 lines 82.8 kB
{"version":3,"file":"msRestAzure.js","sources":["../node_modules/tslib/tslib.es6.js","../lib/lroPollStrategy.ts","../lib/lroPoller.ts","../lib/util/constants.ts","../lib/azureServiceClient.ts","../lib/baseResource.ts","../lib/cloudError.ts","../lib/credentials/cognitiveServicesCredentials.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n 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;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n\nimport { delay, HttpMethods, HttpOperationResponse, RequestOptionsBase, RestError, stripRequest, WebResource, OperationResponse, OperationSpec } from \"@azure/ms-rest-js\";\nimport { AzureServiceClient } from \"./azureServiceClient\";\nimport { LongRunningOperationStates } from \"./util/constants\";\n\nexport type LROPollStrategyType = \"AzureAsyncOperation\" | \"Location\" | \"GetResource\";\n\nexport interface LROPollState {\n pollStrategyType: LROPollStrategyType;\n initialResponse: HttpOperationResponse;\n state: LongRunningOperationStates;\n mostRecentRequest: WebResource;\n mostRecentResponse: HttpOperationResponse;\n resource: any;\n azureAsyncOperationHeaderValue?: string;\n locationHeaderValue?: string;\n options?: RequestOptionsBase;\n}\n\n/**\n * A long-running operation polling strategy base class that other polling strategies should extend.\n */\nexport abstract class LROPollStrategy {\n constructor(private readonly _azureServiceClient: AzureServiceClient, protected readonly _pollState: LROPollState) {\n }\n\n public getOperationStatus(): LongRunningOperationStates {\n return this._pollState.state;\n }\n\n /**\n * Get whether or not this poll strategy's LRO is finished.\n * @returns Whether or not this poll strategy's LRO is finished.\n */\n public isFinished(): boolean {\n return isFinished(this._pollState.state);\n }\n\n /**\n * Send poll requests that check the LRO's status until it is determined that the LRO is finished.\n * @returns Whether or not the LRO succeeded.\n */\n public async pollUntilFinished(): Promise<boolean> {\n while (!this.isFinished()) {\n const delayInSeconds: number = getDelayInSeconds(this._azureServiceClient, this._pollState.mostRecentResponse);\n await delay(delayInSeconds * 1000);\n\n await this.sendPollRequest();\n }\n return this.isFinalStatusAcceptable();\n }\n\n /**\n * Send a single poll request that checks the LRO's status and return the response. If the LRO is\n * finished, then no request will be sent and the last response received will be returned.\n */\n public abstract sendPollRequest(): Promise<void>;\n\n public abstract isFinalStatusAcceptable(): boolean;\n\n protected shouldDoFinalGetResourceRequest(): boolean {\n const initialRequestMethod: HttpMethods = this._pollState.initialResponse.request.method;\n return !this._pollState.resource && (initialRequestMethod === \"PUT\" || initialRequestMethod === \"PATCH\" || initialRequestMethod === \"POST\");\n }\n\n protected abstract doFinalGetResourceRequest(): Promise<void>;\n\n public getMostRecentResponse(): HttpOperationResponse {\n return this._pollState.mostRecentResponse;\n }\n\n public async getOperationResponse(): Promise<HttpOperationResponse> {\n if (this.shouldDoFinalGetResourceRequest()) {\n await this.doFinalGetResourceRequest();\n }\n const response: HttpOperationResponse = this._pollState.mostRecentResponse;\n const result: HttpOperationResponse = {\n ...response,\n headers: response.headers.clone()\n };\n const resource: any = this._pollState.resource;\n if (!resource) {\n result.bodyAsText = response.bodyAsText;\n result.parsedBody = response.parsedBody;\n } else if (typeof resource.valueOf() === \"string\") {\n result.bodyAsText = resource;\n try {\n result.parsedBody = JSON.parse(resource);\n } catch (err) {\n // There was an error parsing the JSON. Hence we set the resource as-is. Most likely, the\n // resource is a string that was already parsed.\n result.parsedBody = resource;\n }\n } else {\n result.bodyAsText = JSON.stringify(resource);\n result.parsedBody = resource;\n }\n return result;\n }\n\n public getRestError(): RestError {\n const error = new RestError(\"\");\n error.request = stripRequest(this._pollState.mostRecentRequest);\n error.response = this._pollState.mostRecentResponse;\n error.message = `Long running operation failed with status: \"${this._pollState.state}\".`;\n error.body = this._pollState.resource;\n if (error.body) {\n const innerError: any = error.body.error;\n if (innerError) {\n if (innerError.message) {\n error.message = `Long running operation failed with error: \"${innerError.message}\".`;\n }\n if (innerError.code) {\n error.code = innerError.code;\n }\n }\n }\n return error;\n }\n\n protected updateState(url: string, shouldDeserialize: boolean | ((response: HttpOperationResponse) => boolean)): Promise<void> {\n return this.updateOperationStatus(url, shouldDeserialize).then(result => {\n this._pollState.state = getProvisioningState(result.parsedBody) || \"Succeeded\";\n this._pollState.mostRecentResponse = result;\n this._pollState.mostRecentRequest = result.request;\n this._pollState.resource = getResponseBody(result);\n }).catch((error) => {\n let resultStatus: number | undefined;\n if (error.response && error.response.status) {\n resultStatus = error.response.status;\n if (this._pollState.initialResponse.request.method !== \"DELETE\" || resultStatus! < 400 || 499 < resultStatus!) {\n throw error;\n }\n } else {\n throw error;\n }\n });\n }\n\n /**\n * Retrieves operation status by querying the operation URL.\n * @param {string} statusUrl URL used to poll operation result.\n */\n protected updateOperationStatus(statusUrl: string, shouldDeserialize: boolean | ((response: HttpOperationResponse) => boolean)): Promise<HttpOperationResponse> {\n const requestUrl: string = statusUrl.replace(\" \", \"%20\");\n const httpRequest = new WebResource(requestUrl, \"GET\");\n const pollState: LROPollState = this._pollState;\n httpRequest.operationSpec = pollState.mostRecentRequest.operationSpec;\n httpRequest.shouldDeserialize = shouldDeserialize;\n httpRequest.operationResponseGetter = getOperationResponse;\n const options: RequestOptionsBase | undefined = pollState.options;\n if (options && options.customHeaders) {\n const customHeaders = options.customHeaders;\n for (const headerName of Object.keys(customHeaders)) {\n httpRequest.headers.set(headerName, customHeaders[headerName]);\n }\n }\n return this._azureServiceClient.sendRequest(httpRequest);\n }\n\n public getPollState(): LROPollState {\n return this._pollState;\n }\n}\n\nfunction getOperationResponse(operationSpec: OperationSpec, response: HttpOperationResponse): OperationResponse | undefined {\n const statusCode: number = response.status;\n const operationResponses: { [statusCode: string]: OperationResponse } = operationSpec.responses;\n let result: OperationResponse | undefined = operationResponses[statusCode];\n if (!result) {\n if (statusCode === 200) {\n result = operationResponses[201] || operationResponses[202];\n } else if (201 <= statusCode && statusCode <= 299) {\n result = {};\n }\n }\n return result;\n}\n\nexport function getDelayInSeconds(azureServiceClient: AzureServiceClient, previousResponse: HttpOperationResponse): number {\n let delayInSeconds = 30;\n if (azureServiceClient.longRunningOperationRetryTimeout != undefined) {\n delayInSeconds = azureServiceClient.longRunningOperationRetryTimeout;\n } else {\n const retryAfterHeaderValue: string | undefined = previousResponse.headers.get(\"retry-after\");\n if (retryAfterHeaderValue) {\n const retryAfterDelayInSeconds: number = parseInt(retryAfterHeaderValue);\n if (!Number.isNaN(retryAfterDelayInSeconds)) {\n delayInSeconds = retryAfterDelayInSeconds;\n }\n }\n }\n return delayInSeconds;\n}\n\nfunction getProvisioningState(responseBody: any): LongRunningOperationStates | undefined {\n let result: LongRunningOperationStates | undefined;\n if (responseBody) {\n if (responseBody.provisioningState) {\n result = responseBody.provisioningState;\n } else if (responseBody.properties) {\n result = responseBody.properties.provisioningState;\n }\n }\n return result;\n}\n\nfunction getResponseBody(response: HttpOperationResponse): any {\n let result: any;\n try {\n if (response.parsedBody) {\n result = response.parsedBody;\n } else if (response.bodyAsText && response.bodyAsText.length > 0) {\n result = JSON.parse(response.bodyAsText);\n }\n } catch (error) {\n const deserializationError = new RestError(`Error \"${error}\" occurred in parsing the responseBody \" +\n \"while creating the PollingState for Long Running Operation- \"${response.bodyAsText}\"`);\n deserializationError.request = response.request;\n deserializationError.response = response;\n throw deserializationError;\n }\n return result;\n}\n\nfunction getStatusFromResponse(response: HttpOperationResponse, responseBody?: any): LongRunningOperationStates {\n if (responseBody == undefined) {\n responseBody = getResponseBody(response);\n }\n\n let result: LongRunningOperationStates;\n switch (response.status) {\n case 202:\n result = \"InProgress\";\n break;\n\n case 204:\n result = \"Succeeded\";\n break;\n\n case 201:\n result = getProvisioningState(responseBody) || \"InProgress\";\n break;\n\n case 200:\n const provisioningState: LongRunningOperationStates | undefined = getProvisioningState(responseBody);\n if (provisioningState) {\n result = provisioningState;\n } else if (getAzureAsyncOperationHeaderValue(response) || getLocationHeaderValue(response)) {\n result = \"InProgress\";\n } else {\n result = \"Succeeded\";\n }\n break;\n\n default:\n result = \"Failed\";\n break;\n }\n return result;\n}\n\nconst terminalStates: LongRunningOperationStates[] = [\"Succeeded\", \"Failed\", \"Canceled\", \"Cancelled\"];\n\n/**\n * Get whether or not a long-running operation with the provided status is finished.\n * @param status The current status of a long-running operation.\n * @returns Whether or not a long-running operation with the provided status is finished.\n */\nexport function isFinished(status: LongRunningOperationStates): boolean {\n let result = false;\n for (const terminalState of terminalStates) {\n if (longRunningOperationStatesEqual(status, terminalState)) {\n result = true;\n break;\n }\n }\n return result;\n}\n\nexport function longRunningOperationStatesEqual(lhs: LongRunningOperationStates, rhs: LongRunningOperationStates): boolean {\n const lhsLowerCased: string = lhs && lhs.toLowerCase();\n const rhsLowerCased: string = rhs && rhs.toLowerCase();\n return lhsLowerCased === rhsLowerCased;\n}\n\n/**\n * Create a new long-running operation polling strategy based on the provided initial response.\n * @param initialResponse The initial response to the long-running operation's initial request.\n * @param azureServiceClient The AzureServiceClient that was used to send the initial request.\n * @param options Any options that were provided to the initial request.\n */\nexport function createLROPollStrategyFromInitialResponse(initialResponse: HttpOperationResponse, azureServiceClient: AzureServiceClient, options?: RequestOptionsBase): LROPollStrategy | undefined {\n const initialRequestMethod: HttpMethods = initialResponse.request.method;\n const initialResponseStatus: number = initialResponse.status;\n\n let lroPollStrategyType: LROPollStrategyType | undefined;\n if (getAzureAsyncOperationHeaderValue(initialResponse)) {\n lroPollStrategyType = \"AzureAsyncOperation\";\n } else if (getLocationHeaderValue(initialResponse)) {\n lroPollStrategyType = \"Location\";\n } else if (initialRequestMethod === \"PUT\" || initialRequestMethod === \"PATCH\") {\n lroPollStrategyType = \"GetResource\";\n } else if (initialResponseStatus !== 201 && initialResponseStatus !== 202 && !isFinished(getStatusFromResponse(initialResponse))) {\n throw new Error(\"Can't determine long running operation polling strategy.\");\n }\n\n let result: LROPollStrategy | undefined;\n if (lroPollStrategyType) {\n const resource: any = getResponseBody(initialResponse);\n const lroPollState: LROPollState = {\n pollStrategyType: lroPollStrategyType,\n options: options,\n initialResponse: initialResponse,\n mostRecentResponse: initialResponse,\n mostRecentRequest: initialResponse.request,\n azureAsyncOperationHeaderValue: getAzureAsyncOperationHeaderValue(initialResponse),\n locationHeaderValue: getLocationHeaderValue(initialResponse),\n resource: resource,\n state: getStatusFromResponse(initialResponse, resource)\n };\n result = createLROPollStrategyFromPollState(azureServiceClient, lroPollState);\n } else {\n result = undefined;\n }\n return result;\n}\n\nexport function createLROPollStrategyFromPollState(azureServiceClient: AzureServiceClient, lroPollState: LROPollState): LROPollStrategy | undefined {\n let result: LROPollStrategy;\n switch (lroPollState.pollStrategyType) {\n case \"AzureAsyncOperation\":\n result = new AzureAsyncOperationLROPollStrategy(azureServiceClient, lroPollState);\n break;\n\n case \"Location\":\n result = new LocationLROPollStrategy(azureServiceClient, lroPollState);\n break;\n\n case \"GetResource\":\n result = new GetResourceLROPollStrategy(azureServiceClient, lroPollState);\n break;\n\n default:\n throw new Error(`Unrecognized LRO poll strategy type: \"${lroPollState.pollStrategyType}\"`);\n break;\n }\n return result;\n}\n\nfunction getLocationHeaderValue(response: HttpOperationResponse): string | undefined {\n return response.headers.get(\"location\");\n}\n\n/**\n * A long-running operation polling strategy that is based on the location header.\n */\nclass LocationLROPollStrategy extends LROPollStrategy {\n private locationStrategyShouldDeserialize(parsedResponse: HttpOperationResponse): boolean {\n let shouldDeserialize = false;\n\n const initialResponse: HttpOperationResponse = this._pollState.initialResponse;\n const initialRequestMethod: HttpMethods = initialResponse.request.method;\n const statusCode: number = parsedResponse.status;\n if (statusCode === 200 ||\n (statusCode === 201 && (initialRequestMethod === \"PUT\" || initialRequestMethod === \"PATCH\")) ||\n (statusCode === 204 && (initialRequestMethod === \"DELETE\" || initialRequestMethod === \"POST\"))) {\n shouldDeserialize = true;\n }\n\n return shouldDeserialize;\n }\n /**\n * Retrieve PUT operation status by polling from \"location\" header.\n * @param {string} method - The HTTP method.\n * @param {PollingState} pollingState - The object to persist current operation state.\n */\n public sendPollRequest(): Promise<void> {\n const lroPollState: LROPollState = this._pollState;\n return this.updateOperationStatus(lroPollState.locationHeaderValue!, this.locationStrategyShouldDeserialize.bind(this)).then((result: HttpOperationResponse) => {\n const locationHeaderValue: string | undefined = getLocationHeaderValue(result);\n if (locationHeaderValue) {\n lroPollState.locationHeaderValue = locationHeaderValue;\n }\n\n lroPollState.mostRecentResponse = result;\n lroPollState.mostRecentRequest = result.request;\n\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n const initialRequestMethod: HttpMethods = initialResponse.request.method;\n const initialResponseStatusCode: number = initialResponse.status;\n const statusCode: number = result.status;\n if (statusCode === 202) {\n lroPollState.state = \"InProgress\";\n } else if (statusCode === 200 ||\n (statusCode === 201 && (initialRequestMethod === \"PUT\" || initialRequestMethod === \"PATCH\")) ||\n (statusCode === 204 && (initialRequestMethod === \"DELETE\" || initialRequestMethod === \"POST\"))) {\n lroPollState.state = \"Succeeded\";\n lroPollState.resource = getResponseBody(result);\n } else if (statusCode === 404 && initialRequestMethod === \"POST\" &&\n (initialResponseStatusCode === 200 || initialResponseStatusCode === 201 || initialResponseStatusCode === 202)) {\n lroPollState.state = \"Failed\";\n lroPollState.resource = getResponseBody(result);\n } else if (400 <= statusCode && statusCode <= 499) {\n const resultBody: string = result.bodyAsText!;\n let errorMessage: string = resultBody;\n try {\n const resultObject = JSON.parse(resultBody);\n errorMessage = resultObject.message;\n } catch (parseError) {\n // Ignore the exception, use resultBody as the error message\n }\n\n throw new RestError(errorMessage, undefined, statusCode, stripRequest(result.request), result, resultBody);\n } else {\n throw new Error(`The response with status code ${statusCode} from polling for long running operation url \"${lroPollState.locationHeaderValue}\" is not valid.`);\n }\n });\n }\n\n public isFinalStatusAcceptable(): boolean {\n const lroPollState: LROPollState = this._pollState;\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n const initialResponseStatusCode: number = initialResponse.status;\n return longRunningOperationStatesEqual(lroPollState.state, \"Succeeded\") ||\n (initialResponse.request.method === \"POST\" && lroPollState.mostRecentResponse.status === 404 &&\n (initialResponseStatusCode === 200 ||\n initialResponseStatusCode === 201 ||\n initialResponseStatusCode === 202));\n }\n\n protected shouldDoFinalGetResourceRequest(): boolean {\n const lroPollState: LROPollState = this._pollState;\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n let result: boolean;\n const initialRequestMethod: HttpMethods = initialResponse.request.method;\n const initialResponseStatusCode: number = initialResponse.status;\n if (initialRequestMethod === \"POST\" && lroPollState.mostRecentResponse.status === 404 &&\n (initialResponseStatusCode === 200 ||\n initialResponseStatusCode === 201 ||\n initialResponseStatusCode === 202)) {\n result = false;\n } else {\n result = super.shouldDoFinalGetResourceRequest() ||\n (initialRequestMethod === \"POST\" && initialResponseStatusCode === 201);\n }\n return result;\n }\n\n protected doFinalGetResourceRequest(): Promise<void> {\n const lroPollState: LROPollState = this._pollState;\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n let getResourceRequestUrl: string;\n const initialResponseStatusCode: number = initialResponse.status;\n const initialRequest: WebResource = initialResponse.request;\n if (initialRequest.method === \"POST\" &&\n (initialResponseStatusCode === 200 ||\n initialResponseStatusCode === 201 ||\n initialResponseStatusCode === 202)) {\n getResourceRequestUrl = lroPollState.locationHeaderValue!;\n } else {\n getResourceRequestUrl = initialRequest.url;\n }\n return this.updateState(getResourceRequestUrl, true);\n }\n}\n\nfunction getAzureAsyncOperationHeaderValue(response: HttpOperationResponse): string | undefined {\n return response.headers.get(\"azure-asyncoperation\");\n}\n\n/**\n * A long-running operation polling strategy that is based on the azure-asyncoperation header.\n */\nclass AzureAsyncOperationLROPollStrategy extends LROPollStrategy {\n /**\n * Retrieve operation status by polling from \"azure-asyncoperation\" header.\n * @param {PollingState} pollingState - The object to persist current operation state.\n * @param {boolean} inPostOrDelete - Invoked by Post Or Delete operation.\n */\n public sendPollRequest(): Promise<void> {\n const lroPollState: LROPollState = this._pollState;\n return this.updateOperationStatus(lroPollState.azureAsyncOperationHeaderValue!, false).then((response: HttpOperationResponse) => {\n const statusCode: number = response.status;\n const parsedResponse: any = response.parsedBody;\n if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {\n const error = new RestError(`Invalid status code (${statusCode}) with response body \"${response.bodyAsText}\" occurred when polling for operation status.`);\n error.statusCode = statusCode;\n error.request = stripRequest(response.request);\n error.response = response;\n error.body = parsedResponse;\n throw error;\n }\n\n if (!parsedResponse) {\n throw new Error(\"The response from long running operation does not contain a body.\");\n } else if (!parsedResponse.status) {\n throw new Error(`The response \"${response.bodyAsText}\" from long running operation does not contain the status property.`);\n }\n\n const azureAsyncOperationHeaderValue: string | undefined = getAzureAsyncOperationHeaderValue(response);\n if (azureAsyncOperationHeaderValue) {\n lroPollState.azureAsyncOperationHeaderValue = azureAsyncOperationHeaderValue;\n }\n\n lroPollState.state = parsedResponse.status;\n lroPollState.mostRecentResponse = response;\n lroPollState.mostRecentRequest = response.request;\n lroPollState.resource = getResponseBody(response);\n });\n }\n\n protected shouldDoFinalGetResourceRequest(): boolean {\n const lroPollState: LROPollState = this._pollState;\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n const initialRequestMethod: HttpMethods = initialResponse.request.method;\n let result = false;\n if (initialRequestMethod === \"PUT\" || initialRequestMethod === \"PATCH\") {\n result = true;\n } else {\n if (lroPollState.locationHeaderValue) {\n const initialResponseStatusCode: number = initialResponse.status;\n if (initialRequestMethod === \"POST\") {\n result = initialResponseStatusCode === 200 || initialResponseStatusCode === 201;\n } else if (initialRequestMethod === \"DELETE\") {\n result = initialResponseStatusCode === 200 || initialResponseStatusCode === 202;\n }\n }\n }\n return result;\n }\n\n protected doFinalGetResourceRequest(): Promise<void> {\n const lroPollState: LROPollState = this._pollState;\n const locationHeaderValue: string | undefined = lroPollState.locationHeaderValue;\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n const initialRequest: WebResource = initialResponse.request;\n let getResourceRequestUrl: string = initialRequest.url;\n if (locationHeaderValue) {\n const initialRequestMethod: HttpMethods = initialRequest.method;\n const initialResponseStatusCode: number = initialResponse.status;\n if (initialRequestMethod === \"POST\" && (initialResponseStatusCode === 200 || initialResponseStatusCode === 201 || initialResponseStatusCode === 202)) {\n getResourceRequestUrl = locationHeaderValue;\n } else if (initialRequestMethod === \"DELETE\" && (initialResponseStatusCode === 200 || initialResponseStatusCode === 202)) {\n getResourceRequestUrl = locationHeaderValue;\n }\n }\n return this.updateState(getResourceRequestUrl, true);\n }\n\n public isFinalStatusAcceptable(): boolean {\n const lroPollState: LROPollState = this._pollState;\n const initialResponse: HttpOperationResponse = lroPollState.initialResponse;\n const initialResponseStatusCode: number = initialResponse.status;\n return longRunningOperationStatesEqual(lroPollState.state, \"Succeeded\") ||\n (initialResponse.request.method === \"POST\" && (initialResponseStatusCode === 200 || initialResponseStatusCode === 201));\n }\n}\n\n/**\n * A long-running operation polling strategy that is based on the resource's provisioning state.\n */\nclass GetResourceLROPollStrategy extends LROPollStrategy {\n public sendPollRequest(): Promise<void> {\n const lroPollState: LROPollState = this._pollState;\n return this.updateOperationStatus(lroPollState.initialResponse.request.url, false).then(result => {\n const statusCode: number = result.status;\n const responseBody: any = result.parsedBody;\n if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202 && statusCode !== 204) {\n const error = new RestError(`Invalid status code with response body \"${result.bodyAsText}\" occurred when polling for operation status.`);\n error.statusCode = statusCode;\n error.request = stripRequest(result.request);\n error.response = result;\n error.body = responseBody;\n throw error;\n }\n\n if (!result.parsedBody) {\n throw new Error(\"The response from long running operation does not contain a body.\");\n }\n\n lroPollState.state = getProvisioningState(result.parsedBody) || \"Succeeded\";\n lroPollState.mostRecentResponse = result;\n lroPollState.mostRecentRequest = result.request;\n lroPollState.resource = getResponseBody(result);\n });\n }\n\n public isFinalStatusAcceptable(): boolean {\n return longRunningOperationStatesEqual(this._pollState.state, \"Succeeded\");\n }\n\n protected doFinalGetResourceRequest(): Promise<void> {\n return this.sendPollRequest();\n }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n\nimport { HttpOperationResponse, RequestOptionsBase, RestResponse, flattenResponse } from \"@azure/ms-rest-js\";\nimport { AzureServiceClient } from \"./azureServiceClient\";\nimport { createLROPollStrategyFromInitialResponse, createLROPollStrategyFromPollState, LROPollState, LROPollStrategy } from \"./lroPollStrategy\";\nimport { LongRunningOperationStates } from \"./util/constants\";\n\n/**\n * An HTTP operation response that provides special methods for interacting with LROs (long running\n * operations).\n */\nexport class LROPoller {\n /**\n * Create a new HttpLongRunningOperationResponse.\n * @param _lroPollStrategy The LROPollStrategy that this HttpLongRunningOperationResponse will\n * use to interact with the LRO.\n */\n constructor(private readonly _lroPollStrategy: LROPollStrategy | undefined, private readonly _initialResponse: HttpOperationResponse) {\n }\n\n /**\n * Get the first response that the service sent back when the LRO was initiated.\n */\n public getInitialResponse(): HttpOperationResponse {\n return this._initialResponse;\n }\n\n /**\n * Get the most recent response that the service sent back during this LRO.\n */\n public getMostRecentResponse(): HttpOperationResponse {\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n return !lroPollStrategy ? this._initialResponse : lroPollStrategy.getMostRecentResponse();\n }\n\n /**\n * Get whether or not the LRO is finished.\n */\n public isFinished(): boolean {\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n return !lroPollStrategy ? true : lroPollStrategy.isFinished();\n }\n\n /**\n * Get whether or not the LRO is finished and its final state is acceptable. If the LRO has not\n * finished yet, then undefined will be returned. An \"acceptable\" final state is determined by the\n * LRO strategy that the Azure service uses to perform long running operations.\n */\n public isFinalStatusAcceptable(): boolean | undefined {\n let result: boolean | undefined;\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n if (!lroPollStrategy) {\n result = true;\n } else if (lroPollStrategy.isFinished()) {\n result = lroPollStrategy.isFinalStatusAcceptable();\n }\n return result;\n }\n\n /**\n * Get the current status of the LRO.\n */\n public getOperationStatus(): LongRunningOperationStates {\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n return !lroPollStrategy ? \"Succeeded\" : lroPollStrategy.getOperationStatus();\n }\n\n /**\n * If the LRO is finished and in an acceptable state, then return the HttpOperationResponse. If\n * the LRO is finished and not in an acceptable state, then throw the error that the LRO produced.\n * If the LRO is not finished, then return undefined.\n */\n public getOperationResponse(): Promise<HttpOperationResponse | undefined> {\n let result: Promise<HttpOperationResponse | undefined>;\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n if (!lroPollStrategy) {\n result = Promise.resolve(this._initialResponse);\n } else if (!lroPollStrategy.isFinished()) {\n result = Promise.resolve(undefined);\n } else if (lroPollStrategy.isFinalStatusAcceptable()) {\n result = lroPollStrategy.getOperationResponse();\n } else {\n throw lroPollStrategy.getRestError();\n }\n return result;\n }\n\n /**\n * Send a single poll request and return the LRO's state.\n */\n public poll(): Promise<LongRunningOperationStates> {\n let result: Promise<LongRunningOperationStates>;\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n if (!lroPollStrategy) {\n result = Promise.resolve<LongRunningOperationStates>(\"Succeeded\");\n } else {\n result = lroPollStrategy.sendPollRequest().then(() => {\n return lroPollStrategy.getOperationStatus();\n });\n }\n return result;\n }\n\n /**\n * Send poll requests that check the LRO's status until it is determined that the LRO is finished.\n */\n public async pollUntilFinished(): Promise<RestResponse> {\n let result: Promise<RestResponse>;\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n\n if (!lroPollStrategy) {\n result = Promise.resolve(flattenAzureResponse(this._initialResponse));\n } else {\n result = lroPollStrategy.pollUntilFinished().then((succeeded: boolean) => {\n if (succeeded) {\n return lroPollStrategy.getOperationResponse().then(flattenAzureResponse);\n } else {\n throw lroPollStrategy.getRestError();\n }\n });\n }\n return result;\n }\n\n /**\n * Get an LROPollState object that can be used to poll this LRO in a different context (such as on\n * a different process or a different machine). If the LRO couldn't produce an LRO polling\n * strategy, then this will return undefined.\n */\n public getPollState(): LROPollState | undefined {\n const lroPollStrategy: LROPollStrategy | undefined = this._lroPollStrategy;\n return !lroPollStrategy ? undefined : lroPollStrategy.getPollState();\n }\n}\n\nexport function createLROPollerFromInitialResponse(azureServiceClient: AzureServiceClient, initialResponse: HttpOperationResponse, options?: RequestOptionsBase): LROPoller {\n const lroPollStrategy: LROPollStrategy | undefined = createLROPollStrategyFromInitialResponse(initialResponse, azureServiceClient, options);\n return new LROPoller(lroPollStrategy, initialResponse);\n}\n\nexport function createLROPollerFromPollState(azureServiceClient: AzureServiceClient, lroMemento: LROPollState): LROPoller {\n const lroPollStrategy: LROPollStrategy | undefined = createLROPollStrategyFromPollState(azureServiceClient, lroMemento);\n return new LROPoller(lroPollStrategy, lroMemento.initialResponse);\n}\n\nfunction flattenAzureResponse(response: HttpOperationResponse): RestResponse {\n const { operationResponseGetter, operationSpec } = response.request;\n return flattenResponse(response, operationResponseGetter && operationSpec && operationResponseGetter(operationSpec, response));\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n\n/**\n * Defines constants for long running operation states.\n *\n * @const\n * @type {string}\n */\nexport type LongRunningOperationStates =\n | \"InProgress\"\n | \"Succeeded\"\n | \"Failed\"\n | \"Canceled\"\n | \"Cancelled\";\n\n/**\n * The default language in the request header.\n *\n * @const\n * @type {string}\n */\nexport const DEFAULT_LANGUAGE = \"en-us\";\n\n/**\n * The ms-rest-azure version.\n * @const\n * @type {string}\n */\nexport const msRestAzureVersion = \"2.1.0\";\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n\nimport { HttpOperationResponse, OperationArguments, OperationSpec, RequestOptionsBase, RequestPrepareOptions, ServiceClient, ServiceClientCredentials, ServiceClientOptions, WebResource, getDefaultUserAgentValue as getDefaultUserAgentValueFromMsRest } from \"@azure/ms-rest-js\";\nimport { TokenCredential } from \"@azure/core-auth\";\nimport { createLROPollerFromInitialResponse, createLROPollerFromPollState, LROPoller } from \"./lroPoller\";\nimport { LROPollState } from \"./lroPollStrategy\";\nimport * as Constants from \"./util/constants\";\n\n/**\n * Options to be provided while creating the client.\n */\nexport interface AzureServiceClientOptions extends ServiceClientOptions {\n /**\n * @property {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. Default value is: \"en-US\".\n */\n acceptLanguage?: string;\n\n /**\n * @property {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for\n * Long Running Operations. Default value is 30.\n */\n longRunningOperationRetryTimeout?: number;\n}\n\n/**\n * @class\n * Initializes a new instance of the AzureServiceClient class.\n * @constructor\n *\n * @param {msRest.ServiceClientCredentilas} credentials - ApplicationTokenCredentials or\n * UserTokenCredentials object used for authentication.\n * @param {AzureServiceClientOptions} options - The parameter options used by AzureServiceClient\n */\nexport class AzureServiceClient extends ServiceClient {\n public acceptLanguage: string = Constants.DEFAULT_LANGUAGE;\n /**\n * The retry timeout in seconds for Long Running Operations. Default value is 30.\n */\n public longRunningOperationRetryTimeout?: number;\n\n constructor(credentials: ServiceClientCredentials | TokenCredential, options?: AzureServiceClientOptions) {\n super(credentials, options = updateOptionsWithDefaultValues(options));\n\n // For convenience, if the credentials have an associated AzureEnvironment,\n // automatically use the baseUri from that environment.\n const env = (credentials as any)?.environment;\n if (env && !this.baseUri) {\n this.baseUri = env.resourceManagerEndpointUrl;\n }\n\n if (options.acceptLanguage != undefined) {\n this.acceptLanguage = options.acceptLanguage;\n }\n\n if (options.longRunningOperationRetryTimeout != undefined) {\n this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout;\n }\n }\n\n /**\n * Send the initial request of a LRO (long running operation) and get back an\n * LROPoller that provides methods for polling the LRO and checking if the LRO is finished.\n * @param operationArguments The arguments to the operation.\n * @param operationSpec The specification for the operation.\n * @param options Additional options to be sent while making the request.\n * @returns The LROPoller object that provides methods for interacting with the LRO.\n */\n sendLRORequest(operationArguments: OperationArguments, operationSpec: OperationSpec, options?: RequestOptionsBase): Promise<LROPoller> {\n return this.sendOperationRequest(operationArguments, operationSpec)\n .then(initialResponse => createLROPollerFromInitialResponse(this, initialResponse._response, options));\n }\n\n /**\n * Provides a mechanism to make a request that will poll and provide the final result.\n * @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object\n * @param {AzureRequestOptionsBase} [options] Additional options to be sent while making the request\n * @returns {Promise<msRest.HttpOperationResponse>} The HttpOperationResponse containing the final polling request, response and the responseBody.\n */\n sendLongRunningRequest(request: RequestPrepareOptions | WebResource, options?: RequestOptionsBase): Promise<HttpOperationResponse> {\n return this.beginLongRunningRequest(request, options)\n .then((lroResponse: LROPoller) => lroResponse.pollUntilFinished())\n .then(res => res._response);\n }\n\n /**\n * Send the initial request of a LRO (long running operation) and get back an\n * HttpLongRunningOperationResponse that provides methods for polling the LRO and checking if the\n * LRO is finished.\n * @param {msRest.RequestPrepareOptions|msRest.WebResource} request - The request object\n * @param {AzureRequestOptionsBase} [options] Additional options to be sent while making the request\n * @returns {Promise<LROPoller>} The HttpLongRunningOperationResponse\n * that provides methods for interacting with the LRO.\n */\n beginLongRunningRequest(request: RequestPrepareOptions | WebResource, options?: RequestOptionsBase): Promise<LROPoller> {\n return this.sendRequest(request)\n .then((initialResponse: HttpOperationResponse) => createLROPollerFromInitialResponse(this, initialResponse, options));\n }\n\n /**\n * Restore an LROPoller from the provided LROPollState. This method can be used to recreate an\n * LROPoller on a different process or machine.\n */\n restoreLROPoller(lroPollState: LROPollState): LROPoller {\n return createLROPollerFromPollState(this, lroPollState);\n }\n}\n\nexport function getDefaultUserAgentValue(): string {\n const defaultUserAgent = getDefaultUserAgentValueFromMsRest();\n return `ms-rest-azure-js/${Constants.msRestAzureVersion} ${defaultUserAgent}`;\n}\n\nexport function updateOptionsWithDefaultValues(options?: AzureServiceClientOptions): AzureServiceClientOptions {\n if (!options) {\n options = {};\n }\n\n if (options.generateClientRequestIdHeader == undefined) {\n options.generateClientRequestIdHeader = true;\n }\n\n if (!options.userAgent) {\n options.userAgent = getDefaultUserAgentValue();\n }\n\n return options;\n}","// Copyright (c) Microsoft Corpora