UNPKG

203 kBJavaScriptView Raw
1/** @license ms-rest-js
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt and ThirdPartyNotices.txt in the project root for license information.
4 */
5(function (global, factory) {
6 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
7 typeof define === 'function' && define.amd ? define(['exports'], factory) :
8 (global = global || self, factory(global.msRest = {}));
9}(this, (function (exports) { 'use strict';
10
11 // Copyright (c) Microsoft Corporation. All rights reserved.
12 // Licensed under the MIT License. See License.txt in the project root for license information.
13 /**
14 * A collection of HttpHeaders that can be sent with a HTTP request.
15 */
16 function getHeaderKey(headerName) {
17 return headerName.toLowerCase();
18 }
19 function isHttpHeadersLike(object) {
20 if (!object || typeof object !== "object") {
21 return false;
22 }
23 if (typeof object.rawHeaders === "function" &&
24 typeof object.clone === "function" &&
25 typeof object.get === "function" &&
26 typeof object.set === "function" &&
27 typeof object.contains === "function" &&
28 typeof object.remove === "function" &&
29 typeof object.headersArray === "function" &&
30 typeof object.headerValues === "function" &&
31 typeof object.headerNames === "function" &&
32 typeof object.toJson === "function") {
33 return true;
34 }
35 return false;
36 }
37 /**
38 * A collection of HTTP header key/value pairs.
39 */
40 var HttpHeaders = /** @class */ (function () {
41 function HttpHeaders(rawHeaders) {
42 this._headersMap = {};
43 if (rawHeaders) {
44 for (var headerName in rawHeaders) {
45 this.set(headerName, rawHeaders[headerName]);
46 }
47 }
48 }
49 /**
50 * Set a header in this collection with the provided name and value. The name is
51 * case-insensitive.
52 * @param headerName The name of the header to set. This value is case-insensitive.
53 * @param headerValue The value of the header to set.
54 */
55 HttpHeaders.prototype.set = function (headerName, headerValue) {
56 this._headersMap[getHeaderKey(headerName)] = {
57 name: headerName,
58 value: headerValue.toString(),
59 };
60 };
61 /**
62 * Get the header value for the provided header name, or undefined if no header exists in this
63 * collection with the provided name.
64 * @param headerName The name of the header.
65 */
66 HttpHeaders.prototype.get = function (headerName) {
67 var header = this._headersMap[getHeaderKey(headerName)];
68 return !header ? undefined : header.value;
69 };
70 /**
71 * Get whether or not this header collection contains a header entry for the provided header name.
72 */
73 HttpHeaders.prototype.contains = function (headerName) {
74 return !!this._headersMap[getHeaderKey(headerName)];
75 };
76 /**
77 * Remove the header with the provided headerName. Return whether or not the header existed and
78 * was removed.
79 * @param headerName The name of the header to remove.
80 */
81 HttpHeaders.prototype.remove = function (headerName) {
82 var result = this.contains(headerName);
83 delete this._headersMap[getHeaderKey(headerName)];
84 return result;
85 };
86 /**
87 * Get the headers that are contained this collection as an object.
88 */
89 HttpHeaders.prototype.rawHeaders = function () {
90 var result = {};
91 for (var headerKey in this._headersMap) {
92 var header = this._headersMap[headerKey];
93 result[header.name.toLowerCase()] = header.value;
94 }
95 return result;
96 };
97 /**
98 * Get the headers that are contained in this collection as an array.
99 */
100 HttpHeaders.prototype.headersArray = function () {
101 var headers = [];
102 for (var headerKey in this._headersMap) {
103 headers.push(this._headersMap[headerKey]);
104 }
105 return headers;
106 };
107 /**
108 * Get the header names that are contained in this collection.
109 */
110 HttpHeaders.prototype.headerNames = function () {
111 var headerNames = [];
112 var headers = this.headersArray();
113 for (var i = 0; i < headers.length; ++i) {
114 headerNames.push(headers[i].name);
115 }
116 return headerNames;
117 };
118 /**
119 * Get the header names that are contained in this collection.
120 */
121 HttpHeaders.prototype.headerValues = function () {
122 var headerValues = [];
123 var headers = this.headersArray();
124 for (var i = 0; i < headers.length; ++i) {
125 headerValues.push(headers[i].value);
126 }
127 return headerValues;
128 };
129 /**
130 * Get the JSON object representation of this HTTP header collection.
131 */
132 HttpHeaders.prototype.toJson = function () {
133 return this.rawHeaders();
134 };
135 /**
136 * Get the string representation of this HTTP header collection.
137 */
138 HttpHeaders.prototype.toString = function () {
139 return JSON.stringify(this.toJson());
140 };
141 /**
142 * Create a deep clone/copy of this HttpHeaders collection.
143 */
144 HttpHeaders.prototype.clone = function () {
145 return new HttpHeaders(this.rawHeaders());
146 };
147 return HttpHeaders;
148 }());
149
150 // Copyright (c) Microsoft Corporation. All rights reserved.
151 // Licensed under the MIT License. See License.txt in the project root for license information.
152 /**
153 * Encodes a string in base64 format.
154 * @param value the string to encode
155 */
156 function encodeString(value) {
157 return btoa(value);
158 }
159 /**
160 * Encodes a byte array in base64 format.
161 * @param value the Uint8Aray to encode
162 */
163 function encodeByteArray(value) {
164 var str = "";
165 for (var i = 0; i < value.length; i++) {
166 str += String.fromCharCode(value[i]);
167 }
168 return btoa(str);
169 }
170 /**
171 * Decodes a base64 string into a byte array.
172 * @param value the base64 string to decode
173 */
174 function decodeString(value) {
175 var byteString = atob(value);
176 var arr = new Uint8Array(byteString.length);
177 for (var i = 0; i < byteString.length; i++) {
178 arr[i] = byteString.charCodeAt(i);
179 }
180 return arr;
181 }
182
183 // Unique ID creation requires a high quality random # generator. In the browser we therefore
184 // require the crypto API and do not support built-in fallback to lower quality random number
185 // generators (like Math.random()).
186 var getRandomValues;
187 var rnds8 = new Uint8Array(16);
188 function rng() {
189 // lazy load so that environments that need to polyfill have a chance to do so
190 if (!getRandomValues) {
191 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
192 // find the complete implementation of crypto (msCrypto) on IE11.
193 getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
194
195 if (!getRandomValues) {
196 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
197 }
198 }
199
200 return getRandomValues(rnds8);
201 }
202
203 var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
204
205 function validate(uuid) {
206 return typeof uuid === 'string' && REGEX.test(uuid);
207 }
208
209 /**
210 * Convert array of 16 byte values to UUID string format of the form:
211 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
212 */
213
214 var byteToHex = [];
215
216 for (var i = 0; i < 256; ++i) {
217 byteToHex.push((i + 0x100).toString(16).substr(1));
218 }
219
220 function stringify(arr) {
221 var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
222 // Note: Be careful editing this code! It's been tuned for performance
223 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
224 var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
225 // of the following:
226 // - One or more input array values don't map to a hex octet (leading to
227 // "undefined" in the uuid)
228 // - Invalid input values for the RFC `version` or `variant` fields
229
230 if (!validate(uuid)) {
231 throw TypeError('Stringified UUID is invalid');
232 }
233
234 return uuid;
235 }
236
237 function v4(options, buf, offset) {
238 options = options || {};
239 var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
240
241 rnds[6] = rnds[6] & 0x0f | 0x40;
242 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
243
244 if (buf) {
245 offset = offset || 0;
246
247 for (var i = 0; i < 16; ++i) {
248 buf[offset + i] = rnds[i];
249 }
250
251 return buf;
252 }
253
254 return stringify(rnds);
255 }
256
257 // Copyright (c) Microsoft Corporation. All rights reserved.
258 // Licensed under the MIT License. See License.txt in the project root for license information.
259 var Constants = {
260 /**
261 * The ms-rest version
262 * @const
263 * @type {string}
264 */
265 msRestVersion: "2.6.1",
266 /**
267 * Specifies HTTP.
268 *
269 * @const
270 * @type {string}
271 */
272 HTTP: "http:",
273 /**
274 * Specifies HTTPS.
275 *
276 * @const
277 * @type {string}
278 */
279 HTTPS: "https:",
280 /**
281 * Specifies HTTP Proxy.
282 *
283 * @const
284 * @type {string}
285 */
286 HTTP_PROXY: "HTTP_PROXY",
287 /**
288 * Specifies HTTPS Proxy.
289 *
290 * @const
291 * @type {string}
292 */
293 HTTPS_PROXY: "HTTPS_PROXY",
294 /**
295 * Specifies NO Proxy.
296 */
297 NO_PROXY: "NO_PROXY",
298 /**
299 * Specifies ALL Proxy.
300 */
301 ALL_PROXY: "ALL_PROXY",
302 HttpConstants: {
303 /**
304 * Http Verbs
305 *
306 * @const
307 * @enum {string}
308 */
309 HttpVerbs: {
310 PUT: "PUT",
311 GET: "GET",
312 DELETE: "DELETE",
313 POST: "POST",
314 MERGE: "MERGE",
315 HEAD: "HEAD",
316 PATCH: "PATCH",
317 },
318 StatusCodes: {
319 TooManyRequests: 429,
320 },
321 },
322 /**
323 * Defines constants for use with HTTP headers.
324 */
325 HeaderConstants: {
326 /**
327 * The Authorization header.
328 *
329 * @const
330 * @type {string}
331 */
332 AUTHORIZATION: "authorization",
333 AUTHORIZATION_SCHEME: "Bearer",
334 /**
335 * The Retry-After response-header field can be used with a 503 (Service
336 * Unavailable) or 349 (Too Many Requests) responses to indicate how long
337 * the service is expected to be unavailable to the requesting client.
338 *
339 * @const
340 * @type {string}
341 */
342 RETRY_AFTER: "Retry-After",
343 /**
344 * The UserAgent header.
345 *
346 * @const
347 * @type {string}
348 */
349 USER_AGENT: "User-Agent",
350 },
351 };
352
353 // Copyright (c) Microsoft Corporation. All rights reserved.
354 /**
355 * A constant that indicates whether the environment is node.js or browser based.
356 */
357 var isNode = typeof process !== "undefined" &&
358 !!process.version &&
359 !!process.versions &&
360 !!process.versions.node;
361 /**
362 * Encodes an URI.
363 *
364 * @param {string} uri The URI to be encoded.
365 * @return {string} The encoded URI.
366 */
367 function encodeUri(uri) {
368 return encodeURIComponent(uri)
369 .replace(/!/g, "%21")
370 .replace(/"/g, "%27")
371 .replace(/\(/g, "%28")
372 .replace(/\)/g, "%29")
373 .replace(/\*/g, "%2A");
374 }
375 /**
376 * Returns a stripped version of the Http Response which only contains body,
377 * headers and the status.
378 *
379 * @param {HttpOperationResponse} response The Http Response
380 *
381 * @return {object} The stripped version of Http Response.
382 */
383 function stripResponse(response) {
384 var strippedResponse = {};
385 strippedResponse.body = response.bodyAsText;
386 strippedResponse.headers = response.headers;
387 strippedResponse.status = response.status;
388 return strippedResponse;
389 }
390 /**
391 * Returns a stripped version of the Http Request that does not contain the
392 * Authorization header.
393 *
394 * @param {WebResource} request The Http Request object
395 *
396 * @return {WebResource} The stripped version of Http Request.
397 */
398 function stripRequest(request) {
399 var strippedRequest = request.clone();
400 if (strippedRequest.headers) {
401 strippedRequest.headers.remove("authorization");
402 }
403 return strippedRequest;
404 }
405 /**
406 * Validates the given uuid as a string
407 *
408 * @param {string} uuid The uuid as a string that needs to be validated
409 *
410 * @return {boolean} True if the uuid is valid; false otherwise.
411 */
412 function isValidUuid(uuid) {
413 var validUuidRegex = new RegExp("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", "ig");
414 return validUuidRegex.test(uuid);
415 }
416 /**
417 * Generated UUID
418 *
419 * @return {string} RFC4122 v4 UUID.
420 */
421 function generateUuid() {
422 return v4();
423 }
424 /**
425 * Executes an array of promises sequentially. Inspiration of this method is here:
426 * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
427 *
428 * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
429 *
430 * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
431 * If not provided then the promise chain starts with undefined.
432 *
433 * @return A chain of resolved or rejected promises
434 */
435 function executePromisesSequentially(promiseFactories, kickstart) {
436 var result = Promise.resolve(kickstart);
437 promiseFactories.forEach(function (promiseFactory) {
438 result = result.then(promiseFactory);
439 });
440 return result;
441 }
442 /**
443 * A wrapper for setTimeout that resolves a promise after t milliseconds.
444 * @param {number} t The number of milliseconds to be delayed.
445 * @param {T} value The value to be resolved with after a timeout of t milliseconds.
446 * @returns {Promise<T>} Resolved promise
447 */
448 function delay(t, value) {
449 return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
450 }
451 /**
452 * Converts a Promise to a callback.
453 * @param {Promise<any>} promise The Promise to be converted to a callback
454 * @returns {Function} A function that takes the callback (cb: Function): void
455 * @deprecated generated code should instead depend on responseToBody
456 */
457 function promiseToCallback(promise) {
458 if (typeof promise.then !== "function") {
459 throw new Error("The provided input is not a Promise.");
460 }
461 return function (cb) {
462 promise.then(function (data) {
463 cb(undefined, data);
464 }, function (err) {
465 cb(err);
466 });
467 };
468 }
469 /**
470 * Converts a Promise to a service callback.
471 * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
472 * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
473 */
474 function promiseToServiceCallback(promise) {
475 if (typeof promise.then !== "function") {
476 throw new Error("The provided input is not a Promise.");
477 }
478 return function (cb) {
479 promise.then(function (data) {
480 process.nextTick(cb, undefined, data.parsedBody, data.request, data);
481 }, function (err) {
482 process.nextTick(cb, err);
483 });
484 };
485 }
486 function prepareXMLRootList(obj, elementName) {
487 var _a;
488 if (!Array.isArray(obj)) {
489 obj = [obj];
490 }
491 return _a = {}, _a[elementName] = obj, _a;
492 }
493 /**
494 * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
495 * @param {object} targetCtor The target object on which the properties need to be applied.
496 * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
497 */
498 function applyMixins(targetCtor, sourceCtors) {
499 sourceCtors.forEach(function (sourceCtors) {
500 Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
501 targetCtor.prototype[name] = sourceCtors.prototype[name];
502 });
503 });
504 }
505 var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
506 /**
507 * Indicates whether the given string is in ISO 8601 format.
508 * @param {string} value The value to be validated for ISO 8601 duration format.
509 * @return {boolean} `true` if valid, `false` otherwise.
510 */
511 function isDuration(value) {
512 return validateISODuration.test(value);
513 }
514 /**
515 * Replace all of the instances of searchValue in value with the provided replaceValue.
516 * @param {string | undefined} value The value to search and replace in.
517 * @param {string} searchValue The value to search for in the value argument.
518 * @param {string} replaceValue The value to replace searchValue with in the value argument.
519 * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
520 */
521 function replaceAll(value, searchValue, replaceValue) {
522 return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
523 }
524 /**
525 * Determines whether the given enity is a basic/primitive type
526 * (string, number, boolean, null, undefined).
527 * @param value Any entity
528 * @return boolean - true is it is primitive type, false otherwise.
529 */
530 function isPrimitiveType(value) {
531 return (typeof value !== "object" && typeof value !== "function") || value === null;
532 }
533
534 // Copyright (c) Microsoft Corporation. All rights reserved.
535 var Serializer = /** @class */ (function () {
536 function Serializer(modelMappers, isXML) {
537 if (modelMappers === void 0) { modelMappers = {}; }
538 this.modelMappers = modelMappers;
539 this.isXML = isXML;
540 }
541 Serializer.prototype.validateConstraints = function (mapper, value, objectName) {
542 var failValidation = function (constraintName, constraintValue) {
543 throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + ".");
544 };
545 if (mapper.constraints && value != undefined) {
546 var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems;
547 if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {
548 failValidation("ExclusiveMaximum", ExclusiveMaximum);
549 }
550 if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {
551 failValidation("ExclusiveMinimum", ExclusiveMinimum);
552 }
553 if (InclusiveMaximum != undefined && value > InclusiveMaximum) {
554 failValidation("InclusiveMaximum", InclusiveMaximum);
555 }
556 if (InclusiveMinimum != undefined && value < InclusiveMinimum) {
557 failValidation("InclusiveMinimum", InclusiveMinimum);
558 }
559 if (MaxItems != undefined && value.length > MaxItems) {
560 failValidation("MaxItems", MaxItems);
561 }
562 if (MaxLength != undefined && value.length > MaxLength) {
563 failValidation("MaxLength", MaxLength);
564 }
565 if (MinItems != undefined && value.length < MinItems) {
566 failValidation("MinItems", MinItems);
567 }
568 if (MinLength != undefined && value.length < MinLength) {
569 failValidation("MinLength", MinLength);
570 }
571 if (MultipleOf != undefined && value % MultipleOf !== 0) {
572 failValidation("MultipleOf", MultipleOf);
573 }
574 if (Pattern) {
575 var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
576 if (typeof value !== "string" || value.match(pattern) === null) {
577 failValidation("Pattern", Pattern);
578 }
579 }
580 if (UniqueItems &&
581 value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {
582 failValidation("UniqueItems", UniqueItems);
583 }
584 }
585 };
586 /**
587 * Serialize the given object based on its metadata defined in the mapper
588 *
589 * @param {Mapper} mapper The mapper which defines the metadata of the serializable object
590 *
591 * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized
592 *
593 * @param {string} objectName Name of the serialized object
594 *
595 * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object
596 */
597 Serializer.prototype.serialize = function (mapper, object, objectName) {
598 var payload = {};
599 var mapperType = mapper.type.name;
600 if (!objectName) {
601 objectName = mapper.serializedName;
602 }
603 if (mapperType.match(/^Sequence$/gi) !== null) {
604 payload = [];
605 }
606 if (mapper.isConstant) {
607 object = mapper.defaultValue;
608 }
609 // This table of allowed values should help explain
610 // the mapper.required and mapper.nullable properties.
611 // X means "neither undefined or null are allowed".
612 // || required
613 // || true | false
614 // nullable || ==========================
615 // true || null | undefined/null
616 // false || X | undefined
617 // undefined || X | undefined/null
618 var required = mapper.required, nullable = mapper.nullable;
619 if (required && nullable && object === undefined) {
620 throw new Error(objectName + " cannot be undefined.");
621 }
622 if (required && !nullable && object == undefined) {
623 throw new Error(objectName + " cannot be null or undefined.");
624 }
625 if (!required && nullable === false && object === null) {
626 throw new Error(objectName + " cannot be null.");
627 }
628 if (object == undefined) {
629 payload = object;
630 }
631 else {
632 // Validate Constraints if any
633 this.validateConstraints(mapper, object, objectName);
634 if (mapperType.match(/^any$/gi) !== null) {
635 payload = object;
636 }
637 else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/gi) !== null) {
638 payload = serializeBasicTypes(mapperType, objectName, object);
639 }
640 else if (mapperType.match(/^Enum$/gi) !== null) {
641 var enumMapper = mapper;
642 payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
643 }
644 else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/gi) !== null) {
645 payload = serializeDateTypes(mapperType, object, objectName);
646 }
647 else if (mapperType.match(/^ByteArray$/gi) !== null) {
648 payload = serializeByteArrayType(objectName, object);
649 }
650 else if (mapperType.match(/^Base64Url$/gi) !== null) {
651 payload = serializeBase64UrlType(objectName, object);
652 }
653 else if (mapperType.match(/^Sequence$/gi) !== null) {
654 payload = serializeSequenceType(this, mapper, object, objectName);
655 }
656 else if (mapperType.match(/^Dictionary$/gi) !== null) {
657 payload = serializeDictionaryType(this, mapper, object, objectName);
658 }
659 else if (mapperType.match(/^Composite$/gi) !== null) {
660 payload = serializeCompositeType(this, mapper, object, objectName);
661 }
662 }
663 return payload;
664 };
665 /**
666 * Deserialize the given object based on its metadata defined in the mapper
667 *
668 * @param {object} mapper The mapper which defines the metadata of the serializable object
669 *
670 * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized
671 *
672 * @param {string} objectName Name of the deserialized object
673 *
674 * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object
675 */
676 Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {
677 if (responseBody == undefined) {
678 if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
679 // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
680 // between the list being empty versus being missing,
681 // so let's do the more user-friendly thing and return an empty list.
682 responseBody = [];
683 }
684 // specifically check for undefined as default value can be a falsey value `0, "", false, null`
685 if (mapper.defaultValue !== undefined) {
686 responseBody = mapper.defaultValue;
687 }
688 return responseBody;
689 }
690 var payload;
691 var mapperType = mapper.type.name;
692 if (!objectName) {
693 objectName = mapper.serializedName;
694 }
695 if (mapperType.match(/^Composite$/gi) !== null) {
696 payload = deserializeCompositeType(this, mapper, responseBody, objectName);
697 }
698 else {
699 if (this.isXML) {
700 /**
701 * If the mapper specifies this as a non-composite type value but the responseBody contains
702 * both header ("$") and body ("_") properties, then just reduce the responseBody value to
703 * the body ("_") property.
704 */
705 if (responseBody["$"] != undefined && responseBody["_"] != undefined) {
706 responseBody = responseBody["_"];
707 }
708 }
709 if (mapperType.match(/^Number$/gi) !== null) {
710 payload = parseFloat(responseBody);
711 if (isNaN(payload)) {
712 payload = responseBody;
713 }
714 }
715 else if (mapperType.match(/^Boolean$/gi) !== null) {
716 if (responseBody === "true") {
717 payload = true;
718 }
719 else if (responseBody === "false") {
720 payload = false;
721 }
722 else {
723 payload = responseBody;
724 }
725 }
726 else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/gi) !== null) {
727 payload = responseBody;
728 }
729 else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/gi) !== null) {
730 payload = new Date(responseBody);
731 }
732 else if (mapperType.match(/^UnixTime$/gi) !== null) {
733 payload = unixTimeToDate(responseBody);
734 }
735 else if (mapperType.match(/^ByteArray$/gi) !== null) {
736 payload = decodeString(responseBody);
737 }
738 else if (mapperType.match(/^Base64Url$/gi) !== null) {
739 payload = base64UrlToByteArray(responseBody);
740 }
741 else if (mapperType.match(/^Sequence$/gi) !== null) {
742 payload = deserializeSequenceType(this, mapper, responseBody, objectName);
743 }
744 else if (mapperType.match(/^Dictionary$/gi) !== null) {
745 payload = deserializeDictionaryType(this, mapper, responseBody, objectName);
746 }
747 }
748 if (mapper.isConstant) {
749 payload = mapper.defaultValue;
750 }
751 return payload;
752 };
753 return Serializer;
754 }());
755 function trimEnd(str, ch) {
756 var len = str.length;
757 while (len - 1 >= 0 && str[len - 1] === ch) {
758 --len;
759 }
760 return str.substr(0, len);
761 }
762 function bufferToBase64Url(buffer) {
763 if (!buffer) {
764 return undefined;
765 }
766 if (!(buffer instanceof Uint8Array)) {
767 throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");
768 }
769 // Uint8Array to Base64.
770 var str = encodeByteArray(buffer);
771 // Base64 to Base64Url.
772 return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
773 }
774 function base64UrlToByteArray(str) {
775 if (!str) {
776 return undefined;
777 }
778 if (str && typeof str.valueOf() !== "string") {
779 throw new Error("Please provide an input of type string for converting to Uint8Array");
780 }
781 // Base64Url to Base64.
782 str = str.replace(/\-/g, "+").replace(/\_/g, "/");
783 // Base64 to Uint8Array.
784 return decodeString(str);
785 }
786 function splitSerializeName(prop) {
787 var classes = [];
788 var partialclass = "";
789 if (prop) {
790 var subwords = prop.split(".");
791 for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {
792 var item = subwords_1[_i];
793 if (item.charAt(item.length - 1) === "\\") {
794 partialclass += item.substr(0, item.length - 1) + ".";
795 }
796 else {
797 partialclass += item;
798 classes.push(partialclass);
799 partialclass = "";
800 }
801 }
802 }
803 return classes;
804 }
805 function dateToUnixTime(d) {
806 if (!d) {
807 return undefined;
808 }
809 if (typeof d.valueOf() === "string") {
810 d = new Date(d);
811 }
812 return Math.floor(d.getTime() / 1000);
813 }
814 function unixTimeToDate(n) {
815 if (!n) {
816 return undefined;
817 }
818 return new Date(n * 1000);
819 }
820 function serializeBasicTypes(typeName, objectName, value) {
821 if (value !== null && value !== undefined) {
822 if (typeName.match(/^Number$/gi) !== null) {
823 if (typeof value !== "number") {
824 throw new Error(objectName + " with value " + value + " must be of type number.");
825 }
826 }
827 else if (typeName.match(/^String$/gi) !== null) {
828 if (typeof value.valueOf() !== "string") {
829 throw new Error(objectName + " with value \"" + value + "\" must be of type string.");
830 }
831 }
832 else if (typeName.match(/^Uuid$/gi) !== null) {
833 if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
834 throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid.");
835 }
836 }
837 else if (typeName.match(/^Boolean$/gi) !== null) {
838 if (typeof value !== "boolean") {
839 throw new Error(objectName + " with value " + value + " must be of type boolean.");
840 }
841 }
842 else if (typeName.match(/^Stream$/gi) !== null) {
843 var objectType = typeof value;
844 if (objectType !== "string" &&
845 objectType !== "function" &&
846 !(value instanceof ArrayBuffer) &&
847 !ArrayBuffer.isView(value) &&
848 !(typeof Blob === "function" && value instanceof Blob)) {
849 throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.");
850 }
851 }
852 }
853 return value;
854 }
855 function serializeEnumType(objectName, allowedValues, value) {
856 if (!allowedValues) {
857 throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type.");
858 }
859 var isPresent = allowedValues.some(function (item) {
860 if (typeof item.valueOf() === "string") {
861 return item.toLowerCase() === value.toLowerCase();
862 }
863 return item === value;
864 });
865 if (!isPresent) {
866 throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + ".");
867 }
868 return value;
869 }
870 function serializeByteArrayType(objectName, value) {
871 if (value != undefined) {
872 if (!(value instanceof Uint8Array)) {
873 throw new Error(objectName + " must be of type Uint8Array.");
874 }
875 value = encodeByteArray(value);
876 }
877 return value;
878 }
879 function serializeBase64UrlType(objectName, value) {
880 if (value != undefined) {
881 if (!(value instanceof Uint8Array)) {
882 throw new Error(objectName + " must be of type Uint8Array.");
883 }
884 value = bufferToBase64Url(value);
885 }
886 return value;
887 }
888 function serializeDateTypes(typeName, value, objectName) {
889 if (value != undefined) {
890 if (typeName.match(/^Date$/gi) !== null) {
891 if (!(value instanceof Date ||
892 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
893 throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
894 }
895 value =
896 value instanceof Date
897 ? value.toISOString().substring(0, 10)
898 : new Date(value).toISOString().substring(0, 10);
899 }
900 else if (typeName.match(/^DateTime$/gi) !== null) {
901 if (!(value instanceof Date ||
902 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
903 throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
904 }
905 value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
906 }
907 else if (typeName.match(/^DateTimeRfc1123$/gi) !== null) {
908 if (!(value instanceof Date ||
909 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
910 throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format.");
911 }
912 value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
913 }
914 else if (typeName.match(/^UnixTime$/gi) !== null) {
915 if (!(value instanceof Date ||
916 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
917 throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " +
918 "for it to be serialized in UnixTime/Epoch format.");
919 }
920 value = dateToUnixTime(value);
921 }
922 else if (typeName.match(/^TimeSpan$/gi) !== null) {
923 if (!isDuration(value)) {
924 throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\".");
925 }
926 value = value;
927 }
928 }
929 return value;
930 }
931 function serializeSequenceType(serializer, mapper, object, objectName) {
932 if (!Array.isArray(object)) {
933 throw new Error(objectName + " must be of type Array.");
934 }
935 var elementType = mapper.type.element;
936 if (!elementType || typeof elementType !== "object") {
937 throw new Error("element\" metadata for an Array must be defined in the " +
938 ("mapper and it must of type \"object\" in " + objectName + "."));
939 }
940 var tempArray = [];
941 for (var i = 0; i < object.length; i++) {
942 tempArray[i] = serializer.serialize(elementType, object[i], objectName);
943 }
944 return tempArray;
945 }
946 function serializeDictionaryType(serializer, mapper, object, objectName) {
947 if (typeof object !== "object") {
948 throw new Error(objectName + " must be of type object.");
949 }
950 var valueType = mapper.type.value;
951 if (!valueType || typeof valueType !== "object") {
952 throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
953 ("mapper and it must of type \"object\" in " + objectName + "."));
954 }
955 var tempDictionary = {};
956 for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
957 var key = _a[_i];
958 tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + "." + key);
959 }
960 return tempDictionary;
961 }
962 /**
963 * Resolves a composite mapper's modelProperties.
964 * @param serializer the serializer containing the entire set of mappers
965 * @param mapper the composite mapper to resolve
966 */
967 function resolveModelProperties(serializer, mapper, objectName) {
968 var modelProps = mapper.type.modelProperties;
969 if (!modelProps) {
970 var className = mapper.type.className;
971 if (!className) {
972 throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\".");
973 }
974 var modelMapper = serializer.modelMappers[className];
975 if (!modelMapper) {
976 throw new Error("mapper() cannot be null or undefined for model \"" + className + "\".");
977 }
978 modelProps = modelMapper.type.modelProperties;
979 if (!modelProps) {
980 throw new Error("modelProperties cannot be null or undefined in the " +
981 ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + className + "\" for object \"" + objectName + "\"."));
982 }
983 }
984 return modelProps;
985 }
986 function serializeCompositeType(serializer, mapper, object, objectName) {
987 var _a;
988 if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
989 mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
990 }
991 if (object != undefined) {
992 var payload = {};
993 var modelProps = resolveModelProperties(serializer, mapper, objectName);
994 for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {
995 var key = _b[_i];
996 var propertyMapper = modelProps[key];
997 if (propertyMapper.readOnly) {
998 continue;
999 }
1000 var propName = void 0;
1001 var parentObject = payload;
1002 if (serializer.isXML) {
1003 if (propertyMapper.xmlIsWrapped) {
1004 propName = propertyMapper.xmlName;
1005 }
1006 else {
1007 propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
1008 }
1009 }
1010 else {
1011 var paths = splitSerializeName(propertyMapper.serializedName);
1012 propName = paths.pop();
1013 for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {
1014 var pathName = paths_1[_c];
1015 var childObject = parentObject[pathName];
1016 if (childObject == undefined && object[key] != undefined) {
1017 parentObject[pathName] = {};
1018 }
1019 parentObject = parentObject[pathName];
1020 }
1021 }
1022 if (parentObject != undefined) {
1023 var propertyObjectName = propertyMapper.serializedName !== ""
1024 ? objectName + "." + propertyMapper.serializedName
1025 : objectName;
1026 var toSerialize = object[key];
1027 var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
1028 if (polymorphicDiscriminator &&
1029 polymorphicDiscriminator.clientName === key &&
1030 toSerialize == undefined) {
1031 toSerialize = mapper.serializedName;
1032 }
1033 var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);
1034 if (serializedValue !== undefined && propName != undefined) {
1035 if (propertyMapper.xmlIsAttribute) {
1036 // $ is the key attributes are kept under in xml2js.
1037 // This keeps things simple while preventing name collision
1038 // with names in user documents.
1039 parentObject.$ = parentObject.$ || {};
1040 parentObject.$[propName] = serializedValue;
1041 }
1042 else if (propertyMapper.xmlIsWrapped) {
1043 parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);
1044 }
1045 else {
1046 parentObject[propName] = serializedValue;
1047 }
1048 }
1049 }
1050 }
1051 var additionalPropertiesMapper = mapper.type.additionalProperties;
1052 if (additionalPropertiesMapper) {
1053 var propNames = Object.keys(modelProps);
1054 var _loop_1 = function (clientPropName) {
1055 var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });
1056 if (isAdditionalProperty) {
1057 payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]');
1058 }
1059 };
1060 for (var clientPropName in object) {
1061 _loop_1(clientPropName);
1062 }
1063 }
1064 return payload;
1065 }
1066 return object;
1067 }
1068 function isSpecialXmlProperty(propertyName) {
1069 return ["$", "_"].includes(propertyName);
1070 }
1071 function deserializeCompositeType(serializer, mapper, responseBody, objectName) {
1072 if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
1073 mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
1074 }
1075 var modelProps = resolveModelProperties(serializer, mapper, objectName);
1076 var instance = {};
1077 var handledPropertyNames = [];
1078 for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {
1079 var key = _a[_i];
1080 var propertyMapper = modelProps[key];
1081 var paths = splitSerializeName(modelProps[key].serializedName);
1082 handledPropertyNames.push(paths[0]);
1083 var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;
1084 var propertyObjectName = objectName;
1085 if (serializedName !== "" && serializedName !== undefined) {
1086 propertyObjectName = objectName + "." + serializedName;
1087 }
1088 var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
1089 if (headerCollectionPrefix) {
1090 var dictionary = {};
1091 for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {
1092 var headerKey = _c[_b];
1093 if (headerKey.startsWith(headerCollectionPrefix)) {
1094 dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);
1095 }
1096 handledPropertyNames.push(headerKey);
1097 }
1098 instance[key] = dictionary;
1099 }
1100 else if (serializer.isXML) {
1101 if (propertyMapper.xmlIsAttribute && responseBody.$) {
1102 instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);
1103 }
1104 else {
1105 var propertyName = xmlElementName || xmlName || serializedName;
1106 var unwrappedProperty = responseBody[propertyName];
1107 if (propertyMapper.xmlIsWrapped) {
1108 unwrappedProperty = responseBody[xmlName];
1109 unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];
1110 var isEmptyWrappedList = unwrappedProperty === undefined;
1111 if (isEmptyWrappedList) {
1112 unwrappedProperty = [];
1113 }
1114 }
1115 instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);
1116 }
1117 }
1118 else {
1119 // deserialize the property if it is present in the provided responseBody instance
1120 var propertyInstance = void 0;
1121 var res = responseBody;
1122 // traversing the object step by step.
1123 for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {
1124 var item = paths_2[_d];
1125 if (!res)
1126 break;
1127 res = res[item];
1128 }
1129 propertyInstance = res;
1130 var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
1131 // checking that the model property name (key)(ex: "fishtype") and the
1132 // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
1133 // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
1134 // is a better approach. The generator is not consistent with escaping '\.' in the
1135 // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
1136 // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
1137 // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
1138 // the transformation of model property name (ex: "fishtype") is done consistently.
1139 // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
1140 if (polymorphicDiscriminator &&
1141 key === polymorphicDiscriminator.clientName &&
1142 propertyInstance == undefined) {
1143 propertyInstance = mapper.serializedName;
1144 }
1145 var serializedValue = void 0;
1146 // paging
1147 if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
1148 propertyInstance = responseBody[key];
1149 var arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
1150 // Copy over any properties that have already been added into the instance, where they do
1151 // not exist on the newly de-serialized array
1152 for (var _e = 0, _f = Object.entries(instance); _e < _f.length; _e++) {
1153 var _g = _f[_e], key_1 = _g[0], value = _g[1];
1154 if (!arrayInstance.hasOwnProperty(key_1)) {
1155 arrayInstance[key_1] = value;
1156 }
1157 }
1158 instance = arrayInstance;
1159 }
1160 else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
1161 serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
1162 instance[key] = serializedValue;
1163 }
1164 }
1165 }
1166 var additionalPropertiesMapper = mapper.type.additionalProperties;
1167 if (additionalPropertiesMapper) {
1168 var isAdditionalProperty = function (responsePropName) {
1169 for (var clientPropName in modelProps) {
1170 var paths = splitSerializeName(modelProps[clientPropName].serializedName);
1171 if (paths[0] === responsePropName) {
1172 return false;
1173 }
1174 }
1175 return true;
1176 };
1177 for (var responsePropName in responseBody) {
1178 if (isAdditionalProperty(responsePropName)) {
1179 instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]');
1180 }
1181 }
1182 }
1183 else if (responseBody) {
1184 for (var _h = 0, _j = Object.keys(responseBody); _h < _j.length; _h++) {
1185 var key = _j[_h];
1186 if (instance[key] === undefined &&
1187 !handledPropertyNames.includes(key) &&
1188 !isSpecialXmlProperty(key)) {
1189 instance[key] = responseBody[key];
1190 }
1191 }
1192 }
1193 return instance;
1194 }
1195 function deserializeDictionaryType(serializer, mapper, responseBody, objectName) {
1196 /*jshint validthis: true */
1197 var value = mapper.type.value;
1198 if (!value || typeof value !== "object") {
1199 throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
1200 ("mapper and it must of type \"object\" in " + objectName));
1201 }
1202 if (responseBody) {
1203 var tempDictionary = {};
1204 for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {
1205 var key = _a[_i];
1206 tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);
1207 }
1208 return tempDictionary;
1209 }
1210 return responseBody;
1211 }
1212 function deserializeSequenceType(serializer, mapper, responseBody, objectName) {
1213 /*jshint validthis: true */
1214 var element = mapper.type.element;
1215 if (!element || typeof element !== "object") {
1216 throw new Error("element\" metadata for an Array must be defined in the " +
1217 ("mapper and it must of type \"object\" in " + objectName));
1218 }
1219 if (responseBody) {
1220 if (!Array.isArray(responseBody)) {
1221 // xml2js will interpret a single element array as just the element, so force it to be an array
1222 responseBody = [responseBody];
1223 }
1224 var tempArray = [];
1225 for (var i = 0; i < responseBody.length; i++) {
1226 tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]");
1227 }
1228 return tempArray;
1229 }
1230 return responseBody;
1231 }
1232 function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
1233 var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
1234 if (polymorphicDiscriminator) {
1235 var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
1236 if (discriminatorName != undefined) {
1237 var discriminatorValue = object[discriminatorName];
1238 if (discriminatorValue != undefined) {
1239 var typeName = mapper.type.uberParent || mapper.type.className;
1240 var indexDiscriminator = discriminatorValue === typeName
1241 ? discriminatorValue
1242 : typeName + "." + discriminatorValue;
1243 var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];
1244 if (polymorphicMapper) {
1245 mapper = polymorphicMapper;
1246 }
1247 }
1248 }
1249 }
1250 return mapper;
1251 }
1252 function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
1253 return (mapper.type.polymorphicDiscriminator ||
1254 getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
1255 getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
1256 }
1257 function getPolymorphicDiscriminatorSafely(serializer, typeName) {
1258 return (typeName &&
1259 serializer.modelMappers[typeName] &&
1260 serializer.modelMappers[typeName].type.polymorphicDiscriminator);
1261 }
1262 // TODO: why is this here?
1263 function serializeObject(toSerialize) {
1264 if (toSerialize == undefined)
1265 return undefined;
1266 if (toSerialize instanceof Uint8Array) {
1267 toSerialize = encodeByteArray(toSerialize);
1268 return toSerialize;
1269 }
1270 else if (toSerialize instanceof Date) {
1271 return toSerialize.toISOString();
1272 }
1273 else if (Array.isArray(toSerialize)) {
1274 var array = [];
1275 for (var i = 0; i < toSerialize.length; i++) {
1276 array.push(serializeObject(toSerialize[i]));
1277 }
1278 return array;
1279 }
1280 else if (typeof toSerialize === "object") {
1281 var dictionary = {};
1282 for (var property in toSerialize) {
1283 dictionary[property] = serializeObject(toSerialize[property]);
1284 }
1285 return dictionary;
1286 }
1287 return toSerialize;
1288 }
1289 /**
1290 * Utility function to create a K:V from a list of strings
1291 */
1292 function strEnum(o) {
1293 var result = {};
1294 for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {
1295 var key = o_1[_i];
1296 result[key] = key;
1297 }
1298 return result;
1299 }
1300 var MapperType = strEnum([
1301 "Base64Url",
1302 "Boolean",
1303 "ByteArray",
1304 "Composite",
1305 "Date",
1306 "DateTime",
1307 "DateTimeRfc1123",
1308 "Dictionary",
1309 "Enum",
1310 "Number",
1311 "Object",
1312 "Sequence",
1313 "String",
1314 "Stream",
1315 "TimeSpan",
1316 "UnixTime",
1317 ]);
1318
1319 // Copyright (c) Microsoft Corporation. All rights reserved.
1320 function isWebResourceLike(object) {
1321 if (typeof object !== "object") {
1322 return false;
1323 }
1324 if (typeof object.url === "string" &&
1325 typeof object.method === "string" &&
1326 typeof object.headers === "object" &&
1327 isHttpHeadersLike(object.headers) &&
1328 typeof object.validateRequestProperties === "function" &&
1329 typeof object.prepare === "function" &&
1330 typeof object.clone === "function") {
1331 return true;
1332 }
1333 return false;
1334 }
1335 /**
1336 * Creates a new WebResource object.
1337 *
1338 * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
1339 * properties to initiate a request.
1340 *
1341 * @constructor
1342 */
1343 var WebResource = /** @class */ (function () {
1344 function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings, redirectLimit) {
1345 this.streamResponseBody = streamResponseBody;
1346 this.url = url || "";
1347 this.method = method || "GET";
1348 this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers);
1349 this.body = body;
1350 this.query = query;
1351 this.formData = undefined;
1352 this.withCredentials = withCredentials || false;
1353 this.abortSignal = abortSignal;
1354 this.timeout = timeout || 0;
1355 this.onUploadProgress = onUploadProgress;
1356 this.onDownloadProgress = onDownloadProgress;
1357 this.proxySettings = proxySettings;
1358 this.keepAlive = keepAlive;
1359 this.agentSettings = agentSettings;
1360 this.redirectLimit = redirectLimit;
1361 }
1362 /**
1363 * Validates that the required properties such as method, url, headers["Content-Type"],
1364 * headers["accept-language"] are defined. It will throw an error if one of the above
1365 * mentioned properties are not defined.
1366 */
1367 WebResource.prototype.validateRequestProperties = function () {
1368 if (!this.method) {
1369 throw new Error("WebResource.method is required.");
1370 }
1371 if (!this.url) {
1372 throw new Error("WebResource.url is required.");
1373 }
1374 };
1375 /**
1376 * Prepares the request.
1377 * @param {RequestPrepareOptions} options Options to provide for preparing the request.
1378 * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.
1379 */
1380 WebResource.prototype.prepare = function (options) {
1381 if (!options) {
1382 throw new Error("options object is required");
1383 }
1384 if (options.method == undefined || typeof options.method.valueOf() !== "string") {
1385 throw new Error("options.method must be a string.");
1386 }
1387 if (options.url && options.pathTemplate) {
1388 throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.");
1389 }
1390 if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") &&
1391 (options.url == undefined || typeof options.url.valueOf() !== "string")) {
1392 throw new Error("Please provide exactly one of options.pathTemplate or options.url.");
1393 }
1394 // set the url if it is provided.
1395 if (options.url) {
1396 if (typeof options.url !== "string") {
1397 throw new Error('options.url must be of type "string".');
1398 }
1399 this.url = options.url;
1400 }
1401 // set the method
1402 if (options.method) {
1403 var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"];
1404 if (validMethods.indexOf(options.method.toUpperCase()) === -1) {
1405 throw new Error('The provided method "' +
1406 options.method +
1407 '" is invalid. Supported HTTP methods are: ' +
1408 JSON.stringify(validMethods));
1409 }
1410 }
1411 this.method = options.method.toUpperCase();
1412 // construct the url if path template is provided
1413 if (options.pathTemplate) {
1414 var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;
1415 if (typeof pathTemplate_1 !== "string") {
1416 throw new Error('options.pathTemplate must be of type "string".');
1417 }
1418 if (!options.baseUrl) {
1419 options.baseUrl = "https://management.azure.com";
1420 }
1421 var baseUrl = options.baseUrl;
1422 var url_1 = baseUrl +
1423 (baseUrl.endsWith("/") ? "" : "/") +
1424 (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1);
1425 var segments = url_1.match(/({\w*\s*\w*})/gi);
1426 if (segments && segments.length) {
1427 if (!pathParameters_1) {
1428 throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided.");
1429 }
1430 segments.forEach(function (item) {
1431 var pathParamName = item.slice(1, -1);
1432 var pathParam = pathParameters_1[pathParamName];
1433 if (pathParam === null ||
1434 pathParam === undefined ||
1435 !(typeof pathParam === "string" || typeof pathParam === "object")) {
1436 throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName +
1437 (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") +
1438 ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") +
1439 ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }."));
1440 }
1441 if (typeof pathParam.valueOf() === "string") {
1442 url_1 = url_1.replace(item, encodeURIComponent(pathParam));
1443 }
1444 if (typeof pathParam.valueOf() === "object") {
1445 if (!pathParam.value) {
1446 throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
1447 }
1448 if (pathParam.skipUrlEncoding) {
1449 url_1 = url_1.replace(item, pathParam.value);
1450 }
1451 else {
1452 url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));
1453 }
1454 }
1455 });
1456 }
1457 this.url = url_1;
1458 }
1459 // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.
1460 if (options.queryParameters) {
1461 var queryParameters = options.queryParameters;
1462 if (typeof queryParameters !== "object") {
1463 throw new Error("options.queryParameters must be of type object. It should be a JSON object " +
1464 "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " +
1465 "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }.");
1466 }
1467 // append question mark if it is not present in the url
1468 if (this.url && this.url.indexOf("?") === -1) {
1469 this.url += "?";
1470 }
1471 // construct queryString
1472 var queryParams = [];
1473 // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().
1474 this.query = {};
1475 for (var queryParamName in queryParameters) {
1476 var queryParam = queryParameters[queryParamName];
1477 if (queryParam) {
1478 if (typeof queryParam === "string") {
1479 queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam));
1480 this.query[queryParamName] = encodeURIComponent(queryParam);
1481 }
1482 else if (typeof queryParam === "object") {
1483 if (!queryParam.value) {
1484 throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
1485 }
1486 if (queryParam.skipUrlEncoding) {
1487 queryParams.push(queryParamName + "=" + queryParam.value);
1488 this.query[queryParamName] = queryParam.value;
1489 }
1490 else {
1491 queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value));
1492 this.query[queryParamName] = encodeURIComponent(queryParam.value);
1493 }
1494 }
1495 }
1496 } // end-of-for
1497 // append the queryString
1498 this.url += queryParams.join("&");
1499 }
1500 // add headers to the request if they are provided
1501 if (options.headers) {
1502 var headers = options.headers;
1503 for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {
1504 var headerName = _a[_i];
1505 this.headers.set(headerName, headers[headerName]);
1506 }
1507 }
1508 // ensure accept-language is set correctly
1509 if (!this.headers.get("accept-language")) {
1510 this.headers.set("accept-language", "en-US");
1511 }
1512 // ensure the request-id is set correctly
1513 if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) {
1514 this.headers.set("x-ms-client-request-id", generateUuid());
1515 }
1516 // default
1517 if (!this.headers.get("Content-Type")) {
1518 this.headers.set("Content-Type", "application/json; charset=utf-8");
1519 }
1520 // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty
1521 this.body = options.body;
1522 if (options.body != undefined) {
1523 // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.
1524 if (options.bodyIsStream) {
1525 if (!this.headers.get("Transfer-Encoding")) {
1526 this.headers.set("Transfer-Encoding", "chunked");
1527 }
1528 if (this.headers.get("Content-Type") !== "application/octet-stream") {
1529 this.headers.set("Content-Type", "application/octet-stream");
1530 }
1531 }
1532 else {
1533 if (options.serializationMapper) {
1534 this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody");
1535 }
1536 if (!options.disableJsonStringifyOnBody) {
1537 this.body = JSON.stringify(options.body);
1538 }
1539 }
1540 }
1541 this.abortSignal = options.abortSignal;
1542 this.onDownloadProgress = options.onDownloadProgress;
1543 this.onUploadProgress = options.onUploadProgress;
1544 this.redirectLimit = options.redirectLimit;
1545 this.streamResponseBody = options.streamResponseBody;
1546 return this;
1547 };
1548 /**
1549 * Clone this WebResource HTTP request object.
1550 * @returns {WebResource} The clone of this WebResource HTTP request object.
1551 */
1552 WebResource.prototype.clone = function () {
1553 var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings, this.redirectLimit);
1554 if (this.formData) {
1555 result.formData = this.formData;
1556 }
1557 if (this.operationSpec) {
1558 result.operationSpec = this.operationSpec;
1559 }
1560 if (this.shouldDeserialize) {
1561 result.shouldDeserialize = this.shouldDeserialize;
1562 }
1563 if (this.operationResponseGetter) {
1564 result.operationResponseGetter = this.operationResponseGetter;
1565 }
1566 return result;
1567 };
1568 return WebResource;
1569 }());
1570
1571 /*! *****************************************************************************
1572 Copyright (c) Microsoft Corporation.
1573
1574 Permission to use, copy, modify, and/or distribute this software for any
1575 purpose with or without fee is hereby granted.
1576
1577 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1578 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1579 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1580 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1581 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1582 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1583 PERFORMANCE OF THIS SOFTWARE.
1584 ***************************************************************************** */
1585 /* global Reflect, Promise */
1586
1587 var extendStatics = function(d, b) {
1588 extendStatics = Object.setPrototypeOf ||
1589 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1590 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
1591 return extendStatics(d, b);
1592 };
1593
1594 function __extends(d, b) {
1595 extendStatics(d, b);
1596 function __() { this.constructor = d; }
1597 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1598 }
1599
1600 var __assign = function() {
1601 __assign = Object.assign || function __assign(t) {
1602 for (var s, i = 1, n = arguments.length; i < n; i++) {
1603 s = arguments[i];
1604 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
1605 }
1606 return t;
1607 };
1608 return __assign.apply(this, arguments);
1609 };
1610
1611 function __awaiter(thisArg, _arguments, P, generator) {
1612 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1613 return new (P || (P = Promise))(function (resolve, reject) {
1614 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1615 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1616 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1617 step((generator = generator.apply(thisArg, _arguments || [])).next());
1618 });
1619 }
1620
1621 function __generator(thisArg, body) {
1622 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1623 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1624 function verb(n) { return function (v) { return step([n, v]); }; }
1625 function step(op) {
1626 if (f) throw new TypeError("Generator is already executing.");
1627 while (_) try {
1628 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1629 if (y = 0, t) op = [op[0] & 2, t.value];
1630 switch (op[0]) {
1631 case 0: case 1: t = op; break;
1632 case 4: _.label++; return { value: op[1], done: false };
1633 case 5: _.label++; y = op[1]; op = [0]; continue;
1634 case 7: op = _.ops.pop(); _.trys.pop(); continue;
1635 default:
1636 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1637 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1638 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1639 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1640 if (t[2]) _.ops.pop();
1641 _.trys.pop(); continue;
1642 }
1643 op = body.call(thisArg, _);
1644 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1645 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1646 }
1647 }
1648
1649 function __spreadArrays() {
1650 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1651 for (var r = Array(s), k = 0, i = 0; i < il; i++)
1652 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1653 r[k] = a[j];
1654 return r;
1655 }
1656
1657 // Copyright (c) Microsoft Corporation. All rights reserved.
1658 var RestError = /** @class */ (function (_super) {
1659 __extends(RestError, _super);
1660 function RestError(message, code, statusCode, request, response, body) {
1661 var _this = _super.call(this, message) || this;
1662 _this.code = code;
1663 _this.statusCode = statusCode;
1664 _this.request = request;
1665 _this.response = response;
1666 _this.body = body;
1667 Object.setPrototypeOf(_this, RestError.prototype);
1668 return _this;
1669 }
1670 RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
1671 RestError.REQUEST_ABORTED_ERROR = "REQUEST_ABORTED_ERROR";
1672 RestError.PARSE_ERROR = "PARSE_ERROR";
1673 return RestError;
1674 }(Error));
1675
1676 // Copyright (c) Microsoft Corporation. All rights reserved.
1677 /**
1678 * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests.
1679 */
1680 var XhrHttpClient = /** @class */ (function () {
1681 function XhrHttpClient() {
1682 }
1683 XhrHttpClient.prototype.sendRequest = function (request) {
1684 var xhr = new XMLHttpRequest();
1685 if (request.agentSettings) {
1686 throw new Error("HTTP agent settings not supported in browser environment");
1687 }
1688 if (request.proxySettings) {
1689 throw new Error("HTTP proxy is not supported in browser environment");
1690 }
1691 var abortSignal = request.abortSignal;
1692 if (abortSignal) {
1693 var listener_1 = function () {
1694 xhr.abort();
1695 };
1696 abortSignal.addEventListener("abort", listener_1);
1697 xhr.addEventListener("readystatechange", function () {
1698 if (xhr.readyState === XMLHttpRequest.DONE) {
1699 abortSignal.removeEventListener("abort", listener_1);
1700 }
1701 });
1702 }
1703 addProgressListener(xhr.upload, request.onUploadProgress);
1704 addProgressListener(xhr, request.onDownloadProgress);
1705 if (request.formData) {
1706 var formData = request.formData;
1707 var requestForm_1 = new FormData();
1708 var appendFormValue = function (key, value) {
1709 if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
1710 requestForm_1.append(key, value.value, value.options);
1711 }
1712 else {
1713 requestForm_1.append(key, value);
1714 }
1715 };
1716 for (var _i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {
1717 var formKey = _a[_i];
1718 var formValue = formData[formKey];
1719 if (Array.isArray(formValue)) {
1720 for (var j = 0; j < formValue.length; j++) {
1721 appendFormValue(formKey, formValue[j]);
1722 }
1723 }
1724 else {
1725 appendFormValue(formKey, formValue);
1726 }
1727 }
1728 request.body = requestForm_1;
1729 request.formData = undefined;
1730 var contentType = request.headers.get("Content-Type");
1731 if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
1732 // browser will automatically apply a suitable content-type header
1733 request.headers.remove("Content-Type");
1734 }
1735 }
1736 xhr.open(request.method, request.url);
1737 xhr.timeout = request.timeout;
1738 xhr.withCredentials = request.withCredentials;
1739 for (var _b = 0, _c = request.headers.headersArray(); _b < _c.length; _b++) {
1740 var header = _c[_b];
1741 xhr.setRequestHeader(header.name, header.value);
1742 }
1743 xhr.responseType = request.streamResponseBody ? "blob" : "text";
1744 // tslint:disable-next-line:no-null-keyword
1745 xhr.send(request.body === undefined ? null : request.body);
1746 if (request.streamResponseBody) {
1747 return new Promise(function (resolve, reject) {
1748 xhr.addEventListener("readystatechange", function () {
1749 // Resolve as soon as headers are loaded
1750 if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
1751 var blobBody = new Promise(function (resolve, reject) {
1752 xhr.addEventListener("load", function () {
1753 resolve(xhr.response);
1754 });
1755 rejectOnTerminalEvent(request, xhr, reject);
1756 });
1757 resolve({
1758 request: request,
1759 status: xhr.status,
1760 headers: parseHeaders(xhr),
1761 blobBody: blobBody,
1762 });
1763 }
1764 });
1765 rejectOnTerminalEvent(request, xhr, reject);
1766 });
1767 }
1768 else {
1769 return new Promise(function (resolve, reject) {
1770 xhr.addEventListener("load", function () {
1771 return resolve({
1772 request: request,
1773 status: xhr.status,
1774 headers: parseHeaders(xhr),
1775 bodyAsText: xhr.responseText,
1776 });
1777 });
1778 rejectOnTerminalEvent(request, xhr, reject);
1779 });
1780 }
1781 };
1782 return XhrHttpClient;
1783 }());
1784 function addProgressListener(xhr, listener) {
1785 if (listener) {
1786 xhr.addEventListener("progress", function (rawEvent) {
1787 return listener({
1788 loadedBytes: rawEvent.loaded,
1789 });
1790 });
1791 }
1792 }
1793 // exported locally for testing
1794 function parseHeaders(xhr) {
1795 var responseHeaders = new HttpHeaders();
1796 var headerLines = xhr
1797 .getAllResponseHeaders()
1798 .trim()
1799 .split(/[\r\n]+/);
1800 for (var _i = 0, headerLines_1 = headerLines; _i < headerLines_1.length; _i++) {
1801 var line = headerLines_1[_i];
1802 var index = line.indexOf(":");
1803 var headerName = line.slice(0, index);
1804 var headerValue = line.slice(index + 2);
1805 responseHeaders.set(headerName, headerValue);
1806 }
1807 return responseHeaders;
1808 }
1809 function rejectOnTerminalEvent(request, xhr, reject) {
1810 xhr.addEventListener("error", function () {
1811 return reject(new RestError("Failed to send request to " + request.url, RestError.REQUEST_SEND_ERROR, undefined, request));
1812 });
1813 xhr.addEventListener("abort", function () {
1814 return reject(new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, request));
1815 });
1816 xhr.addEventListener("timeout", function () {
1817 return reject(new RestError("timeout of " + xhr.timeout + "ms exceeded", RestError.REQUEST_SEND_ERROR, undefined, request));
1818 });
1819 }
1820
1821 // Copyright (c) Microsoft Corporation. All rights reserved.
1822 (function (HttpPipelineLogLevel) {
1823 /**
1824 * A log level that indicates that no logs will be logged.
1825 */
1826 HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
1827 /**
1828 * An error log.
1829 */
1830 HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
1831 /**
1832 * A warning log.
1833 */
1834 HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
1835 /**
1836 * An information log.
1837 */
1838 HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
1839 })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));
1840
1841 // Copyright (c) Microsoft Corporation.
1842 // Licensed under the MIT license.
1843 /**
1844 * Tests an object to determine whether it implements TokenCredential.
1845 *
1846 * @param credential - The assumed TokenCredential to be tested.
1847 */
1848 function isTokenCredential(credential) {
1849 // Check for an object with a 'getToken' function and possibly with
1850 // a 'signRequest' function. We do this check to make sure that
1851 // a ServiceClientCredentials implementor (like TokenClientCredentials
1852 // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
1853 // it doesn't actually implement TokenCredential also.
1854 const castCredential = credential;
1855 return (castCredential &&
1856 typeof castCredential.getToken === "function" &&
1857 (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
1858 }
1859
1860 // Copyright (c) Microsoft Corporation. All rights reserved.
1861 // Licensed under the MIT License. See License.txt in the project root for license information.
1862 /**
1863 * Get the path to this parameter's value as a dotted string (a.b.c).
1864 * @param parameter The parameter to get the path string for.
1865 * @returns The path to this parameter's value as a dotted string.
1866 */
1867 function getPathStringFromParameter(parameter) {
1868 return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);
1869 }
1870 function getPathStringFromParameterPath(parameterPath, mapper) {
1871 var result;
1872 if (typeof parameterPath === "string") {
1873 result = parameterPath;
1874 }
1875 else if (Array.isArray(parameterPath)) {
1876 result = parameterPath.join(".");
1877 }
1878 else {
1879 result = mapper.serializedName;
1880 }
1881 return result;
1882 }
1883
1884 // Copyright (c) Microsoft Corporation. All rights reserved.
1885 function isStreamOperation(operationSpec) {
1886 var result = false;
1887 for (var statusCode in operationSpec.responses) {
1888 var operationResponse = operationSpec.responses[statusCode];
1889 if (operationResponse.bodyMapper &&
1890 operationResponse.bodyMapper.type.name === MapperType.Stream) {
1891 result = true;
1892 break;
1893 }
1894 }
1895 return result;
1896 }
1897
1898 // Copyright (c) Microsoft Corporation. All rights reserved.
1899 // Licensed under the MIT License. See License.txt in the project root for license information.
1900 var parser = new DOMParser();
1901 function parseXML(str) {
1902 try {
1903 var dom = parser.parseFromString(str, "application/xml");
1904 throwIfError(dom);
1905 var obj = domToObject(dom.childNodes[0]);
1906 return Promise.resolve(obj);
1907 }
1908 catch (err) {
1909 return Promise.reject(err);
1910 }
1911 }
1912 var errorNS = "";
1913 try {
1914 errorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0]
1915 .namespaceURI;
1916 }
1917 catch (ignored) {
1918 // Most browsers will return a document containing <parsererror>, but IE will throw.
1919 }
1920 function throwIfError(dom) {
1921 if (errorNS) {
1922 var parserErrors = dom.getElementsByTagNameNS(errorNS, "parsererror");
1923 if (parserErrors.length) {
1924 throw new Error(parserErrors.item(0).innerHTML);
1925 }
1926 }
1927 }
1928 function isElement(node) {
1929 return !!node.attributes;
1930 }
1931 /**
1932 * Get the Element-typed version of the provided Node if the provided node is an element with
1933 * attributes. If it isn't, then undefined is returned.
1934 */
1935 function asElementWithAttributes(node) {
1936 return isElement(node) && node.hasAttributes() ? node : undefined;
1937 }
1938 function domToObject(node) {
1939 var result = {};
1940 var childNodeCount = node.childNodes.length;
1941 var firstChildNode = node.childNodes[0];
1942 var onlyChildTextValue = (firstChildNode &&
1943 childNodeCount === 1 &&
1944 firstChildNode.nodeType === Node.TEXT_NODE &&
1945 firstChildNode.nodeValue) ||
1946 undefined;
1947 var elementWithAttributes = asElementWithAttributes(node);
1948 if (elementWithAttributes) {
1949 result["$"] = {};
1950 for (var i = 0; i < elementWithAttributes.attributes.length; i++) {
1951 var attr = elementWithAttributes.attributes[i];
1952 result["$"][attr.nodeName] = attr.nodeValue;
1953 }
1954 if (onlyChildTextValue) {
1955 result["_"] = onlyChildTextValue;
1956 }
1957 }
1958 else if (childNodeCount === 0) {
1959 result = "";
1960 }
1961 else if (onlyChildTextValue) {
1962 result = onlyChildTextValue;
1963 }
1964 if (!onlyChildTextValue) {
1965 for (var i = 0; i < childNodeCount; i++) {
1966 var child = node.childNodes[i];
1967 // Ignore leading/trailing whitespace nodes
1968 if (child.nodeType !== Node.TEXT_NODE) {
1969 var childObject = domToObject(child);
1970 if (!result[child.nodeName]) {
1971 result[child.nodeName] = childObject;
1972 }
1973 else if (Array.isArray(result[child.nodeName])) {
1974 result[child.nodeName].push(childObject);
1975 }
1976 else {
1977 result[child.nodeName] = [result[child.nodeName], childObject];
1978 }
1979 }
1980 }
1981 }
1982 return result;
1983 }
1984 // tslint:disable-next-line:no-null-keyword
1985 var doc = document.implementation.createDocument(null, null, null);
1986 var serializer = new XMLSerializer();
1987 function stringifyXML(obj, opts) {
1988 var rootName = (opts && opts.rootName) || "root";
1989 var dom = buildNode(obj, rootName)[0];
1990 return ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + serializer.serializeToString(dom));
1991 }
1992 function buildAttributes(attrs) {
1993 var result = [];
1994 for (var _i = 0, _a = Object.keys(attrs); _i < _a.length; _i++) {
1995 var key = _a[_i];
1996 var attr = doc.createAttribute(key);
1997 attr.value = attrs[key].toString();
1998 result.push(attr);
1999 }
2000 return result;
2001 }
2002 function buildNode(obj, elementName) {
2003 if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") {
2004 var elem = doc.createElement(elementName);
2005 elem.textContent = obj.toString();
2006 return [elem];
2007 }
2008 else if (Array.isArray(obj)) {
2009 var result = [];
2010 for (var _i = 0, obj_1 = obj; _i < obj_1.length; _i++) {
2011 var arrayElem = obj_1[_i];
2012 for (var _a = 0, _b = buildNode(arrayElem, elementName); _a < _b.length; _a++) {
2013 var child = _b[_a];
2014 result.push(child);
2015 }
2016 }
2017 return result;
2018 }
2019 else if (typeof obj === "object") {
2020 var elem = doc.createElement(elementName);
2021 for (var _c = 0, _d = Object.keys(obj); _c < _d.length; _c++) {
2022 var key = _d[_c];
2023 if (key === "$") {
2024 for (var _e = 0, _f = buildAttributes(obj[key]); _e < _f.length; _e++) {
2025 var attr = _f[_e];
2026 elem.attributes.setNamedItem(attr);
2027 }
2028 }
2029 else {
2030 for (var _g = 0, _h = buildNode(obj[key], key); _g < _h.length; _g++) {
2031 var child = _h[_g];
2032 elem.appendChild(child);
2033 }
2034 }
2035 }
2036 return [elem];
2037 }
2038 else {
2039 throw new Error("Illegal value passed to buildObject: " + obj);
2040 }
2041 }
2042
2043 // Copyright (c) Microsoft Corporation. All rights reserved.
2044 var BaseRequestPolicy = /** @class */ (function () {
2045 function BaseRequestPolicy(_nextPolicy, _options) {
2046 this._nextPolicy = _nextPolicy;
2047 this._options = _options;
2048 }
2049 /**
2050 * Get whether or not a log with the provided log level should be logged.
2051 * @param logLevel The log level of the log that will be logged.
2052 * @returns Whether or not a log with the provided log level should be logged.
2053 */
2054 BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
2055 return this._options.shouldLog(logLevel);
2056 };
2057 /**
2058 * Attempt to log the provided message to the provided logger. If no logger was provided or if
2059 * the log level does not meat the logger's threshold, then nothing will be logged.
2060 * @param logLevel The log level of this log.
2061 * @param message The message of this log.
2062 */
2063 BaseRequestPolicy.prototype.log = function (logLevel, message) {
2064 this._options.log(logLevel, message);
2065 };
2066 return BaseRequestPolicy;
2067 }());
2068 /**
2069 * Optional properties that can be used when creating a RequestPolicy.
2070 */
2071 var RequestPolicyOptions = /** @class */ (function () {
2072 function RequestPolicyOptions(_logger) {
2073 this._logger = _logger;
2074 }
2075 /**
2076 * Get whether or not a log with the provided log level should be logged.
2077 * @param logLevel The log level of the log that will be logged.
2078 * @returns Whether or not a log with the provided log level should be logged.
2079 */
2080 RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
2081 return (!!this._logger &&
2082 logLevel !== exports.HttpPipelineLogLevel.OFF &&
2083 logLevel <= this._logger.minimumLogLevel);
2084 };
2085 /**
2086 * Attempt to log the provided message to the provided logger. If no logger was provided or if
2087 * the log level does not meat the logger's threshold, then nothing will be logged.
2088 * @param logLevel The log level of this log.
2089 * @param message The message of this log.
2090 */
2091 RequestPolicyOptions.prototype.log = function (logLevel, message) {
2092 if (this._logger && this.shouldLog(logLevel)) {
2093 this._logger.log(logLevel, message);
2094 }
2095 };
2096 return RequestPolicyOptions;
2097 }());
2098
2099 // Copyright (c) Microsoft Corporation. All rights reserved.
2100 /**
2101 * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
2102 * pass through the HTTP pipeline.
2103 */
2104 function deserializationPolicy(deserializationContentTypes) {
2105 return {
2106 create: function (nextPolicy, options) {
2107 return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
2108 },
2109 };
2110 }
2111 var defaultJsonContentTypes = ["application/json", "text/json"];
2112 var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
2113 /**
2114 * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
2115 * HTTP pipeline.
2116 */
2117 var DeserializationPolicy = /** @class */ (function (_super) {
2118 __extends(DeserializationPolicy, _super);
2119 function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
2120 var _this = _super.call(this, nextPolicy, options) || this;
2121 _this.jsonContentTypes =
2122 (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes;
2123 _this.xmlContentTypes =
2124 (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes;
2125 return _this;
2126 }
2127 DeserializationPolicy.prototype.sendRequest = function (request) {
2128 return __awaiter(this, void 0, void 0, function () {
2129 var _this = this;
2130 return __generator(this, function (_a) {
2131 return [2 /*return*/, this._nextPolicy
2132 .sendRequest(request)
2133 .then(function (response) {
2134 return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response);
2135 })];
2136 });
2137 });
2138 };
2139 return DeserializationPolicy;
2140 }(BaseRequestPolicy));
2141 function getOperationResponse(parsedResponse) {
2142 var result;
2143 var request = parsedResponse.request;
2144 var operationSpec = request.operationSpec;
2145 if (operationSpec) {
2146 var operationResponseGetter = request.operationResponseGetter;
2147 if (!operationResponseGetter) {
2148 result = operationSpec.responses[parsedResponse.status];
2149 }
2150 else {
2151 result = operationResponseGetter(operationSpec, parsedResponse);
2152 }
2153 }
2154 return result;
2155 }
2156 function shouldDeserializeResponse(parsedResponse) {
2157 var shouldDeserialize = parsedResponse.request.shouldDeserialize;
2158 var result;
2159 if (shouldDeserialize === undefined) {
2160 result = true;
2161 }
2162 else if (typeof shouldDeserialize === "boolean") {
2163 result = shouldDeserialize;
2164 }
2165 else {
2166 result = shouldDeserialize(parsedResponse);
2167 }
2168 return result;
2169 }
2170 function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
2171 return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
2172 var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
2173 if (shouldDeserialize) {
2174 var operationSpec = parsedResponse.request.operationSpec;
2175 if (operationSpec && operationSpec.responses) {
2176 var statusCode = parsedResponse.status;
2177 var expectedStatusCodes = Object.keys(operationSpec.responses);
2178 var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 ||
2179 (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default");
2180 var responseSpec = getOperationResponse(parsedResponse);
2181 var isExpectedStatusCode = hasNoExpectedStatusCodes
2182 ? 200 <= statusCode && statusCode < 300
2183 : !!responseSpec;
2184 if (!isExpectedStatusCode) {
2185 var defaultResponseSpec = operationSpec.responses.default;
2186 if (defaultResponseSpec) {
2187 var initialErrorMessage = isStreamOperation(operationSpec)
2188 ? "Unexpected status code: " + statusCode
2189 : parsedResponse.bodyAsText;
2190 var error = new RestError(initialErrorMessage);
2191 error.statusCode = statusCode;
2192 error.request = stripRequest(parsedResponse.request);
2193 error.response = stripResponse(parsedResponse);
2194 var parsedErrorResponse = parsedResponse.parsedBody;
2195 try {
2196 if (parsedErrorResponse) {
2197 var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
2198 if (defaultResponseBodyMapper &&
2199 defaultResponseBodyMapper.serializedName === "CloudError") {
2200 if (parsedErrorResponse.error) {
2201 parsedErrorResponse = parsedErrorResponse.error;
2202 }
2203 if (parsedErrorResponse.code) {
2204 error.code = parsedErrorResponse.code;
2205 }
2206 if (parsedErrorResponse.message) {
2207 error.message = parsedErrorResponse.message;
2208 }
2209 }
2210 else {
2211 var internalError = parsedErrorResponse;
2212 if (parsedErrorResponse.error) {
2213 internalError = parsedErrorResponse.error;
2214 }
2215 error.code = internalError.code;
2216 if (internalError.message) {
2217 error.message = internalError.message;
2218 }
2219 }
2220 if (defaultResponseBodyMapper) {
2221 var valueToDeserialize = parsedErrorResponse;
2222 if (operationSpec.isXML &&
2223 defaultResponseBodyMapper.type.name === MapperType.Sequence) {
2224 valueToDeserialize =
2225 typeof parsedErrorResponse === "object"
2226 ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
2227 : [];
2228 }
2229 error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
2230 }
2231 }
2232 }
2233 catch (defaultError) {
2234 error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
2235 }
2236 return Promise.reject(error);
2237 }
2238 }
2239 else if (responseSpec) {
2240 if (responseSpec.bodyMapper) {
2241 var valueToDeserialize = parsedResponse.parsedBody;
2242 if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
2243 valueToDeserialize =
2244 typeof valueToDeserialize === "object"
2245 ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
2246 : [];
2247 }
2248 try {
2249 parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
2250 }
2251 catch (error) {
2252 var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
2253 restError.request = stripRequest(parsedResponse.request);
2254 restError.response = stripResponse(parsedResponse);
2255 return Promise.reject(restError);
2256 }
2257 }
2258 else if (operationSpec.httpMethod === "HEAD") {
2259 // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
2260 parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
2261 }
2262 if (responseSpec.headersMapper) {
2263 parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
2264 }
2265 }
2266 }
2267 }
2268 return Promise.resolve(parsedResponse);
2269 });
2270 }
2271 function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
2272 var errorHandler = function (err) {
2273 var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
2274 var errCode = err.code || RestError.PARSE_ERROR;
2275 var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
2276 return Promise.reject(e);
2277 };
2278 if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
2279 var text_1 = operationResponse.bodyAsText;
2280 var contentType = operationResponse.headers.get("Content-Type") || "";
2281 var contentComponents = !contentType
2282 ? []
2283 : contentType.split(";").map(function (component) { return component.toLowerCase(); });
2284 if (contentComponents.length === 0 ||
2285 contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
2286 return new Promise(function (resolve) {
2287 operationResponse.parsedBody = JSON.parse(text_1);
2288 resolve(operationResponse);
2289 }).catch(errorHandler);
2290 }
2291 else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
2292 return parseXML(text_1)
2293 .then(function (body) {
2294 operationResponse.parsedBody = body;
2295 return operationResponse;
2296 })
2297 .catch(errorHandler);
2298 }
2299 }
2300 return Promise.resolve(operationResponse);
2301 }
2302
2303 // Copyright (c) Microsoft Corporation. All rights reserved.
2304 function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
2305 return {
2306 create: function (nextPolicy, options) {
2307 return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
2308 },
2309 };
2310 }
2311 var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
2312 var DEFAULT_CLIENT_RETRY_COUNT = 3;
2313 var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
2314 var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
2315 /**
2316 * @class
2317 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
2318 */
2319 var ExponentialRetryPolicy = /** @class */ (function (_super) {
2320 __extends(ExponentialRetryPolicy, _super);
2321 /**
2322 * @constructor
2323 * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
2324 * @param {RequestPolicyOptionsLike} options The options for this RequestPolicy.
2325 * @param {number} [retryCount] The client retry count.
2326 * @param {number} [retryInterval] The client retry interval, in milliseconds.
2327 * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
2328 * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
2329 */
2330 function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
2331 var _this = _super.call(this, nextPolicy, options) || this;
2332 function isNumber(n) {
2333 return typeof n === "number";
2334 }
2335 _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
2336 _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
2337 _this.minRetryInterval = isNumber(minRetryInterval)
2338 ? minRetryInterval
2339 : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
2340 _this.maxRetryInterval = isNumber(maxRetryInterval)
2341 ? maxRetryInterval
2342 : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
2343 return _this;
2344 }
2345 ExponentialRetryPolicy.prototype.sendRequest = function (request) {
2346 var _this = this;
2347 return this._nextPolicy
2348 .sendRequest(request.clone())
2349 .then(function (response) { return retry(_this, request, response); })
2350 .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
2351 };
2352 return ExponentialRetryPolicy;
2353 }(BaseRequestPolicy));
2354 /**
2355 * Determines if the operation should be retried and how long to wait until the next retry.
2356 *
2357 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
2358 * @param {number} statusCode The HTTP status code.
2359 * @param {RetryData} retryData The retry data.
2360 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
2361 */
2362 function shouldRetry(policy, statusCode, retryData) {
2363 if (statusCode == undefined ||
2364 (statusCode < 500 && statusCode !== 408) ||
2365 statusCode === 501 ||
2366 statusCode === 505) {
2367 return false;
2368 }
2369 var currentCount;
2370 if (!retryData) {
2371 throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
2372 }
2373 else {
2374 currentCount = retryData && retryData.retryCount;
2375 }
2376 return currentCount < policy.retryCount;
2377 }
2378 /**
2379 * Updates the retry data for the next attempt.
2380 *
2381 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
2382 * @param {RetryData} retryData The retry data.
2383 * @param {RetryError} [err] The operation"s error, if any.
2384 */
2385 function updateRetryData(policy, retryData, err) {
2386 if (!retryData) {
2387 retryData = {
2388 retryCount: 0,
2389 retryInterval: 0,
2390 };
2391 }
2392 if (err) {
2393 if (retryData.error) {
2394 err.innerError = retryData.error;
2395 }
2396 retryData.error = err;
2397 }
2398 // Adjust retry count
2399 retryData.retryCount++;
2400 // Adjust retry interval
2401 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
2402 var boundedRandDelta = policy.retryInterval * 0.8 +
2403 Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
2404 incrementDelta *= boundedRandDelta;
2405 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
2406 return retryData;
2407 }
2408 function retry(policy, request, response, retryData, requestError) {
2409 retryData = updateRetryData(policy, retryData, requestError);
2410 var isAborted = request.abortSignal && request.abortSignal.aborted;
2411 if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
2412 return delay(retryData.retryInterval)
2413 .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
2414 .then(function (res) { return retry(policy, request, res, retryData, undefined); })
2415 .catch(function (err) { return retry(policy, request, response, retryData, err); });
2416 }
2417 else if (isAborted || requestError || !response) {
2418 // If the operation failed in the end, return all errors instead of just the last one
2419 var err = retryData.error ||
2420 new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
2421 return Promise.reject(err);
2422 }
2423 else {
2424 return Promise.resolve(response);
2425 }
2426 }
2427
2428 // Copyright (c) Microsoft Corporation. All rights reserved.
2429 function generateClientRequestIdPolicy(requestIdHeaderName) {
2430 if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
2431 return {
2432 create: function (nextPolicy, options) {
2433 return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
2434 },
2435 };
2436 }
2437 var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
2438 __extends(GenerateClientRequestIdPolicy, _super);
2439 function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
2440 var _this = _super.call(this, nextPolicy, options) || this;
2441 _this._requestIdHeaderName = _requestIdHeaderName;
2442 return _this;
2443 }
2444 GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
2445 if (!request.headers.contains(this._requestIdHeaderName)) {
2446 request.headers.set(this._requestIdHeaderName, generateUuid());
2447 }
2448 return this._nextPolicy.sendRequest(request);
2449 };
2450 return GenerateClientRequestIdPolicy;
2451 }(BaseRequestPolicy));
2452
2453 // Copyright (c) Microsoft Corporation. All rights reserved.
2454 // Licensed under the MIT License. See License.txt in the project root for license information.
2455 function getDefaultUserAgentKey() {
2456 return "x-ms-command-name";
2457 }
2458 function getPlatformSpecificData() {
2459 var navigator = self.navigator;
2460 var osInfo = {
2461 key: "OS",
2462 value: (navigator.oscpu || navigator.platform).replace(" ", ""),
2463 };
2464 return [osInfo];
2465 }
2466
2467 // Copyright (c) Microsoft Corporation. All rights reserved.
2468 function getRuntimeInfo() {
2469 var msRestRuntime = {
2470 key: "ms-rest-js",
2471 value: Constants.msRestVersion,
2472 };
2473 return [msRestRuntime];
2474 }
2475 function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
2476 if (keySeparator === void 0) { keySeparator = " "; }
2477 if (valueSeparator === void 0) { valueSeparator = "/"; }
2478 return telemetryInfo
2479 .map(function (info) {
2480 var value = info.value ? "" + valueSeparator + info.value : "";
2481 return "" + info.key + value;
2482 })
2483 .join(keySeparator);
2484 }
2485 var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
2486 function getDefaultUserAgentValue() {
2487 var runtimeInfo = getRuntimeInfo();
2488 var platformSpecificData = getPlatformSpecificData();
2489 var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
2490 return userAgent;
2491 }
2492 function userAgentPolicy(userAgentData) {
2493 var key = !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key;
2494 var value = !userAgentData || userAgentData.value == undefined
2495 ? getDefaultUserAgentValue()
2496 : userAgentData.value;
2497 return {
2498 create: function (nextPolicy, options) {
2499 return new UserAgentPolicy(nextPolicy, options, key, value);
2500 },
2501 };
2502 }
2503 var UserAgentPolicy = /** @class */ (function (_super) {
2504 __extends(UserAgentPolicy, _super);
2505 function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
2506 var _this = _super.call(this, _nextPolicy, _options) || this;
2507 _this._nextPolicy = _nextPolicy;
2508 _this._options = _options;
2509 _this.headerKey = headerKey;
2510 _this.headerValue = headerValue;
2511 return _this;
2512 }
2513 UserAgentPolicy.prototype.sendRequest = function (request) {
2514 this.addUserAgentHeader(request);
2515 return this._nextPolicy.sendRequest(request);
2516 };
2517 UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
2518 if (!request.headers) {
2519 request.headers = new HttpHeaders();
2520 }
2521 if (!request.headers.get(this.headerKey) && this.headerValue) {
2522 request.headers.set(this.headerKey, this.headerValue);
2523 }
2524 };
2525 return UserAgentPolicy;
2526 }(BaseRequestPolicy));
2527
2528 // Copyright (c) Microsoft Corporation. All rights reserved.
2529 /**
2530 * A class that handles the query portion of a URLBuilder.
2531 */
2532 var URLQuery = /** @class */ (function () {
2533 function URLQuery() {
2534 this._rawQuery = {};
2535 }
2536 /**
2537 * Get whether or not there any query parameters in this URLQuery.
2538 */
2539 URLQuery.prototype.any = function () {
2540 return Object.keys(this._rawQuery).length > 0;
2541 };
2542 /**
2543 * Set a query parameter with the provided name and value. If the parameterValue is undefined or
2544 * empty, then this will attempt to remove an existing query parameter with the provided
2545 * parameterName.
2546 */
2547 URLQuery.prototype.set = function (parameterName, parameterValue) {
2548 if (parameterName) {
2549 if (parameterValue != undefined) {
2550 var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
2551 this._rawQuery[parameterName] = newValue;
2552 }
2553 else {
2554 delete this._rawQuery[parameterName];
2555 }
2556 }
2557 };
2558 /**
2559 * Get the value of the query parameter with the provided name. If no parameter exists with the
2560 * provided parameter name, then undefined will be returned.
2561 */
2562 URLQuery.prototype.get = function (parameterName) {
2563 return parameterName ? this._rawQuery[parameterName] : undefined;
2564 };
2565 /**
2566 * Get the string representation of this query. The return value will not start with a "?".
2567 */
2568 URLQuery.prototype.toString = function () {
2569 var result = "";
2570 for (var parameterName in this._rawQuery) {
2571 if (result) {
2572 result += "&";
2573 }
2574 var parameterValue = this._rawQuery[parameterName];
2575 if (Array.isArray(parameterValue)) {
2576 var parameterStrings = [];
2577 for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
2578 var parameterValueElement = parameterValue_1[_i];
2579 parameterStrings.push(parameterName + "=" + parameterValueElement);
2580 }
2581 result += parameterStrings.join("&");
2582 }
2583 else {
2584 result += parameterName + "=" + parameterValue;
2585 }
2586 }
2587 return result;
2588 };
2589 /**
2590 * Parse a URLQuery from the provided text.
2591 */
2592 URLQuery.parse = function (text) {
2593 var result = new URLQuery();
2594 if (text) {
2595 if (text.startsWith("?")) {
2596 text = text.substring(1);
2597 }
2598 var currentState = "ParameterName";
2599 var parameterName = "";
2600 var parameterValue = "";
2601 for (var i = 0; i < text.length; ++i) {
2602 var currentCharacter = text[i];
2603 switch (currentState) {
2604 case "ParameterName":
2605 switch (currentCharacter) {
2606 case "=":
2607 currentState = "ParameterValue";
2608 break;
2609 case "&":
2610 parameterName = "";
2611 parameterValue = "";
2612 break;
2613 default:
2614 parameterName += currentCharacter;
2615 break;
2616 }
2617 break;
2618 case "ParameterValue":
2619 switch (currentCharacter) {
2620 case "&":
2621 result.set(parameterName, parameterValue);
2622 parameterName = "";
2623 parameterValue = "";
2624 currentState = "ParameterName";
2625 break;
2626 default:
2627 parameterValue += currentCharacter;
2628 break;
2629 }
2630 break;
2631 default:
2632 throw new Error("Unrecognized URLQuery parse state: " + currentState);
2633 }
2634 }
2635 if (currentState === "ParameterValue") {
2636 result.set(parameterName, parameterValue);
2637 }
2638 }
2639 return result;
2640 };
2641 return URLQuery;
2642 }());
2643 /**
2644 * A class that handles creating, modifying, and parsing URLs.
2645 */
2646 var URLBuilder = /** @class */ (function () {
2647 function URLBuilder() {
2648 }
2649 /**
2650 * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
2651 * (such as a host, port, path, or query), those parts will be added to this URL as well.
2652 */
2653 URLBuilder.prototype.setScheme = function (scheme) {
2654 if (!scheme) {
2655 this._scheme = undefined;
2656 }
2657 else {
2658 this.set(scheme, "SCHEME");
2659 }
2660 };
2661 /**
2662 * Get the scheme that has been set in this URL.
2663 */
2664 URLBuilder.prototype.getScheme = function () {
2665 return this._scheme;
2666 };
2667 /**
2668 * Set the host for this URL. If the provided host contains other parts of a URL (such as a
2669 * port, path, or query), those parts will be added to this URL as well.
2670 */
2671 URLBuilder.prototype.setHost = function (host) {
2672 if (!host) {
2673 this._host = undefined;
2674 }
2675 else {
2676 this.set(host, "SCHEME_OR_HOST");
2677 }
2678 };
2679 /**
2680 * Get the host that has been set in this URL.
2681 */
2682 URLBuilder.prototype.getHost = function () {
2683 return this._host;
2684 };
2685 /**
2686 * Set the port for this URL. If the provided port contains other parts of a URL (such as a
2687 * path or query), those parts will be added to this URL as well.
2688 */
2689 URLBuilder.prototype.setPort = function (port) {
2690 if (port == undefined || port === "") {
2691 this._port = undefined;
2692 }
2693 else {
2694 this.set(port.toString(), "PORT");
2695 }
2696 };
2697 /**
2698 * Get the port that has been set in this URL.
2699 */
2700 URLBuilder.prototype.getPort = function () {
2701 return this._port;
2702 };
2703 /**
2704 * Set the path for this URL. If the provided path contains a query, then it will be added to
2705 * this URL as well.
2706 */
2707 URLBuilder.prototype.setPath = function (path) {
2708 if (!path) {
2709 this._path = undefined;
2710 }
2711 else {
2712 var schemeIndex = path.indexOf("://");
2713 if (schemeIndex !== -1) {
2714 var schemeStart = path.lastIndexOf("/", schemeIndex);
2715 // Make sure to only grab the URL part of the path before setting the state back to SCHEME
2716 // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com"
2717 this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME");
2718 }
2719 else {
2720 this.set(path, "PATH");
2721 }
2722 }
2723 };
2724 /**
2725 * Append the provided path to this URL's existing path. If the provided path contains a query,
2726 * then it will be added to this URL as well.
2727 */
2728 URLBuilder.prototype.appendPath = function (path) {
2729 if (path) {
2730 var currentPath = this.getPath();
2731 if (currentPath) {
2732 if (!currentPath.endsWith("/")) {
2733 currentPath += "/";
2734 }
2735 if (path.startsWith("/")) {
2736 path = path.substring(1);
2737 }
2738 path = currentPath + path;
2739 }
2740 this.set(path, "PATH");
2741 }
2742 };
2743 /**
2744 * Get the path that has been set in this URL.
2745 */
2746 URLBuilder.prototype.getPath = function () {
2747 return this._path;
2748 };
2749 /**
2750 * Set the query in this URL.
2751 */
2752 URLBuilder.prototype.setQuery = function (query) {
2753 if (!query) {
2754 this._query = undefined;
2755 }
2756 else {
2757 this._query = URLQuery.parse(query);
2758 }
2759 };
2760 /**
2761 * Set a query parameter with the provided name and value in this URL's query. If the provided
2762 * query parameter value is undefined or empty, then the query parameter will be removed if it
2763 * existed.
2764 */
2765 URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
2766 if (queryParameterName) {
2767 if (!this._query) {
2768 this._query = new URLQuery();
2769 }
2770 this._query.set(queryParameterName, queryParameterValue);
2771 }
2772 };
2773 /**
2774 * Get the value of the query parameter with the provided query parameter name. If no query
2775 * parameter exists with the provided name, then undefined will be returned.
2776 */
2777 URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
2778 return this._query ? this._query.get(queryParameterName) : undefined;
2779 };
2780 /**
2781 * Get the query in this URL.
2782 */
2783 URLBuilder.prototype.getQuery = function () {
2784 return this._query ? this._query.toString() : undefined;
2785 };
2786 /**
2787 * Set the parts of this URL by parsing the provided text using the provided startState.
2788 */
2789 URLBuilder.prototype.set = function (text, startState) {
2790 var tokenizer = new URLTokenizer(text, startState);
2791 while (tokenizer.next()) {
2792 var token = tokenizer.current();
2793 if (token) {
2794 switch (token.type) {
2795 case "SCHEME":
2796 this._scheme = token.text || undefined;
2797 break;
2798 case "HOST":
2799 this._host = token.text || undefined;
2800 break;
2801 case "PORT":
2802 this._port = token.text || undefined;
2803 break;
2804 case "PATH":
2805 var tokenPath = token.text || undefined;
2806 if (!this._path || this._path === "/" || tokenPath !== "/") {
2807 this._path = tokenPath;
2808 }
2809 break;
2810 case "QUERY":
2811 this._query = URLQuery.parse(token.text);
2812 break;
2813 default:
2814 throw new Error("Unrecognized URLTokenType: " + token.type);
2815 }
2816 }
2817 }
2818 };
2819 URLBuilder.prototype.toString = function () {
2820 var result = "";
2821 if (this._scheme) {
2822 result += this._scheme + "://";
2823 }
2824 if (this._host) {
2825 result += this._host;
2826 }
2827 if (this._port) {
2828 result += ":" + this._port;
2829 }
2830 if (this._path) {
2831 if (!this._path.startsWith("/")) {
2832 result += "/";
2833 }
2834 result += this._path;
2835 }
2836 if (this._query && this._query.any()) {
2837 result += "?" + this._query.toString();
2838 }
2839 return result;
2840 };
2841 /**
2842 * If the provided searchValue is found in this URLBuilder, then replace it with the provided
2843 * replaceValue.
2844 */
2845 URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
2846 if (searchValue) {
2847 this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
2848 this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
2849 this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
2850 this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
2851 this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
2852 }
2853 };
2854 URLBuilder.parse = function (text) {
2855 var result = new URLBuilder();
2856 result.set(text, "SCHEME_OR_HOST");
2857 return result;
2858 };
2859 return URLBuilder;
2860 }());
2861 var URLToken = /** @class */ (function () {
2862 function URLToken(text, type) {
2863 this.text = text;
2864 this.type = type;
2865 }
2866 URLToken.scheme = function (text) {
2867 return new URLToken(text, "SCHEME");
2868 };
2869 URLToken.host = function (text) {
2870 return new URLToken(text, "HOST");
2871 };
2872 URLToken.port = function (text) {
2873 return new URLToken(text, "PORT");
2874 };
2875 URLToken.path = function (text) {
2876 return new URLToken(text, "PATH");
2877 };
2878 URLToken.query = function (text) {
2879 return new URLToken(text, "QUERY");
2880 };
2881 return URLToken;
2882 }());
2883 /**
2884 * Get whether or not the provided character (single character string) is an alphanumeric (letter or
2885 * digit) character.
2886 */
2887 function isAlphaNumericCharacter(character) {
2888 var characterCode = character.charCodeAt(0);
2889 return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ ||
2890 (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ ||
2891 (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */);
2892 }
2893 /**
2894 * A class that tokenizes URL strings.
2895 */
2896 var URLTokenizer = /** @class */ (function () {
2897 function URLTokenizer(_text, state) {
2898 this._text = _text;
2899 this._textLength = _text ? _text.length : 0;
2900 this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
2901 this._currentIndex = 0;
2902 }
2903 /**
2904 * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
2905 * hasn't started or has finished tokenizing.
2906 */
2907 URLTokenizer.prototype.current = function () {
2908 return this._currentToken;
2909 };
2910 /**
2911 * Advance to the next URLToken and return whether or not a URLToken was found.
2912 */
2913 URLTokenizer.prototype.next = function () {
2914 if (!hasCurrentCharacter(this)) {
2915 this._currentToken = undefined;
2916 }
2917 else {
2918 switch (this._currentState) {
2919 case "SCHEME":
2920 nextScheme(this);
2921 break;
2922 case "SCHEME_OR_HOST":
2923 nextSchemeOrHost(this);
2924 break;
2925 case "HOST":
2926 nextHost(this);
2927 break;
2928 case "PORT":
2929 nextPort(this);
2930 break;
2931 case "PATH":
2932 nextPath(this);
2933 break;
2934 case "QUERY":
2935 nextQuery(this);
2936 break;
2937 default:
2938 throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
2939 }
2940 }
2941 return !!this._currentToken;
2942 };
2943 return URLTokenizer;
2944 }());
2945 /**
2946 * Read the remaining characters from this Tokenizer's character stream.
2947 */
2948 function readRemaining(tokenizer) {
2949 var result = "";
2950 if (tokenizer._currentIndex < tokenizer._textLength) {
2951 result = tokenizer._text.substring(tokenizer._currentIndex);
2952 tokenizer._currentIndex = tokenizer._textLength;
2953 }
2954 return result;
2955 }
2956 /**
2957 * Whether or not this URLTokenizer has a current character.
2958 */
2959 function hasCurrentCharacter(tokenizer) {
2960 return tokenizer._currentIndex < tokenizer._textLength;
2961 }
2962 /**
2963 * Get the character in the text string at the current index.
2964 */
2965 function getCurrentCharacter(tokenizer) {
2966 return tokenizer._text[tokenizer._currentIndex];
2967 }
2968 /**
2969 * Advance to the character in text that is "step" characters ahead. If no step value is provided,
2970 * then step will default to 1.
2971 */
2972 function nextCharacter(tokenizer, step) {
2973 if (hasCurrentCharacter(tokenizer)) {
2974 if (!step) {
2975 step = 1;
2976 }
2977 tokenizer._currentIndex += step;
2978 }
2979 }
2980 /**
2981 * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
2982 * Tokenizer's stream of characters.
2983 */
2984 function peekCharacters(tokenizer, charactersToPeek) {
2985 var endIndex = tokenizer._currentIndex + charactersToPeek;
2986 if (tokenizer._textLength < endIndex) {
2987 endIndex = tokenizer._textLength;
2988 }
2989 return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
2990 }
2991 /**
2992 * Read characters from this Tokenizer until the end of the stream or until the provided condition
2993 * is false when provided the current character.
2994 */
2995 function readWhile(tokenizer, condition) {
2996 var result = "";
2997 while (hasCurrentCharacter(tokenizer)) {
2998 var currentCharacter = getCurrentCharacter(tokenizer);
2999 if (!condition(currentCharacter)) {
3000 break;
3001 }
3002 else {
3003 result += currentCharacter;
3004 nextCharacter(tokenizer);
3005 }
3006 }
3007 return result;
3008 }
3009 /**
3010 * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
3011 * character stream is reached.
3012 */
3013 function readWhileLetterOrDigit(tokenizer) {
3014 return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
3015 }
3016 /**
3017 * Read characters from this Tokenizer until one of the provided terminating characters is read or
3018 * the end of the character stream is reached.
3019 */
3020 function readUntilCharacter(tokenizer) {
3021 var terminatingCharacters = [];
3022 for (var _i = 1; _i < arguments.length; _i++) {
3023 terminatingCharacters[_i - 1] = arguments[_i];
3024 }
3025 return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
3026 }
3027 function nextScheme(tokenizer) {
3028 var scheme = readWhileLetterOrDigit(tokenizer);
3029 tokenizer._currentToken = URLToken.scheme(scheme);
3030 if (!hasCurrentCharacter(tokenizer)) {
3031 tokenizer._currentState = "DONE";
3032 }
3033 else {
3034 tokenizer._currentState = "HOST";
3035 }
3036 }
3037 function nextSchemeOrHost(tokenizer) {
3038 var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
3039 if (!hasCurrentCharacter(tokenizer)) {
3040 tokenizer._currentToken = URLToken.host(schemeOrHost);
3041 tokenizer._currentState = "DONE";
3042 }
3043 else if (getCurrentCharacter(tokenizer) === ":") {
3044 if (peekCharacters(tokenizer, 3) === "://") {
3045 tokenizer._currentToken = URLToken.scheme(schemeOrHost);
3046 tokenizer._currentState = "HOST";
3047 }
3048 else {
3049 tokenizer._currentToken = URLToken.host(schemeOrHost);
3050 tokenizer._currentState = "PORT";
3051 }
3052 }
3053 else {
3054 tokenizer._currentToken = URLToken.host(schemeOrHost);
3055 if (getCurrentCharacter(tokenizer) === "/") {
3056 tokenizer._currentState = "PATH";
3057 }
3058 else {
3059 tokenizer._currentState = "QUERY";
3060 }
3061 }
3062 }
3063 function nextHost(tokenizer) {
3064 if (peekCharacters(tokenizer, 3) === "://") {
3065 nextCharacter(tokenizer, 3);
3066 }
3067 var host = readUntilCharacter(tokenizer, ":", "/", "?");
3068 tokenizer._currentToken = URLToken.host(host);
3069 if (!hasCurrentCharacter(tokenizer)) {
3070 tokenizer._currentState = "DONE";
3071 }
3072 else if (getCurrentCharacter(tokenizer) === ":") {
3073 tokenizer._currentState = "PORT";
3074 }
3075 else if (getCurrentCharacter(tokenizer) === "/") {
3076 tokenizer._currentState = "PATH";
3077 }
3078 else {
3079 tokenizer._currentState = "QUERY";
3080 }
3081 }
3082 function nextPort(tokenizer) {
3083 if (getCurrentCharacter(tokenizer) === ":") {
3084 nextCharacter(tokenizer);
3085 }
3086 var port = readUntilCharacter(tokenizer, "/", "?");
3087 tokenizer._currentToken = URLToken.port(port);
3088 if (!hasCurrentCharacter(tokenizer)) {
3089 tokenizer._currentState = "DONE";
3090 }
3091 else if (getCurrentCharacter(tokenizer) === "/") {
3092 tokenizer._currentState = "PATH";
3093 }
3094 else {
3095 tokenizer._currentState = "QUERY";
3096 }
3097 }
3098 function nextPath(tokenizer) {
3099 var path = readUntilCharacter(tokenizer, "?");
3100 tokenizer._currentToken = URLToken.path(path);
3101 if (!hasCurrentCharacter(tokenizer)) {
3102 tokenizer._currentState = "DONE";
3103 }
3104 else {
3105 tokenizer._currentState = "QUERY";
3106 }
3107 }
3108 function nextQuery(tokenizer) {
3109 if (getCurrentCharacter(tokenizer) === "?") {
3110 nextCharacter(tokenizer);
3111 }
3112 var query = readRemaining(tokenizer);
3113 tokenizer._currentToken = URLToken.query(query);
3114 tokenizer._currentState = "DONE";
3115 }
3116
3117 // Copyright (c) Microsoft Corporation. All rights reserved.
3118 var DefaultRedirectOptions = {
3119 handleRedirects: true,
3120 maxRetries: 20,
3121 };
3122 function redirectPolicy(maximumRetries) {
3123 if (maximumRetries === void 0) { maximumRetries = 20; }
3124 return {
3125 create: function (nextPolicy, options) {
3126 return new RedirectPolicy(nextPolicy, options, maximumRetries);
3127 },
3128 };
3129 }
3130 var RedirectPolicy = /** @class */ (function (_super) {
3131 __extends(RedirectPolicy, _super);
3132 function RedirectPolicy(nextPolicy, options, maxRetries) {
3133 if (maxRetries === void 0) { maxRetries = 20; }
3134 var _this = _super.call(this, nextPolicy, options) || this;
3135 _this.maxRetries = maxRetries;
3136 return _this;
3137 }
3138 RedirectPolicy.prototype.sendRequest = function (request) {
3139 var _this = this;
3140 return this._nextPolicy
3141 .sendRequest(request)
3142 .then(function (response) { return handleRedirect(_this, response, 0); });
3143 };
3144 return RedirectPolicy;
3145 }(BaseRequestPolicy));
3146 function handleRedirect(policy, response, currentRetries) {
3147 var request = response.request, status = response.status;
3148 var locationHeader = response.headers.get("location");
3149 if (locationHeader &&
3150 (status === 300 ||
3151 (status === 301 && ["GET", "HEAD"].includes(request.method)) ||
3152 (status === 302 && ["GET", "POST", "HEAD"].includes(request.method)) ||
3153 (status === 303 && "POST" === request.method) ||
3154 status === 307) &&
3155 ((request.redirectLimit !== undefined && currentRetries < request.redirectLimit) ||
3156 (request.redirectLimit === undefined && currentRetries < policy.maxRetries))) {
3157 var builder = URLBuilder.parse(request.url);
3158 builder.setPath(locationHeader);
3159 request.url = builder.toString();
3160 // POST request with Status code 302 and 303 should be converted into a
3161 // redirected GET request if the redirect url is present in the location header
3162 // reference: https://tools.ietf.org/html/rfc7231#page-57 && https://fetch.spec.whatwg.org/#http-redirect-fetch
3163 if ((status === 302 || status === 303) && request.method === "POST") {
3164 request.method = "GET";
3165 delete request.body;
3166 }
3167 return policy._nextPolicy
3168 .sendRequest(request)
3169 .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); })
3170 .then(function (res) { return recordRedirect(res, request.url); });
3171 }
3172 return Promise.resolve(response);
3173 }
3174 function recordRedirect(response, redirect) {
3175 // This is called as the recursive calls to handleRedirect() unwind,
3176 // only record the deepest/last redirect
3177 if (!response.redirected) {
3178 response.redirected = true;
3179 response.url = redirect;
3180 }
3181 return response;
3182 }
3183
3184 function rpRegistrationPolicy(retryTimeout) {
3185 if (retryTimeout === void 0) { retryTimeout = 30; }
3186 return {
3187 create: function (nextPolicy, options) {
3188 return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
3189 },
3190 };
3191 }
3192 var RPRegistrationPolicy = /** @class */ (function (_super) {
3193 __extends(RPRegistrationPolicy, _super);
3194 function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
3195 if (_retryTimeout === void 0) { _retryTimeout = 30; }
3196 var _this = _super.call(this, nextPolicy, options) || this;
3197 _this._retryTimeout = _retryTimeout;
3198 return _this;
3199 }
3200 RPRegistrationPolicy.prototype.sendRequest = function (request) {
3201 var _this = this;
3202 return this._nextPolicy
3203 .sendRequest(request.clone())
3204 .then(function (response) { return registerIfNeeded(_this, request, response); });
3205 };
3206 return RPRegistrationPolicy;
3207 }(BaseRequestPolicy));
3208 function registerIfNeeded(policy, request, response) {
3209 if (response.status === 409) {
3210 var rpName = checkRPNotRegisteredError(response.bodyAsText);
3211 if (rpName) {
3212 var urlPrefix = extractSubscriptionUrl(request.url);
3213 return (registerRP(policy, urlPrefix, rpName, request)
3214 // Autoregistration of ${provider} failed for some reason. We will not return this error
3215 // instead will return the initial response with 409 status code back to the user.
3216 // do nothing here as we are returning the original response at the end of this method.
3217 .catch(function () { return false; })
3218 .then(function (registrationStatus) {
3219 if (registrationStatus) {
3220 // Retry the original request. We have to change the x-ms-client-request-id
3221 // otherwise Azure endpoint will return the initial 409 (cached) response.
3222 request.headers.set("x-ms-client-request-id", generateUuid());
3223 return policy._nextPolicy.sendRequest(request.clone());
3224 }
3225 return response;
3226 }));
3227 }
3228 }
3229 return Promise.resolve(response);
3230 }
3231 /**
3232 * Reuses the headers of the original request and url (if specified).
3233 * @param {WebResourceLike} originalRequest The original request
3234 * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
3235 * @returns {object} A new request object with desired headers.
3236 */
3237 function getRequestEssentials(originalRequest, reuseUrlToo) {
3238 if (reuseUrlToo === void 0) { reuseUrlToo = false; }
3239 var reqOptions = originalRequest.clone();
3240 if (reuseUrlToo) {
3241 reqOptions.url = originalRequest.url;
3242 }
3243 // We have to change the x-ms-client-request-id otherwise Azure endpoint
3244 // will return the initial 409 (cached) response.
3245 reqOptions.headers.set("x-ms-client-request-id", generateUuid());
3246 // Set content-type to application/json
3247 reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
3248 return reqOptions;
3249 }
3250 /**
3251 * Validates the error code and message associated with 409 response status code. If it matches to that of
3252 * RP not registered then it returns the name of the RP else returns undefined.
3253 * @param {string} body The response body received after making the original request.
3254 * @returns {string} The name of the RP if condition is satisfied else undefined.
3255 */
3256 function checkRPNotRegisteredError(body) {
3257 var result, responseBody;
3258 if (body) {
3259 try {
3260 responseBody = JSON.parse(body);
3261 }
3262 catch (err) {
3263 // do nothing;
3264 }
3265 if (responseBody &&
3266 responseBody.error &&
3267 responseBody.error.message &&
3268 responseBody.error.code &&
3269 responseBody.error.code === "MissingSubscriptionRegistration") {
3270 var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
3271 if (matchRes) {
3272 result = matchRes.pop();
3273 }
3274 }
3275 }
3276 return result;
3277 }
3278 /**
3279 * Extracts the first part of the URL, just after subscription:
3280 * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
3281 * @param {string} url The original request url
3282 * @returns {string} The url prefix as explained above.
3283 */
3284 function extractSubscriptionUrl(url) {
3285 var result;
3286 var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi);
3287 if (matchRes && matchRes[0]) {
3288 result = matchRes[0];
3289 }
3290 else {
3291 throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
3292 }
3293 return result;
3294 }
3295 /**
3296 * Registers the given provider.
3297 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
3298 * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
3299 * @param {string} provider The provider name to be registered.
3300 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
3301 * with a message that the provider is not registered.
3302 * @param {registrationCallback} callback The callback that handles the RP registration
3303 */
3304 function registerRP(policy, urlPrefix, provider, originalRequest) {
3305 var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
3306 var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
3307 var reqOptions = getRequestEssentials(originalRequest);
3308 reqOptions.method = "POST";
3309 reqOptions.url = postUrl;
3310 return policy._nextPolicy.sendRequest(reqOptions).then(function (response) {
3311 if (response.status !== 200) {
3312 throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
3313 }
3314 return getRegistrationStatus(policy, getUrl, originalRequest);
3315 });
3316 }
3317 /**
3318 * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
3319 * Polling will happen till the registrationState property of the response body is "Registered".
3320 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
3321 * @param {string} url The request url for polling
3322 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
3323 * with a message that the provider is not registered.
3324 * @returns {Promise<boolean>} True if RP Registration is successful.
3325 */
3326 function getRegistrationStatus(policy, url, originalRequest) {
3327 var reqOptions = getRequestEssentials(originalRequest);
3328 reqOptions.url = url;
3329 reqOptions.method = "GET";
3330 return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
3331 var obj = res.parsedBody;
3332 if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
3333 return true;
3334 }
3335 else {
3336 return delay(policy._retryTimeout * 1000)
3337 .then(function () { return getRegistrationStatus(policy, url, originalRequest); });
3338 }
3339 });
3340 }
3341
3342 // Copyright (c) Microsoft Corporation. All rights reserved.
3343 function signingPolicy(authenticationProvider) {
3344 return {
3345 create: function (nextPolicy, options) {
3346 return new SigningPolicy(nextPolicy, options, authenticationProvider);
3347 },
3348 };
3349 }
3350 var SigningPolicy = /** @class */ (function (_super) {
3351 __extends(SigningPolicy, _super);
3352 function SigningPolicy(nextPolicy, options, authenticationProvider) {
3353 var _this = _super.call(this, nextPolicy, options) || this;
3354 _this.authenticationProvider = authenticationProvider;
3355 return _this;
3356 }
3357 SigningPolicy.prototype.signRequest = function (request) {
3358 return this.authenticationProvider.signRequest(request);
3359 };
3360 SigningPolicy.prototype.sendRequest = function (request) {
3361 var _this = this;
3362 return this.signRequest(request).then(function (nextRequest) {
3363 return _this._nextPolicy.sendRequest(nextRequest);
3364 });
3365 };
3366 return SigningPolicy;
3367 }(BaseRequestPolicy));
3368
3369 // Copyright (c) Microsoft Corporation. All rights reserved.
3370 function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3371 return {
3372 create: function (nextPolicy, options) {
3373 return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
3374 },
3375 };
3376 }
3377 /**
3378 * @class
3379 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
3380 *
3381 * @constructor
3382 * @param {number} retryCount The client retry count.
3383 * @param {number} retryInterval The client retry interval, in milliseconds.
3384 * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
3385 * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
3386 */
3387 var SystemErrorRetryPolicy = /** @class */ (function (_super) {
3388 __extends(SystemErrorRetryPolicy, _super);
3389 function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3390 var _this = _super.call(this, nextPolicy, options) || this;
3391 _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
3392 _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
3393 _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
3394 _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
3395 _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
3396 _this.retryInterval =
3397 typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
3398 _this.minRetryInterval =
3399 typeof minRetryInterval === "number"
3400 ? minRetryInterval
3401 : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
3402 _this.maxRetryInterval =
3403 typeof maxRetryInterval === "number"
3404 ? maxRetryInterval
3405 : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
3406 return _this;
3407 }
3408 SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
3409 var _this = this;
3410 return this._nextPolicy
3411 .sendRequest(request.clone())
3412 .catch(function (error) { return retry$1(_this, request, error.response, error); });
3413 };
3414 return SystemErrorRetryPolicy;
3415 }(BaseRequestPolicy));
3416 /**
3417 * Determines if the operation should be retried and how long to wait until the next retry.
3418 *
3419 * @param {number} statusCode The HTTP status code.
3420 * @param {RetryData} retryData The retry data.
3421 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
3422 */
3423 function shouldRetry$1(policy, retryData) {
3424 var currentCount;
3425 if (!retryData) {
3426 throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
3427 }
3428 else {
3429 currentCount = retryData && retryData.retryCount;
3430 }
3431 return currentCount < policy.retryCount;
3432 }
3433 /**
3434 * Updates the retry data for the next attempt.
3435 *
3436 * @param {RetryData} retryData The retry data.
3437 * @param {object} err The operation"s error, if any.
3438 */
3439 function updateRetryData$1(policy, retryData, err) {
3440 if (!retryData) {
3441 retryData = {
3442 retryCount: 0,
3443 retryInterval: 0,
3444 };
3445 }
3446 if (err) {
3447 if (retryData.error) {
3448 err.innerError = retryData.error;
3449 }
3450 retryData.error = err;
3451 }
3452 // Adjust retry count
3453 retryData.retryCount++;
3454 // Adjust retry interval
3455 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
3456 var boundedRandDelta = policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 0.4));
3457 incrementDelta *= boundedRandDelta;
3458 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
3459 return retryData;
3460 }
3461 function retry$1(policy, request, operationResponse, err, retryData) {
3462 return __awaiter(this, void 0, void 0, function () {
3463 var error_1;
3464 return __generator(this, function (_a) {
3465 switch (_a.label) {
3466 case 0:
3467 retryData = updateRetryData$1(policy, retryData, err);
3468 if (!(err &&
3469 err.code &&
3470 shouldRetry$1(policy, retryData) &&
3471 (err.code === "ETIMEDOUT" ||
3472 err.code === "ESOCKETTIMEDOUT" ||
3473 err.code === "ECONNREFUSED" ||
3474 err.code === "ECONNRESET" ||
3475 err.code === "ENOENT"))) return [3 /*break*/, 5];
3476 _a.label = 1;
3477 case 1:
3478 _a.trys.push([1, 3, , 4]);
3479 return [4 /*yield*/, delay(retryData.retryInterval)];
3480 case 2:
3481 _a.sent();
3482 return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())];
3483 case 3:
3484 error_1 = _a.sent();
3485 return [2 /*return*/, retry$1(policy, request, operationResponse, error_1, retryData)];
3486 case 4: return [3 /*break*/, 6];
3487 case 5:
3488 if (err) {
3489 // If the operation failed in the end, return all errors instead of just the last one
3490 return [2 /*return*/, Promise.reject(retryData.error)];
3491 }
3492 return [2 /*return*/, operationResponse];
3493 case 6: return [2 /*return*/];
3494 }
3495 });
3496 });
3497 }
3498
3499 // Copyright (c) Microsoft Corporation. All rights reserved.
3500 (function (QueryCollectionFormat) {
3501 QueryCollectionFormat["Csv"] = ",";
3502 QueryCollectionFormat["Ssv"] = " ";
3503 QueryCollectionFormat["Tsv"] = "\t";
3504 QueryCollectionFormat["Pipes"] = "|";
3505 QueryCollectionFormat["Multi"] = "Multi";
3506 })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
3507
3508 // Copyright (c) Microsoft Corporation. All rights reserved.
3509 var agentNotSupportedInBrowser = new Error("AgentPolicy is not supported in browser environment");
3510 function agentPolicy(_agentSettings) {
3511 return {
3512 create: function (_nextPolicy, _options) {
3513 throw agentNotSupportedInBrowser;
3514 },
3515 };
3516 }
3517 var AgentPolicy = /** @class */ (function (_super) {
3518 __extends(AgentPolicy, _super);
3519 function AgentPolicy(nextPolicy, options) {
3520 var _this = _super.call(this, nextPolicy, options) || this;
3521 throw agentNotSupportedInBrowser;
3522 }
3523 AgentPolicy.prototype.sendRequest = function (_request) {
3524 throw agentNotSupportedInBrowser;
3525 };
3526 return AgentPolicy;
3527 }(BaseRequestPolicy));
3528
3529 // Copyright (c) Microsoft Corporation. All rights reserved.
3530 var proxyNotSupportedInBrowser = new Error("ProxyPolicy is not supported in browser environment");
3531 function getDefaultProxySettings(_proxyUrl) {
3532 return undefined;
3533 }
3534 function proxyPolicy(_proxySettings) {
3535 return {
3536 create: function (_nextPolicy, _options) {
3537 throw proxyNotSupportedInBrowser;
3538 },
3539 };
3540 }
3541 var ProxyPolicy = /** @class */ (function (_super) {
3542 __extends(ProxyPolicy, _super);
3543 function ProxyPolicy(nextPolicy, options) {
3544 var _this = _super.call(this, nextPolicy, options) || this;
3545 throw proxyNotSupportedInBrowser;
3546 }
3547 ProxyPolicy.prototype.sendRequest = function (_request) {
3548 throw proxyNotSupportedInBrowser;
3549 };
3550 return ProxyPolicy;
3551 }(BaseRequestPolicy));
3552
3553 // Copyright (c) Microsoft Corporation. All rights reserved.
3554 var StatusCodes = Constants.HttpConstants.StatusCodes;
3555 var DEFAULT_RETRY_COUNT = 3;
3556 function throttlingRetryPolicy(maxRetries) {
3557 if (maxRetries === void 0) { maxRetries = DEFAULT_RETRY_COUNT; }
3558 return {
3559 create: function (nextPolicy, options) {
3560 return new ThrottlingRetryPolicy(nextPolicy, options, maxRetries);
3561 },
3562 };
3563 }
3564 /**
3565 * To learn more, please refer to
3566 * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
3567 * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
3568 * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
3569 */
3570 var ThrottlingRetryPolicy = /** @class */ (function (_super) {
3571 __extends(ThrottlingRetryPolicy, _super);
3572 function ThrottlingRetryPolicy(nextPolicy, options, retryLimit) {
3573 var _this = _super.call(this, nextPolicy, options) || this;
3574 _this.retryLimit = retryLimit;
3575 return _this;
3576 }
3577 ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
3578 return __awaiter(this, void 0, void 0, function () {
3579 var _this = this;
3580 return __generator(this, function (_a) {
3581 return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
3582 return _this.retry(httpRequest, response, 0);
3583 })];
3584 });
3585 });
3586 };
3587 ThrottlingRetryPolicy.prototype.retry = function (httpRequest, httpResponse, retryCount) {
3588 return __awaiter(this, void 0, void 0, function () {
3589 var retryAfterHeader, delayInMs, res;
3590 return __generator(this, function (_a) {
3591 switch (_a.label) {
3592 case 0:
3593 if (httpResponse.status !== StatusCodes.TooManyRequests) {
3594 return [2 /*return*/, httpResponse];
3595 }
3596 retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
3597 if (!(retryAfterHeader && retryCount < this.retryLimit)) return [3 /*break*/, 3];
3598 delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
3599 if (!delayInMs) return [3 /*break*/, 3];
3600 return [4 /*yield*/, delay(delayInMs)];
3601 case 1:
3602 _a.sent();
3603 return [4 /*yield*/, this._nextPolicy.sendRequest(httpRequest)];
3604 case 2:
3605 res = _a.sent();
3606 return [2 /*return*/, this.retry(httpRequest, res, retryCount + 1)];
3607 case 3: return [2 /*return*/, httpResponse];
3608 }
3609 });
3610 });
3611 };
3612 ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
3613 var retryAfterInSeconds = Number(headerValue);
3614 if (Number.isNaN(retryAfterInSeconds)) {
3615 return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
3616 }
3617 else {
3618 return retryAfterInSeconds * 1000;
3619 }
3620 };
3621 ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
3622 try {
3623 var now = Date.now();
3624 var date = Date.parse(headerValue);
3625 var diff = date - now;
3626 return Number.isNaN(diff) ? undefined : diff;
3627 }
3628 catch (error) {
3629 return undefined;
3630 }
3631 };
3632 return ThrottlingRetryPolicy;
3633 }(BaseRequestPolicy));
3634
3635 // Copyright (c) Microsoft Corporation. All rights reserved.
3636 var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
3637 /**
3638 * Resource manager endpoints to match in order to specify a valid scope to the AzureIdentityCredentialAdapter.
3639 */
3640 var azureResourceManagerEndpoints = [
3641 "https://management.windows.net",
3642 "https://management.chinacloudapi.cn",
3643 "https://management.usgovcloudapi.net",
3644 "https://management.cloudapi.de",
3645 ];
3646 /**
3647 * This class provides a simple extension to use {@link TokenCredential} from `@azure/identity` library to
3648 * use with legacy Azure SDKs that accept {@link ServiceClientCredentials} family of credentials for authentication.
3649 */
3650 var AzureIdentityCredentialAdapter = /** @class */ (function () {
3651 function AzureIdentityCredentialAdapter(azureTokenCredential, scopes) {
3652 if (scopes === void 0) { scopes = "https://management.azure.com/.default"; }
3653 this.azureTokenCredential = azureTokenCredential;
3654 this.scopes = scopes;
3655 }
3656 AzureIdentityCredentialAdapter.prototype.getToken = function () {
3657 return __awaiter(this, void 0, void 0, function () {
3658 var accessToken, result;
3659 return __generator(this, function (_a) {
3660 switch (_a.label) {
3661 case 0: return [4 /*yield*/, this.azureTokenCredential.getToken(this.scopes)];
3662 case 1:
3663 accessToken = _a.sent();
3664 if (accessToken !== null) {
3665 result = {
3666 accessToken: accessToken.token,
3667 tokenType: DEFAULT_AUTHORIZATION_SCHEME,
3668 expiresOn: accessToken.expiresOnTimestamp,
3669 };
3670 return [2 /*return*/, result];
3671 }
3672 else {
3673 throw new Error("Could find token for scope");
3674 }
3675 }
3676 });
3677 });
3678 };
3679 AzureIdentityCredentialAdapter.prototype.signRequest = function (webResource) {
3680 return __awaiter(this, void 0, void 0, function () {
3681 var tokenResponse;
3682 return __generator(this, function (_a) {
3683 switch (_a.label) {
3684 case 0: return [4 /*yield*/, this.getToken()];
3685 case 1:
3686 tokenResponse = _a.sent();
3687 webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, tokenResponse.tokenType + " " + tokenResponse.accessToken);
3688 return [2 /*return*/, Promise.resolve(webResource)];
3689 }
3690 });
3691 });
3692 };
3693 return AzureIdentityCredentialAdapter;
3694 }());
3695
3696 // Copyright (c) Microsoft Corporation. All rights reserved.
3697 /**
3698 * @class
3699 * Initializes a new instance of the ServiceClient.
3700 */
3701 var ServiceClient = /** @class */ (function () {
3702 /**
3703 * The ServiceClient constructor
3704 * @constructor
3705 * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
3706 * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
3707 */
3708 function ServiceClient(credentials, options) {
3709 if (!options) {
3710 options = {};
3711 }
3712 if (options.baseUri) {
3713 this.baseUri = options.baseUri;
3714 }
3715 var serviceClientCredentials;
3716 if (isTokenCredential(credentials)) {
3717 var scope = undefined;
3718 if ((options === null || options === void 0 ? void 0 : options.baseUri) && azureResourceManagerEndpoints.includes(options === null || options === void 0 ? void 0 : options.baseUri)) {
3719 scope = options.baseUri + "/.default";
3720 }
3721 serviceClientCredentials = new AzureIdentityCredentialAdapter(credentials, scope);
3722 }
3723 else {
3724 serviceClientCredentials = credentials;
3725 }
3726 if (serviceClientCredentials && !serviceClientCredentials.signRequest) {
3727 throw new Error("credentials argument needs to implement signRequest method");
3728 }
3729 this._withCredentials = options.withCredentials || false;
3730 this._httpClient = options.httpClient || new XhrHttpClient();
3731 this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
3732 var requestPolicyFactories;
3733 if (Array.isArray(options.requestPolicyFactories)) {
3734 requestPolicyFactories = options.requestPolicyFactories;
3735 }
3736 else {
3737 requestPolicyFactories = createDefaultRequestPolicyFactories(serviceClientCredentials, options);
3738 if (options.requestPolicyFactories) {
3739 var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
3740 if (newRequestPolicyFactories) {
3741 requestPolicyFactories = newRequestPolicyFactories;
3742 }
3743 }
3744 }
3745 this._requestPolicyFactories = requestPolicyFactories;
3746 }
3747 /**
3748 * Send the provided httpRequest.
3749 */
3750 ServiceClient.prototype.sendRequest = function (options) {
3751 if (options === null || options === undefined || typeof options !== "object") {
3752 throw new Error("options cannot be null or undefined and it must be of type object.");
3753 }
3754 var httpRequest;
3755 try {
3756 if (isWebResourceLike(options)) {
3757 options.validateRequestProperties();
3758 httpRequest = options;
3759 }
3760 else {
3761 httpRequest = new WebResource();
3762 httpRequest = httpRequest.prepare(options);
3763 }
3764 }
3765 catch (error) {
3766 return Promise.reject(error);
3767 }
3768 var httpPipeline = this._httpClient;
3769 if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
3770 for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
3771 httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
3772 }
3773 }
3774 return httpPipeline.sendRequest(httpRequest);
3775 };
3776 /**
3777 * Send an HTTP request that is populated using the provided OperationSpec.
3778 * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
3779 * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
3780 * @param {ServiceCallback} callback The callback to call when the response is received.
3781 */
3782 ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
3783 if (typeof operationArguments.options === "function") {
3784 callback = operationArguments.options;
3785 operationArguments.options = undefined;
3786 }
3787 var httpRequest = new WebResource();
3788 var result;
3789 try {
3790 var baseUri = operationSpec.baseUrl || this.baseUri;
3791 if (!baseUri) {
3792 throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use.");
3793 }
3794 httpRequest.method = operationSpec.httpMethod;
3795 httpRequest.operationSpec = operationSpec;
3796 var requestUrl = URLBuilder.parse(baseUri);
3797 if (operationSpec.path) {
3798 requestUrl.appendPath(operationSpec.path);
3799 }
3800 if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
3801 for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
3802 var urlParameter = _a[_i];
3803 var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
3804 urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
3805 if (!urlParameter.skipEncoding) {
3806 urlParameterValue = encodeURIComponent(urlParameterValue);
3807 }
3808 requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
3809 }
3810 }
3811 if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
3812 for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
3813 var queryParameter = _c[_b];
3814 var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
3815 if (queryParameterValue != undefined) {
3816 queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
3817 if (queryParameter.collectionFormat != undefined) {
3818 if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
3819 if (queryParameterValue.length === 0) {
3820 queryParameterValue = "";
3821 }
3822 else {
3823 for (var index in queryParameterValue) {
3824 var item = queryParameterValue[index];
3825 queryParameterValue[index] = item == undefined ? "" : item.toString();
3826 }
3827 }
3828 }
3829 else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv ||
3830 queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) {
3831 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
3832 }
3833 }
3834 if (!queryParameter.skipEncoding) {
3835 if (Array.isArray(queryParameterValue)) {
3836 for (var index in queryParameterValue) {
3837 if (queryParameterValue[index] !== undefined &&
3838 queryParameterValue[index] !== null) {
3839 queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
3840 }
3841 }
3842 }
3843 else {
3844 queryParameterValue = encodeURIComponent(queryParameterValue);
3845 }
3846 }
3847 if (queryParameter.collectionFormat != undefined &&
3848 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi &&
3849 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv &&
3850 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) {
3851 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
3852 }
3853 requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
3854 }
3855 }
3856 }
3857 httpRequest.url = requestUrl.toString();
3858 var contentType = operationSpec.contentType || this.requestContentType;
3859 if (contentType) {
3860 httpRequest.headers.set("Content-Type", contentType);
3861 }
3862 if (operationSpec.headerParameters) {
3863 for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
3864 var headerParameter = _e[_d];
3865 var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
3866 if (headerValue != undefined) {
3867 headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
3868 var headerCollectionPrefix = headerParameter.mapper
3869 .headerCollectionPrefix;
3870 if (headerCollectionPrefix) {
3871 for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
3872 var key = _g[_f];
3873 httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
3874 }
3875 }
3876 else {
3877 httpRequest.headers.set(headerParameter.mapper.serializedName ||
3878 getPathStringFromParameter(headerParameter), headerValue);
3879 }
3880 }
3881 }
3882 }
3883 var options = operationArguments.options;
3884 if (options) {
3885 if (options.customHeaders) {
3886 for (var customHeaderName in options.customHeaders) {
3887 httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
3888 }
3889 }
3890 if (options.abortSignal) {
3891 httpRequest.abortSignal = options.abortSignal;
3892 }
3893 if (options.timeout) {
3894 httpRequest.timeout = options.timeout;
3895 }
3896 if (options.onUploadProgress) {
3897 httpRequest.onUploadProgress = options.onUploadProgress;
3898 }
3899 if (options.onDownloadProgress) {
3900 httpRequest.onDownloadProgress = options.onDownloadProgress;
3901 }
3902 }
3903 httpRequest.withCredentials = this._withCredentials;
3904 serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
3905 if (httpRequest.streamResponseBody == undefined) {
3906 httpRequest.streamResponseBody = isStreamOperation(operationSpec);
3907 }
3908 result = this.sendRequest(httpRequest).then(function (res) {
3909 return flattenResponse(res, operationSpec.responses[res.status]);
3910 });
3911 }
3912 catch (error) {
3913 result = Promise.reject(error);
3914 }
3915 var cb = callback;
3916 if (cb) {
3917 result
3918 // tslint:disable-next-line:no-null-keyword
3919 .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
3920 .catch(function (err) { return cb(err); });
3921 }
3922 return result;
3923 };
3924 return ServiceClient;
3925 }());
3926 function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
3927 if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
3928 httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
3929 var bodyMapper = operationSpec.requestBody.mapper;
3930 var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
3931 var typeName = bodyMapper.type.name;
3932 try {
3933 if (httpRequest.body != undefined || required) {
3934 var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
3935 httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
3936 var isStream = typeName === MapperType.Stream;
3937 if (operationSpec.isXML) {
3938 if (typeName === MapperType.Sequence) {
3939 httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
3940 }
3941 else if (!isStream) {
3942 httpRequest.body = stringifyXML(httpRequest.body, {
3943 rootName: xmlName || serializedName,
3944 });
3945 }
3946 }
3947 else if (!isStream) {
3948 httpRequest.body = JSON.stringify(httpRequest.body);
3949 }
3950 }
3951 }
3952 catch (error) {
3953 throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
3954 }
3955 }
3956 else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
3957 httpRequest.formData = {};
3958 for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
3959 var formDataParameter = _a[_i];
3960 var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
3961 if (formDataParameterValue != undefined) {
3962 var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
3963 httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
3964 }
3965 }
3966 }
3967 }
3968 function isRequestPolicyFactory(instance) {
3969 return typeof instance.create === "function";
3970 }
3971 function getValueOrFunctionResult(value, defaultValueCreator) {
3972 var result;
3973 if (typeof value === "string") {
3974 result = value;
3975 }
3976 else {
3977 result = defaultValueCreator();
3978 if (typeof value === "function") {
3979 result = value(result);
3980 }
3981 }
3982 return result;
3983 }
3984 function createDefaultRequestPolicyFactories(credentials, options) {
3985 var factories = [];
3986 if (options.generateClientRequestIdHeader) {
3987 factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
3988 }
3989 if (credentials) {
3990 if (isRequestPolicyFactory(credentials)) {
3991 factories.push(credentials);
3992 }
3993 else {
3994 factories.push(signingPolicy(credentials));
3995 }
3996 }
3997 var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
3998 var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
3999 if (userAgentHeaderName && userAgentHeaderValue) {
4000 factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
4001 }
4002 var redirectOptions = __assign(__assign({}, DefaultRedirectOptions), options.redirectOptions);
4003 if (redirectOptions.handleRedirects) {
4004 factories.push(redirectPolicy(redirectOptions.maxRetries));
4005 }
4006 factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
4007 if (!options.noRetryPolicy) {
4008 factories.push(exponentialRetryPolicy());
4009 factories.push(systemErrorRetryPolicy());
4010 factories.push(throttlingRetryPolicy());
4011 }
4012 factories.push(deserializationPolicy(options.deserializationContentTypes));
4013 var proxySettings = options.proxySettings || getDefaultProxySettings();
4014 if (proxySettings) {
4015 factories.push(proxyPolicy());
4016 }
4017 if (options.agentSettings) {
4018 factories.push(agentPolicy(options.agentSettings));
4019 }
4020 return factories;
4021 }
4022 function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
4023 return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
4024 }
4025 function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
4026 var value;
4027 if (typeof parameterPath === "string") {
4028 parameterPath = [parameterPath];
4029 }
4030 if (Array.isArray(parameterPath)) {
4031 if (parameterPath.length > 0) {
4032 if (parameterMapper.isConstant) {
4033 value = parameterMapper.defaultValue;
4034 }
4035 else {
4036 var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
4037 if (!propertySearchResult.propertyFound) {
4038 propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
4039 }
4040 var useDefaultValue = false;
4041 if (!propertySearchResult.propertyFound) {
4042 useDefaultValue =
4043 parameterMapper.required ||
4044 (parameterPath[0] === "options" && parameterPath.length === 2);
4045 }
4046 value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
4047 }
4048 // Serialize just for validation purposes.
4049 var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
4050 serializer.serialize(parameterMapper, value, parameterPathString);
4051 }
4052 }
4053 else {
4054 if (parameterMapper.required) {
4055 value = {};
4056 }
4057 for (var propertyName in parameterPath) {
4058 var propertyMapper = parameterMapper.type.modelProperties[propertyName];
4059 var propertyPath = parameterPath[propertyName];
4060 var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
4061 // Serialize just for validation purposes.
4062 var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
4063 serializer.serialize(propertyMapper, propertyValue, propertyPathString);
4064 if (propertyValue !== undefined) {
4065 if (!value) {
4066 value = {};
4067 }
4068 value[propertyName] = propertyValue;
4069 }
4070 }
4071 }
4072 return value;
4073 }
4074 function getPropertyFromParameterPath(parent, parameterPath) {
4075 var result = { propertyFound: false };
4076 var i = 0;
4077 for (; i < parameterPath.length; ++i) {
4078 var parameterPathPart = parameterPath[i];
4079 // Make sure to check inherited properties too, so don't use hasOwnProperty().
4080 if (parent != undefined && parameterPathPart in parent) {
4081 parent = parent[parameterPathPart];
4082 }
4083 else {
4084 break;
4085 }
4086 }
4087 if (i === parameterPath.length) {
4088 result.propertyValue = parent;
4089 result.propertyFound = true;
4090 }
4091 return result;
4092 }
4093 function flattenResponse(_response, responseSpec) {
4094 var parsedHeaders = _response.parsedHeaders;
4095 var bodyMapper = responseSpec && responseSpec.bodyMapper;
4096 var addOperationResponse = function (obj) {
4097 return Object.defineProperty(obj, "_response", {
4098 value: _response,
4099 });
4100 };
4101 if (bodyMapper) {
4102 var typeName = bodyMapper.type.name;
4103 if (typeName === "Stream") {
4104 return addOperationResponse(__assign(__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
4105 }
4106 var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {};
4107 var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
4108 if (typeName === "Sequence" || isPageableResponse) {
4109 // We're expecting a sequece(array) make sure that the response body is in the
4110 // correct format, if not make it an empty array []
4111 var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : [];
4112 var arrayResponse = __spreadArrays(parsedBody);
4113 for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
4114 var key = _a[_i];
4115 if (modelProperties_1[key].serializedName) {
4116 arrayResponse[key] = _response.parsedBody[key];
4117 }
4118 }
4119 if (parsedHeaders) {
4120 for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
4121 var key = _c[_b];
4122 arrayResponse[key] = parsedHeaders[key];
4123 }
4124 }
4125 addOperationResponse(arrayResponse);
4126 return arrayResponse;
4127 }
4128 if (typeName === "Composite" || typeName === "Dictionary") {
4129 return addOperationResponse(__assign(__assign({}, parsedHeaders), _response.parsedBody));
4130 }
4131 }
4132 if (bodyMapper ||
4133 _response.request.method === "HEAD" ||
4134 isPrimitiveType(_response.parsedBody)) {
4135 // primitive body types and HEAD booleans
4136 return addOperationResponse(__assign(__assign({}, parsedHeaders), { body: _response.parsedBody }));
4137 }
4138 return addOperationResponse(__assign(__assign({}, parsedHeaders), _response.parsedBody));
4139 }
4140
4141 // Copyright (c) Microsoft Corporation. All rights reserved.
4142 function logPolicy(logger) {
4143 if (logger === void 0) { logger = console.log; }
4144 return {
4145 create: function (nextPolicy, options) {
4146 return new LogPolicy(nextPolicy, options, logger);
4147 },
4148 };
4149 }
4150 var LogPolicy = /** @class */ (function (_super) {
4151 __extends(LogPolicy, _super);
4152 function LogPolicy(nextPolicy, options, logger) {
4153 if (logger === void 0) { logger = console.log; }
4154 var _this = _super.call(this, nextPolicy, options) || this;
4155 _this.logger = logger;
4156 return _this;
4157 }
4158 LogPolicy.prototype.sendRequest = function (request) {
4159 var _this = this;
4160 return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
4161 };
4162 return LogPolicy;
4163 }(BaseRequestPolicy));
4164 function logResponse(policy, response) {
4165 policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
4166 policy.logger(">> Response status code: " + response.status);
4167 var responseBody = response.bodyAsText;
4168 policy.logger(">> Body: " + responseBody);
4169 return Promise.resolve(response);
4170 }
4171
4172 // Copyright (c) Microsoft Corporation. All rights reserved.
4173 var HeaderConstants = Constants.HeaderConstants;
4174 var DEFAULT_AUTHORIZATION_SCHEME$1 = "Bearer";
4175 /**
4176 * A credentials object that uses a token string and a authorzation scheme to authenticate.
4177 */
4178 var TokenCredentials = /** @class */ (function () {
4179 /**
4180 * Creates a new TokenCredentials object.
4181 *
4182 * @constructor
4183 * @param {string} token The token.
4184 * @param {string} [authorizationScheme] The authorization scheme.
4185 */
4186 function TokenCredentials(token, authorizationScheme) {
4187 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
4188 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
4189 if (!token) {
4190 throw new Error("token cannot be null or undefined.");
4191 }
4192 this.token = token;
4193 this.authorizationScheme = authorizationScheme;
4194 }
4195 /**
4196 * Signs a request with the Authentication header.
4197 *
4198 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
4199 * @return {Promise<WebResourceLike>} The signed request object.
4200 */
4201 TokenCredentials.prototype.signRequest = function (webResource) {
4202 if (!webResource.headers)
4203 webResource.headers = new HttpHeaders();
4204 webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
4205 return Promise.resolve(webResource);
4206 };
4207 return TokenCredentials;
4208 }());
4209
4210 // Copyright (c) Microsoft Corporation. All rights reserved.
4211 var HeaderConstants$1 = Constants.HeaderConstants;
4212 var DEFAULT_AUTHORIZATION_SCHEME$2 = "Basic";
4213 var BasicAuthenticationCredentials = /** @class */ (function () {
4214 /**
4215 * Creates a new BasicAuthenticationCredentials object.
4216 *
4217 * @constructor
4218 * @param {string} userName User name.
4219 * @param {string} password Password.
4220 * @param {string} [authorizationScheme] The authorization scheme.
4221 */
4222 function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
4223 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2; }
4224 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2;
4225 if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
4226 throw new Error("userName cannot be null or undefined and must be of type string.");
4227 }
4228 if (password === null || password === undefined || typeof password.valueOf() !== "string") {
4229 throw new Error("password cannot be null or undefined and must be of type string.");
4230 }
4231 this.userName = userName;
4232 this.password = password;
4233 this.authorizationScheme = authorizationScheme;
4234 }
4235 /**
4236 * Signs a request with the Authentication header.
4237 *
4238 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
4239 * @returns {Promise<WebResourceLike>} The signed request object.
4240 */
4241 BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
4242 var credentials = this.userName + ":" + this.password;
4243 var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
4244 if (!webResource.headers)
4245 webResource.headers = new HttpHeaders();
4246 webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
4247 return Promise.resolve(webResource);
4248 };
4249 return BasicAuthenticationCredentials;
4250 }());
4251
4252 // Copyright (c) Microsoft Corporation. All rights reserved.
4253 /**
4254 * Authenticates to a service using an API key.
4255 */
4256 var ApiKeyCredentials = /** @class */ (function () {
4257 /**
4258 * @constructor
4259 * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
4260 */
4261 function ApiKeyCredentials(options) {
4262 if (!options || (options && !options.inHeader && !options.inQuery)) {
4263 throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
4264 }
4265 this.inHeader = options.inHeader;
4266 this.inQuery = options.inQuery;
4267 }
4268 /**
4269 * Signs a request with the values provided in the inHeader and inQuery parameter.
4270 *
4271 * @param {WebResource} webResource The WebResource to be signed.
4272 * @returns {Promise<WebResource>} The signed request object.
4273 */
4274 ApiKeyCredentials.prototype.signRequest = function (webResource) {
4275 if (!webResource) {
4276 return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
4277 }
4278 if (this.inHeader) {
4279 if (!webResource.headers) {
4280 webResource.headers = new HttpHeaders();
4281 }
4282 for (var headerName in this.inHeader) {
4283 webResource.headers.set(headerName, this.inHeader[headerName]);
4284 }
4285 }
4286 if (this.inQuery) {
4287 if (!webResource.url) {
4288 return Promise.reject(new Error("url cannot be null in the request object."));
4289 }
4290 if (webResource.url.indexOf("?") < 0) {
4291 webResource.url += "?";
4292 }
4293 for (var key in this.inQuery) {
4294 if (!webResource.url.endsWith("?")) {
4295 webResource.url += "&";
4296 }
4297 webResource.url += key + "=" + this.inQuery[key];
4298 }
4299 }
4300 return Promise.resolve(webResource);
4301 };
4302 return ApiKeyCredentials;
4303 }());
4304
4305 // Copyright (c) Microsoft Corporation. All rights reserved.
4306 var TopicCredentials = /** @class */ (function (_super) {
4307 __extends(TopicCredentials, _super);
4308 /**
4309 * Creates a new EventGrid TopicCredentials object.
4310 *
4311 * @constructor
4312 * @param {string} topicKey The EventGrid topic key
4313 */
4314 function TopicCredentials(topicKey) {
4315 var _this = this;
4316 if (!topicKey || (topicKey && typeof topicKey !== "string")) {
4317 throw new Error("topicKey cannot be null or undefined and must be of type string.");
4318 }
4319 var options = {
4320 inHeader: {
4321 "aeg-sas-key": topicKey,
4322 },
4323 };
4324 _this = _super.call(this, options) || this;
4325 return _this;
4326 }
4327 return TopicCredentials;
4328 }(ApiKeyCredentials));
4329
4330 // Copyright (c) Microsoft Corporation. All rights reserved.
4331 var DomainCredentials = /** @class */ (function (_super) {
4332 __extends(DomainCredentials, _super);
4333 /**
4334 * Creates a new EventGrid DomainCredentials object.
4335 *
4336 * @constructor
4337 * @param {string} domainKey The EventGrid domain key
4338 */
4339 function DomainCredentials(domainKey) {
4340 var _this = this;
4341 if (!domainKey || (domainKey && typeof domainKey !== "string")) {
4342 throw new Error("domainKey cannot be null or undefined and must be of type string.");
4343 }
4344 var options = {
4345 inHeader: {
4346 "aeg-sas-key": domainKey,
4347 },
4348 };
4349 _this = _super.call(this, options) || this;
4350 return _this;
4351 }
4352 return DomainCredentials;
4353 }(ApiKeyCredentials));
4354
4355 exports.ApiKeyCredentials = ApiKeyCredentials;
4356 exports.AzureIdentityCredentialAdapter = AzureIdentityCredentialAdapter;
4357 exports.BaseRequestPolicy = BaseRequestPolicy;
4358 exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
4359 exports.Constants = Constants;
4360 exports.DefaultHttpClient = XhrHttpClient;
4361 exports.DomainCredentials = DomainCredentials;
4362 exports.HttpHeaders = HttpHeaders;
4363 exports.MapperType = MapperType;
4364 exports.RequestPolicyOptions = RequestPolicyOptions;
4365 exports.RestError = RestError;
4366 exports.Serializer = Serializer;
4367 exports.ServiceClient = ServiceClient;
4368 exports.TokenCredentials = TokenCredentials;
4369 exports.TopicCredentials = TopicCredentials;
4370 exports.URLBuilder = URLBuilder;
4371 exports.URLQuery = URLQuery;
4372 exports.WebResource = WebResource;
4373 exports.agentPolicy = agentPolicy;
4374 exports.applyMixins = applyMixins;
4375 exports.delay = delay;
4376 exports.deserializationPolicy = deserializationPolicy;
4377 exports.deserializeResponseBody = deserializeResponseBody;
4378 exports.encodeUri = encodeUri;
4379 exports.executePromisesSequentially = executePromisesSequentially;
4380 exports.exponentialRetryPolicy = exponentialRetryPolicy;
4381 exports.flattenResponse = flattenResponse;
4382 exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
4383 exports.generateUuid = generateUuid;
4384 exports.getDefaultProxySettings = getDefaultProxySettings;
4385 exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
4386 exports.isDuration = isDuration;
4387 exports.isNode = isNode;
4388 exports.isValidUuid = isValidUuid;
4389 exports.logPolicy = logPolicy;
4390 exports.promiseToCallback = promiseToCallback;
4391 exports.promiseToServiceCallback = promiseToServiceCallback;
4392 exports.proxyPolicy = proxyPolicy;
4393 exports.redirectPolicy = redirectPolicy;
4394 exports.serializeObject = serializeObject;
4395 exports.signingPolicy = signingPolicy;
4396 exports.stripRequest = stripRequest;
4397 exports.stripResponse = stripResponse;
4398 exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
4399 exports.throttlingRetryPolicy = throttlingRetryPolicy;
4400 exports.userAgentPolicy = userAgentPolicy;
4401
4402 Object.defineProperty(exports, '__esModule', { value: true });
4403
4404})));
4405//# sourceMappingURL=msRest.browser.js.map