From df6abcc733fa14327c82798d7708a84870433c17 Mon Sep 17 00:00:00 2001 From: Dmitry Shibanov Date: Wed, 19 Apr 2023 13:40:45 +0200 Subject: [PATCH] update xml2js (#652) --- .licenses/npm/@azure/core-http.dep.yml | 2 +- .licenses/npm/@azure/core-util.dep.yml | 32 + .licenses/npm/@azure/ms-rest-js.dep.yml | 2 +- .licenses/npm/semver-7.1.3.dep.yml | 26 - .licenses/npm/tslib-2.5.0.dep.yml | 35 + .licenses/npm/xml2js.dep.yml | 2 +- dist/cache-save/index.js | 3022 +++++++++++++---------- dist/setup/index.js | 3022 +++++++++++++---------- package-lock.json | 91 +- 9 files changed, 3664 insertions(+), 2570 deletions(-) create mode 100644 .licenses/npm/@azure/core-util.dep.yml delete mode 100644 .licenses/npm/semver-7.1.3.dep.yml create mode 100644 .licenses/npm/tslib-2.5.0.dep.yml diff --git a/.licenses/npm/@azure/core-http.dep.yml b/.licenses/npm/@azure/core-http.dep.yml index 6a2bfc5..7139005 100644 --- a/.licenses/npm/@azure/core-http.dep.yml +++ b/.licenses/npm/@azure/core-http.dep.yml @@ -1,6 +1,6 @@ --- name: "@azure/core-http" -version: 2.2.2 +version: 2.3.2 type: npm summary: Isomorphic client Runtime for Typescript/node.js/browser javascript client libraries generated using AutoRest diff --git a/.licenses/npm/@azure/core-util.dep.yml b/.licenses/npm/@azure/core-util.dep.yml new file mode 100644 index 0000000..fcf1506 --- /dev/null +++ b/.licenses/npm/@azure/core-util.dep.yml @@ -0,0 +1,32 @@ +--- +name: "@azure/core-util" +version: 1.3.1 +type: npm +summary: Core library for shared utility methods +homepage: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/core/core-util/ +license: mit +licenses: +- sources: LICENSE + text: | + The MIT License (MIT) + + Copyright (c) 2020 Microsoft + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +notices: [] diff --git a/.licenses/npm/@azure/ms-rest-js.dep.yml b/.licenses/npm/@azure/ms-rest-js.dep.yml index fb2116f..869e765 100644 --- a/.licenses/npm/@azure/ms-rest-js.dep.yml +++ b/.licenses/npm/@azure/ms-rest-js.dep.yml @@ -1,6 +1,6 @@ --- name: "@azure/ms-rest-js" -version: 2.6.0 +version: 2.6.6 type: npm summary: Isomorphic client Runtime for Typescript/node.js/browser javascript client libraries generated using AutoRest diff --git a/.licenses/npm/semver-7.1.3.dep.yml b/.licenses/npm/semver-7.1.3.dep.yml deleted file mode 100644 index 90750cf..0000000 --- a/.licenses/npm/semver-7.1.3.dep.yml +++ /dev/null @@ -1,26 +0,0 @@ ---- -name: semver -version: 7.1.3 -type: npm -summary: The semantic version parser used by npm. -homepage: https://github.com/npm/node-semver#readme -license: isc -licenses: -- sources: LICENSE - text: | - The ISC License - - Copyright (c) Isaac Z. Schlueter and Contributors - - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted, provided that the above - copyright notice and this permission notice appear in all copies. - - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR - IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -notices: [] diff --git a/.licenses/npm/tslib-2.5.0.dep.yml b/.licenses/npm/tslib-2.5.0.dep.yml new file mode 100644 index 0000000..dbba6bc --- /dev/null +++ b/.licenses/npm/tslib-2.5.0.dep.yml @@ -0,0 +1,35 @@ +--- +name: tslib +version: 2.5.0 +type: npm +summary: Runtime library for TypeScript helper functions +homepage: https://www.typescriptlang.org/ +license: 0bsd +licenses: +- sources: LICENSE.txt + text: |- + 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. +notices: +- sources: CopyrightNotice.txt + text: "/******************************************************************************\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***************************************************************************** + */" diff --git a/.licenses/npm/xml2js.dep.yml b/.licenses/npm/xml2js.dep.yml index ea43d8d..92bce8d 100644 --- a/.licenses/npm/xml2js.dep.yml +++ b/.licenses/npm/xml2js.dep.yml @@ -1,6 +1,6 @@ --- name: xml2js -version: 0.4.23 +version: 0.5.0 type: npm summary: Simple XML to JavaScript object converter. homepage: https://github.com/Leonidas-from-XIV/node-xml2js diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index d5f534d..2c83ce9 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -8988,26 +8988,52 @@ exports.isTokenCredential = isTokenCredential; Object.defineProperty(exports, "__esModule", ({ value: true })); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var uuid = __nccwpck_require__(3415); -var tough = __nccwpck_require__(7372); +var util = __nccwpck_require__(3837); +var tslib = __nccwpck_require__(2107); +var xml2js = __nccwpck_require__(6189); +var coreUtil = __nccwpck_require__(1333); +var logger$1 = __nccwpck_require__(3233); +var coreAuth = __nccwpck_require__(9645); +var os = __nccwpck_require__(2037); var http = __nccwpck_require__(3685); var https = __nccwpck_require__(5687); -var node_fetch = _interopDefault(__nccwpck_require__(467)); +var tough = __nccwpck_require__(7372); var abortController = __nccwpck_require__(2557); -var FormData = _interopDefault(__nccwpck_require__(6279)); -var util = __nccwpck_require__(3837); -var url = __nccwpck_require__(7310); -var stream = __nccwpck_require__(2781); -var logger$1 = __nccwpck_require__(3233); var tunnel = __nccwpck_require__(4294); -var tslib = __nccwpck_require__(2107); -var coreAuth = __nccwpck_require__(9645); -var xml2js = __nccwpck_require__(6189); -var os = __nccwpck_require__(2037); +var stream = __nccwpck_require__(2781); +var FormData = __nccwpck_require__(6279); +var node_fetch = __nccwpck_require__(467); var coreTracing = __nccwpck_require__(4175); -__nccwpck_require__(6821); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js); +var os__namespace = /*#__PURE__*/_interopNamespace(os); +var http__namespace = /*#__PURE__*/_interopNamespace(http); +var https__namespace = /*#__PURE__*/_interopNamespace(https); +var tough__namespace = /*#__PURE__*/_interopNamespace(tough); +var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel); +var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData); +var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -9056,7 +9082,7 @@ class HttpHeaders { set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, - value: headerValue.toString() + value: headerValue.toString(), }; } /** @@ -9088,12 +9114,7 @@ class HttpHeaders { * Get the headers that are contained this collection as an object. */ rawHeaders() { - const result = {}; - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - result[header.name.toLowerCase()] = header.value; - } - return result; + return this.toJson({ preserveCase: true }); } /** * Get the headers that are contained in this collection as an array. @@ -9130,14 +9151,27 @@ class HttpHeaders { /** * Get the JSON object representation of this HTTP header collection. */ - toJson() { - return this.rawHeaders(); + toJson(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[header.name] = header.value; + } + } + else { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[getHeaderKey(header.name)] = header.value; + } + } + return result; } /** * Get the string representation of this HTTP header collection. */ toString() { - return JSON.stringify(this.toJson()); + return JSON.stringify(this.toJson({ preserveCase: true })); } /** * Create a deep clone/copy of this HttpHeaders collection. @@ -9181,11 +9215,14 @@ function decodeString(value) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * A set of constants used internally when processing requests. + */ const Constants = { /** * The core-http version */ - coreHttpVersion: "2.2.2", + coreHttpVersion: "2.3.2", /** * Specifies HTTP. */ @@ -9221,12 +9258,12 @@ const Constants = { POST: "POST", MERGE: "MERGE", HEAD: "HEAD", - PATCH: "PATCH" + PATCH: "PATCH", }, StatusCodes: { TooManyRequests: 429, - ServiceUnavailable: 503 - } + ServiceUnavailable: 503, + }, }, /** * Defines constants for use with HTTP headers. @@ -9246,8 +9283,8 @@ const Constants = { /** * The UserAgent header. */ - USER_AGENT: "User-Agent" - } + USER_AGENT: "User-Agent", + }, }; // Copyright (c) Microsoft Corporation. @@ -9462,18 +9499,39 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. +// This file contains utility code to serialize and deserialize network operations according to `OperationSpec` objects generated by AutoRest.TypeScript from OpenAPI specifications. +/** + * Used to map raw response objects to final shapes. + * Helps packing and unpacking Dates and other encoded types that are not intrinsic to JSON. + * Also allows pulling values from headers, as well as inserting default values and constants. + */ class Serializer { - constructor(modelMappers = {}, isXML) { + constructor( + /** + * The provided model mapper. + */ + modelMappers = {}, + /** + * Whether the contents are XML or not. + */ + isXML) { this.modelMappers = modelMappers; this.isXML = isXML; } + /** + * Validates constraints, if any. This function will throw if the provided value does not respect those constraints. + * @param mapper - The definition of data models. + * @param value - The value. + * @param objectName - Name of the object. Used in the error messages. + * @deprecated Removing the constraints validation on client side. + */ validateConstraints(mapper, value, objectName) { const failValidation = (constraintName, constraintValue) => { throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); }; if (mapper.constraints && value != undefined) { const valueAsNumber = value; - const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } @@ -9515,20 +9573,20 @@ class Serializer { } } /** - * Serialize the given object based on its metadata defined in the mapper + * Serialize the given object based on its metadata defined in the mapper. * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param object - A valid Javascript object to be serialized - * @param objectName - Name of the serialized object - * @param options - additional options to deserialization - * @returns A valid serialized Javascript object + * @param mapper - The mapper which defines the metadata of the serializable object. + * @param object - A valid Javascript object to be serialized. + * @param objectName - Name of the serialized object. + * @param options - additional options to deserialization. + * @returns A valid serialized Javascript object. */ serialize(mapper, object, objectName, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; let payload = {}; const mapperType = mapper.type.name; @@ -9564,8 +9622,6 @@ class Serializer { payload = object; } else { - // Validate Constraints if any - this.validateConstraints(mapper, object, objectName); if (mapperType.match(/^any$/i) !== null) { payload = object; } @@ -9598,20 +9654,20 @@ class Serializer { return payload; } /** - * Deserialize the given object based on its metadata defined in the mapper + * Deserialize the given object based on its metadata defined in the mapper. * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param responseBody - A valid Javascript entity to be deserialized - * @param objectName - Name of the deserialized object + * @param mapper - The mapper which defines the metadata of the serializable object. + * @param responseBody - A valid Javascript entity to be deserialized. + * @param objectName - Name of the deserialized object. * @param options - Controls behavior of XML parser and builder. - * @returns A valid deserialized Javascript object + * @returns A valid deserialized Javascript object. */ deserialize(mapper, responseBody, objectName, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; if (responseBody == undefined) { if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { @@ -9710,9 +9766,7 @@ function bufferToBase64Url(buffer) { // Uint8Array to Base64. const str = encodeByteArray(buffer); // Base64 to Base64Url. - return trimEnd(str, "=") - .replace(/\+/g, "-") - .replace(/\//g, "_"); + return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); } function base64UrlToByteArray(str) { if (!str) { @@ -9928,10 +9982,10 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, return tempDictionary; } /** - * Resolves the additionalProperties property from a referenced mapper - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * Resolves the additionalProperties property from a referenced mapper. + * @param serializer - The serializer containing the entire set of mappers. + * @param mapper - The composite mapper to resolve. + * @param objectName - Name of the object being serialized. */ function resolveAdditionalProperties(serializer, mapper, objectName) { const additionalProperties = mapper.type.additionalProperties; @@ -9942,7 +9996,7 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { return additionalProperties; } /** - * Finds the mapper referenced by className + * Finds the mapper referenced by `className`. * @param serializer - The serializer containing the entire set of mappers * @param mapper - The composite mapper to resolve * @param objectName - Name of the object being serialized @@ -10085,7 +10139,8 @@ function isSpecialXmlProperty(propertyName, options) { return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); } function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - var _a; + var _a, _b; + const xmlCharKey = (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } @@ -10116,6 +10171,16 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); } + else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== undefined) { + instance[key] = responseBody[xmlCharKey]; + } + else if (typeof responseBody === "string") { + // The special case where xml parser parses "content" into JSON of + // `{ name: "content"}` instead of `{ name: { "_": "content" }}` + instance[key] = responseBody; + } + } else { const propertyName = xmlElementName || xmlName || serializedName; if (propertyMapper.xmlIsWrapped) { @@ -10134,7 +10199,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, xmlName is "Cors" and xmlElementName is"CorsRule". */ const wrapped = responseBody[xmlName]; - const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); } else { @@ -10281,7 +10346,9 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator); } -// TODO: why is this here? +/** + * Utility function that serializes an object that might contain binary information into a plain object, array or a string. + */ function serializeObject(toSerialize) { const castToSerialize = toSerialize; if (toSerialize == undefined) @@ -10319,6 +10386,9 @@ function strEnum(o) { } return result; } +/** + * String enum containing the string types of property mappers. + */ // eslint-disable-next-line @typescript-eslint/no-redeclare const MapperType = strEnum([ "Base64Url", @@ -10336,7 +10406,7 @@ const MapperType = strEnum([ "String", "Stream", "TimeSpan", - "UnixTime" + "UnixTime", ]); // Copyright (c) Microsoft Corporation. @@ -10599,9 +10669,6 @@ class WebResource { } } -// Copyright (c) Microsoft Corporation. -const custom = util.inspect.custom; - // Copyright (c) Microsoft Corporation. /** * A class that handles the query portion of a URLBuilder. @@ -10899,6 +10966,10 @@ class URLBuilder { } } } + /** + * Serializes the URL as a string. + * @returns the URL as a string. + */ toString() { let result = ""; if (this._scheme) { @@ -10934,6 +11005,9 @@ class URLBuilder { this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); } } + /** + * Parses a given string URL into a new {@link URLBuilder}. + */ static parse(text) { const result = new URLBuilder(); result.set(text, "SCHEME_OR_HOST"); @@ -11190,6 +11264,60 @@ function nextQuery(tokenizer) { tokenizer._currentState = "DONE"; } +// Copyright (c) Microsoft Corporation. +function createProxyAgent(requestUrl, proxySettings, headers) { + const host = URLBuilder.parse(proxySettings.host).getHost(); + if (!host) { + throw new Error("Expecting a non-empty host in proxy settings."); + } + if (!isValidPort(proxySettings.port)) { + throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); + } + const tunnelOptions = { + proxy: { + host: host, + port: proxySettings.port, + headers: (headers && headers.rawHeaders()) || {}, + }, + }; + if (proxySettings.username && proxySettings.password) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; + } + else if (proxySettings.username) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; + } + const isRequestHttps = isUrlHttps(requestUrl); + const isProxyHttps = isUrlHttps(proxySettings.host); + const proxyAgent = { + isHttps: isRequestHttps, + agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), + }; + return proxyAgent; +} +function isUrlHttps(url) { + const urlScheme = URLBuilder.parse(url).getScheme() || ""; + return urlScheme.toLowerCase() === "https"; +} +function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { + if (isRequestHttps && isProxyHttps) { + return tunnel__namespace.httpsOverHttps(tunnelOptions); + } + else if (isRequestHttps && !isProxyHttps) { + return tunnel__namespace.httpsOverHttp(tunnelOptions); + } + else if (!isRequestHttps && isProxyHttps) { + return tunnel__namespace.httpOverHttps(tunnelOptions); + } + else { + return tunnel__namespace.httpOverHttp(tunnelOptions); + } +} +function isValidPort(port) { + // any port in 0-65535 range is valid (RFC 793) even though almost all implementations + // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports + return 0 <= port && port <= 65535; +} + // Copyright (c) Microsoft Corporation. const RedactedString = "REDACTED"; const defaultAllowedHeaderNames = [ @@ -11230,7 +11358,8 @@ const defaultAllowedHeaderNames = [ "Retry-After", "Server", "Transfer-Encoding", - "User-Agent" + "User-Agent", + "WWW-Authenticate", ]; const defaultAllowedQueryParameters = ["api-version"]; class Sanitizer { @@ -11323,8 +11452,14 @@ class Sanitizer { } } +// Copyright (c) Microsoft Corporation. +const custom = util.inspect.custom; + // Copyright (c) Microsoft Corporation. const errorSanitizer = new Sanitizer(); +/** + * An error resulting from an HTTP request to a service endpoint. + */ class RestError extends Error { constructor(message, code, statusCode, request, response) { super(message); @@ -11342,13 +11477,22 @@ class RestError extends Error { return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; } } +/** + * A constant string to identify errors that may arise when making an HTTP request that indicates an issue with the transport layer (e.g. the hostname of the URL cannot be resolved via DNS.) + */ RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +/** + * A constant string to identify errors that may arise from parsing an incoming HTTP response. Usually indicates a malformed HTTP body, such as an encoded JSON payload that is incomplete. + */ RestError.PARSE_ERROR = "PARSE_ERROR"; // Copyright (c) Microsoft Corporation. const logger = logger$1.createClientLogger("core-http"); // Copyright (c) Microsoft Corporation. +function getCachedAgent(isHttps, agentCache) { + return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; +} class ReportTransform extends stream.Transform { constructor(progressCallback) { super(); @@ -11362,7 +11506,44 @@ class ReportTransform extends stream.Transform { callback(undefined); } } -class FetchHttpClient { +function isReadableStream(body) { + return body && typeof body.pipe === "function"; +} +function isStreamComplete(stream, aborter) { + return new Promise((resolve) => { + stream.once("close", () => { + aborter === null || aborter === void 0 ? void 0 : aborter.abort(); + resolve(); + }); + stream.once("end", resolve); + stream.once("error", resolve); + }); +} +/** + * Transforms a set of headers into the key/value pair defined by {@link HttpHeadersLike} + */ +function parseHeaders(headers) { + const httpHeaders = new HttpHeaders(); + headers.forEach((value, key) => { + httpHeaders.set(key, value); + }); + return httpHeaders; +} +/** + * An HTTP client that uses `node-fetch`. + */ +class NodeFetchHttpClient { + constructor() { + // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent + this.proxyAgentMap = new Map(); + this.keepAliveAgents = {}; + this.cookieJar = new tough__namespace.CookieJar(undefined, { looseMode: true }); + } + /** + * Provides minimum viable error handling and the logic that executes the abstract methods. + * @param httpRequest - Object representing the outgoing HTTP request. + * @returns An object representing the incoming HTTP response. + */ async sendRequest(httpRequest) { var _a; if (!httpRequest && typeof httpRequest !== "object") { @@ -11388,7 +11569,7 @@ class FetchHttpClient { } if (httpRequest.formData) { const formData = httpRequest.formData; - const requestForm = new FormData(); + const requestForm = new FormData__default["default"](); const appendFormValue = (key, value) => { // value function probably returns a stream so we can provide a fresh stream on each retry if (typeof value === "function") { @@ -11444,7 +11625,11 @@ class FetchHttpClient { body = uploadReportStream; } const platformSpecificRequestInit = await this.prepareRequest(httpRequest); - const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); + const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, + // the types for RequestInit are from the browser, which expects AbortSignal to + // have `reason` and `throwIfAborted`, but these don't exist on our polyfill + // for Node. + signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); let operationResponse; try { const response = await this.fetch(httpRequest.url, requestInit); @@ -11458,7 +11643,7 @@ class FetchHttpClient { readableStreamBody: streaming ? response.body : undefined, - bodyAsText: !streaming ? await response.text() : undefined + bodyAsText: !streaming ? await response.text() : undefined, }; const onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { @@ -11512,94 +11697,6 @@ class FetchHttpClient { } } } -} -function isReadableStream(body) { - return body && typeof body.pipe === "function"; -} -function isStreamComplete(stream, aborter) { - return new Promise((resolve) => { - stream.once("close", () => { - aborter === null || aborter === void 0 ? void 0 : aborter.abort(); - resolve(); - }); - stream.once("end", resolve); - stream.once("error", resolve); - }); -} -function parseHeaders(headers) { - const httpHeaders = new HttpHeaders(); - headers.forEach((value, key) => { - httpHeaders.set(key, value); - }); - return httpHeaders; -} - -// Copyright (c) Microsoft Corporation. -function createProxyAgent(requestUrl, proxySettings, headers) { - const host = URLBuilder.parse(proxySettings.host).getHost(); - if (!host) { - throw new Error("Expecting a non-empty host in proxy settings."); - } - if (!isValidPort(proxySettings.port)) { - throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); - } - const tunnelOptions = { - proxy: { - host: host, - port: proxySettings.port, - headers: (headers && headers.rawHeaders()) || {} - } - }; - if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; - } - else if (proxySettings.username) { - tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; - } - const isRequestHttps = isUrlHttps(requestUrl); - const isProxyHttps = isUrlHttps(proxySettings.host); - const proxyAgent = { - isHttps: isRequestHttps, - agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) - }; - return proxyAgent; -} -function isUrlHttps(url) { - const urlScheme = URLBuilder.parse(url).getScheme() || ""; - return urlScheme.toLowerCase() === "https"; -} -function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { - if (isRequestHttps && isProxyHttps) { - return tunnel.httpsOverHttps(tunnelOptions); - } - else if (isRequestHttps && !isProxyHttps) { - return tunnel.httpsOverHttp(tunnelOptions); - } - else if (!isRequestHttps && isProxyHttps) { - return tunnel.httpOverHttps(tunnelOptions); - } - else { - return tunnel.httpOverHttp(tunnelOptions); - } -} -function isValidPort(port) { - // any port in 0-65535 range is valid (RFC 793) even though almost all implementations - // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports - return 0 <= port && port <= 65535; -} - -// Copyright (c) Microsoft Corporation. -function getCachedAgent(isHttps, agentCache) { - return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; -} -class NodeFetchHttpClient extends FetchHttpClient { - constructor() { - super(...arguments); - // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent - this.proxyAgentMap = new Map(); - this.keepAliveAgents = {}; - this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); - } getOrCreateAgent(httpRequest) { var _a; const isHttps = isUrlHttps(httpRequest.url); @@ -11631,24 +11728,30 @@ class NodeFetchHttpClient extends FetchHttpClient { return agent; } const agentOptions = { - keepAlive: httpRequest.keepAlive + keepAlive: httpRequest.keepAlive, }; if (isHttps) { - agent = this.keepAliveAgents.httpsAgent = new https.Agent(agentOptions); + agent = this.keepAliveAgents.httpsAgent = new https__namespace.Agent(agentOptions); } else { - agent = this.keepAliveAgents.httpAgent = new http.Agent(agentOptions); + agent = this.keepAliveAgents.httpAgent = new http__namespace.Agent(agentOptions); } return agent; } else { - return isHttps ? https.globalAgent : http.globalAgent; + return isHttps ? https__namespace.globalAgent : http__namespace.globalAgent; } } + /** + * Uses `node-fetch` to perform the request. + */ // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs async fetch(input, init) { - return node_fetch(input, init); + return node_fetch__default["default"](input, init); } + /** + * Prepares a request based on the provided web resource. + */ async prepareRequest(httpRequest) { const requestInit = {}; if (this.cookieJar && !httpRequest.headers.get("Cookie")) { @@ -11669,6 +11772,9 @@ class NodeFetchHttpClient extends FetchHttpClient { requestInit.compress = httpRequest.decompressResponse; return requestInit; } + /** + * Process an HTTP response. Handles persisting a cookie for subsequent requests if the response has a "Set-Cookie" header. + */ async processRequest(operationResponse) { if (this.cookieJar) { const setCookieHeader = operationResponse.headers.get("Set-Cookie"); @@ -11689,6 +11795,11 @@ class NodeFetchHttpClient extends FetchHttpClient { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The different levels of logs that can be used with the HttpPipelineLogger. + */ +exports.HttpPipelineLogLevel = void 0; (function (HttpPipelineLogLevel) { /** * A log level that indicates that no logs will be logged. @@ -11708,13 +11819,13 @@ class NodeFetchHttpClient extends FetchHttpClient { HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); +// Copyright (c) Microsoft Corporation. /** * Converts an OperationOptions to a RequestOptionsBase * * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { - var _a; const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); let result = additionalOptions; if (requestOptions) { @@ -11723,14 +11834,28 @@ function operationOptionsToRequestOptionsBase(opts) { if (tracingOptions) { result.tracingContext = tracingOptions.tracingContext; // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. - result.spanOptions = (_a = tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions; + result.spanOptions = tracingOptions === null || tracingOptions === void 0 ? void 0 : tracingOptions.spanOptions; } return result; } // Copyright (c) Microsoft Corporation. +/** + * The base class from which all request policies derive. + */ class BaseRequestPolicy { - constructor(_nextPolicy, _options) { + /** + * The main method to implement that manipulates a request/response. + */ + constructor( + /** + * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. + */ + _nextPolicy, + /** + * The options that can be passed to a given request policy. + */ + _options) { this._nextPolicy = _nextPolicy; this._options = _options; } @@ -11783,15 +11908,606 @@ class RequestPolicyOptions { } // Copyright (c) Microsoft Corporation. +// Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed +// by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 +// By creating a new copy of the settings each time we instantiate the parser, +// we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. +const xml2jsDefaultOptionsV2 = { + explicitCharkey: false, + trim: false, + normalize: false, + normalizeTags: false, + attrkey: XML_ATTRKEY, + explicitArray: true, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: true, + validator: undefined, + xmlns: false, + explicitChildren: false, + preserveChildrenOrder: false, + childkey: "$$", + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: undefined, + attrValueProcessors: undefined, + tagNameProcessors: undefined, + valueProcessors: undefined, + rootName: "root", + xmldec: { + version: "1.0", + encoding: "UTF-8", + standalone: true, + }, + doctype: undefined, + renderOpts: { + pretty: true, + indent: " ", + newline: "\n", + }, + headless: false, + chunkSize: 10000, + emptyTag: "", + cdata: false, +}; +// The xml2js settings for general XML parsing operations. +const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); +xml2jsParserSettings.explicitArray = false; +// The xml2js settings for general XML building operations. +const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); +xml2jsBuilderSettings.explicitArray = false; +xml2jsBuilderSettings.renderOpts = { + pretty: false, +}; +/** + * Converts given JSON object to XML string + * @param obj - JSON object to be converted into XML string + * @param opts - Options that govern the parsing of given JSON object + */ +function stringifyXML(obj, opts = {}) { + var _a; + xml2jsBuilderSettings.rootName = opts.rootName; + xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + const builder = new xml2js__namespace.Builder(xml2jsBuilderSettings); + return builder.buildObject(obj); +} +/** + * Converts given XML string into JSON + * @param str - String containing the XML content to be parsed into JSON + * @param opts - Options that govern the parsing of given xml string + */ +function parseXML(str, opts = {}) { + var _a; + xml2jsParserSettings.explicitRoot = !!opts.includeRoot; + xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + const xmlParser = new xml2js__namespace.Parser(xml2jsParserSettings); + return new Promise((resolve, reject) => { + if (!str) { + reject(new Error("Document is empty")); + } + else { + xmlParser.parseString(str, (err, res) => { + if (err) { + reject(err); + } + else { + resolve(res); + } + }); + } + }); +} + +// Copyright (c) Microsoft Corporation. +/** + * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they + * pass through the HTTP pipeline. + */ +function deserializationPolicy(deserializationContentTypes, parsingOptions) { + return { + create: (nextPolicy, options) => { + return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); + }, + }; +} +const defaultJsonContentTypes = ["application/json", "text/json"]; +const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +const DefaultDeserializationOptions = { + expectedContentTypes: { + json: defaultJsonContentTypes, + xml: defaultXmlContentTypes, + }, +}; +/** + * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the + * HTTP pipeline. + */ +class DeserializationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { + var _a; + super(nextPolicy, requestPolicyOptions); + this.jsonContentTypes = + (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; + this.xmlContentTypes = + (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; + this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + } + async sendRequest(request) { + return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { + xmlCharKey: this.xmlCharKey, + })); + } +} +function getOperationResponse(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationSpec = request.operationSpec; + if (operationSpec) { + const operationResponseGetter = request.operationResponseGetter; + if (!operationResponseGetter) { + result = operationSpec.responses[parsedResponse.status]; + } + else { + result = operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; +} +function shouldDeserializeResponse(parsedResponse) { + const shouldDeserialize = parsedResponse.request.shouldDeserialize; + let result; + if (shouldDeserialize === undefined) { + result = true; + } + else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } + else { + result = shouldDeserialize(parsedResponse); + } + return result; +} +/** + * Given a particular set of content types to parse as either JSON or XML, consumes the HTTP response to produce the result object defined by the request's {@link OperationSpec}. + * @param jsonContentTypes - Response content types to parse the body as JSON. + * @param xmlContentTypes - Response content types to parse the body as XML. + * @param response - HTTP Response from the pipeline. + * @param options - Options to the serializer, mostly for configuring the XML parser if needed. + * @returns A parsed {@link HttpOperationResponse} object that can be returned by the {@link ServiceClient}. + */ +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { + var _a, _b, _c; + const updatedOptions = { + rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }; + return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationSpec = parsedResponse.request.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponse(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); + if (error) { + throw error; + } + else if (shouldReturnResponse) { + return parsedResponse; + } + // An operation response spec does exist for current status code, so + // use it to deserialize the response. + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof valueToDeserialize === "object" + ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] + : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } + catch (innerError) { + const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + throw restError; + } + } + else if (operationSpec.httpMethod === "HEAD") { + // head methods never have a body, but we return a boolean to indicate presence/absence of the resource + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders", options); + } + } + return parsedResponse; + }); +} +function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return (expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); +} +function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { + var _a; + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) + ? isSuccessByStatus + : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } + else { + return { error: null, shouldReturnResponse: false }; + } + } + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || + parsedResponse.request.streamResponseBody; + const initialErrorMessage = streaming + ? `Unexpected status code: ${parsedResponse.status}` + : parsedResponse.bodyAsText; + const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + // If the item failed but there's no error spec or default spec to deserialize the error, + // we should fail so we just throw the parsed response + if (!errorResponseSpec) { + throw error; + } + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec.headersMapper; + try { + // If error response has a body, try to deserialize it using default body mapper. + // Then try to extract error code & message from it + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let parsedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; + } + parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); + } + const internalError = parsedBody.error || parsedError || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + error.response.parsedBody = parsedError; + } + } + // If error response has headers, try to deserialize it using default header mapper + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders"); + } + } + catch (defaultError) { + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + } + return { error, shouldReturnResponse: false }; +} +function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { + var _a; + const errorHandler = (err) => { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError.PARSE_ERROR; + const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); + return Promise.reject(e); + }; + const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || + operationResponse.request.streamResponseBody; + if (!streaming && operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType + ? [] + : contentType.split(";").map((component) => component.toLowerCase()); + if (contentComponents.length === 0 || + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + return new Promise((resolve) => { + operationResponse.parsedBody = JSON.parse(text); + resolve(operationResponse); + }).catch(errorHandler); + } + else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + return parseXML(text, opts) + .then((body) => { + operationResponse.parsedBody = body; + return operationResponse; + }) + .catch(errorHandler); + } + } + return Promise.resolve(operationResponse); +} + +// Copyright (c) Microsoft Corporation. +/** + * By default, HTTP connections are maintained for future requests. + */ +const DefaultKeepAliveOptions = { + enable: true, +}; +/** + * Creates a policy that controls whether HTTP connections are maintained on future requests. + * @param keepAliveOptions - Keep alive options. By default, HTTP connections are maintained for future requests. + * @returns An instance of the {@link KeepAlivePolicy} + */ +function keepAlivePolicy(keepAliveOptions) { + return { + create: (nextPolicy, options) => { + return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); + }, + }; +} +/** + * KeepAlivePolicy is a policy used to control keep alive settings for every request. + */ +class KeepAlivePolicy extends BaseRequestPolicy { + /** + * Creates an instance of KeepAlivePolicy. + * + * @param nextPolicy - + * @param options - + * @param keepAliveOptions - + */ + constructor(nextPolicy, options, keepAliveOptions) { + super(nextPolicy, options); + this.keepAliveOptions = keepAliveOptions; + } + /** + * Sends out request. + * + * @param request - + * @returns + */ + async sendRequest(request) { + request.keepAlive = this.keepAliveOptions.enable; + return this._nextPolicy.sendRequest(request); + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Methods that are allowed to follow redirects 301 and 302 + */ +const allowedRedirect = ["GET", "HEAD"]; +const DefaultRedirectOptions = { + handleRedirects: true, + maxRetries: 20, +}; +/** + * Creates a redirect policy, which sends a repeats the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + * @param maximumRetries - Maximum number of redirects to follow. + * @returns An instance of the {@link RedirectPolicy} + */ +function redirectPolicy(maximumRetries = 20) { + return { + create: (nextPolicy, options) => { + return new RedirectPolicy(nextPolicy, options, maximumRetries); + }, + }; +} +/** + * Resends the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + */ +class RedirectPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, maxRetries = 20) { + super(nextPolicy, options); + this.maxRetries = maxRetries; + } + sendRequest(request) { + return this._nextPolicy + .sendRequest(request) + .then((response) => handleRedirect(this, response, 0)); + } +} +function handleRedirect(policy, response, currentRetries) { + const { request, status } = response; + const locationHeader = response.headers.get("location"); + if (locationHeader && + (status === 300 || + (status === 301 && allowedRedirect.includes(request.method)) || + (status === 302 && allowedRedirect.includes(request.method)) || + (status === 303 && request.method === "POST") || + status === 307) && + (!policy.maxRetries || currentRetries < policy.maxRetries)) { + const builder = URLBuilder.parse(request.url); + builder.setPath(locationHeader); + request.url = builder.toString(); + // POST request with Status code 303 should be converted into a + // redirected GET request if the redirect url is present in the location header + if (status === 303) { + request.method = "GET"; + delete request.body; + } + return policy._nextPolicy + .sendRequest(request) + .then((res) => handleRedirect(policy, res, currentRetries + 1)); + } + return Promise.resolve(response); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const DEFAULT_CLIENT_RETRY_COUNT = 3; +// intervals are in ms +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; +const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; +function isNumber(n) { + return typeof n === "number"; +} +/** + * @internal + * Determines if the operation should be retried. + * + * @param retryLimit - Specifies the max number of retries. + * @param predicate - Initial chekck on whether to retry based on given responses or errors + * @param retryData - The retry data. + * @returns True if the operation qualifies for a retry; false otherwise. + */ +function shouldRetry(retryLimit, predicate, retryData, response, error) { + if (!predicate(response, error)) { + return false; + } + return retryData.retryCount < retryLimit; +} +/** + * @internal + * Updates the retry data for the next attempt. + * + * @param retryOptions - specifies retry interval, and its lower bound and upper bound. + * @param retryData - The retry data. + * @param err - The operation"s error, if any. + */ +function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { + if (err) { + if (retryData.error) { + err.innerError = retryData.error; + } + retryData.error = err; + } + // Adjust retry count + retryData.retryCount++; + // Adjust retry interval + let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; + const boundedRandDelta = retryOptions.retryInterval * 0.8 + + Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); + incrementDelta *= boundedRandDelta; + retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); + return retryData; +} + +// Copyright (c) Microsoft Corporation. +/** + * Policy that retries the request as many times as configured for as long as the max retry time interval specified, each retry waiting longer to begin than the last time. + * @param retryCount - Maximum number of retries. + * @param retryInterval - Base time between retries. + * @param maxRetryInterval - Maximum time to wait between retries. + */ +function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { + return { + create: (nextPolicy, options) => { + return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); + }, + }; +} +/** + * Describes the Retry Mode type. Currently supporting only Exponential. + */ +exports.RetryMode = void 0; +(function (RetryMode) { + /** + * Currently supported retry mode. + * Each time a retry happens, it will take exponentially more time than the last time. + */ + RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; +})(exports.RetryMode || (exports.RetryMode = {})); +const DefaultRetryOptions = { + maxRetries: DEFAULT_CLIENT_RETRY_COUNT, + retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, + maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, +}; +/** + * Instantiates a new "ExponentialRetryPolicyFilter" instance. + */ +class ExponentialRetryPolicy extends BaseRequestPolicy { + /** + * @param nextPolicy - The next RequestPolicy in the pipeline chain. + * @param options - The options for this RequestPolicy. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + */ + constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) + ? maxRetryInterval + : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + } + sendRequest(request) { + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => retry$1(this, request, response)) + .catch((error) => retry$1(this, request, error.response, undefined, error)); + } +} +async function retry$1(policy, request, response, retryData, requestError) { + function shouldPolicyRetry(responseParam) { + const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { + return false; + } + if (statusCode === undefined || + (statusCode < 500 && statusCode !== 408) || + statusCode === 501 || + statusCode === 505) { + return false; + } + return true; + } + retryData = updateRetryData({ + retryInterval: policy.retryInterval, + minRetryInterval: 0, + maxRetryInterval: policy.maxRetryInterval, + }, retryData, requestError); + const isAborted = request.abortSignal && request.abortSignal.aborted; + if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { + logger.info(`Retrying request in ${retryData.retryInterval}`); + try { + await coreUtil.delay(retryData.retryInterval); + const res = await policy._nextPolicy.sendRequest(request.clone()); + return retry$1(policy, request, res, retryData); + } + catch (err) { + return retry$1(policy, request, response, retryData, err); + } + } + else if (isAborted || requestError || !response) { + // If the operation failed in the end, return all errors instead of just the last one + const err = retryData.error || + new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); + throw err; + } + else { + return response; + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that logs information about the outgoing request and the incoming responses. + * @param loggingOptions - Logging options. + * @returns An instance of the {@link LogPolicy} + */ function logPolicy(loggingOptions = {}) { return { create: (nextPolicy, options) => { return new LogPolicy(nextPolicy, options, loggingOptions); - } + }, }; } +/** + * A policy that logs information about the outgoing request and the incoming responses. + */ class LogPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { + constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [], } = {}) { super(nextPolicy, options); this.logger = logger$1; this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); @@ -11890,519 +12606,352 @@ function getStreamResponseStatusCodes(operationSpec) { } // Copyright (c) Microsoft Corporation. -// Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed -// by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 -// By creating a new copy of the settings each time we instantiate the parser, -// we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. -const xml2jsDefaultOptionsV2 = { - explicitCharkey: false, - trim: false, - normalize: false, - normalizeTags: false, - attrkey: XML_ATTRKEY, - explicitArray: true, - ignoreAttrs: false, - mergeAttrs: false, - explicitRoot: true, - validator: undefined, - xmlns: false, - explicitChildren: false, - preserveChildrenOrder: false, - childkey: "$$", - charsAsChildren: false, - includeWhiteChars: false, - async: false, - strict: true, - attrNameProcessors: undefined, - attrValueProcessors: undefined, - tagNameProcessors: undefined, - valueProcessors: undefined, - rootName: "root", - xmldec: { - version: "1.0", - encoding: "UTF-8", - standalone: true - }, - doctype: undefined, - renderOpts: { - pretty: true, - indent: " ", - newline: "\n" - }, - headless: false, - chunkSize: 10000, - emptyTag: "", - cdata: false -}; -// The xml2js settings for general XML parsing operations. -const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); -xml2jsParserSettings.explicitArray = false; -// The xml2js settings for general XML building operations. -const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); -xml2jsBuilderSettings.explicitArray = false; -xml2jsBuilderSettings.renderOpts = { - pretty: false -}; -/** - * Converts given JSON object to XML string - * @param obj - JSON object to be converted into XML string - * @param opts - Options that govern the parsing of given JSON object - */ -function stringifyXML(obj, opts = {}) { - var _a; - xml2jsBuilderSettings.rootName = opts.rootName; - xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - const builder = new xml2js.Builder(xml2jsBuilderSettings); - return builder.buildObject(obj); +function getDefaultUserAgentKey() { + return Constants.HeaderConstants.USER_AGENT; } -/** - * Converts given XML string into JSON - * @param str - String containing the XML content to be parsed into JSON - * @param opts - Options that govern the parsing of given xml string - */ -function parseXML(str, opts = {}) { - var _a; - xml2jsParserSettings.explicitRoot = !!opts.includeRoot; - xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - const xmlParser = new xml2js.Parser(xml2jsParserSettings); - return new Promise((resolve, reject) => { - if (!str) { - reject(new Error("Document is empty")); - } - else { - xmlParser.parseString(str, (err, res) => { - if (err) { - reject(err); - } - else { - resolve(res); - } - }); - } - }); +function getPlatformSpecificData() { + const runtimeInfo = { + key: "Node", + value: process.version, + }; + const osInfo = { + key: "OS", + value: `(${os__namespace.arch()}-${os__namespace.type()}-${os__namespace.release()})`, + }; + return [runtimeInfo, osInfo]; } // Copyright (c) Microsoft Corporation. +function getRuntimeInfo() { + const msRestRuntime = { + key: "core-http", + value: Constants.coreHttpVersion, + }; + return [msRestRuntime]; +} +function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { + return telemetryInfo + .map((info) => { + const value = info.value ? `${valueSeparator}${info.value}` : ""; + return `${info.key}${value}`; + }) + .join(keySeparator); +} +const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; /** - * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they - * pass through the HTTP pipeline. + * The default approach to generate user agents. + * Uses static information from this package, plus system information available from the runtime. */ -function deserializationPolicy(deserializationContentTypes, parsingOptions) { +function getDefaultUserAgentValue() { + const runtimeInfo = getRuntimeInfo(); + const platformSpecificData = getPlatformSpecificData(); + const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); + return userAgent; +} +/** + * Returns a policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. + * @param userAgentData - Telemetry information. + * @returns A new {@link UserAgentPolicy}. + */ +function userAgentPolicy(userAgentData) { + const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null + ? getDefaultUserAgentKey() + : userAgentData.key; + const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null + ? getDefaultUserAgentValue() + : userAgentData.value; return { create: (nextPolicy, options) => { - return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); - } + return new UserAgentPolicy(nextPolicy, options, key, value); + }, }; } -const defaultJsonContentTypes = ["application/json", "text/json"]; -const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; -const DefaultDeserializationOptions = { - expectedContentTypes: { - json: defaultJsonContentTypes, - xml: defaultXmlContentTypes - } -}; /** - * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the - * HTTP pipeline. + * A policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. */ -class DeserializationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { - var _a; - super(nextPolicy, requestPolicyOptions); - this.jsonContentTypes = - (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - this.xmlContentTypes = - (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - } - async sendRequest(request) { - return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { - xmlCharKey: this.xmlCharKey - })); - } -} -function getOperationResponse(parsedResponse) { - let result; - const request = parsedResponse.request; - const operationSpec = request.operationSpec; - if (operationSpec) { - const operationResponseGetter = request.operationResponseGetter; - if (!operationResponseGetter) { - result = operationSpec.responses[parsedResponse.status]; - } - else { - result = operationResponseGetter(operationSpec, parsedResponse); - } - } - return result; -} -function shouldDeserializeResponse(parsedResponse) { - const shouldDeserialize = parsedResponse.request.shouldDeserialize; - let result; - if (shouldDeserialize === undefined) { - result = true; - } - else if (typeof shouldDeserialize === "boolean") { - result = shouldDeserialize; - } - else { - result = shouldDeserialize(parsedResponse); - } - return result; -} -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { - var _a, _b, _c; - const updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; - return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { - if (!shouldDeserializeResponse(parsedResponse)) { - return parsedResponse; - } - const operationSpec = parsedResponse.request.operationSpec; - if (!operationSpec || !operationSpec.responses) { - return parsedResponse; - } - const responseSpec = getOperationResponse(parsedResponse); - const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); - if (error) { - throw error; - } - else if (shouldReturnResponse) { - return parsedResponse; - } - // An operation response spec does exist for current status code, so - // use it to deserialize the response. - if (responseSpec) { - if (responseSpec.bodyMapper) { - let valueToDeserialize = parsedResponse.parsedBody; - if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof valueToDeserialize === "object" - ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] - : []; - } - try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); - } - catch (innerError) { - const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - throw restError; - } - } - else if (operationSpec.httpMethod === "HEAD") { - // head methods never have a body, but we return a boolean to indicate presence/absence of the resource - parsedResponse.parsedBody = response.status >= 200 && response.status < 300; - } - if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options); - } - } - return parsedResponse; - }); -} -function isOperationSpecEmpty(operationSpec) { - const expectedStatusCodes = Object.keys(operationSpec.responses); - return (expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); -} -function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { - var _a; - const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) - ? isSuccessByStatus - : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } - } - else { - return { error: null, shouldReturnResponse: false }; - } - } - const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || - parsedResponse.request.streamResponseBody; - const initialErrorMessage = streaming - ? `Unexpected status code: ${parsedResponse.status}` - : parsedResponse.bodyAsText; - const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - // If the item failed but there's no error spec or default spec to deserialize the error, - // we should fail so we just throw the parsed response - if (!errorResponseSpec) { - throw error; - } - const defaultBodyMapper = errorResponseSpec.bodyMapper; - const defaultHeadersMapper = errorResponseSpec.headersMapper; - try { - // If error response has a body, try to deserialize it using default body mapper. - // Then try to extract error code & message from it - if (parsedResponse.parsedBody) { - const parsedBody = parsedResponse.parsedBody; - let parsedError; - if (defaultBodyMapper) { - let valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; - } - parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); - } - const internalError = parsedBody.error || parsedError || parsedBody; - error.code = internalError.code; - if (internalError.message) { - error.message = internalError.message; - } - if (defaultBodyMapper) { - error.response.parsedBody = parsedError; - } - } - // If error response has headers, try to deserialize it using default header mapper - if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); - } - } - catch (defaultError) { - error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; - } - return { error, shouldReturnResponse: false }; -} -function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { - var _a; - const errorHandler = (err) => { - const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; - const errCode = err.code || RestError.PARSE_ERROR; - const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); - return Promise.reject(e); - }; - const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || - operationResponse.request.streamResponseBody; - if (!streaming && operationResponse.bodyAsText) { - const text = operationResponse.bodyAsText; - const contentType = operationResponse.headers.get("Content-Type") || ""; - const contentComponents = !contentType - ? [] - : contentType.split(";").map((component) => component.toLowerCase()); - if (contentComponents.length === 0 || - contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { - return new Promise((resolve) => { - operationResponse.parsedBody = JSON.parse(text); - resolve(operationResponse); - }).catch(errorHandler); - } - else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { - return parseXML(text, opts) - .then((body) => { - operationResponse.parsedBody = body; - return operationResponse; - }) - .catch(errorHandler); - } - } - return Promise.resolve(operationResponse); -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const DEFAULT_CLIENT_RETRY_COUNT = 3; -// intervals are in ms -const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; -const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; -const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; -function isNumber(n) { - return typeof n === "number"; -} -/** - * @internal - * Determines if the operation should be retried. - * - * @param retryLimit - Specifies the max number of retries. - * @param predicate - Initial chekck on whether to retry based on given responses or errors - * @param retryData - The retry data. - * @returns True if the operation qualifies for a retry; false otherwise. - */ -function shouldRetry(retryLimit, predicate, retryData, response, error) { - if (!predicate(response, error)) { - return false; - } - return retryData.retryCount < retryLimit; -} -/** - * @internal - * Updates the retry data for the next attempt. - * - * @param retryOptions - specifies retry interval, and its lower bound and upper bound. - * @param retryData - The retry data. - * @param err - The operation"s error, if any. - */ -function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { - if (err) { - if (retryData.error) { - err.innerError = retryData.error; - } - retryData.error = err; - } - // Adjust retry count - retryData.retryCount++; - // Adjust retry interval - let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; - const boundedRandDelta = retryOptions.retryInterval * 0.8 + - Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); - incrementDelta *= boundedRandDelta; - retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); - return retryData; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Helper TypeGuard that checks if the value is not null or undefined. - * @param thing - Anything - * @internal - */ -function isDefined(thing) { - return typeof thing !== "undefined" && thing !== null; -} - -// Copyright (c) Microsoft Corporation. -const StandardAbortMessage = "The operation was aborted."; -/** - * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. - * @param delayInMs - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @param options - The options for delay - currently abort options - * @param abortSignal - The abortSignal associated with containing operation. - * @param abortErrorMsg - The abort error message associated with containing operation. - * @returns - Resolved promise - */ -function delay(delayInMs, value, options) { - return new Promise((resolve, reject) => { - let timer = undefined; - let onAborted = undefined; - const rejectOnAbort = () => { - return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (isDefined(timer)) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); -} - -// Copyright (c) Microsoft Corporation. -function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { - return { - create: (nextPolicy, options) => { - return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); - } - }; -} -(function (RetryMode) { - RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; -})(exports.RetryMode || (exports.RetryMode = {})); -const DefaultRetryOptions = { - maxRetries: DEFAULT_CLIENT_RETRY_COUNT, - retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, - maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL -}; -/** - * Instantiates a new "ExponentialRetryPolicyFilter" instance. - */ -class ExponentialRetryPolicy extends BaseRequestPolicy { - /** - * @param nextPolicy - The next RequestPolicy in the pipeline chain. - * @param options - The options for this RequestPolicy. - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. - */ - constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { - super(nextPolicy, options); - this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - this.maxRetryInterval = isNumber(maxRetryInterval) - ? maxRetryInterval - : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; +class UserAgentPolicy extends BaseRequestPolicy { + constructor(_nextPolicy, _options, headerKey, headerValue) { + super(_nextPolicy, _options); + this._nextPolicy = _nextPolicy; + this._options = _options; + this.headerKey = headerKey; + this.headerValue = headerValue; } sendRequest(request) { - return this._nextPolicy - .sendRequest(request.clone()) - .then((response) => retry(this, request, response)) - .catch((error) => retry(this, request, error.response, undefined, error)); + this.addUserAgentHeader(request); + return this._nextPolicy.sendRequest(request); } -} -async function retry(policy, request, response, retryData, requestError) { - function shouldPolicyRetry(responseParam) { - const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; - if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { - return false; + /** + * Adds the user agent header to the outgoing request. + */ + addUserAgentHeader(request) { + if (!request.headers) { + request.headers = new HttpHeaders(); } - if (statusCode === undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { - return false; + if (!request.headers.get(this.headerKey) && this.headerValue) { + request.headers.set(this.headerKey, this.headerValue); } - return true; - } - retryData = updateRetryData({ - retryInterval: policy.retryInterval, - minRetryInterval: 0, - maxRetryInterval: policy.maxRetryInterval - }, retryData, requestError); - const isAborted = request.abortSignal && request.abortSignal.aborted; - if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { - logger.info(`Retrying request in ${retryData.retryInterval}`); - try { - await delay(retryData.retryInterval); - const res = await policy._nextPolicy.sendRequest(request.clone()); - return retry(policy, request, res, retryData); - } - catch (err) { - return retry(policy, request, response, retryData, err); - } - } - else if (isAborted || requestError || !response) { - // If the operation failed in the end, return all errors instead of just the last one - const err = retryData.error || - new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); - throw err; - } - else { - return response; } } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The format that will be used to join an array of values together for a query parameter value. + */ +exports.QueryCollectionFormat = void 0; +(function (QueryCollectionFormat) { + /** + * CSV: Each pair of segments joined by a single comma. + */ + QueryCollectionFormat["Csv"] = ","; + /** + * SSV: Each pair of segments joined by a single space character. + */ + QueryCollectionFormat["Ssv"] = " "; + /** + * TSV: Each pair of segments joined by a single tab character. + */ + QueryCollectionFormat["Tsv"] = "\t"; + /** + * Pipes: Each pair of segments joined by a single pipe character. + */ + QueryCollectionFormat["Pipes"] = "|"; + /** + * Denotes this is an array of values that should be passed to the server in multiple key/value pairs, e.g. `?queryParam=value1&queryParam=value2` + */ + QueryCollectionFormat["Multi"] = "Multi"; +})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); + +// Copyright (c) Microsoft Corporation. +// Default options for the cycler if none are provided +const DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1000, + retryIntervalInMs: 3000, + refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry +}; +/** + * Converts an an unreliable access token getter (which may resolve with null) + * into an AccessTokenGetter by retrying the unreliable getter in a regular + * interval. + * + * @param getAccessToken - a function that produces a promise of an access + * token that may fail by returning null + * @param retryIntervalInMs - the time (in milliseconds) to wait between retry + * attempts + * @param timeoutInMs - the timestamp after which the refresh attempt will fail, + * throwing an exception + * @returns - a promise that, if it resolves, will resolve with an access token + */ +async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { + // This wrapper handles exceptions gracefully as long as we haven't exceeded + // the timeout. + async function tryGetAccessToken() { + if (Date.now() < timeoutInMs) { + try { + return await getAccessToken(); + } + catch (_a) { + return null; + } + } + else { + const finalToken = await getAccessToken(); + // Timeout is up, so throw if it's still null + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await coreUtil.delay(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; +} +/** + * Creates a token cycler from a credential, scopes, and optional settings. + * + * A token cycler represents a way to reliably retrieve a valid access token + * from a TokenCredential. It will handle initializing the token, refreshing it + * when it nears expiration, and synchronizes refresh attempts to avoid + * concurrency hazards. + * + * @param credential - the underlying TokenCredential that provides the access + * token + * @param scopes - the scopes to request authorization for + * @param tokenCyclerOptions - optionally override default settings for the cycler + * + * @returns - a function that reliably produces a valid access token + */ +function createTokenCycler(credential, scopes, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + /** + * This little holder defines several predicates that we use to construct + * the rules of refreshing the token. + */ + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + return (!cycler.isRefreshing && + ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); + }, + }; + /** + * Starts a refresh job or returns the existing job if one is already + * running. + */ + function refresh(getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + // We bind `scopes` here to avoid passing it around a lot + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + // Take advantage of promise chaining to insert an assignment to `token` + // before the refresh can be considered done. + refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) + .then((_token) => { + refreshWorker = null; + token = _token; + return token; + }) + .catch((reason) => { + // We also should reset the refresher if we enter a failed state. All + // existing awaiters will throw, but subsequent requests will start a + // new retry chain. + refreshWorker = null; + token = null; + throw reason; + }); + } + return refreshWorker; + } + return async (tokenOptions) => { + // + // Simple rules: + // - If we MUST refresh, then return the refresh task, blocking + // the pipeline until a token is available. + // - If we SHOULD refresh, then run refresh but don't return it + // (we can still use the cached token). + // - Return the token, since it's fine if we didn't return in + // step 1. + // + if (cycler.mustRefresh) + return refresh(tokenOptions); + if (cycler.shouldRefresh) { + refresh(tokenOptions); + } + return token; + }; +} +// #endregion +/** + * Creates a new factory for a RequestPolicy that applies a bearer token to + * the requests' `Authorization` headers. + * + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. + */ +function bearerTokenAuthenticationPolicy(credential, scopes) { + // This simple function encapsulates the entire process of reliably retrieving the token + const getToken = createTokenCycler(credential, scopes /* , options */); + class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + async sendRequest(webResource) { + if (!webResource.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + const { token } = await getToken({ + abortSignal: webResource.abortSignal, + tracingOptions: { + tracingContext: webResource.tracingContext, + }, + }); + webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); + return this._nextPolicy.sendRequest(webResource); + } + } + return { + create: (nextPolicy, options) => { + return new BearerTokenAuthenticationPolicy(nextPolicy, options); + }, + }; +} + +// Copyright (c) Microsoft Corporation. +/** + * Returns a request policy factory that can be used to create an instance of + * {@link DisableResponseDecompressionPolicy}. + */ +function disableResponseDecompressionPolicy() { + return { + create: (nextPolicy, options) => { + return new DisableResponseDecompressionPolicy(nextPolicy, options); + }, + }; +} +/** + * A policy to disable response decompression according to Accept-Encoding header + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding + */ +class DisableResponseDecompressionPolicy extends BaseRequestPolicy { + /** + * Creates an instance of DisableResponseDecompressionPolicy. + * + * @param nextPolicy - + * @param options - + */ + // The parent constructor is protected. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + /** + * Sends out request. + * + * @param request - + * @returns + */ + async sendRequest(request) { + request.decompressResponse = false; + return this._nextPolicy.sendRequest(request); + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that assigns a unique request id to outgoing requests. + * @param requestIdHeaderName - The name of the header to use when assigning the unique id to the request. + */ function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { return { create: (nextPolicy, options) => { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); - } + }, }; } class GenerateClientRequestIdPolicy extends BaseRequestPolicy { @@ -12419,130 +12968,190 @@ class GenerateClientRequestIdPolicy extends BaseRequestPolicy { } // Copyright (c) Microsoft Corporation. -function getDefaultUserAgentKey() { - return Constants.HeaderConstants.USER_AGENT; -} -function getPlatformSpecificData() { - const runtimeInfo = { - key: "Node", - value: process.version - }; - const osInfo = { - key: "OS", - value: `(${os.arch()}-${os.type()}-${os.release()})` - }; - return [runtimeInfo, osInfo]; +let cachedHttpClient; +function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = new NodeFetchHttpClient(); + } + return cachedHttpClient; } // Copyright (c) Microsoft Corporation. -function getRuntimeInfo() { - const msRestRuntime = { - key: "core-http", - value: Constants.coreHttpVersion - }; - return [msRestRuntime]; -} -function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { - return telemetryInfo - .map((info) => { - const value = info.value ? `${valueSeparator}${info.value}` : ""; - return `${info.key}${value}`; - }) - .join(keySeparator); -} -const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; -function getDefaultUserAgentValue() { - const runtimeInfo = getRuntimeInfo(); - const platformSpecificData = getPlatformSpecificData(); - const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); - return userAgent; -} -function userAgentPolicy(userAgentData) { - const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null - ? getDefaultUserAgentKey() - : userAgentData.key; - const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null - ? getDefaultUserAgentValue() - : userAgentData.value; +function ndJsonPolicy() { return { create: (nextPolicy, options) => { - return new UserAgentPolicy(nextPolicy, options, key, value); - } + return new NdJsonPolicy(nextPolicy, options); + }, }; } -class UserAgentPolicy extends BaseRequestPolicy { - constructor(_nextPolicy, _options, headerKey, headerValue) { - super(_nextPolicy, _options); - this._nextPolicy = _nextPolicy; - this._options = _options; - this.headerKey = headerKey; - this.headerValue = headerValue; +/** + * NdJsonPolicy that formats a JSON array as newline-delimited JSON + */ +class NdJsonPolicy extends BaseRequestPolicy { + /** + * Creates an instance of KeepAlivePolicy. + */ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - sendRequest(request) { - this.addUserAgentHeader(request); + /** + * Sends a request. + */ + async sendRequest(request) { + // There currently isn't a good way to bypass the serializer + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } return this._nextPolicy.sendRequest(request); } - addUserAgentHeader(request) { - if (!request.headers) { - request.headers = new HttpHeaders(); - } - if (!request.headers.get(this.headerKey) && this.headerValue) { - request.headers.set(this.headerKey, this.headerValue); - } - } } // Copyright (c) Microsoft Corporation. /** - * Methods that are allowed to follow redirects 301 and 302 + * Stores the patterns specified in NO_PROXY environment variable. + * @internal */ -const allowedRedirect = ["GET", "HEAD"]; -const DefaultRedirectOptions = { - handleRedirects: true, - maxRetries: 20 -}; -function redirectPolicy(maximumRetries = 20) { - return { - create: (nextPolicy, options) => { - return new RedirectPolicy(nextPolicy, options, maximumRetries); +const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); +function loadEnvironmentProxyValue() { + if (!process) { + return undefined; + } + const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); + const allProxy = getEnvironmentValue(Constants.ALL_PROXY); + const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; +} +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn't have the proxy settings set. + * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 + */ +function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = URLBuilder.parse(uri).getHost(); + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } + else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } } + else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; +} +/** + * @internal + */ +function loadNoProxy() { + const noProxy = getEnvironmentValue(Constants.NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length); + } + return []; +} +/** + * Converts a given URL of a proxy server into `ProxySettings` or attempts to retrieve `ProxySettings` from the current environment if one is not passed. + * @param proxyUrl - URL of the proxy + * @returns The default proxy settings, or undefined. + */ +function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return undefined; + } + } + const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); + const parsedUrl = URLBuilder.parse(urlWithoutAuth); + const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + return { + host: schema + parsedUrl.getHost(), + port: Number.parseInt(parsedUrl.getPort() || "80"), + username, + password, }; } -class RedirectPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, maxRetries = 20) { +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +function proxyPolicy(proxySettings, options) { + if (!proxySettings) { + proxySettings = getDefaultProxySettings(); + } + if (!noProxyListLoaded) { + globalNoProxyList.push(...loadNoProxy()); + } + return { + create: (nextPolicy, requestPolicyOptions) => { + return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); + }, + }; +} +function extractAuthFromUrl(url) { + const atIndex = url.indexOf("@"); + if (atIndex === -1) { + return { urlWithoutAuth: url }; + } + const schemeIndex = url.indexOf("://"); + const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; + const auth = url.substring(authStart, atIndex); + const colonIndex = auth.indexOf(":"); + const hasPassword = colonIndex !== -1; + const username = hasPassword ? auth.substring(0, colonIndex) : auth; + const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; + const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); + return { + username, + password, + urlWithoutAuth, + }; +} +class ProxyPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, proxySettings, customNoProxyList) { super(nextPolicy, options); - this.maxRetries = maxRetries; + this.proxySettings = proxySettings; + this.customNoProxyList = customNoProxyList; } sendRequest(request) { - return this._nextPolicy - .sendRequest(request) - .then((response) => handleRedirect(this, response, 0)); - } -} -function handleRedirect(policy, response, currentRetries) { - const { request, status } = response; - const locationHeader = response.headers.get("location"); - if (locationHeader && - (status === 300 || - (status === 301 && allowedRedirect.includes(request.method)) || - (status === 302 && allowedRedirect.includes(request.method)) || - (status === 303 && request.method === "POST") || - status === 307) && - (!policy.maxRetries || currentRetries < policy.maxRetries)) { - const builder = URLBuilder.parse(request.url); - builder.setPath(locationHeader); - request.url = builder.toString(); - // POST request with Status code 303 should be converted into a - // redirected GET request if the redirect url is present in the location header - if (status === 303) { - request.method = "GET"; - delete request.body; + var _a; + if (!request.proxySettings && + !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { + request.proxySettings = this.proxySettings; } - return policy._nextPolicy - .sendRequest(request) - .then((res) => handleRedirect(policy, res, currentRetries + 1)); + return this._nextPolicy.sendRequest(request); } - return Promise.resolve(response); } // Copyright (c) Microsoft Corporation. @@ -12550,7 +13159,7 @@ function rpRegistrationPolicy(retryTimeout = 30) { return { create: (nextPolicy, options) => { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); - } + }, }; } class RPRegistrationPolicy extends BaseRequestPolicy { @@ -12689,199 +13298,58 @@ async function getRegistrationStatus(policy, url, originalRequest) { return true; } else { - await delay(policy._retryTimeout * 1000); + await coreUtil.delay(policy._retryTimeout * 1000); return getRegistrationStatus(policy, url, originalRequest); } } // Copyright (c) Microsoft Corporation. -// Default options for the cycler if none are provided -const DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1000, - retryIntervalInMs: 3000, - refreshWindowInMs: 1000 * 60 * 2 // Start refreshing 2m before expiry -}; /** - * Converts an an unreliable access token getter (which may resolve with null) - * into an AccessTokenGetter by retrying the unreliable getter in a regular - * interval. - * - * @param getAccessToken - a function that produces a promise of an access - * token that may fail by returning null - * @param retryIntervalInMs - the time (in milliseconds) to wait between retry - * attempts - * @param timeoutInMs - the timestamp after which the refresh attempt will fail, - * throwing an exception - * @returns - a promise that, if it resolves, will resolve with an access token + * Creates a policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. + * @param authenticationProvider - The authentication provider. + * @returns An instance of the {@link SigningPolicy}. */ -async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { - // This wrapper handles exceptions gracefully as long as we haven't exceeded - // the timeout. - async function tryGetAccessToken() { - if (Date.now() < timeoutInMs) { - try { - return await getAccessToken(); - } - catch (_a) { - return null; - } - } - else { - const finalToken = await getAccessToken(); - // Timeout is up, so throw if it's still null - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; - } - } - let token = await tryGetAccessToken(); - while (token === null) { - await delay(retryIntervalInMs); - token = await tryGetAccessToken(); - } - return token; -} -/** - * Creates a token cycler from a credential, scopes, and optional settings. - * - * A token cycler represents a way to reliably retrieve a valid access token - * from a TokenCredential. It will handle initializing the token, refreshing it - * when it nears expiration, and synchronizes refresh attempts to avoid - * concurrency hazards. - * - * @param credential - the underlying TokenCredential that provides the access - * token - * @param scopes - the scopes to request authorization for - * @param tokenCyclerOptions - optionally override default settings for the cycler - * - * @returns - a function that reliably produces a valid access token - */ -function createTokenCycler(credential, scopes, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - /** - * This little holder defines several predicates that we use to construct - * the rules of refreshing the token. - */ - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - return (!cycler.isRefreshing && - ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); - } - }; - /** - * Starts a refresh job or returns the existing job if one is already - * running. - */ - function refresh(getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - // We bind `scopes` here to avoid passing it around a lot - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - // Take advantage of promise chaining to insert an assignment to `token` - // before the refresh can be considered done. - refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) - .then((_token) => { - refreshWorker = null; - token = _token; - return token; - }) - .catch((reason) => { - // We also should reset the refresher if we enter a failed state. All - // existing awaiters will throw, but subsequent requests will start a - // new retry chain. - refreshWorker = null; - token = null; - throw reason; - }); - } - return refreshWorker; - } - return async (tokenOptions) => { - // - // Simple rules: - // - If we MUST refresh, then return the refresh task, blocking - // the pipeline until a token is available. - // - If we SHOULD refresh, then run refresh but don't return it - // (we can still use the cached token). - // - Return the token, since it's fine if we didn't return in - // step 1. - // - if (cycler.mustRefresh) - return refresh(tokenOptions); - if (cycler.shouldRefresh) { - refresh(tokenOptions); - } - return token; - }; -} -// #endregion -/** - * Creates a new factory for a RequestPolicy that applies a bearer token to - * the requests' `Authorization` headers. - * - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. - */ -function bearerTokenAuthenticationPolicy(credential, scopes) { - // This simple function encapsulates the entire process of reliably retrieving the token - const getToken = createTokenCycler(credential, scopes /* , options */); - class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - async sendRequest(webResource) { - if (!webResource.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - const { token } = await getToken({ - abortSignal: webResource.abortSignal, - tracingOptions: { - tracingContext: webResource.tracingContext - } - }); - webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); - return this._nextPolicy.sendRequest(webResource); - } - } +function signingPolicy(authenticationProvider) { return { create: (nextPolicy, options) => { - return new BearerTokenAuthenticationPolicy(nextPolicy, options); - } + return new SigningPolicy(nextPolicy, options, authenticationProvider); + }, }; } +/** + * A policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. + */ +class SigningPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, authenticationProvider) { + super(nextPolicy, options); + this.authenticationProvider = authenticationProvider; + } + signRequest(request) { + return this.authenticationProvider.signRequest(request); + } + sendRequest(request) { + return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); + } +} // Copyright (c) Microsoft Corporation. +/** + * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". + * @param retryCount - Maximum number of retries. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @returns An instance of the {@link SystemErrorRetryPolicy} + */ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { return { create: (nextPolicy, options) => { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - } + }, }; } /** + * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". * @param retryCount - The client retry count. * @param retryInterval - The client retry interval, in milliseconds. * @param minRetryInterval - The minimum retry interval, in milliseconds. @@ -12902,10 +13370,10 @@ class SystemErrorRetryPolicy extends BaseRequestPolicy { sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .catch((error) => retry$1(this, request, error.response, error)); + .catch((error) => retry(this, request, error.response, error)); } } -async function retry$1(policy, request, operationResponse, err, retryData) { +async function retry(policy, request, operationResponse, err, retryData) { retryData = updateRetryData(policy, retryData, err); function shouldPolicyRetry(_response, error) { if (error && @@ -12922,11 +13390,11 @@ async function retry$1(policy, request, operationResponse, err, retryData) { if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { // If previous operation ended with an error and the policy allows a retry, do that try { - await delay(retryData.retryInterval); + await coreUtil.delay(retryData.retryInterval); return policy._nextPolicy.sendRequest(request.clone()); } catch (nestedErr) { - return retry$1(policy, request, operationResponse, nestedErr, retryData); + return retry(policy, request, operationResponse, nestedErr, retryData); } } else { @@ -12938,155 +13406,6 @@ async function retry$1(policy, request, operationResponse, err, retryData) { } } -// Copyright (c) Microsoft Corporation. -(function (QueryCollectionFormat) { - QueryCollectionFormat["Csv"] = ","; - QueryCollectionFormat["Ssv"] = " "; - QueryCollectionFormat["Tsv"] = "\t"; - QueryCollectionFormat["Pipes"] = "|"; - QueryCollectionFormat["Multi"] = "Multi"; -})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); - -// Copyright (c) Microsoft Corporation. -/** - * Stores the patterns specified in NO_PROXY environment variable. - * @internal - */ -const globalNoProxyList = []; -let noProxyListLoaded = false; -/** A cache of whether a host should bypass the proxy. */ -const globalBypassedMap = new Map(); -function loadEnvironmentProxyValue() { - if (!process) { - return undefined; - } - const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - const allProxy = getEnvironmentValue(Constants.ALL_PROXY); - const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; -} -/** - * Check whether the host of a given `uri` matches any pattern in the no proxy list. - * If there's a match, any request sent to the same host shouldn't have the proxy settings set. - * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 - */ -function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = URLBuilder.parse(uri).getHost(); - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } - else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } - } - } - else { - if (host === pattern) { - isBypassedFlag = true; - } - } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; -} -/** - * @internal - */ -function loadNoProxy() { - const noProxy = getEnvironmentValue(Constants.NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy - .split(",") - .map((item) => item.trim()) - .filter((item) => item.length); - } - return []; -} -function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return undefined; - } - } - const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); - const parsedUrl = URLBuilder.parse(urlWithoutAuth); - const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; - return { - host: schema + parsedUrl.getHost(), - port: Number.parseInt(parsedUrl.getPort() || "80"), - username, - password - }; -} -/** - * A policy that allows one to apply proxy settings to all requests. - * If not passed static settings, they will be retrieved from the HTTPS_PROXY - * or HTTP_PROXY environment variables. - * @param proxySettings - ProxySettings to use on each request. - * @param options - additional settings, for example, custom NO_PROXY patterns - */ -function proxyPolicy(proxySettings, options) { - if (!proxySettings) { - proxySettings = getDefaultProxySettings(); - } - if (!noProxyListLoaded) { - globalNoProxyList.push(...loadNoProxy()); - } - return { - create: (nextPolicy, requestPolicyOptions) => { - return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); - } - }; -} -function extractAuthFromUrl(url) { - const atIndex = url.indexOf("@"); - if (atIndex === -1) { - return { urlWithoutAuth: url }; - } - const schemeIndex = url.indexOf("://"); - const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - const auth = url.substring(authStart, atIndex); - const colonIndex = auth.indexOf(":"); - const hasPassword = colonIndex !== -1; - const username = hasPassword ? auth.substring(0, colonIndex) : auth; - const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); - return { - username, - password, - urlWithoutAuth - }; -} -class ProxyPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, proxySettings, customNoProxyList) { - super(nextPolicy, options); - this.proxySettings = proxySettings; - this.customNoProxyList = customNoProxyList; - } - sendRequest(request) { - var _a; - if (!request.proxySettings && - !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { - request.proxySettings = this.proxySettings; - } - return this._nextPolicy.sendRequest(request); - } -} - // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** @@ -13096,15 +13415,28 @@ const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; // Copyright (c) Microsoft Corporation. const StatusCodes = Constants.HttpConstants.StatusCodes; +/** + * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. + * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * @returns + */ function throttlingRetryPolicy() { return { create: (nextPolicy, options) => { return new ThrottlingRetryPolicy(nextPolicy, options); - } + }, }; } -const StandardAbortMessage$1 = "The operation was aborted."; +const StandardAbortMessage = "The operation was aborted."; /** + * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. + * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. + * * To learn more, please refer to * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and @@ -13133,12 +13465,12 @@ class ThrottlingRetryPolicy extends BaseRequestPolicy { const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); if (delayInMs) { this.numberOfRetries += 1; - await delay(delayInMs, undefined, { + await coreUtil.delay(delayInMs, { abortSignal: httpRequest.abortSignal, - abortErrorMsg: StandardAbortMessage$1 + abortErrorMsg: StandardAbortMessage, }); if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw new abortController.AbortError(StandardAbortMessage$1); + throw new abortController.AbortError(StandardAbortMessage); } if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { return this.sendRequest(httpRequest); @@ -13172,77 +13504,26 @@ class ThrottlingRetryPolicy extends BaseRequestPolicy { } } -// Copyright (c) Microsoft Corporation. -function signingPolicy(authenticationProvider) { - return { - create: (nextPolicy, options) => { - return new SigningPolicy(nextPolicy, options, authenticationProvider); - } - }; -} -class SigningPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, authenticationProvider) { - super(nextPolicy, options); - this.authenticationProvider = authenticationProvider; - } - signRequest(request) { - return this.authenticationProvider.signRequest(request); - } - sendRequest(request) { - return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); - } -} - -// Copyright (c) Microsoft Corporation. -const DefaultKeepAliveOptions = { - enable: true -}; -function keepAlivePolicy(keepAliveOptions) { - return { - create: (nextPolicy, options) => { - return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); - } - }; -} -/** - * KeepAlivePolicy is a policy used to control keep alive settings for every request. - */ -class KeepAlivePolicy extends BaseRequestPolicy { - /** - * Creates an instance of KeepAlivePolicy. - * - * @param nextPolicy - - * @param options - - * @param keepAliveOptions - - */ - constructor(nextPolicy, options, keepAliveOptions) { - super(nextPolicy, options); - this.keepAliveOptions = keepAliveOptions; - } - /** - * Sends out request. - * - * @param request - - * @returns - */ - async sendRequest(request) { - request.keepAlive = this.keepAliveOptions.enable; - return this._nextPolicy.sendRequest(request); - } -} - // Copyright (c) Microsoft Corporation. const createSpan = coreTracing.createSpanFunction({ packagePrefix: "", - namespace: "" + namespace: "", }); +/** + * Creates a policy that wraps outgoing requests with a tracing span. + * @param tracingOptions - Tracing options. + * @returns An instance of the {@link TracingPolicy} class. + */ function tracingPolicy(tracingOptions = {}) { return { create(nextPolicy, options) { return new TracingPolicy(nextPolicy, options, tracingOptions); - } + }, }; } +/** + * A policy that wraps outgoing requests with a tracing span. + */ class TracingPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, tracingOptions) { super(nextPolicy, options); @@ -13269,14 +13550,13 @@ class TracingPolicy extends BaseRequestPolicy { tryCreateSpan(request) { var _a; try { - const path = URLBuilder.parse(request.url).getPath() || "/"; // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. // We can pass this as a separate parameter once we upgrade to the latest core-tracing. - const { span } = createSpan(path, { + const { span } = createSpan(`HTTP ${request.method}`, { tracingOptions: { spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), - tracingContext: request.tracingContext - } + tracingContext: request.tracingContext, + }, }); // If the span is not recording, don't do any more work. if (!span.isRecording()) { @@ -13290,7 +13570,7 @@ class TracingPolicy extends BaseRequestPolicy { span.setAttributes({ "http.method": request.method, "http.url": request.url, - requestId: request.requestId + requestId: request.requestId, }); if (this.userAgent) { span.setAttribute("http.user_agent", this.userAgent); @@ -13317,7 +13597,7 @@ class TracingPolicy extends BaseRequestPolicy { try { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, - message: err.message + message: err.message, }); if (err.statusCode) { span.setAttribute("http.status_code", err.statusCode); @@ -13336,7 +13616,7 @@ class TracingPolicy extends BaseRequestPolicy { span.setAttribute("serviceRequestId", serviceRequestId); } span.setStatus({ - code: coreTracing.SpanStatusCode.OK + code: coreTracing.SpanStatusCode.OK, }); span.end(); } @@ -13346,88 +13626,6 @@ class TracingPolicy extends BaseRequestPolicy { } } -// Copyright (c) Microsoft Corporation. -/** - * Returns a request policy factory that can be used to create an instance of - * {@link DisableResponseDecompressionPolicy}. - */ -function disableResponseDecompressionPolicy() { - return { - create: (nextPolicy, options) => { - return new DisableResponseDecompressionPolicy(nextPolicy, options); - } - }; -} -/** - * A policy to disable response decompression according to Accept-Encoding header - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding - */ -class DisableResponseDecompressionPolicy extends BaseRequestPolicy { - /** - * Creates an instance of DisableResponseDecompressionPolicy. - * - * @param nextPolicy - - * @param options - - */ - // The parent constructor is protected. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends out request. - * - * @param request - - * @returns - */ - async sendRequest(request) { - request.decompressResponse = false; - return this._nextPolicy.sendRequest(request); - } -} - -// Copyright (c) Microsoft Corporation. -function ndJsonPolicy() { - return { - create: (nextPolicy, options) => { - return new NdJsonPolicy(nextPolicy, options); - } - }; -} -/** - * NdJsonPolicy that formats a JSON array as newline-delimited JSON - */ -class NdJsonPolicy extends BaseRequestPolicy { - /** - * Creates an instance of KeepAlivePolicy. - */ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends a request. - */ - async sendRequest(request) { - // There currently isn't a good way to bypass the serializer - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return this._nextPolicy.sendRequest(request); - } -} - -// Copyright (c) Microsoft Corporation. -let cachedHttpClient; -function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = new NodeFetchHttpClient(); - } - return cachedHttpClient; -} - // Copyright (c) Microsoft Corporation. /** * ServiceClient sends service requests and receives responses. @@ -13477,7 +13675,7 @@ class ServiceClient { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); } return bearerTokenPolicyFactory.create(nextPolicy, createOptions); - } + }, }; }; authPolicyFactory = wrappedPolicyFactory(); @@ -13712,7 +13910,7 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op const updatedOptions = { rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, - xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY + xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY, }; const xmlCharKey = serializerOptions.xmlCharKey; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { @@ -13731,13 +13929,13 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op if (typeName === MapperType.Sequence) { httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, - xmlCharKey + xmlCharKey, }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { rootName: xmlName || serializedName, - xmlCharKey + xmlCharKey, }); } } @@ -13821,6 +14019,12 @@ function createDefaultRequestPolicyFactories(authPolicyFactory, options) { factories.push(logPolicy({ logger: logger.info })); return factories; } +/** + * Creates an HTTP pipeline based on the given options. + * @param pipelineOptions - Defines options that are used to configure policies in the HTTP pipeline for an SDK client. + * @param authPolicyFactory - An optional authentication policy factory to use for signing requests. + * @returns A set of options that can be passed to create a new {@link ServiceClient}. + */ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { const requestPolicyFactories = []; if (pipelineOptions.sendStreamingJson) { @@ -13859,7 +14063,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { } return { httpClient: pipelineOptions.httpClient, - requestPolicyFactories + requestPolicyFactories, }; } function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { @@ -13935,12 +14139,18 @@ function getPropertyFromParameterPath(parent, parameterPath) { } return result; } +/** + * Parses an {@link HttpOperationResponse} into a normalized HTTP response object ({@link RestResponse}). + * @param _response - Wrapper object for http response. + * @param responseSpec - Mappers for how to parse the response properties. + * @returns - A normalized response object. + */ function flattenResponse(_response, responseSpec) { const parsedHeaders = _response.parsedHeaders; const bodyMapper = responseSpec && responseSpec.bodyMapper; const addOperationResponse = (obj) => { return Object.defineProperty(obj, "_response", { - value: _response + value: _response, }); }; if (bodyMapper) { @@ -13981,8 +14191,8 @@ function getCredentialScopes(options, baseUri) { if (options === null || options === void 0 ? void 0 : options.credentialScopes) { const scopes = options.credentialScopes; return Array.isArray(scopes) - ? scopes.map((scope) => new url.URL(scope).toString()) - : new url.URL(scopes).toString(); + ? scopes.map((scope) => new URL(scope).toString()) + : new URL(scopes).toString(); } if (baseUri) { return `${baseUri}/.default`; @@ -14026,9 +14236,16 @@ class ExpiringAccessTokenCache { this.cachedToken = undefined; this.tokenRefreshBufferMs = tokenRefreshBufferMs; } + /** + * Saves an access token into the internal in-memory cache. + * @param accessToken - Access token or undefined to clear the cache. + */ setCachedToken(accessToken) { this.cachedToken = accessToken; } + /** + * Returns the cached access token, or `undefined` if one is not cached or the cached one is expiring soon. + */ getCachedToken() { if (this.cachedToken && Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { @@ -14087,6 +14304,9 @@ class AccessTokenRefresher { // Copyright (c) Microsoft Corporation. const HeaderConstants = Constants.HeaderConstants; const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; +/** + * A simple {@link ServiceClientCredential} that authenticates with a username and a password. + */ class BasicAuthenticationCredentials { /** * Creates a new BasicAuthenticationCredentials object. @@ -14096,6 +14316,10 @@ class BasicAuthenticationCredentials { * @param authorizationScheme - The authorization scheme. */ constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { + /** + * Authorization scheme. Defaults to "Basic". + * More information about authorization schemes is available here: https://developer.mozilla.org/docs/Web/HTTP/Authentication#authentication_schemes + */ this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { throw new Error("userName cannot be null or undefined and must be of type string."); @@ -14175,6 +14399,9 @@ class ApiKeyCredentials { } // Copyright (c) Microsoft Corporation. +/** + * A {@link TopicCredentials} object used for Azure Event Grid. + */ class TopicCredentials extends ApiKeyCredentials { /** * Creates a new EventGrid TopicCredentials object. @@ -14187,18 +14414,20 @@ class TopicCredentials extends ApiKeyCredentials { } const options = { inHeader: { - "aeg-sas-key": topicKey - } + "aeg-sas-key": topicKey, + }, }; super(options); } } +Object.defineProperty(exports, "delay", ({ + enumerable: true, + get: function () { return coreUtil.delay; } +})); Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, - get: function () { - return coreAuth.isTokenCredential; - } + get: function () { return coreAuth.isTokenCredential; } })); exports.AccessTokenRefresher = AccessTokenRefresher; exports.ApiKeyCredentials = ApiKeyCredentials; @@ -14223,7 +14452,6 @@ exports.applyMixins = applyMixins; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; exports.createPipelineFromOptions = createPipelineFromOptions; exports.createSpanFunction = createSpanFunction; -exports.delay = delay; exports.deserializationPolicy = deserializationPolicy; exports.deserializeResponseBody = deserializeResponseBody; exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy; @@ -17127,6 +17355,284 @@ exports.setSpanContext = setSpanContext; //# sourceMappingURL=index.js.map +/***/ }), + +/***/ 1333: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var abortController = __nccwpck_require__(2557); +var crypto = __nccwpck_require__(6113); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var _a$1; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_a$1 = process.versions) === null || _a$1 === void 0 ? void 0 : _a$1.node); + +// Copyright (c) Microsoft Corporation. +/** + * Creates an abortable promise. + * @param buildPromise - A function that takes the resolve and reject functions as parameters. + * @param options - The options for the abortable promise. + * @returns A promise that can be aborted. + */ +function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve, reject) => { + function rejectOnAbort() { + reject(new abortController.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } + catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); +} + +// Copyright (c) Microsoft Corporation. +const StandardAbortMessage = "The delay was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @param options - The options for delay - currently abort options + * @returns Promise that is resolved after timeInMs + */ +function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return createAbortablePromise((resolve) => { + token = setTimeout(resolve, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, + }); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +function getRandomIntegerInclusive(min, max) { + // Make sure inputs are integers. + min = Math.ceil(min); + max = Math.floor(max); + // Pick a random offset from zero to the size of the range. + // Since Math.random() can never return 1, we have to make the range one larger + // in order to be inclusive of the maximum value after we take the floor. + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +function isObject(input) { + return (typeof input === "object" && + input !== null && + !Array.isArray(input) && + !(input instanceof RegExp) && + !(input instanceof Date)); +} + +// Copyright (c) Microsoft Corporation. +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +function isError(e) { + if (isObject(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; +} +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +function getErrorMessage(e) { + if (isError(e)) { + return e.message; + } + else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } + else { + stringified = String(e); + } + } + catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return crypto.createHmac("sha256", decodedKey).update(stringToSign).digest(encoding); +} +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +async function computeSha256Hash(content, encoding) { + return crypto.createHash("sha256").update(content).digest(encoding); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + */ +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + */ +function isObjectWithProperties(thing, properties) { + if (!isDefined(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + */ +function objectHasProperty(thing, property) { + return (isDefined(thing) && typeof thing === "object" && property in thing); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + */ +function generateUUID() { + let uuid = ""; + for (let i = 0; i < 32; i++) { + // Generate a random number between 0 and 15 + const randomNumber = Math.floor(Math.random() * 16); + // Set the UUID version to 4 in the 13th position + if (i === 12) { + uuid += "4"; + } + else if (i === 16) { + // Set the UUID variant to "10" in the 17th position + uuid += (randomNumber & 0x3) | 0x8; + } + else { + // Add a random hexadecimal digit to the UUID string + uuid += randomNumber.toString(16); + } + // Add hyphens to the UUID string at the appropriate positions + if (i === 7 || i === 11 || i === 15 || i === 19) { + uuid += "-"; + } + } + return uuid; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var _a; +// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+. +let uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" + ? globalThis.crypto.randomUUID.bind(globalThis.crypto) + : crypto.randomUUID; +// Not defined in earlier versions of Node.js 14 +if (!uuidFunction) { + uuidFunction = generateUUID; +} +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + */ +function randomUUID() { + return uuidFunction(); +} + +exports.computeSha256Hash = computeSha256Hash; +exports.computeSha256Hmac = computeSha256Hmac; +exports.createAbortablePromise = createAbortablePromise; +exports.delay = delay; +exports.getErrorMessage = getErrorMessage; +exports.getRandomIntegerInclusive = getRandomIntegerInclusive; +exports.isDefined = isDefined; +exports.isError = isError; +exports.isNode = isNode; +exports.isObject = isObject; +exports.isObjectWithProperties = isObjectWithProperties; +exports.objectHasProperty = objectHasProperty; +exports.randomUUID = randomUUID; +//# sourceMappingURL=index.js.map + + /***/ }), /***/ 3233: @@ -54835,14 +55341,14 @@ module.exports = v4; this.saxParser.onopentag = (function(_this) { return function(node) { var key, newValue, obj, processedKey, ref; - obj = {}; + obj = Object.create(null); obj[charkey] = ""; if (!_this.options.ignoreAttrs) { ref = node.attributes; for (key in ref) { if (!hasProp.call(ref, key)) continue; if (!(attrkey in obj) && !_this.options.mergeAttrs) { - obj[attrkey] = {}; + obj[attrkey] = Object.create(null); } newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; @@ -54892,7 +55398,11 @@ module.exports = v4; } } if (isEmpty(obj)) { - obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + if (typeof _this.options.emptyTag === 'function') { + obj = _this.options.emptyTag(); + } else { + obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + } } if (_this.options.validator != null) { xpath = "/" + ((function() { @@ -54916,7 +55426,7 @@ module.exports = v4; } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { if (!_this.options.preserveChildrenOrder) { - node = {}; + node = Object.create(null); if (_this.options.attrkey in obj) { node[_this.options.attrkey] = obj[_this.options.attrkey]; delete obj[_this.options.attrkey]; @@ -54931,7 +55441,7 @@ module.exports = v4; obj = node; } else if (s) { s[_this.options.childkey] = s[_this.options.childkey] || []; - objClone = {}; + objClone = Object.create(null); for (key in obj) { if (!hasProp.call(obj, key)) continue; objClone[key] = obj[key]; @@ -54948,7 +55458,7 @@ module.exports = v4; } else { if (_this.options.explicitRoot) { old = obj; - obj = {}; + obj = Object.create(null); obj[nodeName] = old; } _this.resultObject = obj; diff --git a/dist/setup/index.js b/dist/setup/index.js index aaeeac4..e7c2300 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -13153,26 +13153,52 @@ exports.isTokenCredential = isTokenCredential; Object.defineProperty(exports, "__esModule", ({ value: true })); -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - var uuid = __nccwpck_require__(3415); -var tough = __nccwpck_require__(7372); +var util = __nccwpck_require__(3837); +var tslib = __nccwpck_require__(2107); +var xml2js = __nccwpck_require__(6189); +var coreUtil = __nccwpck_require__(1333); +var logger$1 = __nccwpck_require__(3233); +var coreAuth = __nccwpck_require__(9645); +var os = __nccwpck_require__(2037); var http = __nccwpck_require__(3685); var https = __nccwpck_require__(5687); -var node_fetch = _interopDefault(__nccwpck_require__(467)); +var tough = __nccwpck_require__(7372); var abortController = __nccwpck_require__(2557); -var FormData = _interopDefault(__nccwpck_require__(6279)); -var util = __nccwpck_require__(3837); -var url = __nccwpck_require__(7310); -var stream = __nccwpck_require__(2781); -var logger$1 = __nccwpck_require__(3233); var tunnel = __nccwpck_require__(4294); -var tslib = __nccwpck_require__(2107); -var coreAuth = __nccwpck_require__(9645); -var xml2js = __nccwpck_require__(6189); -var os = __nccwpck_require__(2037); +var stream = __nccwpck_require__(2781); +var FormData = __nccwpck_require__(6279); +var node_fetch = __nccwpck_require__(467); var coreTracing = __nccwpck_require__(4175); -__nccwpck_require__(6821); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var xml2js__namespace = /*#__PURE__*/_interopNamespace(xml2js); +var os__namespace = /*#__PURE__*/_interopNamespace(os); +var http__namespace = /*#__PURE__*/_interopNamespace(http); +var https__namespace = /*#__PURE__*/_interopNamespace(https); +var tough__namespace = /*#__PURE__*/_interopNamespace(tough); +var tunnel__namespace = /*#__PURE__*/_interopNamespace(tunnel); +var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData); +var node_fetch__default = /*#__PURE__*/_interopDefaultLegacy(node_fetch); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -13221,7 +13247,7 @@ class HttpHeaders { set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, - value: headerValue.toString() + value: headerValue.toString(), }; } /** @@ -13253,12 +13279,7 @@ class HttpHeaders { * Get the headers that are contained this collection as an object. */ rawHeaders() { - const result = {}; - for (const headerKey in this._headersMap) { - const header = this._headersMap[headerKey]; - result[header.name.toLowerCase()] = header.value; - } - return result; + return this.toJson({ preserveCase: true }); } /** * Get the headers that are contained in this collection as an array. @@ -13295,14 +13316,27 @@ class HttpHeaders { /** * Get the JSON object representation of this HTTP header collection. */ - toJson() { - return this.rawHeaders(); + toJson(options = {}) { + const result = {}; + if (options.preserveCase) { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[header.name] = header.value; + } + } + else { + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + result[getHeaderKey(header.name)] = header.value; + } + } + return result; } /** * Get the string representation of this HTTP header collection. */ toString() { - return JSON.stringify(this.toJson()); + return JSON.stringify(this.toJson({ preserveCase: true })); } /** * Create a deep clone/copy of this HttpHeaders collection. @@ -13346,11 +13380,14 @@ function decodeString(value) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +/** + * A set of constants used internally when processing requests. + */ const Constants = { /** * The core-http version */ - coreHttpVersion: "2.2.2", + coreHttpVersion: "2.3.2", /** * Specifies HTTP. */ @@ -13386,12 +13423,12 @@ const Constants = { POST: "POST", MERGE: "MERGE", HEAD: "HEAD", - PATCH: "PATCH" + PATCH: "PATCH", }, StatusCodes: { TooManyRequests: 429, - ServiceUnavailable: 503 - } + ServiceUnavailable: 503, + }, }, /** * Defines constants for use with HTTP headers. @@ -13411,8 +13448,8 @@ const Constants = { /** * The UserAgent header. */ - USER_AGENT: "User-Agent" - } + USER_AGENT: "User-Agent", + }, }; // Copyright (c) Microsoft Corporation. @@ -13627,18 +13664,39 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. +// This file contains utility code to serialize and deserialize network operations according to `OperationSpec` objects generated by AutoRest.TypeScript from OpenAPI specifications. +/** + * Used to map raw response objects to final shapes. + * Helps packing and unpacking Dates and other encoded types that are not intrinsic to JSON. + * Also allows pulling values from headers, as well as inserting default values and constants. + */ class Serializer { - constructor(modelMappers = {}, isXML) { + constructor( + /** + * The provided model mapper. + */ + modelMappers = {}, + /** + * Whether the contents are XML or not. + */ + isXML) { this.modelMappers = modelMappers; this.isXML = isXML; } + /** + * Validates constraints, if any. This function will throw if the provided value does not respect those constraints. + * @param mapper - The definition of data models. + * @param value - The value. + * @param objectName - Name of the object. Used in the error messages. + * @deprecated Removing the constraints validation on client side. + */ validateConstraints(mapper, value, objectName) { const failValidation = (constraintName, constraintValue) => { throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); }; if (mapper.constraints && value != undefined) { const valueAsNumber = value; - const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } @@ -13680,20 +13738,20 @@ class Serializer { } } /** - * Serialize the given object based on its metadata defined in the mapper + * Serialize the given object based on its metadata defined in the mapper. * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param object - A valid Javascript object to be serialized - * @param objectName - Name of the serialized object - * @param options - additional options to deserialization - * @returns A valid serialized Javascript object + * @param mapper - The mapper which defines the metadata of the serializable object. + * @param object - A valid Javascript object to be serialized. + * @param objectName - Name of the serialized object. + * @param options - additional options to deserialization. + * @returns A valid serialized Javascript object. */ serialize(mapper, object, objectName, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; let payload = {}; const mapperType = mapper.type.name; @@ -13729,8 +13787,6 @@ class Serializer { payload = object; } else { - // Validate Constraints if any - this.validateConstraints(mapper, object, objectName); if (mapperType.match(/^any$/i) !== null) { payload = object; } @@ -13763,20 +13819,20 @@ class Serializer { return payload; } /** - * Deserialize the given object based on its metadata defined in the mapper + * Deserialize the given object based on its metadata defined in the mapper. * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param responseBody - A valid Javascript entity to be deserialized - * @param objectName - Name of the deserialized object + * @param mapper - The mapper which defines the metadata of the serializable object. + * @param responseBody - A valid Javascript entity to be deserialized. + * @param objectName - Name of the deserialized object. * @param options - Controls behavior of XML parser and builder. - * @returns A valid deserialized Javascript object + * @returns A valid deserialized Javascript object. */ deserialize(mapper, responseBody, objectName, options = {}) { var _a, _b, _c; const updatedOptions = { rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, }; if (responseBody == undefined) { if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { @@ -13875,9 +13931,7 @@ function bufferToBase64Url(buffer) { // Uint8Array to Base64. const str = encodeByteArray(buffer); // Base64 to Base64Url. - return trimEnd(str, "=") - .replace(/\+/g, "-") - .replace(/\//g, "_"); + return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); } function base64UrlToByteArray(str) { if (!str) { @@ -14093,10 +14147,10 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, return tempDictionary; } /** - * Resolves the additionalProperties property from a referenced mapper - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * Resolves the additionalProperties property from a referenced mapper. + * @param serializer - The serializer containing the entire set of mappers. + * @param mapper - The composite mapper to resolve. + * @param objectName - Name of the object being serialized. */ function resolveAdditionalProperties(serializer, mapper, objectName) { const additionalProperties = mapper.type.additionalProperties; @@ -14107,7 +14161,7 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { return additionalProperties; } /** - * Finds the mapper referenced by className + * Finds the mapper referenced by `className`. * @param serializer - The serializer containing the entire set of mappers * @param mapper - The composite mapper to resolve * @param objectName - Name of the object being serialized @@ -14250,7 +14304,8 @@ function isSpecialXmlProperty(propertyName, options) { return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); } function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - var _a; + var _a, _b; + const xmlCharKey = (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } @@ -14281,6 +14336,16 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); } + else if (propertyMapper.xmlIsMsText) { + if (responseBody[xmlCharKey] !== undefined) { + instance[key] = responseBody[xmlCharKey]; + } + else if (typeof responseBody === "string") { + // The special case where xml parser parses "content" into JSON of + // `{ name: "content"}` instead of `{ name: { "_": "content" }}` + instance[key] = responseBody; + } + } else { const propertyName = xmlElementName || xmlName || serializedName; if (propertyMapper.xmlIsWrapped) { @@ -14299,7 +14364,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, xmlName is "Cors" and xmlElementName is"CorsRule". */ const wrapped = responseBody[xmlName]; - const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; + const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); } else { @@ -14446,7 +14511,9 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator); } -// TODO: why is this here? +/** + * Utility function that serializes an object that might contain binary information into a plain object, array or a string. + */ function serializeObject(toSerialize) { const castToSerialize = toSerialize; if (toSerialize == undefined) @@ -14484,6 +14551,9 @@ function strEnum(o) { } return result; } +/** + * String enum containing the string types of property mappers. + */ // eslint-disable-next-line @typescript-eslint/no-redeclare const MapperType = strEnum([ "Base64Url", @@ -14501,7 +14571,7 @@ const MapperType = strEnum([ "String", "Stream", "TimeSpan", - "UnixTime" + "UnixTime", ]); // Copyright (c) Microsoft Corporation. @@ -14764,9 +14834,6 @@ class WebResource { } } -// Copyright (c) Microsoft Corporation. -const custom = util.inspect.custom; - // Copyright (c) Microsoft Corporation. /** * A class that handles the query portion of a URLBuilder. @@ -15064,6 +15131,10 @@ class URLBuilder { } } } + /** + * Serializes the URL as a string. + * @returns the URL as a string. + */ toString() { let result = ""; if (this._scheme) { @@ -15099,6 +15170,9 @@ class URLBuilder { this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); } } + /** + * Parses a given string URL into a new {@link URLBuilder}. + */ static parse(text) { const result = new URLBuilder(); result.set(text, "SCHEME_OR_HOST"); @@ -15355,6 +15429,60 @@ function nextQuery(tokenizer) { tokenizer._currentState = "DONE"; } +// Copyright (c) Microsoft Corporation. +function createProxyAgent(requestUrl, proxySettings, headers) { + const host = URLBuilder.parse(proxySettings.host).getHost(); + if (!host) { + throw new Error("Expecting a non-empty host in proxy settings."); + } + if (!isValidPort(proxySettings.port)) { + throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); + } + const tunnelOptions = { + proxy: { + host: host, + port: proxySettings.port, + headers: (headers && headers.rawHeaders()) || {}, + }, + }; + if (proxySettings.username && proxySettings.password) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; + } + else if (proxySettings.username) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; + } + const isRequestHttps = isUrlHttps(requestUrl); + const isProxyHttps = isUrlHttps(proxySettings.host); + const proxyAgent = { + isHttps: isRequestHttps, + agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions), + }; + return proxyAgent; +} +function isUrlHttps(url) { + const urlScheme = URLBuilder.parse(url).getScheme() || ""; + return urlScheme.toLowerCase() === "https"; +} +function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { + if (isRequestHttps && isProxyHttps) { + return tunnel__namespace.httpsOverHttps(tunnelOptions); + } + else if (isRequestHttps && !isProxyHttps) { + return tunnel__namespace.httpsOverHttp(tunnelOptions); + } + else if (!isRequestHttps && isProxyHttps) { + return tunnel__namespace.httpOverHttps(tunnelOptions); + } + else { + return tunnel__namespace.httpOverHttp(tunnelOptions); + } +} +function isValidPort(port) { + // any port in 0-65535 range is valid (RFC 793) even though almost all implementations + // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports + return 0 <= port && port <= 65535; +} + // Copyright (c) Microsoft Corporation. const RedactedString = "REDACTED"; const defaultAllowedHeaderNames = [ @@ -15395,7 +15523,8 @@ const defaultAllowedHeaderNames = [ "Retry-After", "Server", "Transfer-Encoding", - "User-Agent" + "User-Agent", + "WWW-Authenticate", ]; const defaultAllowedQueryParameters = ["api-version"]; class Sanitizer { @@ -15488,8 +15617,14 @@ class Sanitizer { } } +// Copyright (c) Microsoft Corporation. +const custom = util.inspect.custom; + // Copyright (c) Microsoft Corporation. const errorSanitizer = new Sanitizer(); +/** + * An error resulting from an HTTP request to a service endpoint. + */ class RestError extends Error { constructor(message, code, statusCode, request, response) { super(message); @@ -15507,13 +15642,22 @@ class RestError extends Error { return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; } } +/** + * A constant string to identify errors that may arise when making an HTTP request that indicates an issue with the transport layer (e.g. the hostname of the URL cannot be resolved via DNS.) + */ RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +/** + * A constant string to identify errors that may arise from parsing an incoming HTTP response. Usually indicates a malformed HTTP body, such as an encoded JSON payload that is incomplete. + */ RestError.PARSE_ERROR = "PARSE_ERROR"; // Copyright (c) Microsoft Corporation. const logger = logger$1.createClientLogger("core-http"); // Copyright (c) Microsoft Corporation. +function getCachedAgent(isHttps, agentCache) { + return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; +} class ReportTransform extends stream.Transform { constructor(progressCallback) { super(); @@ -15527,7 +15671,44 @@ class ReportTransform extends stream.Transform { callback(undefined); } } -class FetchHttpClient { +function isReadableStream(body) { + return body && typeof body.pipe === "function"; +} +function isStreamComplete(stream, aborter) { + return new Promise((resolve) => { + stream.once("close", () => { + aborter === null || aborter === void 0 ? void 0 : aborter.abort(); + resolve(); + }); + stream.once("end", resolve); + stream.once("error", resolve); + }); +} +/** + * Transforms a set of headers into the key/value pair defined by {@link HttpHeadersLike} + */ +function parseHeaders(headers) { + const httpHeaders = new HttpHeaders(); + headers.forEach((value, key) => { + httpHeaders.set(key, value); + }); + return httpHeaders; +} +/** + * An HTTP client that uses `node-fetch`. + */ +class NodeFetchHttpClient { + constructor() { + // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent + this.proxyAgentMap = new Map(); + this.keepAliveAgents = {}; + this.cookieJar = new tough__namespace.CookieJar(undefined, { looseMode: true }); + } + /** + * Provides minimum viable error handling and the logic that executes the abstract methods. + * @param httpRequest - Object representing the outgoing HTTP request. + * @returns An object representing the incoming HTTP response. + */ async sendRequest(httpRequest) { var _a; if (!httpRequest && typeof httpRequest !== "object") { @@ -15553,7 +15734,7 @@ class FetchHttpClient { } if (httpRequest.formData) { const formData = httpRequest.formData; - const requestForm = new FormData(); + const requestForm = new FormData__default["default"](); const appendFormValue = (key, value) => { // value function probably returns a stream so we can provide a fresh stream on each retry if (typeof value === "function") { @@ -15609,7 +15790,11 @@ class FetchHttpClient { body = uploadReportStream; } const platformSpecificRequestInit = await this.prepareRequest(httpRequest); - const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); + const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, + // the types for RequestInit are from the browser, which expects AbortSignal to + // have `reason` and `throwIfAborted`, but these don't exist on our polyfill + // for Node. + signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); let operationResponse; try { const response = await this.fetch(httpRequest.url, requestInit); @@ -15623,7 +15808,7 @@ class FetchHttpClient { readableStreamBody: streaming ? response.body : undefined, - bodyAsText: !streaming ? await response.text() : undefined + bodyAsText: !streaming ? await response.text() : undefined, }; const onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { @@ -15677,94 +15862,6 @@ class FetchHttpClient { } } } -} -function isReadableStream(body) { - return body && typeof body.pipe === "function"; -} -function isStreamComplete(stream, aborter) { - return new Promise((resolve) => { - stream.once("close", () => { - aborter === null || aborter === void 0 ? void 0 : aborter.abort(); - resolve(); - }); - stream.once("end", resolve); - stream.once("error", resolve); - }); -} -function parseHeaders(headers) { - const httpHeaders = new HttpHeaders(); - headers.forEach((value, key) => { - httpHeaders.set(key, value); - }); - return httpHeaders; -} - -// Copyright (c) Microsoft Corporation. -function createProxyAgent(requestUrl, proxySettings, headers) { - const host = URLBuilder.parse(proxySettings.host).getHost(); - if (!host) { - throw new Error("Expecting a non-empty host in proxy settings."); - } - if (!isValidPort(proxySettings.port)) { - throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); - } - const tunnelOptions = { - proxy: { - host: host, - port: proxySettings.port, - headers: (headers && headers.rawHeaders()) || {} - } - }; - if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; - } - else if (proxySettings.username) { - tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; - } - const isRequestHttps = isUrlHttps(requestUrl); - const isProxyHttps = isUrlHttps(proxySettings.host); - const proxyAgent = { - isHttps: isRequestHttps, - agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) - }; - return proxyAgent; -} -function isUrlHttps(url) { - const urlScheme = URLBuilder.parse(url).getScheme() || ""; - return urlScheme.toLowerCase() === "https"; -} -function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { - if (isRequestHttps && isProxyHttps) { - return tunnel.httpsOverHttps(tunnelOptions); - } - else if (isRequestHttps && !isProxyHttps) { - return tunnel.httpsOverHttp(tunnelOptions); - } - else if (!isRequestHttps && isProxyHttps) { - return tunnel.httpOverHttps(tunnelOptions); - } - else { - return tunnel.httpOverHttp(tunnelOptions); - } -} -function isValidPort(port) { - // any port in 0-65535 range is valid (RFC 793) even though almost all implementations - // will reserve 0 for a specific purpose, and a range of numbers for ephemeral ports - return 0 <= port && port <= 65535; -} - -// Copyright (c) Microsoft Corporation. -function getCachedAgent(isHttps, agentCache) { - return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; -} -class NodeFetchHttpClient extends FetchHttpClient { - constructor() { - super(...arguments); - // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent - this.proxyAgentMap = new Map(); - this.keepAliveAgents = {}; - this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); - } getOrCreateAgent(httpRequest) { var _a; const isHttps = isUrlHttps(httpRequest.url); @@ -15796,24 +15893,30 @@ class NodeFetchHttpClient extends FetchHttpClient { return agent; } const agentOptions = { - keepAlive: httpRequest.keepAlive + keepAlive: httpRequest.keepAlive, }; if (isHttps) { - agent = this.keepAliveAgents.httpsAgent = new https.Agent(agentOptions); + agent = this.keepAliveAgents.httpsAgent = new https__namespace.Agent(agentOptions); } else { - agent = this.keepAliveAgents.httpAgent = new http.Agent(agentOptions); + agent = this.keepAliveAgents.httpAgent = new http__namespace.Agent(agentOptions); } return agent; } else { - return isHttps ? https.globalAgent : http.globalAgent; + return isHttps ? https__namespace.globalAgent : http__namespace.globalAgent; } } + /** + * Uses `node-fetch` to perform the request. + */ // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs async fetch(input, init) { - return node_fetch(input, init); + return node_fetch__default["default"](input, init); } + /** + * Prepares a request based on the provided web resource. + */ async prepareRequest(httpRequest) { const requestInit = {}; if (this.cookieJar && !httpRequest.headers.get("Cookie")) { @@ -15834,6 +15937,9 @@ class NodeFetchHttpClient extends FetchHttpClient { requestInit.compress = httpRequest.decompressResponse; return requestInit; } + /** + * Process an HTTP response. Handles persisting a cookie for subsequent requests if the response has a "Set-Cookie" header. + */ async processRequest(operationResponse) { if (this.cookieJar) { const setCookieHeader = operationResponse.headers.get("Set-Cookie"); @@ -15854,6 +15960,11 @@ class NodeFetchHttpClient extends FetchHttpClient { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The different levels of logs that can be used with the HttpPipelineLogger. + */ +exports.HttpPipelineLogLevel = void 0; (function (HttpPipelineLogLevel) { /** * A log level that indicates that no logs will be logged. @@ -15873,13 +15984,13 @@ class NodeFetchHttpClient extends FetchHttpClient { HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO"; })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {})); +// Copyright (c) Microsoft Corporation. /** * Converts an OperationOptions to a RequestOptionsBase * * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { - var _a; const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); let result = additionalOptions; if (requestOptions) { @@ -15888,14 +15999,28 @@ function operationOptionsToRequestOptionsBase(opts) { if (tracingOptions) { result.tracingContext = tracingOptions.tracingContext; // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. - result.spanOptions = (_a = tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions; + result.spanOptions = tracingOptions === null || tracingOptions === void 0 ? void 0 : tracingOptions.spanOptions; } return result; } // Copyright (c) Microsoft Corporation. +/** + * The base class from which all request policies derive. + */ class BaseRequestPolicy { - constructor(_nextPolicy, _options) { + /** + * The main method to implement that manipulates a request/response. + */ + constructor( + /** + * The next policy in the pipeline. Each policy is responsible for executing the next one if the request is to continue through the pipeline. + */ + _nextPolicy, + /** + * The options that can be passed to a given request policy. + */ + _options) { this._nextPolicy = _nextPolicy; this._options = _options; } @@ -15948,15 +16073,606 @@ class RequestPolicyOptions { } // Copyright (c) Microsoft Corporation. +// Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed +// by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 +// By creating a new copy of the settings each time we instantiate the parser, +// we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. +const xml2jsDefaultOptionsV2 = { + explicitCharkey: false, + trim: false, + normalize: false, + normalizeTags: false, + attrkey: XML_ATTRKEY, + explicitArray: true, + ignoreAttrs: false, + mergeAttrs: false, + explicitRoot: true, + validator: undefined, + xmlns: false, + explicitChildren: false, + preserveChildrenOrder: false, + childkey: "$$", + charsAsChildren: false, + includeWhiteChars: false, + async: false, + strict: true, + attrNameProcessors: undefined, + attrValueProcessors: undefined, + tagNameProcessors: undefined, + valueProcessors: undefined, + rootName: "root", + xmldec: { + version: "1.0", + encoding: "UTF-8", + standalone: true, + }, + doctype: undefined, + renderOpts: { + pretty: true, + indent: " ", + newline: "\n", + }, + headless: false, + chunkSize: 10000, + emptyTag: "", + cdata: false, +}; +// The xml2js settings for general XML parsing operations. +const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); +xml2jsParserSettings.explicitArray = false; +// The xml2js settings for general XML building operations. +const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); +xml2jsBuilderSettings.explicitArray = false; +xml2jsBuilderSettings.renderOpts = { + pretty: false, +}; +/** + * Converts given JSON object to XML string + * @param obj - JSON object to be converted into XML string + * @param opts - Options that govern the parsing of given JSON object + */ +function stringifyXML(obj, opts = {}) { + var _a; + xml2jsBuilderSettings.rootName = opts.rootName; + xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + const builder = new xml2js__namespace.Builder(xml2jsBuilderSettings); + return builder.buildObject(obj); +} +/** + * Converts given XML string into JSON + * @param str - String containing the XML content to be parsed into JSON + * @param opts - Options that govern the parsing of given xml string + */ +function parseXML(str, opts = {}) { + var _a; + xml2jsParserSettings.explicitRoot = !!opts.includeRoot; + xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + const xmlParser = new xml2js__namespace.Parser(xml2jsParserSettings); + return new Promise((resolve, reject) => { + if (!str) { + reject(new Error("Document is empty")); + } + else { + xmlParser.parseString(str, (err, res) => { + if (err) { + reject(err); + } + else { + resolve(res); + } + }); + } + }); +} + +// Copyright (c) Microsoft Corporation. +/** + * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they + * pass through the HTTP pipeline. + */ +function deserializationPolicy(deserializationContentTypes, parsingOptions) { + return { + create: (nextPolicy, options) => { + return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); + }, + }; +} +const defaultJsonContentTypes = ["application/json", "text/json"]; +const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +const DefaultDeserializationOptions = { + expectedContentTypes: { + json: defaultJsonContentTypes, + xml: defaultXmlContentTypes, + }, +}; +/** + * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the + * HTTP pipeline. + */ +class DeserializationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { + var _a; + super(nextPolicy, requestPolicyOptions); + this.jsonContentTypes = + (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; + this.xmlContentTypes = + (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; + this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + } + async sendRequest(request) { + return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { + xmlCharKey: this.xmlCharKey, + })); + } +} +function getOperationResponse(parsedResponse) { + let result; + const request = parsedResponse.request; + const operationSpec = request.operationSpec; + if (operationSpec) { + const operationResponseGetter = request.operationResponseGetter; + if (!operationResponseGetter) { + result = operationSpec.responses[parsedResponse.status]; + } + else { + result = operationResponseGetter(operationSpec, parsedResponse); + } + } + return result; +} +function shouldDeserializeResponse(parsedResponse) { + const shouldDeserialize = parsedResponse.request.shouldDeserialize; + let result; + if (shouldDeserialize === undefined) { + result = true; + } + else if (typeof shouldDeserialize === "boolean") { + result = shouldDeserialize; + } + else { + result = shouldDeserialize(parsedResponse); + } + return result; +} +/** + * Given a particular set of content types to parse as either JSON or XML, consumes the HTTP response to produce the result object defined by the request's {@link OperationSpec}. + * @param jsonContentTypes - Response content types to parse the body as JSON. + * @param xmlContentTypes - Response content types to parse the body as XML. + * @param response - HTTP Response from the pipeline. + * @param options - Options to the serializer, mostly for configuring the XML parser if needed. + * @returns A parsed {@link HttpOperationResponse} object that can be returned by the {@link ServiceClient}. + */ +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { + var _a, _b, _c; + const updatedOptions = { + rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", + includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, + xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, + }; + return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { + if (!shouldDeserializeResponse(parsedResponse)) { + return parsedResponse; + } + const operationSpec = parsedResponse.request.operationSpec; + if (!operationSpec || !operationSpec.responses) { + return parsedResponse; + } + const responseSpec = getOperationResponse(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); + if (error) { + throw error; + } + else if (shouldReturnResponse) { + return parsedResponse; + } + // An operation response spec does exist for current status code, so + // use it to deserialize the response. + if (responseSpec) { + if (responseSpec.bodyMapper) { + let valueToDeserialize = parsedResponse.parsedBody; + if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof valueToDeserialize === "object" + ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] + : []; + } + try { + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + } + catch (innerError) { + const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + throw restError; + } + } + else if (operationSpec.httpMethod === "HEAD") { + // head methods never have a body, but we return a boolean to indicate presence/absence of the resource + parsedResponse.parsedBody = response.status >= 200 && response.status < 300; + } + if (responseSpec.headersMapper) { + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders", options); + } + } + return parsedResponse; + }); +} +function isOperationSpecEmpty(operationSpec) { + const expectedStatusCodes = Object.keys(operationSpec.responses); + return (expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); +} +function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { + var _a; + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) + ? isSuccessByStatus + : !!responseSpec; + if (isExpectedStatusCode) { + if (responseSpec) { + if (!responseSpec.isError) { + return { error: null, shouldReturnResponse: false }; + } + } + else { + return { error: null, shouldReturnResponse: false }; + } + } + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || + parsedResponse.request.streamResponseBody; + const initialErrorMessage = streaming + ? `Unexpected status code: ${parsedResponse.status}` + : parsedResponse.bodyAsText; + const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + // If the item failed but there's no error spec or default spec to deserialize the error, + // we should fail so we just throw the parsed response + if (!errorResponseSpec) { + throw error; + } + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const defaultHeadersMapper = errorResponseSpec.headersMapper; + try { + // If error response has a body, try to deserialize it using default body mapper. + // Then try to extract error code & message from it + if (parsedResponse.parsedBody) { + const parsedBody = parsedResponse.parsedBody; + let parsedError; + if (defaultBodyMapper) { + let valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; + } + parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); + } + const internalError = parsedBody.error || parsedError || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + error.response.parsedBody = parsedError; + } + } + // If error response has headers, try to deserialize it using default header mapper + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJson(), "operationRes.parsedHeaders"); + } + } + catch (defaultError) { + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; + } + return { error, shouldReturnResponse: false }; +} +function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { + var _a; + const errorHandler = (err) => { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError.PARSE_ERROR; + const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); + return Promise.reject(e); + }; + const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || + operationResponse.request.streamResponseBody; + if (!streaming && operationResponse.bodyAsText) { + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType + ? [] + : contentType.split(";").map((component) => component.toLowerCase()); + if (contentComponents.length === 0 || + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + return new Promise((resolve) => { + operationResponse.parsedBody = JSON.parse(text); + resolve(operationResponse); + }).catch(errorHandler); + } + else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + return parseXML(text, opts) + .then((body) => { + operationResponse.parsedBody = body; + return operationResponse; + }) + .catch(errorHandler); + } + } + return Promise.resolve(operationResponse); +} + +// Copyright (c) Microsoft Corporation. +/** + * By default, HTTP connections are maintained for future requests. + */ +const DefaultKeepAliveOptions = { + enable: true, +}; +/** + * Creates a policy that controls whether HTTP connections are maintained on future requests. + * @param keepAliveOptions - Keep alive options. By default, HTTP connections are maintained for future requests. + * @returns An instance of the {@link KeepAlivePolicy} + */ +function keepAlivePolicy(keepAliveOptions) { + return { + create: (nextPolicy, options) => { + return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); + }, + }; +} +/** + * KeepAlivePolicy is a policy used to control keep alive settings for every request. + */ +class KeepAlivePolicy extends BaseRequestPolicy { + /** + * Creates an instance of KeepAlivePolicy. + * + * @param nextPolicy - + * @param options - + * @param keepAliveOptions - + */ + constructor(nextPolicy, options, keepAliveOptions) { + super(nextPolicy, options); + this.keepAliveOptions = keepAliveOptions; + } + /** + * Sends out request. + * + * @param request - + * @returns + */ + async sendRequest(request) { + request.keepAlive = this.keepAliveOptions.enable; + return this._nextPolicy.sendRequest(request); + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Methods that are allowed to follow redirects 301 and 302 + */ +const allowedRedirect = ["GET", "HEAD"]; +const DefaultRedirectOptions = { + handleRedirects: true, + maxRetries: 20, +}; +/** + * Creates a redirect policy, which sends a repeats the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + * @param maximumRetries - Maximum number of redirects to follow. + * @returns An instance of the {@link RedirectPolicy} + */ +function redirectPolicy(maximumRetries = 20) { + return { + create: (nextPolicy, options) => { + return new RedirectPolicy(nextPolicy, options, maximumRetries); + }, + }; +} +/** + * Resends the request to a new destination if a response arrives with a "location" header, and a status code between 300 and 307. + */ +class RedirectPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, maxRetries = 20) { + super(nextPolicy, options); + this.maxRetries = maxRetries; + } + sendRequest(request) { + return this._nextPolicy + .sendRequest(request) + .then((response) => handleRedirect(this, response, 0)); + } +} +function handleRedirect(policy, response, currentRetries) { + const { request, status } = response; + const locationHeader = response.headers.get("location"); + if (locationHeader && + (status === 300 || + (status === 301 && allowedRedirect.includes(request.method)) || + (status === 302 && allowedRedirect.includes(request.method)) || + (status === 303 && request.method === "POST") || + status === 307) && + (!policy.maxRetries || currentRetries < policy.maxRetries)) { + const builder = URLBuilder.parse(request.url); + builder.setPath(locationHeader); + request.url = builder.toString(); + // POST request with Status code 303 should be converted into a + // redirected GET request if the redirect url is present in the location header + if (status === 303) { + request.method = "GET"; + delete request.body; + } + return policy._nextPolicy + .sendRequest(request) + .then((res) => handleRedirect(policy, res, currentRetries + 1)); + } + return Promise.resolve(response); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const DEFAULT_CLIENT_RETRY_COUNT = 3; +// intervals are in ms +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; +const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; +function isNumber(n) { + return typeof n === "number"; +} +/** + * @internal + * Determines if the operation should be retried. + * + * @param retryLimit - Specifies the max number of retries. + * @param predicate - Initial chekck on whether to retry based on given responses or errors + * @param retryData - The retry data. + * @returns True if the operation qualifies for a retry; false otherwise. + */ +function shouldRetry(retryLimit, predicate, retryData, response, error) { + if (!predicate(response, error)) { + return false; + } + return retryData.retryCount < retryLimit; +} +/** + * @internal + * Updates the retry data for the next attempt. + * + * @param retryOptions - specifies retry interval, and its lower bound and upper bound. + * @param retryData - The retry data. + * @param err - The operation"s error, if any. + */ +function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { + if (err) { + if (retryData.error) { + err.innerError = retryData.error; + } + retryData.error = err; + } + // Adjust retry count + retryData.retryCount++; + // Adjust retry interval + let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; + const boundedRandDelta = retryOptions.retryInterval * 0.8 + + Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); + incrementDelta *= boundedRandDelta; + retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); + return retryData; +} + +// Copyright (c) Microsoft Corporation. +/** + * Policy that retries the request as many times as configured for as long as the max retry time interval specified, each retry waiting longer to begin than the last time. + * @param retryCount - Maximum number of retries. + * @param retryInterval - Base time between retries. + * @param maxRetryInterval - Maximum time to wait between retries. + */ +function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { + return { + create: (nextPolicy, options) => { + return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); + }, + }; +} +/** + * Describes the Retry Mode type. Currently supporting only Exponential. + */ +exports.RetryMode = void 0; +(function (RetryMode) { + /** + * Currently supported retry mode. + * Each time a retry happens, it will take exponentially more time than the last time. + */ + RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; +})(exports.RetryMode || (exports.RetryMode = {})); +const DefaultRetryOptions = { + maxRetries: DEFAULT_CLIENT_RETRY_COUNT, + retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, + maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, +}; +/** + * Instantiates a new "ExponentialRetryPolicyFilter" instance. + */ +class ExponentialRetryPolicy extends BaseRequestPolicy { + /** + * @param nextPolicy - The next RequestPolicy in the pipeline chain. + * @param options - The options for this RequestPolicy. + * @param retryCount - The client retry count. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + */ + constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) + ? maxRetryInterval + : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + } + sendRequest(request) { + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => retry$1(this, request, response)) + .catch((error) => retry$1(this, request, error.response, undefined, error)); + } +} +async function retry$1(policy, request, response, retryData, requestError) { + function shouldPolicyRetry(responseParam) { + const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { + return false; + } + if (statusCode === undefined || + (statusCode < 500 && statusCode !== 408) || + statusCode === 501 || + statusCode === 505) { + return false; + } + return true; + } + retryData = updateRetryData({ + retryInterval: policy.retryInterval, + minRetryInterval: 0, + maxRetryInterval: policy.maxRetryInterval, + }, retryData, requestError); + const isAborted = request.abortSignal && request.abortSignal.aborted; + if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { + logger.info(`Retrying request in ${retryData.retryInterval}`); + try { + await coreUtil.delay(retryData.retryInterval); + const res = await policy._nextPolicy.sendRequest(request.clone()); + return retry$1(policy, request, res, retryData); + } + catch (err) { + return retry$1(policy, request, response, retryData, err); + } + } + else if (isAborted || requestError || !response) { + // If the operation failed in the end, return all errors instead of just the last one + const err = retryData.error || + new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); + throw err; + } + else { + return response; + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that logs information about the outgoing request and the incoming responses. + * @param loggingOptions - Logging options. + * @returns An instance of the {@link LogPolicy} + */ function logPolicy(loggingOptions = {}) { return { create: (nextPolicy, options) => { return new LogPolicy(nextPolicy, options, loggingOptions); - } + }, }; } +/** + * A policy that logs information about the outgoing request and the incoming responses. + */ class LogPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { + constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [], } = {}) { super(nextPolicy, options); this.logger = logger$1; this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); @@ -16055,519 +16771,352 @@ function getStreamResponseStatusCodes(operationSpec) { } // Copyright (c) Microsoft Corporation. -// Note: The reason we re-define all of the xml2js default settings (version 2.0) here is because the default settings object exposed -// by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 -// By creating a new copy of the settings each time we instantiate the parser, -// we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. -const xml2jsDefaultOptionsV2 = { - explicitCharkey: false, - trim: false, - normalize: false, - normalizeTags: false, - attrkey: XML_ATTRKEY, - explicitArray: true, - ignoreAttrs: false, - mergeAttrs: false, - explicitRoot: true, - validator: undefined, - xmlns: false, - explicitChildren: false, - preserveChildrenOrder: false, - childkey: "$$", - charsAsChildren: false, - includeWhiteChars: false, - async: false, - strict: true, - attrNameProcessors: undefined, - attrValueProcessors: undefined, - tagNameProcessors: undefined, - valueProcessors: undefined, - rootName: "root", - xmldec: { - version: "1.0", - encoding: "UTF-8", - standalone: true - }, - doctype: undefined, - renderOpts: { - pretty: true, - indent: " ", - newline: "\n" - }, - headless: false, - chunkSize: 10000, - emptyTag: "", - cdata: false -}; -// The xml2js settings for general XML parsing operations. -const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); -xml2jsParserSettings.explicitArray = false; -// The xml2js settings for general XML building operations. -const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); -xml2jsBuilderSettings.explicitArray = false; -xml2jsBuilderSettings.renderOpts = { - pretty: false -}; -/** - * Converts given JSON object to XML string - * @param obj - JSON object to be converted into XML string - * @param opts - Options that govern the parsing of given JSON object - */ -function stringifyXML(obj, opts = {}) { - var _a; - xml2jsBuilderSettings.rootName = opts.rootName; - xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - const builder = new xml2js.Builder(xml2jsBuilderSettings); - return builder.buildObject(obj); +function getDefaultUserAgentKey() { + return Constants.HeaderConstants.USER_AGENT; } -/** - * Converts given XML string into JSON - * @param str - String containing the XML content to be parsed into JSON - * @param opts - Options that govern the parsing of given xml string - */ -function parseXML(str, opts = {}) { - var _a; - xml2jsParserSettings.explicitRoot = !!opts.includeRoot; - xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - const xmlParser = new xml2js.Parser(xml2jsParserSettings); - return new Promise((resolve, reject) => { - if (!str) { - reject(new Error("Document is empty")); - } - else { - xmlParser.parseString(str, (err, res) => { - if (err) { - reject(err); - } - else { - resolve(res); - } - }); - } - }); +function getPlatformSpecificData() { + const runtimeInfo = { + key: "Node", + value: process.version, + }; + const osInfo = { + key: "OS", + value: `(${os__namespace.arch()}-${os__namespace.type()}-${os__namespace.release()})`, + }; + return [runtimeInfo, osInfo]; } // Copyright (c) Microsoft Corporation. +function getRuntimeInfo() { + const msRestRuntime = { + key: "core-http", + value: Constants.coreHttpVersion, + }; + return [msRestRuntime]; +} +function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { + return telemetryInfo + .map((info) => { + const value = info.value ? `${valueSeparator}${info.value}` : ""; + return `${info.key}${value}`; + }) + .join(keySeparator); +} +const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; /** - * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they - * pass through the HTTP pipeline. + * The default approach to generate user agents. + * Uses static information from this package, plus system information available from the runtime. */ -function deserializationPolicy(deserializationContentTypes, parsingOptions) { +function getDefaultUserAgentValue() { + const runtimeInfo = getRuntimeInfo(); + const platformSpecificData = getPlatformSpecificData(); + const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); + return userAgent; +} +/** + * Returns a policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. + * @param userAgentData - Telemetry information. + * @returns A new {@link UserAgentPolicy}. + */ +function userAgentPolicy(userAgentData) { + const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null + ? getDefaultUserAgentKey() + : userAgentData.key; + const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null + ? getDefaultUserAgentValue() + : userAgentData.value; return { create: (nextPolicy, options) => { - return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); - } + return new UserAgentPolicy(nextPolicy, options, key, value); + }, }; } -const defaultJsonContentTypes = ["application/json", "text/json"]; -const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; -const DefaultDeserializationOptions = { - expectedContentTypes: { - json: defaultJsonContentTypes, - xml: defaultXmlContentTypes - } -}; /** - * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the - * HTTP pipeline. + * A policy that adds the user agent header to outgoing requests based on the given {@link TelemetryInfo}. */ -class DeserializationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { - var _a; - super(nextPolicy, requestPolicyOptions); - this.jsonContentTypes = - (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - this.xmlContentTypes = - (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - } - async sendRequest(request) { - return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { - xmlCharKey: this.xmlCharKey - })); - } -} -function getOperationResponse(parsedResponse) { - let result; - const request = parsedResponse.request; - const operationSpec = request.operationSpec; - if (operationSpec) { - const operationResponseGetter = request.operationResponseGetter; - if (!operationResponseGetter) { - result = operationSpec.responses[parsedResponse.status]; - } - else { - result = operationResponseGetter(operationSpec, parsedResponse); - } - } - return result; -} -function shouldDeserializeResponse(parsedResponse) { - const shouldDeserialize = parsedResponse.request.shouldDeserialize; - let result; - if (shouldDeserialize === undefined) { - result = true; - } - else if (typeof shouldDeserialize === "boolean") { - result = shouldDeserialize; - } - else { - result = shouldDeserialize(parsedResponse); - } - return result; -} -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { - var _a, _b, _c; - const updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; - return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { - if (!shouldDeserializeResponse(parsedResponse)) { - return parsedResponse; - } - const operationSpec = parsedResponse.request.operationSpec; - if (!operationSpec || !operationSpec.responses) { - return parsedResponse; - } - const responseSpec = getOperationResponse(parsedResponse); - const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); - if (error) { - throw error; - } - else if (shouldReturnResponse) { - return parsedResponse; - } - // An operation response spec does exist for current status code, so - // use it to deserialize the response. - if (responseSpec) { - if (responseSpec.bodyMapper) { - let valueToDeserialize = parsedResponse.parsedBody; - if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof valueToDeserialize === "object" - ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] - : []; - } - try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); - } - catch (innerError) { - const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - throw restError; - } - } - else if (operationSpec.httpMethod === "HEAD") { - // head methods never have a body, but we return a boolean to indicate presence/absence of the resource - parsedResponse.parsedBody = response.status >= 200 && response.status < 300; - } - if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options); - } - } - return parsedResponse; - }); -} -function isOperationSpecEmpty(operationSpec) { - const expectedStatusCodes = Object.keys(operationSpec.responses); - return (expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); -} -function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { - var _a; - const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) - ? isSuccessByStatus - : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } - } - else { - return { error: null, shouldReturnResponse: false }; - } - } - const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - const streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || - parsedResponse.request.streamResponseBody; - const initialErrorMessage = streaming - ? `Unexpected status code: ${parsedResponse.status}` - : parsedResponse.bodyAsText; - const error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - // If the item failed but there's no error spec or default spec to deserialize the error, - // we should fail so we just throw the parsed response - if (!errorResponseSpec) { - throw error; - } - const defaultBodyMapper = errorResponseSpec.bodyMapper; - const defaultHeadersMapper = errorResponseSpec.headersMapper; - try { - // If error response has a body, try to deserialize it using default body mapper. - // Then try to extract error code & message from it - if (parsedResponse.parsedBody) { - const parsedBody = parsedResponse.parsedBody; - let parsedError; - if (defaultBodyMapper) { - let valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; - } - parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); - } - const internalError = parsedBody.error || parsedError || parsedBody; - error.code = internalError.code; - if (internalError.message) { - error.message = internalError.message; - } - if (defaultBodyMapper) { - error.response.parsedBody = parsedError; - } - } - // If error response has headers, try to deserialize it using default header mapper - if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); - } - } - catch (defaultError) { - error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; - } - return { error, shouldReturnResponse: false }; -} -function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { - var _a; - const errorHandler = (err) => { - const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; - const errCode = err.code || RestError.PARSE_ERROR; - const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); - return Promise.reject(e); - }; - const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || - operationResponse.request.streamResponseBody; - if (!streaming && operationResponse.bodyAsText) { - const text = operationResponse.bodyAsText; - const contentType = operationResponse.headers.get("Content-Type") || ""; - const contentComponents = !contentType - ? [] - : contentType.split(";").map((component) => component.toLowerCase()); - if (contentComponents.length === 0 || - contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { - return new Promise((resolve) => { - operationResponse.parsedBody = JSON.parse(text); - resolve(operationResponse); - }).catch(errorHandler); - } - else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { - return parseXML(text, opts) - .then((body) => { - operationResponse.parsedBody = body; - return operationResponse; - }) - .catch(errorHandler); - } - } - return Promise.resolve(operationResponse); -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -const DEFAULT_CLIENT_RETRY_COUNT = 3; -// intervals are in ms -const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; -const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; -const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; -function isNumber(n) { - return typeof n === "number"; -} -/** - * @internal - * Determines if the operation should be retried. - * - * @param retryLimit - Specifies the max number of retries. - * @param predicate - Initial chekck on whether to retry based on given responses or errors - * @param retryData - The retry data. - * @returns True if the operation qualifies for a retry; false otherwise. - */ -function shouldRetry(retryLimit, predicate, retryData, response, error) { - if (!predicate(response, error)) { - return false; - } - return retryData.retryCount < retryLimit; -} -/** - * @internal - * Updates the retry data for the next attempt. - * - * @param retryOptions - specifies retry interval, and its lower bound and upper bound. - * @param retryData - The retry data. - * @param err - The operation"s error, if any. - */ -function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { - if (err) { - if (retryData.error) { - err.innerError = retryData.error; - } - retryData.error = err; - } - // Adjust retry count - retryData.retryCount++; - // Adjust retry interval - let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; - const boundedRandDelta = retryOptions.retryInterval * 0.8 + - Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); - incrementDelta *= boundedRandDelta; - retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); - return retryData; -} - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Helper TypeGuard that checks if the value is not null or undefined. - * @param thing - Anything - * @internal - */ -function isDefined(thing) { - return typeof thing !== "undefined" && thing !== null; -} - -// Copyright (c) Microsoft Corporation. -const StandardAbortMessage = "The operation was aborted."; -/** - * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. - * @param delayInMs - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @param options - The options for delay - currently abort options - * @param abortSignal - The abortSignal associated with containing operation. - * @param abortErrorMsg - The abort error message associated with containing operation. - * @returns - Resolved promise - */ -function delay(delayInMs, value, options) { - return new Promise((resolve, reject) => { - let timer = undefined; - let onAborted = undefined; - const rejectOnAbort = () => { - return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (isDefined(timer)) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); -} - -// Copyright (c) Microsoft Corporation. -function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { - return { - create: (nextPolicy, options) => { - return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); - } - }; -} -(function (RetryMode) { - RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; -})(exports.RetryMode || (exports.RetryMode = {})); -const DefaultRetryOptions = { - maxRetries: DEFAULT_CLIENT_RETRY_COUNT, - retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, - maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL -}; -/** - * Instantiates a new "ExponentialRetryPolicyFilter" instance. - */ -class ExponentialRetryPolicy extends BaseRequestPolicy { - /** - * @param nextPolicy - The next RequestPolicy in the pipeline chain. - * @param options - The options for this RequestPolicy. - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. - */ - constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { - super(nextPolicy, options); - this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - this.maxRetryInterval = isNumber(maxRetryInterval) - ? maxRetryInterval - : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; +class UserAgentPolicy extends BaseRequestPolicy { + constructor(_nextPolicy, _options, headerKey, headerValue) { + super(_nextPolicy, _options); + this._nextPolicy = _nextPolicy; + this._options = _options; + this.headerKey = headerKey; + this.headerValue = headerValue; } sendRequest(request) { - return this._nextPolicy - .sendRequest(request.clone()) - .then((response) => retry(this, request, response)) - .catch((error) => retry(this, request, error.response, undefined, error)); + this.addUserAgentHeader(request); + return this._nextPolicy.sendRequest(request); } -} -async function retry(policy, request, response, retryData, requestError) { - function shouldPolicyRetry(responseParam) { - const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; - if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { - return false; + /** + * Adds the user agent header to the outgoing request. + */ + addUserAgentHeader(request) { + if (!request.headers) { + request.headers = new HttpHeaders(); } - if (statusCode === undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { - return false; + if (!request.headers.get(this.headerKey) && this.headerValue) { + request.headers.set(this.headerKey, this.headerValue); } - return true; - } - retryData = updateRetryData({ - retryInterval: policy.retryInterval, - minRetryInterval: 0, - maxRetryInterval: policy.maxRetryInterval - }, retryData, requestError); - const isAborted = request.abortSignal && request.abortSignal.aborted; - if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { - logger.info(`Retrying request in ${retryData.retryInterval}`); - try { - await delay(retryData.retryInterval); - const res = await policy._nextPolicy.sendRequest(request.clone()); - return retry(policy, request, res, retryData); - } - catch (err) { - return retry(policy, request, response, retryData, err); - } - } - else if (isAborted || requestError || !response) { - // If the operation failed in the end, return all errors instead of just the last one - const err = retryData.error || - new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); - throw err; - } - else { - return response; } } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * The format that will be used to join an array of values together for a query parameter value. + */ +exports.QueryCollectionFormat = void 0; +(function (QueryCollectionFormat) { + /** + * CSV: Each pair of segments joined by a single comma. + */ + QueryCollectionFormat["Csv"] = ","; + /** + * SSV: Each pair of segments joined by a single space character. + */ + QueryCollectionFormat["Ssv"] = " "; + /** + * TSV: Each pair of segments joined by a single tab character. + */ + QueryCollectionFormat["Tsv"] = "\t"; + /** + * Pipes: Each pair of segments joined by a single pipe character. + */ + QueryCollectionFormat["Pipes"] = "|"; + /** + * Denotes this is an array of values that should be passed to the server in multiple key/value pairs, e.g. `?queryParam=value1&queryParam=value2` + */ + QueryCollectionFormat["Multi"] = "Multi"; +})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); + +// Copyright (c) Microsoft Corporation. +// Default options for the cycler if none are provided +const DEFAULT_CYCLER_OPTIONS = { + forcedRefreshWindowInMs: 1000, + retryIntervalInMs: 3000, + refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry +}; +/** + * Converts an an unreliable access token getter (which may resolve with null) + * into an AccessTokenGetter by retrying the unreliable getter in a regular + * interval. + * + * @param getAccessToken - a function that produces a promise of an access + * token that may fail by returning null + * @param retryIntervalInMs - the time (in milliseconds) to wait between retry + * attempts + * @param timeoutInMs - the timestamp after which the refresh attempt will fail, + * throwing an exception + * @returns - a promise that, if it resolves, will resolve with an access token + */ +async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { + // This wrapper handles exceptions gracefully as long as we haven't exceeded + // the timeout. + async function tryGetAccessToken() { + if (Date.now() < timeoutInMs) { + try { + return await getAccessToken(); + } + catch (_a) { + return null; + } + } + else { + const finalToken = await getAccessToken(); + // Timeout is up, so throw if it's still null + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await coreUtil.delay(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; +} +/** + * Creates a token cycler from a credential, scopes, and optional settings. + * + * A token cycler represents a way to reliably retrieve a valid access token + * from a TokenCredential. It will handle initializing the token, refreshing it + * when it nears expiration, and synchronizes refresh attempts to avoid + * concurrency hazards. + * + * @param credential - the underlying TokenCredential that provides the access + * token + * @param scopes - the scopes to request authorization for + * @param tokenCyclerOptions - optionally override default settings for the cycler + * + * @returns - a function that reliably produces a valid access token + */ +function createTokenCycler(credential, scopes, tokenCyclerOptions) { + let refreshWorker = null; + let token = null; + const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + /** + * This little holder defines several predicates that we use to construct + * the rules of refreshing the token. + */ + const cycler = { + /** + * Produces true if a refresh job is currently in progress. + */ + get isRefreshing() { + return refreshWorker !== null; + }, + /** + * Produces true if the cycler SHOULD refresh (we are within the refresh + * window and not already refreshing) + */ + get shouldRefresh() { + var _a; + return (!cycler.isRefreshing && + ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); + }, + /** + * Produces true if the cycler MUST refresh (null or nearly-expired + * token). + */ + get mustRefresh() { + return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); + }, + }; + /** + * Starts a refresh job or returns the existing job if one is already + * running. + */ + function refresh(getTokenOptions) { + var _a; + if (!cycler.isRefreshing) { + // We bind `scopes` here to avoid passing it around a lot + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); + // Take advantage of promise chaining to insert an assignment to `token` + // before the refresh can be considered done. + refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, + // If we don't have a token, then we should timeout immediately + (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) + .then((_token) => { + refreshWorker = null; + token = _token; + return token; + }) + .catch((reason) => { + // We also should reset the refresher if we enter a failed state. All + // existing awaiters will throw, but subsequent requests will start a + // new retry chain. + refreshWorker = null; + token = null; + throw reason; + }); + } + return refreshWorker; + } + return async (tokenOptions) => { + // + // Simple rules: + // - If we MUST refresh, then return the refresh task, blocking + // the pipeline until a token is available. + // - If we SHOULD refresh, then run refresh but don't return it + // (we can still use the cached token). + // - Return the token, since it's fine if we didn't return in + // step 1. + // + if (cycler.mustRefresh) + return refresh(tokenOptions); + if (cycler.shouldRefresh) { + refresh(tokenOptions); + } + return token; + }; +} +// #endregion +/** + * Creates a new factory for a RequestPolicy that applies a bearer token to + * the requests' `Authorization` headers. + * + * @param credential - The TokenCredential implementation that can supply the bearer token. + * @param scopes - The scopes for which the bearer token applies. + */ +function bearerTokenAuthenticationPolicy(credential, scopes) { + // This simple function encapsulates the entire process of reliably retrieving the token + const getToken = createTokenCycler(credential, scopes /* , options */); + class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + async sendRequest(webResource) { + if (!webResource.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + const { token } = await getToken({ + abortSignal: webResource.abortSignal, + tracingOptions: { + tracingContext: webResource.tracingContext, + }, + }); + webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); + return this._nextPolicy.sendRequest(webResource); + } + } + return { + create: (nextPolicy, options) => { + return new BearerTokenAuthenticationPolicy(nextPolicy, options); + }, + }; +} + +// Copyright (c) Microsoft Corporation. +/** + * Returns a request policy factory that can be used to create an instance of + * {@link DisableResponseDecompressionPolicy}. + */ +function disableResponseDecompressionPolicy() { + return { + create: (nextPolicy, options) => { + return new DisableResponseDecompressionPolicy(nextPolicy, options); + }, + }; +} +/** + * A policy to disable response decompression according to Accept-Encoding header + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding + */ +class DisableResponseDecompressionPolicy extends BaseRequestPolicy { + /** + * Creates an instance of DisableResponseDecompressionPolicy. + * + * @param nextPolicy - + * @param options - + */ + // The parent constructor is protected. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ + constructor(nextPolicy, options) { + super(nextPolicy, options); + } + /** + * Sends out request. + * + * @param request - + * @returns + */ + async sendRequest(request) { + request.decompressResponse = false; + return this._nextPolicy.sendRequest(request); + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Creates a policy that assigns a unique request id to outgoing requests. + * @param requestIdHeaderName - The name of the header to use when assigning the unique id to the request. + */ function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { return { create: (nextPolicy, options) => { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); - } + }, }; } class GenerateClientRequestIdPolicy extends BaseRequestPolicy { @@ -16584,130 +17133,190 @@ class GenerateClientRequestIdPolicy extends BaseRequestPolicy { } // Copyright (c) Microsoft Corporation. -function getDefaultUserAgentKey() { - return Constants.HeaderConstants.USER_AGENT; -} -function getPlatformSpecificData() { - const runtimeInfo = { - key: "Node", - value: process.version - }; - const osInfo = { - key: "OS", - value: `(${os.arch()}-${os.type()}-${os.release()})` - }; - return [runtimeInfo, osInfo]; +let cachedHttpClient; +function getCachedDefaultHttpClient() { + if (!cachedHttpClient) { + cachedHttpClient = new NodeFetchHttpClient(); + } + return cachedHttpClient; } // Copyright (c) Microsoft Corporation. -function getRuntimeInfo() { - const msRestRuntime = { - key: "core-http", - value: Constants.coreHttpVersion - }; - return [msRestRuntime]; -} -function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { - return telemetryInfo - .map((info) => { - const value = info.value ? `${valueSeparator}${info.value}` : ""; - return `${info.key}${value}`; - }) - .join(keySeparator); -} -const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; -function getDefaultUserAgentValue() { - const runtimeInfo = getRuntimeInfo(); - const platformSpecificData = getPlatformSpecificData(); - const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); - return userAgent; -} -function userAgentPolicy(userAgentData) { - const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null - ? getDefaultUserAgentKey() - : userAgentData.key; - const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null - ? getDefaultUserAgentValue() - : userAgentData.value; +function ndJsonPolicy() { return { create: (nextPolicy, options) => { - return new UserAgentPolicy(nextPolicy, options, key, value); - } + return new NdJsonPolicy(nextPolicy, options); + }, }; } -class UserAgentPolicy extends BaseRequestPolicy { - constructor(_nextPolicy, _options, headerKey, headerValue) { - super(_nextPolicy, _options); - this._nextPolicy = _nextPolicy; - this._options = _options; - this.headerKey = headerKey; - this.headerValue = headerValue; +/** + * NdJsonPolicy that formats a JSON array as newline-delimited JSON + */ +class NdJsonPolicy extends BaseRequestPolicy { + /** + * Creates an instance of KeepAlivePolicy. + */ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - sendRequest(request) { - this.addUserAgentHeader(request); + /** + * Sends a request. + */ + async sendRequest(request) { + // There currently isn't a good way to bypass the serializer + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } return this._nextPolicy.sendRequest(request); } - addUserAgentHeader(request) { - if (!request.headers) { - request.headers = new HttpHeaders(); - } - if (!request.headers.get(this.headerKey) && this.headerValue) { - request.headers.set(this.headerKey, this.headerValue); - } - } } // Copyright (c) Microsoft Corporation. /** - * Methods that are allowed to follow redirects 301 and 302 + * Stores the patterns specified in NO_PROXY environment variable. + * @internal */ -const allowedRedirect = ["GET", "HEAD"]; -const DefaultRedirectOptions = { - handleRedirects: true, - maxRetries: 20 -}; -function redirectPolicy(maximumRetries = 20) { - return { - create: (nextPolicy, options) => { - return new RedirectPolicy(nextPolicy, options, maximumRetries); +const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); +function loadEnvironmentProxyValue() { + if (!process) { + return undefined; + } + const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); + const allProxy = getEnvironmentValue(Constants.ALL_PROXY); + const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); + return httpsProxy || allProxy || httpProxy; +} +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn't have the proxy settings set. + * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 + */ +function isBypassed(uri, noProxyList, bypassedMap) { + if (noProxyList.length === 0) { + return false; + } + const host = URLBuilder.parse(uri).getHost(); + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); + } + let isBypassedFlag = false; + for (const pattern of noProxyList) { + if (pattern[0] === ".") { + // This should match either domain it self or any subdomain or host + // .foo.com will match foo.com it self or *.foo.com + if (host.endsWith(pattern)) { + isBypassedFlag = true; + } + else { + if (host.length === pattern.length - 1 && host === pattern.slice(1)) { + isBypassedFlag = true; + } + } } + else { + if (host === pattern) { + isBypassedFlag = true; + } + } + } + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); + return isBypassedFlag; +} +/** + * @internal + */ +function loadNoProxy() { + const noProxy = getEnvironmentValue(Constants.NO_PROXY); + noProxyListLoaded = true; + if (noProxy) { + return noProxy + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length); + } + return []; +} +/** + * Converts a given URL of a proxy server into `ProxySettings` or attempts to retrieve `ProxySettings` from the current environment if one is not passed. + * @param proxyUrl - URL of the proxy + * @returns The default proxy settings, or undefined. + */ +function getDefaultProxySettings(proxyUrl) { + if (!proxyUrl) { + proxyUrl = loadEnvironmentProxyValue(); + if (!proxyUrl) { + return undefined; + } + } + const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); + const parsedUrl = URLBuilder.parse(urlWithoutAuth); + const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + return { + host: schema + parsedUrl.getHost(), + port: Number.parseInt(parsedUrl.getPort() || "80"), + username, + password, }; } -class RedirectPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, maxRetries = 20) { +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +function proxyPolicy(proxySettings, options) { + if (!proxySettings) { + proxySettings = getDefaultProxySettings(); + } + if (!noProxyListLoaded) { + globalNoProxyList.push(...loadNoProxy()); + } + return { + create: (nextPolicy, requestPolicyOptions) => { + return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); + }, + }; +} +function extractAuthFromUrl(url) { + const atIndex = url.indexOf("@"); + if (atIndex === -1) { + return { urlWithoutAuth: url }; + } + const schemeIndex = url.indexOf("://"); + const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; + const auth = url.substring(authStart, atIndex); + const colonIndex = auth.indexOf(":"); + const hasPassword = colonIndex !== -1; + const username = hasPassword ? auth.substring(0, colonIndex) : auth; + const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; + const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); + return { + username, + password, + urlWithoutAuth, + }; +} +class ProxyPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, proxySettings, customNoProxyList) { super(nextPolicy, options); - this.maxRetries = maxRetries; + this.proxySettings = proxySettings; + this.customNoProxyList = customNoProxyList; } sendRequest(request) { - return this._nextPolicy - .sendRequest(request) - .then((response) => handleRedirect(this, response, 0)); - } -} -function handleRedirect(policy, response, currentRetries) { - const { request, status } = response; - const locationHeader = response.headers.get("location"); - if (locationHeader && - (status === 300 || - (status === 301 && allowedRedirect.includes(request.method)) || - (status === 302 && allowedRedirect.includes(request.method)) || - (status === 303 && request.method === "POST") || - status === 307) && - (!policy.maxRetries || currentRetries < policy.maxRetries)) { - const builder = URLBuilder.parse(request.url); - builder.setPath(locationHeader); - request.url = builder.toString(); - // POST request with Status code 303 should be converted into a - // redirected GET request if the redirect url is present in the location header - if (status === 303) { - request.method = "GET"; - delete request.body; + var _a; + if (!request.proxySettings && + !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { + request.proxySettings = this.proxySettings; } - return policy._nextPolicy - .sendRequest(request) - .then((res) => handleRedirect(policy, res, currentRetries + 1)); + return this._nextPolicy.sendRequest(request); } - return Promise.resolve(response); } // Copyright (c) Microsoft Corporation. @@ -16715,7 +17324,7 @@ function rpRegistrationPolicy(retryTimeout = 30) { return { create: (nextPolicy, options) => { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); - } + }, }; } class RPRegistrationPolicy extends BaseRequestPolicy { @@ -16854,199 +17463,58 @@ async function getRegistrationStatus(policy, url, originalRequest) { return true; } else { - await delay(policy._retryTimeout * 1000); + await coreUtil.delay(policy._retryTimeout * 1000); return getRegistrationStatus(policy, url, originalRequest); } } // Copyright (c) Microsoft Corporation. -// Default options for the cycler if none are provided -const DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1000, - retryIntervalInMs: 3000, - refreshWindowInMs: 1000 * 60 * 2 // Start refreshing 2m before expiry -}; /** - * Converts an an unreliable access token getter (which may resolve with null) - * into an AccessTokenGetter by retrying the unreliable getter in a regular - * interval. - * - * @param getAccessToken - a function that produces a promise of an access - * token that may fail by returning null - * @param retryIntervalInMs - the time (in milliseconds) to wait between retry - * attempts - * @param timeoutInMs - the timestamp after which the refresh attempt will fail, - * throwing an exception - * @returns - a promise that, if it resolves, will resolve with an access token + * Creates a policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. + * @param authenticationProvider - The authentication provider. + * @returns An instance of the {@link SigningPolicy}. */ -async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { - // This wrapper handles exceptions gracefully as long as we haven't exceeded - // the timeout. - async function tryGetAccessToken() { - if (Date.now() < timeoutInMs) { - try { - return await getAccessToken(); - } - catch (_a) { - return null; - } - } - else { - const finalToken = await getAccessToken(); - // Timeout is up, so throw if it's still null - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; - } - } - let token = await tryGetAccessToken(); - while (token === null) { - await delay(retryIntervalInMs); - token = await tryGetAccessToken(); - } - return token; -} -/** - * Creates a token cycler from a credential, scopes, and optional settings. - * - * A token cycler represents a way to reliably retrieve a valid access token - * from a TokenCredential. It will handle initializing the token, refreshing it - * when it nears expiration, and synchronizes refresh attempts to avoid - * concurrency hazards. - * - * @param credential - the underlying TokenCredential that provides the access - * token - * @param scopes - the scopes to request authorization for - * @param tokenCyclerOptions - optionally override default settings for the cycler - * - * @returns - a function that reliably produces a valid access token - */ -function createTokenCycler(credential, scopes, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - /** - * This little holder defines several predicates that we use to construct - * the rules of refreshing the token. - */ - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - return (!cycler.isRefreshing && - ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now()); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); - } - }; - /** - * Starts a refresh job or returns the existing job if one is already - * running. - */ - function refresh(getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - // We bind `scopes` here to avoid passing it around a lot - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - // Take advantage of promise chaining to insert an assignment to `token` - // before the refresh can be considered done. - refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) - .then((_token) => { - refreshWorker = null; - token = _token; - return token; - }) - .catch((reason) => { - // We also should reset the refresher if we enter a failed state. All - // existing awaiters will throw, but subsequent requests will start a - // new retry chain. - refreshWorker = null; - token = null; - throw reason; - }); - } - return refreshWorker; - } - return async (tokenOptions) => { - // - // Simple rules: - // - If we MUST refresh, then return the refresh task, blocking - // the pipeline until a token is available. - // - If we SHOULD refresh, then run refresh but don't return it - // (we can still use the cached token). - // - Return the token, since it's fine if we didn't return in - // step 1. - // - if (cycler.mustRefresh) - return refresh(tokenOptions); - if (cycler.shouldRefresh) { - refresh(tokenOptions); - } - return token; - }; -} -// #endregion -/** - * Creates a new factory for a RequestPolicy that applies a bearer token to - * the requests' `Authorization` headers. - * - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. - */ -function bearerTokenAuthenticationPolicy(credential, scopes) { - // This simple function encapsulates the entire process of reliably retrieving the token - const getToken = createTokenCycler(credential, scopes /* , options */); - class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - async sendRequest(webResource) { - if (!webResource.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - const { token } = await getToken({ - abortSignal: webResource.abortSignal, - tracingOptions: { - tracingContext: webResource.tracingContext - } - }); - webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); - return this._nextPolicy.sendRequest(webResource); - } - } +function signingPolicy(authenticationProvider) { return { create: (nextPolicy, options) => { - return new BearerTokenAuthenticationPolicy(nextPolicy, options); - } + return new SigningPolicy(nextPolicy, options, authenticationProvider); + }, }; } +/** + * A policy that signs outgoing requests by calling to the provided `authenticationProvider`'s `signRequest` method. + */ +class SigningPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, authenticationProvider) { + super(nextPolicy, options); + this.authenticationProvider = authenticationProvider; + } + signRequest(request) { + return this.authenticationProvider.signRequest(request); + } + sendRequest(request) { + return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); + } +} // Copyright (c) Microsoft Corporation. +/** + * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". + * @param retryCount - Maximum number of retries. + * @param retryInterval - The client retry interval, in milliseconds. + * @param minRetryInterval - The minimum retry interval, in milliseconds. + * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @returns An instance of the {@link SystemErrorRetryPolicy} + */ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { return { create: (nextPolicy, options) => { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); - } + }, }; } /** + * A policy that retries when there's a system error, identified by the codes "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET" or "ENOENT". * @param retryCount - The client retry count. * @param retryInterval - The client retry interval, in milliseconds. * @param minRetryInterval - The minimum retry interval, in milliseconds. @@ -17067,10 +17535,10 @@ class SystemErrorRetryPolicy extends BaseRequestPolicy { sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .catch((error) => retry$1(this, request, error.response, error)); + .catch((error) => retry(this, request, error.response, error)); } } -async function retry$1(policy, request, operationResponse, err, retryData) { +async function retry(policy, request, operationResponse, err, retryData) { retryData = updateRetryData(policy, retryData, err); function shouldPolicyRetry(_response, error) { if (error && @@ -17087,11 +17555,11 @@ async function retry$1(policy, request, operationResponse, err, retryData) { if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { // If previous operation ended with an error and the policy allows a retry, do that try { - await delay(retryData.retryInterval); + await coreUtil.delay(retryData.retryInterval); return policy._nextPolicy.sendRequest(request.clone()); } catch (nestedErr) { - return retry$1(policy, request, operationResponse, nestedErr, retryData); + return retry(policy, request, operationResponse, nestedErr, retryData); } } else { @@ -17103,155 +17571,6 @@ async function retry$1(policy, request, operationResponse, err, retryData) { } } -// Copyright (c) Microsoft Corporation. -(function (QueryCollectionFormat) { - QueryCollectionFormat["Csv"] = ","; - QueryCollectionFormat["Ssv"] = " "; - QueryCollectionFormat["Tsv"] = "\t"; - QueryCollectionFormat["Pipes"] = "|"; - QueryCollectionFormat["Multi"] = "Multi"; -})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); - -// Copyright (c) Microsoft Corporation. -/** - * Stores the patterns specified in NO_PROXY environment variable. - * @internal - */ -const globalNoProxyList = []; -let noProxyListLoaded = false; -/** A cache of whether a host should bypass the proxy. */ -const globalBypassedMap = new Map(); -function loadEnvironmentProxyValue() { - if (!process) { - return undefined; - } - const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - const allProxy = getEnvironmentValue(Constants.ALL_PROXY); - const httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; -} -/** - * Check whether the host of a given `uri` matches any pattern in the no proxy list. - * If there's a match, any request sent to the same host shouldn't have the proxy settings set. - * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 - */ -function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = URLBuilder.parse(uri).getHost(); - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } - else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } - } - } - else { - if (host === pattern) { - isBypassedFlag = true; - } - } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; -} -/** - * @internal - */ -function loadNoProxy() { - const noProxy = getEnvironmentValue(Constants.NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy - .split(",") - .map((item) => item.trim()) - .filter((item) => item.length); - } - return []; -} -function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return undefined; - } - } - const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); - const parsedUrl = URLBuilder.parse(urlWithoutAuth); - const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; - return { - host: schema + parsedUrl.getHost(), - port: Number.parseInt(parsedUrl.getPort() || "80"), - username, - password - }; -} -/** - * A policy that allows one to apply proxy settings to all requests. - * If not passed static settings, they will be retrieved from the HTTPS_PROXY - * or HTTP_PROXY environment variables. - * @param proxySettings - ProxySettings to use on each request. - * @param options - additional settings, for example, custom NO_PROXY patterns - */ -function proxyPolicy(proxySettings, options) { - if (!proxySettings) { - proxySettings = getDefaultProxySettings(); - } - if (!noProxyListLoaded) { - globalNoProxyList.push(...loadNoProxy()); - } - return { - create: (nextPolicy, requestPolicyOptions) => { - return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); - } - }; -} -function extractAuthFromUrl(url) { - const atIndex = url.indexOf("@"); - if (atIndex === -1) { - return { urlWithoutAuth: url }; - } - const schemeIndex = url.indexOf("://"); - const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - const auth = url.substring(authStart, atIndex); - const colonIndex = auth.indexOf(":"); - const hasPassword = colonIndex !== -1; - const username = hasPassword ? auth.substring(0, colonIndex) : auth; - const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); - return { - username, - password, - urlWithoutAuth - }; -} -class ProxyPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, proxySettings, customNoProxyList) { - super(nextPolicy, options); - this.proxySettings = proxySettings; - this.customNoProxyList = customNoProxyList; - } - sendRequest(request) { - var _a; - if (!request.proxySettings && - !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { - request.proxySettings = this.proxySettings; - } - return this._nextPolicy.sendRequest(request); - } -} - // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** @@ -17261,15 +17580,28 @@ const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; // Copyright (c) Microsoft Corporation. const StatusCodes = Constants.HttpConstants.StatusCodes; +/** + * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. + * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. + * + * To learn more, please refer to + * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, + * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and + * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors + * @returns + */ function throttlingRetryPolicy() { return { create: (nextPolicy, options) => { return new ThrottlingRetryPolicy(nextPolicy, options); - } + }, }; } -const StandardAbortMessage$1 = "The operation was aborted."; +const StandardAbortMessage = "The operation was aborted."; /** + * Creates a policy that re-sends the request if the response indicates the request failed because of throttling reasons. + * For example, if the response contains a `Retry-After` header, it will retry sending the request based on the value of that header. + * * To learn more, please refer to * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and @@ -17298,12 +17630,12 @@ class ThrottlingRetryPolicy extends BaseRequestPolicy { const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); if (delayInMs) { this.numberOfRetries += 1; - await delay(delayInMs, undefined, { + await coreUtil.delay(delayInMs, { abortSignal: httpRequest.abortSignal, - abortErrorMsg: StandardAbortMessage$1 + abortErrorMsg: StandardAbortMessage, }); if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw new abortController.AbortError(StandardAbortMessage$1); + throw new abortController.AbortError(StandardAbortMessage); } if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { return this.sendRequest(httpRequest); @@ -17337,77 +17669,26 @@ class ThrottlingRetryPolicy extends BaseRequestPolicy { } } -// Copyright (c) Microsoft Corporation. -function signingPolicy(authenticationProvider) { - return { - create: (nextPolicy, options) => { - return new SigningPolicy(nextPolicy, options, authenticationProvider); - } - }; -} -class SigningPolicy extends BaseRequestPolicy { - constructor(nextPolicy, options, authenticationProvider) { - super(nextPolicy, options); - this.authenticationProvider = authenticationProvider; - } - signRequest(request) { - return this.authenticationProvider.signRequest(request); - } - sendRequest(request) { - return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); - } -} - -// Copyright (c) Microsoft Corporation. -const DefaultKeepAliveOptions = { - enable: true -}; -function keepAlivePolicy(keepAliveOptions) { - return { - create: (nextPolicy, options) => { - return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); - } - }; -} -/** - * KeepAlivePolicy is a policy used to control keep alive settings for every request. - */ -class KeepAlivePolicy extends BaseRequestPolicy { - /** - * Creates an instance of KeepAlivePolicy. - * - * @param nextPolicy - - * @param options - - * @param keepAliveOptions - - */ - constructor(nextPolicy, options, keepAliveOptions) { - super(nextPolicy, options); - this.keepAliveOptions = keepAliveOptions; - } - /** - * Sends out request. - * - * @param request - - * @returns - */ - async sendRequest(request) { - request.keepAlive = this.keepAliveOptions.enable; - return this._nextPolicy.sendRequest(request); - } -} - // Copyright (c) Microsoft Corporation. const createSpan = coreTracing.createSpanFunction({ packagePrefix: "", - namespace: "" + namespace: "", }); +/** + * Creates a policy that wraps outgoing requests with a tracing span. + * @param tracingOptions - Tracing options. + * @returns An instance of the {@link TracingPolicy} class. + */ function tracingPolicy(tracingOptions = {}) { return { create(nextPolicy, options) { return new TracingPolicy(nextPolicy, options, tracingOptions); - } + }, }; } +/** + * A policy that wraps outgoing requests with a tracing span. + */ class TracingPolicy extends BaseRequestPolicy { constructor(nextPolicy, options, tracingOptions) { super(nextPolicy, options); @@ -17434,14 +17715,13 @@ class TracingPolicy extends BaseRequestPolicy { tryCreateSpan(request) { var _a; try { - const path = URLBuilder.parse(request.url).getPath() || "/"; // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. // We can pass this as a separate parameter once we upgrade to the latest core-tracing. - const { span } = createSpan(path, { + const { span } = createSpan(`HTTP ${request.method}`, { tracingOptions: { spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), - tracingContext: request.tracingContext - } + tracingContext: request.tracingContext, + }, }); // If the span is not recording, don't do any more work. if (!span.isRecording()) { @@ -17455,7 +17735,7 @@ class TracingPolicy extends BaseRequestPolicy { span.setAttributes({ "http.method": request.method, "http.url": request.url, - requestId: request.requestId + requestId: request.requestId, }); if (this.userAgent) { span.setAttribute("http.user_agent", this.userAgent); @@ -17482,7 +17762,7 @@ class TracingPolicy extends BaseRequestPolicy { try { span.setStatus({ code: coreTracing.SpanStatusCode.ERROR, - message: err.message + message: err.message, }); if (err.statusCode) { span.setAttribute("http.status_code", err.statusCode); @@ -17501,7 +17781,7 @@ class TracingPolicy extends BaseRequestPolicy { span.setAttribute("serviceRequestId", serviceRequestId); } span.setStatus({ - code: coreTracing.SpanStatusCode.OK + code: coreTracing.SpanStatusCode.OK, }); span.end(); } @@ -17511,88 +17791,6 @@ class TracingPolicy extends BaseRequestPolicy { } } -// Copyright (c) Microsoft Corporation. -/** - * Returns a request policy factory that can be used to create an instance of - * {@link DisableResponseDecompressionPolicy}. - */ -function disableResponseDecompressionPolicy() { - return { - create: (nextPolicy, options) => { - return new DisableResponseDecompressionPolicy(nextPolicy, options); - } - }; -} -/** - * A policy to disable response decompression according to Accept-Encoding header - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding - */ -class DisableResponseDecompressionPolicy extends BaseRequestPolicy { - /** - * Creates an instance of DisableResponseDecompressionPolicy. - * - * @param nextPolicy - - * @param options - - */ - // The parent constructor is protected. - /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends out request. - * - * @param request - - * @returns - */ - async sendRequest(request) { - request.decompressResponse = false; - return this._nextPolicy.sendRequest(request); - } -} - -// Copyright (c) Microsoft Corporation. -function ndJsonPolicy() { - return { - create: (nextPolicy, options) => { - return new NdJsonPolicy(nextPolicy, options); - } - }; -} -/** - * NdJsonPolicy that formats a JSON array as newline-delimited JSON - */ -class NdJsonPolicy extends BaseRequestPolicy { - /** - * Creates an instance of KeepAlivePolicy. - */ - constructor(nextPolicy, options) { - super(nextPolicy, options); - } - /** - * Sends a request. - */ - async sendRequest(request) { - // There currently isn't a good way to bypass the serializer - if (typeof request.body === "string" && request.body.startsWith("[")) { - const body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); - } - } - return this._nextPolicy.sendRequest(request); - } -} - -// Copyright (c) Microsoft Corporation. -let cachedHttpClient; -function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = new NodeFetchHttpClient(); - } - return cachedHttpClient; -} - // Copyright (c) Microsoft Corporation. /** * ServiceClient sends service requests and receives responses. @@ -17642,7 +17840,7 @@ class ServiceClient { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); } return bearerTokenPolicyFactory.create(nextPolicy, createOptions); - } + }, }; }; authPolicyFactory = wrappedPolicyFactory(); @@ -17877,7 +18075,7 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op const updatedOptions = { rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, - xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY + xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY, }; const xmlCharKey = serializerOptions.xmlCharKey; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { @@ -17896,13 +18094,13 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op if (typeName === MapperType.Sequence) { httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, - xmlCharKey + xmlCharKey, }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { rootName: xmlName || serializedName, - xmlCharKey + xmlCharKey, }); } } @@ -17986,6 +18184,12 @@ function createDefaultRequestPolicyFactories(authPolicyFactory, options) { factories.push(logPolicy({ logger: logger.info })); return factories; } +/** + * Creates an HTTP pipeline based on the given options. + * @param pipelineOptions - Defines options that are used to configure policies in the HTTP pipeline for an SDK client. + * @param authPolicyFactory - An optional authentication policy factory to use for signing requests. + * @returns A set of options that can be passed to create a new {@link ServiceClient}. + */ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { const requestPolicyFactories = []; if (pipelineOptions.sendStreamingJson) { @@ -18024,7 +18228,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { } return { httpClient: pipelineOptions.httpClient, - requestPolicyFactories + requestPolicyFactories, }; } function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { @@ -18100,12 +18304,18 @@ function getPropertyFromParameterPath(parent, parameterPath) { } return result; } +/** + * Parses an {@link HttpOperationResponse} into a normalized HTTP response object ({@link RestResponse}). + * @param _response - Wrapper object for http response. + * @param responseSpec - Mappers for how to parse the response properties. + * @returns - A normalized response object. + */ function flattenResponse(_response, responseSpec) { const parsedHeaders = _response.parsedHeaders; const bodyMapper = responseSpec && responseSpec.bodyMapper; const addOperationResponse = (obj) => { return Object.defineProperty(obj, "_response", { - value: _response + value: _response, }); }; if (bodyMapper) { @@ -18146,8 +18356,8 @@ function getCredentialScopes(options, baseUri) { if (options === null || options === void 0 ? void 0 : options.credentialScopes) { const scopes = options.credentialScopes; return Array.isArray(scopes) - ? scopes.map((scope) => new url.URL(scope).toString()) - : new url.URL(scopes).toString(); + ? scopes.map((scope) => new URL(scope).toString()) + : new URL(scopes).toString(); } if (baseUri) { return `${baseUri}/.default`; @@ -18191,9 +18401,16 @@ class ExpiringAccessTokenCache { this.cachedToken = undefined; this.tokenRefreshBufferMs = tokenRefreshBufferMs; } + /** + * Saves an access token into the internal in-memory cache. + * @param accessToken - Access token or undefined to clear the cache. + */ setCachedToken(accessToken) { this.cachedToken = accessToken; } + /** + * Returns the cached access token, or `undefined` if one is not cached or the cached one is expiring soon. + */ getCachedToken() { if (this.cachedToken && Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { @@ -18252,6 +18469,9 @@ class AccessTokenRefresher { // Copyright (c) Microsoft Corporation. const HeaderConstants = Constants.HeaderConstants; const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; +/** + * A simple {@link ServiceClientCredential} that authenticates with a username and a password. + */ class BasicAuthenticationCredentials { /** * Creates a new BasicAuthenticationCredentials object. @@ -18261,6 +18481,10 @@ class BasicAuthenticationCredentials { * @param authorizationScheme - The authorization scheme. */ constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { + /** + * Authorization scheme. Defaults to "Basic". + * More information about authorization schemes is available here: https://developer.mozilla.org/docs/Web/HTTP/Authentication#authentication_schemes + */ this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { throw new Error("userName cannot be null or undefined and must be of type string."); @@ -18340,6 +18564,9 @@ class ApiKeyCredentials { } // Copyright (c) Microsoft Corporation. +/** + * A {@link TopicCredentials} object used for Azure Event Grid. + */ class TopicCredentials extends ApiKeyCredentials { /** * Creates a new EventGrid TopicCredentials object. @@ -18352,18 +18579,20 @@ class TopicCredentials extends ApiKeyCredentials { } const options = { inHeader: { - "aeg-sas-key": topicKey - } + "aeg-sas-key": topicKey, + }, }; super(options); } } +Object.defineProperty(exports, "delay", ({ + enumerable: true, + get: function () { return coreUtil.delay; } +})); Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, - get: function () { - return coreAuth.isTokenCredential; - } + get: function () { return coreAuth.isTokenCredential; } })); exports.AccessTokenRefresher = AccessTokenRefresher; exports.ApiKeyCredentials = ApiKeyCredentials; @@ -18388,7 +18617,6 @@ exports.applyMixins = applyMixins; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; exports.createPipelineFromOptions = createPipelineFromOptions; exports.createSpanFunction = createSpanFunction; -exports.delay = delay; exports.deserializationPolicy = deserializationPolicy; exports.deserializeResponseBody = deserializeResponseBody; exports.disableResponseDecompressionPolicy = disableResponseDecompressionPolicy; @@ -21292,6 +21520,284 @@ exports.setSpanContext = setSpanContext; //# sourceMappingURL=index.js.map +/***/ }), + +/***/ 1333: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var abortController = __nccwpck_require__(2557); +var crypto = __nccwpck_require__(6113); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var _a$1; +/** + * A constant that indicates whether the environment the code is running is Node.JS. + */ +const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_a$1 = process.versions) === null || _a$1 === void 0 ? void 0 : _a$1.node); + +// Copyright (c) Microsoft Corporation. +/** + * Creates an abortable promise. + * @param buildPromise - A function that takes the resolve and reject functions as parameters. + * @param options - The options for the abortable promise. + * @returns A promise that can be aborted. + */ +function createAbortablePromise(buildPromise, options) { + const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve, reject) => { + function rejectOnAbort() { + reject(new abortController.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); + } + function removeListeners() { + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); + } + function onAbort() { + cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); + removeListeners(); + rejectOnAbort(); + } + if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { + return rejectOnAbort(); + } + try { + buildPromise((x) => { + removeListeners(); + resolve(x); + }, (x) => { + removeListeners(); + reject(x); + }); + } + catch (err) { + reject(err); + } + abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); + }); +} + +// Copyright (c) Microsoft Corporation. +const StandardAbortMessage = "The delay was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. + * @param timeInMs - The number of milliseconds to be delayed. + * @param options - The options for delay - currently abort options + * @returns Promise that is resolved after timeInMs + */ +function delay(timeInMs, options) { + let token; + const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; + return createAbortablePromise((resolve) => { + token = setTimeout(resolve, timeInMs); + }, { + cleanupBeforeAbort: () => clearTimeout(token), + abortSignal, + abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, + }); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Returns a random integer value between a lower and upper bound, + * inclusive of both bounds. + * Note that this uses Math.random and isn't secure. If you need to use + * this for any kind of security purpose, find a better source of random. + * @param min - The smallest integer value allowed. + * @param max - The largest integer value allowed. + */ +function getRandomIntegerInclusive(min, max) { + // Make sure inputs are integers. + min = Math.ceil(min); + max = Math.floor(max); + // Pick a random offset from zero to the size of the range. + // Since Math.random() can never return 1, we have to make the range one larger + // in order to be inclusive of the maximum value after we take the floor. + const offset = Math.floor(Math.random() * (max - min + 1)); + return offset + min; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper to determine when an input is a generic JS object. + * @returns true when input is an object type that is not null, Array, RegExp, or Date. + */ +function isObject(input) { + return (typeof input === "object" && + input !== null && + !Array.isArray(input) && + !(input instanceof RegExp) && + !(input instanceof Date)); +} + +// Copyright (c) Microsoft Corporation. +/** + * Typeguard for an error object shape (has name and message) + * @param e - Something caught by a catch clause. + */ +function isError(e) { + if (isObject(e)) { + const hasName = typeof e.name === "string"; + const hasMessage = typeof e.message === "string"; + return hasName && hasMessage; + } + return false; +} +/** + * Given what is thought to be an error object, return the message if possible. + * If the message is missing, returns a stringified version of the input. + * @param e - Something thrown from a try block + * @returns The error message or a string of the input + */ +function getErrorMessage(e) { + if (isError(e)) { + return e.message; + } + else { + let stringified; + try { + if (typeof e === "object" && e) { + stringified = JSON.stringify(e); + } + else { + stringified = String(e); + } + } + catch (err) { + stringified = "[unable to stringify input]"; + } + return `Unknown error ${stringified}`; + } +} + +// Copyright (c) Microsoft Corporation. +/** + * Generates a SHA-256 HMAC signature. + * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. + * @param stringToSign - The data to be signed. + * @param encoding - The textual encoding to use for the returned HMAC digest. + */ +async function computeSha256Hmac(key, stringToSign, encoding) { + const decodedKey = Buffer.from(key, "base64"); + return crypto.createHmac("sha256", decodedKey).update(stringToSign).digest(encoding); +} +/** + * Generates a SHA-256 hash. + * @param content - The data to be included in the hash. + * @param encoding - The textual encoding to use for the returned hash. + */ +async function computeSha256Hash(content, encoding) { + return crypto.createHash("sha256").update(content).digest(encoding); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if something is defined or not. + * @param thing - Anything + */ +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified properties. + * @param thing - Anything. + * @param properties - The name of the properties that should appear in the object. + */ +function isObjectWithProperties(thing, properties) { + if (!isDefined(thing) || typeof thing !== "object") { + return false; + } + for (const property of properties) { + if (!objectHasProperty(thing, property)) { + return false; + } + } + return true; +} +/** + * Helper TypeGuard that checks if the input is an object with the specified property. + * @param thing - Any object. + * @param property - The name of the property that should appear in the object. + */ +function objectHasProperty(thing, property) { + return (isDefined(thing) && typeof thing === "object" && property in thing); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + */ +function generateUUID() { + let uuid = ""; + for (let i = 0; i < 32; i++) { + // Generate a random number between 0 and 15 + const randomNumber = Math.floor(Math.random() * 16); + // Set the UUID version to 4 in the 13th position + if (i === 12) { + uuid += "4"; + } + else if (i === 16) { + // Set the UUID variant to "10" in the 17th position + uuid += (randomNumber & 0x3) | 0x8; + } + else { + // Add a random hexadecimal digit to the UUID string + uuid += randomNumber.toString(16); + } + // Add hyphens to the UUID string at the appropriate positions + if (i === 7 || i === 11 || i === 15 || i === 19) { + uuid += "-"; + } + } + return uuid; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +var _a; +// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+. +let uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" + ? globalThis.crypto.randomUUID.bind(globalThis.crypto) + : crypto.randomUUID; +// Not defined in earlier versions of Node.js 14 +if (!uuidFunction) { + uuidFunction = generateUUID; +} +/** + * Generated Universally Unique Identifier + * + * @returns RFC4122 v4 UUID. + */ +function randomUUID() { + return uuidFunction(); +} + +exports.computeSha256Hash = computeSha256Hash; +exports.computeSha256Hmac = computeSha256Hmac; +exports.createAbortablePromise = createAbortablePromise; +exports.delay = delay; +exports.getErrorMessage = getErrorMessage; +exports.getRandomIntegerInclusive = getRandomIntegerInclusive; +exports.isDefined = isDefined; +exports.isError = isError; +exports.isNode = isNode; +exports.isObject = isObject; +exports.isObjectWithProperties = isObjectWithProperties; +exports.objectHasProperty = objectHasProperty; +exports.randomUUID = randomUUID; +//# sourceMappingURL=index.js.map + + /***/ }), /***/ 3233: @@ -61697,14 +62203,14 @@ module.exports = v4; this.saxParser.onopentag = (function(_this) { return function(node) { var key, newValue, obj, processedKey, ref; - obj = {}; + obj = Object.create(null); obj[charkey] = ""; if (!_this.options.ignoreAttrs) { ref = node.attributes; for (key in ref) { if (!hasProp.call(ref, key)) continue; if (!(attrkey in obj) && !_this.options.mergeAttrs) { - obj[attrkey] = {}; + obj[attrkey] = Object.create(null); } newValue = _this.options.attrValueProcessors ? processItem(_this.options.attrValueProcessors, node.attributes[key], key) : node.attributes[key]; processedKey = _this.options.attrNameProcessors ? processItem(_this.options.attrNameProcessors, key) : key; @@ -61754,7 +62260,11 @@ module.exports = v4; } } if (isEmpty(obj)) { - obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + if (typeof _this.options.emptyTag === 'function') { + obj = _this.options.emptyTag(); + } else { + obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr; + } } if (_this.options.validator != null) { xpath = "/" + ((function() { @@ -61778,7 +62288,7 @@ module.exports = v4; } if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') { if (!_this.options.preserveChildrenOrder) { - node = {}; + node = Object.create(null); if (_this.options.attrkey in obj) { node[_this.options.attrkey] = obj[_this.options.attrkey]; delete obj[_this.options.attrkey]; @@ -61793,7 +62303,7 @@ module.exports = v4; obj = node; } else if (s) { s[_this.options.childkey] = s[_this.options.childkey] || []; - objClone = {}; + objClone = Object.create(null); for (key in obj) { if (!hasProp.call(obj, key)) continue; objClone[key] = obj[key]; @@ -61810,7 +62320,7 @@ module.exports = v4; } else { if (_this.options.explicitRoot) { old = obj; - obj = {}; + obj = Object.create(null); obj[nodeName] = old; } _this.resultObject = obj; diff --git a/package-lock.json b/package-lock.json index 395457c..589c9cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -192,28 +192,28 @@ "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" }, "node_modules/@azure/core-http": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-2.2.2.tgz", - "integrity": "sha512-V1DdoO9V/sFimKpdWoNBgsE+QUjQgpXYnxrTdUp5RyhsTJjvEVn/HKmTQXIHuLUUo6IyIWj+B+Dg4VaXse9dIA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-2.3.2.tgz", + "integrity": "sha512-Z4dfbglV9kNZO177CNx4bo5ekFuYwwsvjLiKdZI4r84bYGv3irrbQz7JC3/rUfFH2l4T/W6OFleJaa2X0IaQqw==", "dependencies": { "@azure/abort-controller": "^1.0.0", - "@azure/core-asynciterator-polyfill": "^1.0.0", "@azure/core-auth": "^1.3.0", "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-util": "^1.1.1", "@azure/logger": "^1.0.0", "@types/node-fetch": "^2.5.0", "@types/tunnel": "^0.0.3", "form-data": "^4.0.0", - "node-fetch": "^2.6.0", + "node-fetch": "^2.6.7", "process": "^0.11.10", "tough-cookie": "^4.0.0", "tslib": "^2.2.0", "tunnel": "^0.0.6", "uuid": "^8.3.0", - "xml2js": "^0.4.19" + "xml2js": "^0.5.0" }, "engines": { - "node": ">=12.0.0" + "node": ">=14.0.0" } }, "node_modules/@azure/core-http/node_modules/form-data": { @@ -295,6 +295,23 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" }, + "node_modules/@azure/core-util": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.3.1.tgz", + "integrity": "sha512-pjfOUAb+MPLODhGuXot/Hy8wUgPD0UTqYkY3BiYcwEETrLcUCVM1t0roIvlQMgvn1lc48TGy5bsonsFpF862Jw==", + "dependencies": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@azure/core-util/node_modules/tslib": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", + "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==" + }, "node_modules/@azure/logger": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.0.3.tgz", @@ -312,19 +329,19 @@ "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" }, "node_modules/@azure/ms-rest-js": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.6.0.tgz", - "integrity": "sha512-4C5FCtvEzWudblB+h92/TYYPiq7tuElX8icVYToxOdggnYqeec4Se14mjse5miInKtZahiFHdl8lZA/jziEc5g==", + "version": "2.6.6", + "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.6.6.tgz", + "integrity": "sha512-WYIda8VvrkZE68xHgOxUXvjThxNf1nnGPPe0rAljqK5HJHIZ12Pi3YhEDOn3Ge7UnwaaM3eFO0VtAy4nGVI27Q==", "dependencies": { "@azure/core-auth": "^1.1.4", "abort-controller": "^3.0.0", "form-data": "^2.5.0", - "node-fetch": "^2.6.0", + "node-fetch": "^2.6.7", "tough-cookie": "^3.0.1", "tslib": "^1.10.0", "tunnel": "0.0.6", "uuid": "^8.3.2", - "xml2js": "^0.4.19" + "xml2js": "^0.5.0" } }, "node_modules/@azure/ms-rest-js/node_modules/form-data": { @@ -6697,9 +6714,9 @@ "dev": true }, "node_modules/xml2js": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", - "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", + "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" @@ -6929,25 +6946,25 @@ } }, "@azure/core-http": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-2.2.2.tgz", - "integrity": "sha512-V1DdoO9V/sFimKpdWoNBgsE+QUjQgpXYnxrTdUp5RyhsTJjvEVn/HKmTQXIHuLUUo6IyIWj+B+Dg4VaXse9dIA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-2.3.2.tgz", + "integrity": "sha512-Z4dfbglV9kNZO177CNx4bo5ekFuYwwsvjLiKdZI4r84bYGv3irrbQz7JC3/rUfFH2l4T/W6OFleJaa2X0IaQqw==", "requires": { "@azure/abort-controller": "^1.0.0", - "@azure/core-asynciterator-polyfill": "^1.0.0", "@azure/core-auth": "^1.3.0", "@azure/core-tracing": "1.0.0-preview.13", + "@azure/core-util": "^1.1.1", "@azure/logger": "^1.0.0", "@types/node-fetch": "^2.5.0", "@types/tunnel": "^0.0.3", "form-data": "^4.0.0", - "node-fetch": "^2.6.0", + "node-fetch": "^2.6.7", "process": "^0.11.10", "tough-cookie": "^4.0.0", "tslib": "^2.2.0", "tunnel": "^0.0.6", "uuid": "^8.3.0", - "xml2js": "^0.4.19" + "xml2js": "^0.5.0" }, "dependencies": { "form-data": { @@ -7022,6 +7039,22 @@ } } }, + "@azure/core-util": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.3.1.tgz", + "integrity": "sha512-pjfOUAb+MPLODhGuXot/Hy8wUgPD0UTqYkY3BiYcwEETrLcUCVM1t0roIvlQMgvn1lc48TGy5bsonsFpF862Jw==", + "requires": { + "@azure/abort-controller": "^1.0.0", + "tslib": "^2.2.0" + }, + "dependencies": { + "tslib": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz", + "integrity": "sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==" + } + } + }, "@azure/logger": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.0.3.tgz", @@ -7038,19 +7071,19 @@ } }, "@azure/ms-rest-js": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.6.0.tgz", - "integrity": "sha512-4C5FCtvEzWudblB+h92/TYYPiq7tuElX8icVYToxOdggnYqeec4Se14mjse5miInKtZahiFHdl8lZA/jziEc5g==", + "version": "2.6.6", + "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.6.6.tgz", + "integrity": "sha512-WYIda8VvrkZE68xHgOxUXvjThxNf1nnGPPe0rAljqK5HJHIZ12Pi3YhEDOn3Ge7UnwaaM3eFO0VtAy4nGVI27Q==", "requires": { "@azure/core-auth": "^1.1.4", "abort-controller": "^3.0.0", "form-data": "^2.5.0", - "node-fetch": "^2.6.0", + "node-fetch": "^2.6.7", "tough-cookie": "^3.0.1", "tslib": "^1.10.0", "tunnel": "0.0.6", "uuid": "^8.3.2", - "xml2js": "^0.4.19" + "xml2js": "^0.5.0" }, "dependencies": { "form-data": { @@ -11872,9 +11905,9 @@ "dev": true }, "xml2js": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", - "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", + "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", "requires": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0"