UNPKG

204 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.4",
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 _a, _b;
1901 var parser = new DOMParser();
1902 // Policy to make our code Trusted Types compliant.
1903 // https://github.com/w3c/webappsec-trusted-types
1904 // We are calling DOMParser.parseFromString() to parse XML payload from Azure services.
1905 // The parsed DOM object is not exposed to outside. Scripts are disabled when parsing
1906 // according to the spec. There are no HTML/XSS security concerns on the usage of
1907 // parseFromString() here.
1908 var ttPolicy;
1909 try {
1910 if (typeof self.trustedTypes !== "undefined") {
1911 ttPolicy = self.trustedTypes.createPolicy("@azure/ms-rest-js#xml.browser", {
1912 createHTML: function (s) { return s; },
1913 });
1914 }
1915 }
1916 catch (e) {
1917 console.warn('Could not create trusted types policy "@azure/ms-rest-js#xml.browser"');
1918 }
1919 function parseXML(str) {
1920 var _a;
1921 try {
1922 var dom = parser.parseFromString(((_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(str)) !== null && _a !== void 0 ? _a : str), "application/xml");
1923 throwIfError(dom);
1924 var obj = domToObject(dom.childNodes[0]);
1925 return Promise.resolve(obj);
1926 }
1927 catch (err) {
1928 return Promise.reject(err);
1929 }
1930 }
1931 var errorNS = "";
1932 try {
1933 var invalidXML = ((_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML("INVALID")) !== null && _a !== void 0 ? _a : "INVALID");
1934 errorNS = (_b = parser.parseFromString(invalidXML, "text/xml").getElementsByTagName("parsererror")[0]
1935 .namespaceURI) !== null && _b !== void 0 ? _b : "";
1936 }
1937 catch (ignored) {
1938 // Most browsers will return a document containing <parsererror>, but IE will throw.
1939 }
1940 function throwIfError(dom) {
1941 if (errorNS) {
1942 var parserErrors = dom.getElementsByTagNameNS(errorNS, "parsererror");
1943 if (parserErrors.length) {
1944 throw new Error(parserErrors.item(0).innerHTML);
1945 }
1946 }
1947 }
1948 function isElement(node) {
1949 return !!node.attributes;
1950 }
1951 /**
1952 * Get the Element-typed version of the provided Node if the provided node is an element with
1953 * attributes. If it isn't, then undefined is returned.
1954 */
1955 function asElementWithAttributes(node) {
1956 return isElement(node) && node.hasAttributes() ? node : undefined;
1957 }
1958 function domToObject(node) {
1959 var result = {};
1960 var childNodeCount = node.childNodes.length;
1961 var firstChildNode = node.childNodes[0];
1962 var onlyChildTextValue = (firstChildNode &&
1963 childNodeCount === 1 &&
1964 firstChildNode.nodeType === Node.TEXT_NODE &&
1965 firstChildNode.nodeValue) ||
1966 undefined;
1967 var elementWithAttributes = asElementWithAttributes(node);
1968 if (elementWithAttributes) {
1969 result["$"] = {};
1970 for (var i = 0; i < elementWithAttributes.attributes.length; i++) {
1971 var attr = elementWithAttributes.attributes[i];
1972 result["$"][attr.nodeName] = attr.nodeValue;
1973 }
1974 if (onlyChildTextValue) {
1975 result["_"] = onlyChildTextValue;
1976 }
1977 }
1978 else if (childNodeCount === 0) {
1979 result = "";
1980 }
1981 else if (onlyChildTextValue) {
1982 result = onlyChildTextValue;
1983 }
1984 if (!onlyChildTextValue) {
1985 for (var i = 0; i < childNodeCount; i++) {
1986 var child = node.childNodes[i];
1987 // Ignore leading/trailing whitespace nodes
1988 if (child.nodeType !== Node.TEXT_NODE) {
1989 var childObject = domToObject(child);
1990 if (!result[child.nodeName]) {
1991 result[child.nodeName] = childObject;
1992 }
1993 else if (Array.isArray(result[child.nodeName])) {
1994 result[child.nodeName].push(childObject);
1995 }
1996 else {
1997 result[child.nodeName] = [result[child.nodeName], childObject];
1998 }
1999 }
2000 }
2001 }
2002 return result;
2003 }
2004 // tslint:disable-next-line:no-null-keyword
2005 var doc = document.implementation.createDocument(null, null, null);
2006 var serializer = new XMLSerializer();
2007 function stringifyXML(obj, opts) {
2008 var rootName = (opts && opts.rootName) || "root";
2009 var dom = buildNode(obj, rootName)[0];
2010 return ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + serializer.serializeToString(dom));
2011 }
2012 function buildAttributes(attrs) {
2013 var result = [];
2014 for (var _i = 0, _a = Object.keys(attrs); _i < _a.length; _i++) {
2015 var key = _a[_i];
2016 var attr = doc.createAttribute(key);
2017 attr.value = attrs[key].toString();
2018 result.push(attr);
2019 }
2020 return result;
2021 }
2022 function buildNode(obj, elementName) {
2023 if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean") {
2024 var elem = doc.createElement(elementName);
2025 elem.textContent = obj.toString();
2026 return [elem];
2027 }
2028 else if (Array.isArray(obj)) {
2029 var result = [];
2030 for (var _i = 0, obj_1 = obj; _i < obj_1.length; _i++) {
2031 var arrayElem = obj_1[_i];
2032 for (var _a = 0, _b = buildNode(arrayElem, elementName); _a < _b.length; _a++) {
2033 var child = _b[_a];
2034 result.push(child);
2035 }
2036 }
2037 return result;
2038 }
2039 else if (typeof obj === "object") {
2040 var elem = doc.createElement(elementName);
2041 for (var _c = 0, _d = Object.keys(obj); _c < _d.length; _c++) {
2042 var key = _d[_c];
2043 if (key === "$") {
2044 for (var _e = 0, _f = buildAttributes(obj[key]); _e < _f.length; _e++) {
2045 var attr = _f[_e];
2046 elem.attributes.setNamedItem(attr);
2047 }
2048 }
2049 else {
2050 for (var _g = 0, _h = buildNode(obj[key], key); _g < _h.length; _g++) {
2051 var child = _h[_g];
2052 elem.appendChild(child);
2053 }
2054 }
2055 }
2056 return [elem];
2057 }
2058 else {
2059 throw new Error("Illegal value passed to buildObject: " + obj);
2060 }
2061 }
2062
2063 // Copyright (c) Microsoft Corporation. All rights reserved.
2064 var BaseRequestPolicy = /** @class */ (function () {
2065 function BaseRequestPolicy(_nextPolicy, _options) {
2066 this._nextPolicy = _nextPolicy;
2067 this._options = _options;
2068 }
2069 /**
2070 * Get whether or not a log with the provided log level should be logged.
2071 * @param logLevel The log level of the log that will be logged.
2072 * @returns Whether or not a log with the provided log level should be logged.
2073 */
2074 BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
2075 return this._options.shouldLog(logLevel);
2076 };
2077 /**
2078 * Attempt to log the provided message to the provided logger. If no logger was provided or if
2079 * the log level does not meat the logger's threshold, then nothing will be logged.
2080 * @param logLevel The log level of this log.
2081 * @param message The message of this log.
2082 */
2083 BaseRequestPolicy.prototype.log = function (logLevel, message) {
2084 this._options.log(logLevel, message);
2085 };
2086 return BaseRequestPolicy;
2087 }());
2088 /**
2089 * Optional properties that can be used when creating a RequestPolicy.
2090 */
2091 var RequestPolicyOptions = /** @class */ (function () {
2092 function RequestPolicyOptions(_logger) {
2093 this._logger = _logger;
2094 }
2095 /**
2096 * Get whether or not a log with the provided log level should be logged.
2097 * @param logLevel The log level of the log that will be logged.
2098 * @returns Whether or not a log with the provided log level should be logged.
2099 */
2100 RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
2101 return (!!this._logger &&
2102 logLevel !== exports.HttpPipelineLogLevel.OFF &&
2103 logLevel <= this._logger.minimumLogLevel);
2104 };
2105 /**
2106 * Attempt to log the provided message to the provided logger. If no logger was provided or if
2107 * the log level does not meat the logger's threshold, then nothing will be logged.
2108 * @param logLevel The log level of this log.
2109 * @param message The message of this log.
2110 */
2111 RequestPolicyOptions.prototype.log = function (logLevel, message) {
2112 if (this._logger && this.shouldLog(logLevel)) {
2113 this._logger.log(logLevel, message);
2114 }
2115 };
2116 return RequestPolicyOptions;
2117 }());
2118
2119 // Copyright (c) Microsoft Corporation. All rights reserved.
2120 /**
2121 * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
2122 * pass through the HTTP pipeline.
2123 */
2124 function deserializationPolicy(deserializationContentTypes) {
2125 return {
2126 create: function (nextPolicy, options) {
2127 return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
2128 },
2129 };
2130 }
2131 var defaultJsonContentTypes = ["application/json", "text/json"];
2132 var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
2133 /**
2134 * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
2135 * HTTP pipeline.
2136 */
2137 var DeserializationPolicy = /** @class */ (function (_super) {
2138 __extends(DeserializationPolicy, _super);
2139 function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
2140 var _this = _super.call(this, nextPolicy, options) || this;
2141 _this.jsonContentTypes =
2142 (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes;
2143 _this.xmlContentTypes =
2144 (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes;
2145 return _this;
2146 }
2147 DeserializationPolicy.prototype.sendRequest = function (request) {
2148 return __awaiter(this, void 0, void 0, function () {
2149 var _this = this;
2150 return __generator(this, function (_a) {
2151 return [2 /*return*/, this._nextPolicy
2152 .sendRequest(request)
2153 .then(function (response) {
2154 return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response);
2155 })];
2156 });
2157 });
2158 };
2159 return DeserializationPolicy;
2160 }(BaseRequestPolicy));
2161 function getOperationResponse(parsedResponse) {
2162 var result;
2163 var request = parsedResponse.request;
2164 var operationSpec = request.operationSpec;
2165 if (operationSpec) {
2166 var operationResponseGetter = request.operationResponseGetter;
2167 if (!operationResponseGetter) {
2168 result = operationSpec.responses[parsedResponse.status];
2169 }
2170 else {
2171 result = operationResponseGetter(operationSpec, parsedResponse);
2172 }
2173 }
2174 return result;
2175 }
2176 function shouldDeserializeResponse(parsedResponse) {
2177 var shouldDeserialize = parsedResponse.request.shouldDeserialize;
2178 var result;
2179 if (shouldDeserialize === undefined) {
2180 result = true;
2181 }
2182 else if (typeof shouldDeserialize === "boolean") {
2183 result = shouldDeserialize;
2184 }
2185 else {
2186 result = shouldDeserialize(parsedResponse);
2187 }
2188 return result;
2189 }
2190 function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
2191 return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
2192 var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
2193 if (shouldDeserialize) {
2194 var operationSpec = parsedResponse.request.operationSpec;
2195 if (operationSpec && operationSpec.responses) {
2196 var statusCode = parsedResponse.status;
2197 var expectedStatusCodes = Object.keys(operationSpec.responses);
2198 var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 ||
2199 (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default");
2200 var responseSpec = getOperationResponse(parsedResponse);
2201 var isExpectedStatusCode = hasNoExpectedStatusCodes
2202 ? 200 <= statusCode && statusCode < 300
2203 : !!responseSpec;
2204 if (!isExpectedStatusCode) {
2205 var defaultResponseSpec = operationSpec.responses.default;
2206 if (defaultResponseSpec) {
2207 var initialErrorMessage = isStreamOperation(operationSpec)
2208 ? "Unexpected status code: " + statusCode
2209 : parsedResponse.bodyAsText;
2210 var error = new RestError(initialErrorMessage);
2211 error.statusCode = statusCode;
2212 error.request = stripRequest(parsedResponse.request);
2213 error.response = stripResponse(parsedResponse);
2214 var parsedErrorResponse = parsedResponse.parsedBody;
2215 try {
2216 if (parsedErrorResponse) {
2217 var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
2218 if (defaultResponseBodyMapper &&
2219 defaultResponseBodyMapper.serializedName === "CloudError") {
2220 if (parsedErrorResponse.error) {
2221 parsedErrorResponse = parsedErrorResponse.error;
2222 }
2223 if (parsedErrorResponse.code) {
2224 error.code = parsedErrorResponse.code;
2225 }
2226 if (parsedErrorResponse.message) {
2227 error.message = parsedErrorResponse.message;
2228 }
2229 }
2230 else {
2231 var internalError = parsedErrorResponse;
2232 if (parsedErrorResponse.error) {
2233 internalError = parsedErrorResponse.error;
2234 }
2235 error.code = internalError.code;
2236 if (internalError.message) {
2237 error.message = internalError.message;
2238 }
2239 }
2240 if (defaultResponseBodyMapper) {
2241 var valueToDeserialize = parsedErrorResponse;
2242 if (operationSpec.isXML &&
2243 defaultResponseBodyMapper.type.name === MapperType.Sequence) {
2244 valueToDeserialize =
2245 typeof parsedErrorResponse === "object"
2246 ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
2247 : [];
2248 }
2249 error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
2250 }
2251 }
2252 }
2253 catch (defaultError) {
2254 error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
2255 }
2256 return Promise.reject(error);
2257 }
2258 }
2259 else if (responseSpec) {
2260 if (responseSpec.bodyMapper) {
2261 var valueToDeserialize = parsedResponse.parsedBody;
2262 if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
2263 valueToDeserialize =
2264 typeof valueToDeserialize === "object"
2265 ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
2266 : [];
2267 }
2268 try {
2269 parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
2270 }
2271 catch (error) {
2272 var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
2273 restError.request = stripRequest(parsedResponse.request);
2274 restError.response = stripResponse(parsedResponse);
2275 return Promise.reject(restError);
2276 }
2277 }
2278 else if (operationSpec.httpMethod === "HEAD") {
2279 // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
2280 parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
2281 }
2282 if (responseSpec.headersMapper) {
2283 parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
2284 }
2285 }
2286 }
2287 }
2288 return Promise.resolve(parsedResponse);
2289 });
2290 }
2291 function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
2292 var errorHandler = function (err) {
2293 var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
2294 var errCode = err.code || RestError.PARSE_ERROR;
2295 var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
2296 return Promise.reject(e);
2297 };
2298 if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
2299 var text_1 = operationResponse.bodyAsText;
2300 var contentType = operationResponse.headers.get("Content-Type") || "";
2301 var contentComponents = !contentType
2302 ? []
2303 : contentType.split(";").map(function (component) { return component.toLowerCase(); });
2304 if (contentComponents.length === 0 ||
2305 contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
2306 return new Promise(function (resolve) {
2307 operationResponse.parsedBody = JSON.parse(text_1);
2308 resolve(operationResponse);
2309 }).catch(errorHandler);
2310 }
2311 else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
2312 return parseXML(text_1)
2313 .then(function (body) {
2314 operationResponse.parsedBody = body;
2315 return operationResponse;
2316 })
2317 .catch(errorHandler);
2318 }
2319 }
2320 return Promise.resolve(operationResponse);
2321 }
2322
2323 // Copyright (c) Microsoft Corporation. All rights reserved.
2324 function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
2325 return {
2326 create: function (nextPolicy, options) {
2327 return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
2328 },
2329 };
2330 }
2331 var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
2332 var DEFAULT_CLIENT_RETRY_COUNT = 3;
2333 var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
2334 var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
2335 /**
2336 * @class
2337 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
2338 */
2339 var ExponentialRetryPolicy = /** @class */ (function (_super) {
2340 __extends(ExponentialRetryPolicy, _super);
2341 /**
2342 * @constructor
2343 * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
2344 * @param {RequestPolicyOptionsLike} options The options for this RequestPolicy.
2345 * @param {number} [retryCount] The client retry count.
2346 * @param {number} [retryInterval] The client retry interval, in milliseconds.
2347 * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
2348 * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
2349 */
2350 function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
2351 var _this = _super.call(this, nextPolicy, options) || this;
2352 function isNumber(n) {
2353 return typeof n === "number";
2354 }
2355 _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
2356 _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
2357 _this.minRetryInterval = isNumber(minRetryInterval)
2358 ? minRetryInterval
2359 : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
2360 _this.maxRetryInterval = isNumber(maxRetryInterval)
2361 ? maxRetryInterval
2362 : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
2363 return _this;
2364 }
2365 ExponentialRetryPolicy.prototype.sendRequest = function (request) {
2366 var _this = this;
2367 return this._nextPolicy
2368 .sendRequest(request.clone())
2369 .then(function (response) { return retry(_this, request, response); })
2370 .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
2371 };
2372 return ExponentialRetryPolicy;
2373 }(BaseRequestPolicy));
2374 /**
2375 * Determines if the operation should be retried and how long to wait until the next retry.
2376 *
2377 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
2378 * @param {number} statusCode The HTTP status code.
2379 * @param {RetryData} retryData The retry data.
2380 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
2381 */
2382 function shouldRetry(policy, statusCode, retryData) {
2383 if (statusCode == undefined ||
2384 (statusCode < 500 && statusCode !== 408) ||
2385 statusCode === 501 ||
2386 statusCode === 505) {
2387 return false;
2388 }
2389 var currentCount;
2390 if (!retryData) {
2391 throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
2392 }
2393 else {
2394 currentCount = retryData && retryData.retryCount;
2395 }
2396 return currentCount < policy.retryCount;
2397 }
2398 /**
2399 * Updates the retry data for the next attempt.
2400 *
2401 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
2402 * @param {RetryData} retryData The retry data.
2403 * @param {RetryError} [err] The operation"s error, if any.
2404 */
2405 function updateRetryData(policy, retryData, err) {
2406 if (!retryData) {
2407 retryData = {
2408 retryCount: 0,
2409 retryInterval: 0,
2410 };
2411 }
2412 if (err) {
2413 if (retryData.error) {
2414 err.innerError = retryData.error;
2415 }
2416 retryData.error = err;
2417 }
2418 // Adjust retry count
2419 retryData.retryCount++;
2420 // Adjust retry interval
2421 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
2422 var boundedRandDelta = policy.retryInterval * 0.8 +
2423 Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
2424 incrementDelta *= boundedRandDelta;
2425 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
2426 return retryData;
2427 }
2428 function retry(policy, request, response, retryData, requestError) {
2429 retryData = updateRetryData(policy, retryData, requestError);
2430 var isAborted = request.abortSignal && request.abortSignal.aborted;
2431 if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
2432 return delay(retryData.retryInterval)
2433 .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
2434 .then(function (res) { return retry(policy, request, res, retryData, undefined); })
2435 .catch(function (err) { return retry(policy, request, response, retryData, err); });
2436 }
2437 else if (isAborted || requestError || !response) {
2438 // If the operation failed in the end, return all errors instead of just the last one
2439 var err = retryData.error ||
2440 new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
2441 return Promise.reject(err);
2442 }
2443 else {
2444 return Promise.resolve(response);
2445 }
2446 }
2447
2448 // Copyright (c) Microsoft Corporation. All rights reserved.
2449 function generateClientRequestIdPolicy(requestIdHeaderName) {
2450 if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
2451 return {
2452 create: function (nextPolicy, options) {
2453 return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
2454 },
2455 };
2456 }
2457 var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
2458 __extends(GenerateClientRequestIdPolicy, _super);
2459 function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
2460 var _this = _super.call(this, nextPolicy, options) || this;
2461 _this._requestIdHeaderName = _requestIdHeaderName;
2462 return _this;
2463 }
2464 GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
2465 if (!request.headers.contains(this._requestIdHeaderName)) {
2466 request.headers.set(this._requestIdHeaderName, generateUuid());
2467 }
2468 return this._nextPolicy.sendRequest(request);
2469 };
2470 return GenerateClientRequestIdPolicy;
2471 }(BaseRequestPolicy));
2472
2473 // Copyright (c) Microsoft Corporation. All rights reserved.
2474 // Licensed under the MIT License. See License.txt in the project root for license information.
2475 function getDefaultUserAgentKey() {
2476 return "x-ms-command-name";
2477 }
2478 function getPlatformSpecificData() {
2479 var navigator = self.navigator;
2480 var osInfo = {
2481 key: "OS",
2482 value: (navigator.oscpu || navigator.platform).replace(" ", ""),
2483 };
2484 return [osInfo];
2485 }
2486
2487 // Copyright (c) Microsoft Corporation. All rights reserved.
2488 function getRuntimeInfo() {
2489 var msRestRuntime = {
2490 key: "ms-rest-js",
2491 value: Constants.msRestVersion,
2492 };
2493 return [msRestRuntime];
2494 }
2495 function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
2496 if (keySeparator === void 0) { keySeparator = " "; }
2497 if (valueSeparator === void 0) { valueSeparator = "/"; }
2498 return telemetryInfo
2499 .map(function (info) {
2500 var value = info.value ? "" + valueSeparator + info.value : "";
2501 return "" + info.key + value;
2502 })
2503 .join(keySeparator);
2504 }
2505 var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
2506 function getDefaultUserAgentValue() {
2507 var runtimeInfo = getRuntimeInfo();
2508 var platformSpecificData = getPlatformSpecificData();
2509 var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
2510 return userAgent;
2511 }
2512 function userAgentPolicy(userAgentData) {
2513 var key = !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key;
2514 var value = !userAgentData || userAgentData.value == undefined
2515 ? getDefaultUserAgentValue()
2516 : userAgentData.value;
2517 return {
2518 create: function (nextPolicy, options) {
2519 return new UserAgentPolicy(nextPolicy, options, key, value);
2520 },
2521 };
2522 }
2523 var UserAgentPolicy = /** @class */ (function (_super) {
2524 __extends(UserAgentPolicy, _super);
2525 function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
2526 var _this = _super.call(this, _nextPolicy, _options) || this;
2527 _this._nextPolicy = _nextPolicy;
2528 _this._options = _options;
2529 _this.headerKey = headerKey;
2530 _this.headerValue = headerValue;
2531 return _this;
2532 }
2533 UserAgentPolicy.prototype.sendRequest = function (request) {
2534 this.addUserAgentHeader(request);
2535 return this._nextPolicy.sendRequest(request);
2536 };
2537 UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
2538 if (!request.headers) {
2539 request.headers = new HttpHeaders();
2540 }
2541 if (!request.headers.get(this.headerKey) && this.headerValue) {
2542 request.headers.set(this.headerKey, this.headerValue);
2543 }
2544 };
2545 return UserAgentPolicy;
2546 }(BaseRequestPolicy));
2547
2548 // Copyright (c) Microsoft Corporation. All rights reserved.
2549 /**
2550 * A class that handles the query portion of a URLBuilder.
2551 */
2552 var URLQuery = /** @class */ (function () {
2553 function URLQuery() {
2554 this._rawQuery = {};
2555 }
2556 /**
2557 * Get whether or not there any query parameters in this URLQuery.
2558 */
2559 URLQuery.prototype.any = function () {
2560 return Object.keys(this._rawQuery).length > 0;
2561 };
2562 /**
2563 * Set a query parameter with the provided name and value. If the parameterValue is undefined or
2564 * empty, then this will attempt to remove an existing query parameter with the provided
2565 * parameterName.
2566 */
2567 URLQuery.prototype.set = function (parameterName, parameterValue) {
2568 if (parameterName) {
2569 if (parameterValue != undefined) {
2570 var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
2571 this._rawQuery[parameterName] = newValue;
2572 }
2573 else {
2574 delete this._rawQuery[parameterName];
2575 }
2576 }
2577 };
2578 /**
2579 * Get the value of the query parameter with the provided name. If no parameter exists with the
2580 * provided parameter name, then undefined will be returned.
2581 */
2582 URLQuery.prototype.get = function (parameterName) {
2583 return parameterName ? this._rawQuery[parameterName] : undefined;
2584 };
2585 /**
2586 * Get the string representation of this query. The return value will not start with a "?".
2587 */
2588 URLQuery.prototype.toString = function () {
2589 var result = "";
2590 for (var parameterName in this._rawQuery) {
2591 if (result) {
2592 result += "&";
2593 }
2594 var parameterValue = this._rawQuery[parameterName];
2595 if (Array.isArray(parameterValue)) {
2596 var parameterStrings = [];
2597 for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
2598 var parameterValueElement = parameterValue_1[_i];
2599 parameterStrings.push(parameterName + "=" + parameterValueElement);
2600 }
2601 result += parameterStrings.join("&");
2602 }
2603 else {
2604 result += parameterName + "=" + parameterValue;
2605 }
2606 }
2607 return result;
2608 };
2609 /**
2610 * Parse a URLQuery from the provided text.
2611 */
2612 URLQuery.parse = function (text) {
2613 var result = new URLQuery();
2614 if (text) {
2615 if (text.startsWith("?")) {
2616 text = text.substring(1);
2617 }
2618 var currentState = "ParameterName";
2619 var parameterName = "";
2620 var parameterValue = "";
2621 for (var i = 0; i < text.length; ++i) {
2622 var currentCharacter = text[i];
2623 switch (currentState) {
2624 case "ParameterName":
2625 switch (currentCharacter) {
2626 case "=":
2627 currentState = "ParameterValue";
2628 break;
2629 case "&":
2630 parameterName = "";
2631 parameterValue = "";
2632 break;
2633 default:
2634 parameterName += currentCharacter;
2635 break;
2636 }
2637 break;
2638 case "ParameterValue":
2639 switch (currentCharacter) {
2640 case "&":
2641 result.set(parameterName, parameterValue);
2642 parameterName = "";
2643 parameterValue = "";
2644 currentState = "ParameterName";
2645 break;
2646 default:
2647 parameterValue += currentCharacter;
2648 break;
2649 }
2650 break;
2651 default:
2652 throw new Error("Unrecognized URLQuery parse state: " + currentState);
2653 }
2654 }
2655 if (currentState === "ParameterValue") {
2656 result.set(parameterName, parameterValue);
2657 }
2658 }
2659 return result;
2660 };
2661 return URLQuery;
2662 }());
2663 /**
2664 * A class that handles creating, modifying, and parsing URLs.
2665 */
2666 var URLBuilder = /** @class */ (function () {
2667 function URLBuilder() {
2668 }
2669 /**
2670 * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
2671 * (such as a host, port, path, or query), those parts will be added to this URL as well.
2672 */
2673 URLBuilder.prototype.setScheme = function (scheme) {
2674 if (!scheme) {
2675 this._scheme = undefined;
2676 }
2677 else {
2678 this.set(scheme, "SCHEME");
2679 }
2680 };
2681 /**
2682 * Get the scheme that has been set in this URL.
2683 */
2684 URLBuilder.prototype.getScheme = function () {
2685 return this._scheme;
2686 };
2687 /**
2688 * Set the host for this URL. If the provided host contains other parts of a URL (such as a
2689 * port, path, or query), those parts will be added to this URL as well.
2690 */
2691 URLBuilder.prototype.setHost = function (host) {
2692 if (!host) {
2693 this._host = undefined;
2694 }
2695 else {
2696 this.set(host, "SCHEME_OR_HOST");
2697 }
2698 };
2699 /**
2700 * Get the host that has been set in this URL.
2701 */
2702 URLBuilder.prototype.getHost = function () {
2703 return this._host;
2704 };
2705 /**
2706 * Set the port for this URL. If the provided port contains other parts of a URL (such as a
2707 * path or query), those parts will be added to this URL as well.
2708 */
2709 URLBuilder.prototype.setPort = function (port) {
2710 if (port == undefined || port === "") {
2711 this._port = undefined;
2712 }
2713 else {
2714 this.set(port.toString(), "PORT");
2715 }
2716 };
2717 /**
2718 * Get the port that has been set in this URL.
2719 */
2720 URLBuilder.prototype.getPort = function () {
2721 return this._port;
2722 };
2723 /**
2724 * Set the path for this URL. If the provided path contains a query, then it will be added to
2725 * this URL as well.
2726 */
2727 URLBuilder.prototype.setPath = function (path) {
2728 if (!path) {
2729 this._path = undefined;
2730 }
2731 else {
2732 var schemeIndex = path.indexOf("://");
2733 if (schemeIndex !== -1) {
2734 var schemeStart = path.lastIndexOf("/", schemeIndex);
2735 // Make sure to only grab the URL part of the path before setting the state back to SCHEME
2736 // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com"
2737 this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME");
2738 }
2739 else {
2740 this.set(path, "PATH");
2741 }
2742 }
2743 };
2744 /**
2745 * Append the provided path to this URL's existing path. If the provided path contains a query,
2746 * then it will be added to this URL as well.
2747 */
2748 URLBuilder.prototype.appendPath = function (path) {
2749 if (path) {
2750 var currentPath = this.getPath();
2751 if (currentPath) {
2752 if (!currentPath.endsWith("/")) {
2753 currentPath += "/";
2754 }
2755 if (path.startsWith("/")) {
2756 path = path.substring(1);
2757 }
2758 path = currentPath + path;
2759 }
2760 this.set(path, "PATH");
2761 }
2762 };
2763 /**
2764 * Get the path that has been set in this URL.
2765 */
2766 URLBuilder.prototype.getPath = function () {
2767 return this._path;
2768 };
2769 /**
2770 * Set the query in this URL.
2771 */
2772 URLBuilder.prototype.setQuery = function (query) {
2773 if (!query) {
2774 this._query = undefined;
2775 }
2776 else {
2777 this._query = URLQuery.parse(query);
2778 }
2779 };
2780 /**
2781 * Set a query parameter with the provided name and value in this URL's query. If the provided
2782 * query parameter value is undefined or empty, then the query parameter will be removed if it
2783 * existed.
2784 */
2785 URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
2786 if (queryParameterName) {
2787 if (!this._query) {
2788 this._query = new URLQuery();
2789 }
2790 this._query.set(queryParameterName, queryParameterValue);
2791 }
2792 };
2793 /**
2794 * Get the value of the query parameter with the provided query parameter name. If no query
2795 * parameter exists with the provided name, then undefined will be returned.
2796 */
2797 URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
2798 return this._query ? this._query.get(queryParameterName) : undefined;
2799 };
2800 /**
2801 * Get the query in this URL.
2802 */
2803 URLBuilder.prototype.getQuery = function () {
2804 return this._query ? this._query.toString() : undefined;
2805 };
2806 /**
2807 * Set the parts of this URL by parsing the provided text using the provided startState.
2808 */
2809 URLBuilder.prototype.set = function (text, startState) {
2810 var tokenizer = new URLTokenizer(text, startState);
2811 while (tokenizer.next()) {
2812 var token = tokenizer.current();
2813 if (token) {
2814 switch (token.type) {
2815 case "SCHEME":
2816 this._scheme = token.text || undefined;
2817 break;
2818 case "HOST":
2819 this._host = token.text || undefined;
2820 break;
2821 case "PORT":
2822 this._port = token.text || undefined;
2823 break;
2824 case "PATH":
2825 var tokenPath = token.text || undefined;
2826 if (!this._path || this._path === "/" || tokenPath !== "/") {
2827 this._path = tokenPath;
2828 }
2829 break;
2830 case "QUERY":
2831 this._query = URLQuery.parse(token.text);
2832 break;
2833 default:
2834 throw new Error("Unrecognized URLTokenType: " + token.type);
2835 }
2836 }
2837 }
2838 };
2839 URLBuilder.prototype.toString = function () {
2840 var result = "";
2841 if (this._scheme) {
2842 result += this._scheme + "://";
2843 }
2844 if (this._host) {
2845 result += this._host;
2846 }
2847 if (this._port) {
2848 result += ":" + this._port;
2849 }
2850 if (this._path) {
2851 if (!this._path.startsWith("/")) {
2852 result += "/";
2853 }
2854 result += this._path;
2855 }
2856 if (this._query && this._query.any()) {
2857 result += "?" + this._query.toString();
2858 }
2859 return result;
2860 };
2861 /**
2862 * If the provided searchValue is found in this URLBuilder, then replace it with the provided
2863 * replaceValue.
2864 */
2865 URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
2866 if (searchValue) {
2867 this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
2868 this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
2869 this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
2870 this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
2871 this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
2872 }
2873 };
2874 URLBuilder.parse = function (text) {
2875 var result = new URLBuilder();
2876 result.set(text, "SCHEME_OR_HOST");
2877 return result;
2878 };
2879 return URLBuilder;
2880 }());
2881 var URLToken = /** @class */ (function () {
2882 function URLToken(text, type) {
2883 this.text = text;
2884 this.type = type;
2885 }
2886 URLToken.scheme = function (text) {
2887 return new URLToken(text, "SCHEME");
2888 };
2889 URLToken.host = function (text) {
2890 return new URLToken(text, "HOST");
2891 };
2892 URLToken.port = function (text) {
2893 return new URLToken(text, "PORT");
2894 };
2895 URLToken.path = function (text) {
2896 return new URLToken(text, "PATH");
2897 };
2898 URLToken.query = function (text) {
2899 return new URLToken(text, "QUERY");
2900 };
2901 return URLToken;
2902 }());
2903 /**
2904 * Get whether or not the provided character (single character string) is an alphanumeric (letter or
2905 * digit) character.
2906 */
2907 function isAlphaNumericCharacter(character) {
2908 var characterCode = character.charCodeAt(0);
2909 return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ ||
2910 (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ ||
2911 (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */);
2912 }
2913 /**
2914 * A class that tokenizes URL strings.
2915 */
2916 var URLTokenizer = /** @class */ (function () {
2917 function URLTokenizer(_text, state) {
2918 this._text = _text;
2919 this._textLength = _text ? _text.length : 0;
2920 this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
2921 this._currentIndex = 0;
2922 }
2923 /**
2924 * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
2925 * hasn't started or has finished tokenizing.
2926 */
2927 URLTokenizer.prototype.current = function () {
2928 return this._currentToken;
2929 };
2930 /**
2931 * Advance to the next URLToken and return whether or not a URLToken was found.
2932 */
2933 URLTokenizer.prototype.next = function () {
2934 if (!hasCurrentCharacter(this)) {
2935 this._currentToken = undefined;
2936 }
2937 else {
2938 switch (this._currentState) {
2939 case "SCHEME":
2940 nextScheme(this);
2941 break;
2942 case "SCHEME_OR_HOST":
2943 nextSchemeOrHost(this);
2944 break;
2945 case "HOST":
2946 nextHost(this);
2947 break;
2948 case "PORT":
2949 nextPort(this);
2950 break;
2951 case "PATH":
2952 nextPath(this);
2953 break;
2954 case "QUERY":
2955 nextQuery(this);
2956 break;
2957 default:
2958 throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
2959 }
2960 }
2961 return !!this._currentToken;
2962 };
2963 return URLTokenizer;
2964 }());
2965 /**
2966 * Read the remaining characters from this Tokenizer's character stream.
2967 */
2968 function readRemaining(tokenizer) {
2969 var result = "";
2970 if (tokenizer._currentIndex < tokenizer._textLength) {
2971 result = tokenizer._text.substring(tokenizer._currentIndex);
2972 tokenizer._currentIndex = tokenizer._textLength;
2973 }
2974 return result;
2975 }
2976 /**
2977 * Whether or not this URLTokenizer has a current character.
2978 */
2979 function hasCurrentCharacter(tokenizer) {
2980 return tokenizer._currentIndex < tokenizer._textLength;
2981 }
2982 /**
2983 * Get the character in the text string at the current index.
2984 */
2985 function getCurrentCharacter(tokenizer) {
2986 return tokenizer._text[tokenizer._currentIndex];
2987 }
2988 /**
2989 * Advance to the character in text that is "step" characters ahead. If no step value is provided,
2990 * then step will default to 1.
2991 */
2992 function nextCharacter(tokenizer, step) {
2993 if (hasCurrentCharacter(tokenizer)) {
2994 if (!step) {
2995 step = 1;
2996 }
2997 tokenizer._currentIndex += step;
2998 }
2999 }
3000 /**
3001 * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
3002 * Tokenizer's stream of characters.
3003 */
3004 function peekCharacters(tokenizer, charactersToPeek) {
3005 var endIndex = tokenizer._currentIndex + charactersToPeek;
3006 if (tokenizer._textLength < endIndex) {
3007 endIndex = tokenizer._textLength;
3008 }
3009 return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
3010 }
3011 /**
3012 * Read characters from this Tokenizer until the end of the stream or until the provided condition
3013 * is false when provided the current character.
3014 */
3015 function readWhile(tokenizer, condition) {
3016 var result = "";
3017 while (hasCurrentCharacter(tokenizer)) {
3018 var currentCharacter = getCurrentCharacter(tokenizer);
3019 if (!condition(currentCharacter)) {
3020 break;
3021 }
3022 else {
3023 result += currentCharacter;
3024 nextCharacter(tokenizer);
3025 }
3026 }
3027 return result;
3028 }
3029 /**
3030 * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
3031 * character stream is reached.
3032 */
3033 function readWhileLetterOrDigit(tokenizer) {
3034 return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
3035 }
3036 /**
3037 * Read characters from this Tokenizer until one of the provided terminating characters is read or
3038 * the end of the character stream is reached.
3039 */
3040 function readUntilCharacter(tokenizer) {
3041 var terminatingCharacters = [];
3042 for (var _i = 1; _i < arguments.length; _i++) {
3043 terminatingCharacters[_i - 1] = arguments[_i];
3044 }
3045 return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
3046 }
3047 function nextScheme(tokenizer) {
3048 var scheme = readWhileLetterOrDigit(tokenizer);
3049 tokenizer._currentToken = URLToken.scheme(scheme);
3050 if (!hasCurrentCharacter(tokenizer)) {
3051 tokenizer._currentState = "DONE";
3052 }
3053 else {
3054 tokenizer._currentState = "HOST";
3055 }
3056 }
3057 function nextSchemeOrHost(tokenizer) {
3058 var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
3059 if (!hasCurrentCharacter(tokenizer)) {
3060 tokenizer._currentToken = URLToken.host(schemeOrHost);
3061 tokenizer._currentState = "DONE";
3062 }
3063 else if (getCurrentCharacter(tokenizer) === ":") {
3064 if (peekCharacters(tokenizer, 3) === "://") {
3065 tokenizer._currentToken = URLToken.scheme(schemeOrHost);
3066 tokenizer._currentState = "HOST";
3067 }
3068 else {
3069 tokenizer._currentToken = URLToken.host(schemeOrHost);
3070 tokenizer._currentState = "PORT";
3071 }
3072 }
3073 else {
3074 tokenizer._currentToken = URLToken.host(schemeOrHost);
3075 if (getCurrentCharacter(tokenizer) === "/") {
3076 tokenizer._currentState = "PATH";
3077 }
3078 else {
3079 tokenizer._currentState = "QUERY";
3080 }
3081 }
3082 }
3083 function nextHost(tokenizer) {
3084 if (peekCharacters(tokenizer, 3) === "://") {
3085 nextCharacter(tokenizer, 3);
3086 }
3087 var host = readUntilCharacter(tokenizer, ":", "/", "?");
3088 tokenizer._currentToken = URLToken.host(host);
3089 if (!hasCurrentCharacter(tokenizer)) {
3090 tokenizer._currentState = "DONE";
3091 }
3092 else if (getCurrentCharacter(tokenizer) === ":") {
3093 tokenizer._currentState = "PORT";
3094 }
3095 else if (getCurrentCharacter(tokenizer) === "/") {
3096 tokenizer._currentState = "PATH";
3097 }
3098 else {
3099 tokenizer._currentState = "QUERY";
3100 }
3101 }
3102 function nextPort(tokenizer) {
3103 if (getCurrentCharacter(tokenizer) === ":") {
3104 nextCharacter(tokenizer);
3105 }
3106 var port = readUntilCharacter(tokenizer, "/", "?");
3107 tokenizer._currentToken = URLToken.port(port);
3108 if (!hasCurrentCharacter(tokenizer)) {
3109 tokenizer._currentState = "DONE";
3110 }
3111 else if (getCurrentCharacter(tokenizer) === "/") {
3112 tokenizer._currentState = "PATH";
3113 }
3114 else {
3115 tokenizer._currentState = "QUERY";
3116 }
3117 }
3118 function nextPath(tokenizer) {
3119 var path = readUntilCharacter(tokenizer, "?");
3120 tokenizer._currentToken = URLToken.path(path);
3121 if (!hasCurrentCharacter(tokenizer)) {
3122 tokenizer._currentState = "DONE";
3123 }
3124 else {
3125 tokenizer._currentState = "QUERY";
3126 }
3127 }
3128 function nextQuery(tokenizer) {
3129 if (getCurrentCharacter(tokenizer) === "?") {
3130 nextCharacter(tokenizer);
3131 }
3132 var query = readRemaining(tokenizer);
3133 tokenizer._currentToken = URLToken.query(query);
3134 tokenizer._currentState = "DONE";
3135 }
3136
3137 // Copyright (c) Microsoft Corporation. All rights reserved.
3138 var DefaultRedirectOptions = {
3139 handleRedirects: true,
3140 maxRetries: 20,
3141 };
3142 function redirectPolicy(maximumRetries) {
3143 if (maximumRetries === void 0) { maximumRetries = 20; }
3144 return {
3145 create: function (nextPolicy, options) {
3146 return new RedirectPolicy(nextPolicy, options, maximumRetries);
3147 },
3148 };
3149 }
3150 var RedirectPolicy = /** @class */ (function (_super) {
3151 __extends(RedirectPolicy, _super);
3152 function RedirectPolicy(nextPolicy, options, maxRetries) {
3153 if (maxRetries === void 0) { maxRetries = 20; }
3154 var _this = _super.call(this, nextPolicy, options) || this;
3155 _this.maxRetries = maxRetries;
3156 return _this;
3157 }
3158 RedirectPolicy.prototype.sendRequest = function (request) {
3159 var _this = this;
3160 return this._nextPolicy
3161 .sendRequest(request)
3162 .then(function (response) { return handleRedirect(_this, response, 0); });
3163 };
3164 return RedirectPolicy;
3165 }(BaseRequestPolicy));
3166 function handleRedirect(policy, response, currentRetries) {
3167 var request = response.request, status = response.status;
3168 var locationHeader = response.headers.get("location");
3169 if (locationHeader &&
3170 (status === 300 ||
3171 (status === 301 && ["GET", "HEAD"].includes(request.method)) ||
3172 (status === 302 && ["GET", "POST", "HEAD"].includes(request.method)) ||
3173 (status === 303 && "POST" === request.method) ||
3174 status === 307) &&
3175 ((request.redirectLimit !== undefined && currentRetries < request.redirectLimit) ||
3176 (request.redirectLimit === undefined && currentRetries < policy.maxRetries))) {
3177 var builder = URLBuilder.parse(request.url);
3178 builder.setPath(locationHeader);
3179 request.url = builder.toString();
3180 // POST request with Status code 302 and 303 should be converted into a
3181 // redirected GET request if the redirect url is present in the location header
3182 // reference: https://tools.ietf.org/html/rfc7231#page-57 && https://fetch.spec.whatwg.org/#http-redirect-fetch
3183 if ((status === 302 || status === 303) && request.method === "POST") {
3184 request.method = "GET";
3185 delete request.body;
3186 }
3187 return policy._nextPolicy
3188 .sendRequest(request)
3189 .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); })
3190 .then(function (res) { return recordRedirect(res, request.url); });
3191 }
3192 return Promise.resolve(response);
3193 }
3194 function recordRedirect(response, redirect) {
3195 // This is called as the recursive calls to handleRedirect() unwind,
3196 // only record the deepest/last redirect
3197 if (!response.redirected) {
3198 response.redirected = true;
3199 response.url = redirect;
3200 }
3201 return response;
3202 }
3203
3204 function rpRegistrationPolicy(retryTimeout) {
3205 if (retryTimeout === void 0) { retryTimeout = 30; }
3206 return {
3207 create: function (nextPolicy, options) {
3208 return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
3209 },
3210 };
3211 }
3212 var RPRegistrationPolicy = /** @class */ (function (_super) {
3213 __extends(RPRegistrationPolicy, _super);
3214 function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
3215 if (_retryTimeout === void 0) { _retryTimeout = 30; }
3216 var _this = _super.call(this, nextPolicy, options) || this;
3217 _this._retryTimeout = _retryTimeout;
3218 return _this;
3219 }
3220 RPRegistrationPolicy.prototype.sendRequest = function (request) {
3221 var _this = this;
3222 return this._nextPolicy
3223 .sendRequest(request.clone())
3224 .then(function (response) { return registerIfNeeded(_this, request, response); });
3225 };
3226 return RPRegistrationPolicy;
3227 }(BaseRequestPolicy));
3228 function registerIfNeeded(policy, request, response) {
3229 if (response.status === 409) {
3230 var rpName = checkRPNotRegisteredError(response.bodyAsText);
3231 if (rpName) {
3232 var urlPrefix = extractSubscriptionUrl(request.url);
3233 return (registerRP(policy, urlPrefix, rpName, request)
3234 // Autoregistration of ${provider} failed for some reason. We will not return this error
3235 // instead will return the initial response with 409 status code back to the user.
3236 // do nothing here as we are returning the original response at the end of this method.
3237 .catch(function () { return false; })
3238 .then(function (registrationStatus) {
3239 if (registrationStatus) {
3240 // Retry the original request. We have to change the x-ms-client-request-id
3241 // otherwise Azure endpoint will return the initial 409 (cached) response.
3242 request.headers.set("x-ms-client-request-id", generateUuid());
3243 return policy._nextPolicy.sendRequest(request.clone());
3244 }
3245 return response;
3246 }));
3247 }
3248 }
3249 return Promise.resolve(response);
3250 }
3251 /**
3252 * Reuses the headers of the original request and url (if specified).
3253 * @param {WebResourceLike} originalRequest The original request
3254 * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
3255 * @returns {object} A new request object with desired headers.
3256 */
3257 function getRequestEssentials(originalRequest, reuseUrlToo) {
3258 if (reuseUrlToo === void 0) { reuseUrlToo = false; }
3259 var reqOptions = originalRequest.clone();
3260 if (reuseUrlToo) {
3261 reqOptions.url = originalRequest.url;
3262 }
3263 // We have to change the x-ms-client-request-id otherwise Azure endpoint
3264 // will return the initial 409 (cached) response.
3265 reqOptions.headers.set("x-ms-client-request-id", generateUuid());
3266 // Set content-type to application/json
3267 reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
3268 return reqOptions;
3269 }
3270 /**
3271 * Validates the error code and message associated with 409 response status code. If it matches to that of
3272 * RP not registered then it returns the name of the RP else returns undefined.
3273 * @param {string} body The response body received after making the original request.
3274 * @returns {string} The name of the RP if condition is satisfied else undefined.
3275 */
3276 function checkRPNotRegisteredError(body) {
3277 var result, responseBody;
3278 if (body) {
3279 try {
3280 responseBody = JSON.parse(body);
3281 }
3282 catch (err) {
3283 // do nothing;
3284 }
3285 if (responseBody &&
3286 responseBody.error &&
3287 responseBody.error.message &&
3288 responseBody.error.code &&
3289 responseBody.error.code === "MissingSubscriptionRegistration") {
3290 var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
3291 if (matchRes) {
3292 result = matchRes.pop();
3293 }
3294 }
3295 }
3296 return result;
3297 }
3298 /**
3299 * Extracts the first part of the URL, just after subscription:
3300 * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
3301 * @param {string} url The original request url
3302 * @returns {string} The url prefix as explained above.
3303 */
3304 function extractSubscriptionUrl(url) {
3305 var result;
3306 var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi);
3307 if (matchRes && matchRes[0]) {
3308 result = matchRes[0];
3309 }
3310 else {
3311 throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
3312 }
3313 return result;
3314 }
3315 /**
3316 * Registers the given provider.
3317 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
3318 * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
3319 * @param {string} provider The provider name to be registered.
3320 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
3321 * with a message that the provider is not registered.
3322 * @param {registrationCallback} callback The callback that handles the RP registration
3323 */
3324 function registerRP(policy, urlPrefix, provider, originalRequest) {
3325 var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
3326 var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
3327 var reqOptions = getRequestEssentials(originalRequest);
3328 reqOptions.method = "POST";
3329 reqOptions.url = postUrl;
3330 return policy._nextPolicy.sendRequest(reqOptions).then(function (response) {
3331 if (response.status !== 200) {
3332 throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
3333 }
3334 return getRegistrationStatus(policy, getUrl, originalRequest);
3335 });
3336 }
3337 /**
3338 * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
3339 * Polling will happen till the registrationState property of the response body is "Registered".
3340 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
3341 * @param {string} url The request url for polling
3342 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
3343 * with a message that the provider is not registered.
3344 * @returns {Promise<boolean>} True if RP Registration is successful.
3345 */
3346 function getRegistrationStatus(policy, url, originalRequest) {
3347 var reqOptions = getRequestEssentials(originalRequest);
3348 reqOptions.url = url;
3349 reqOptions.method = "GET";
3350 return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
3351 var obj = res.parsedBody;
3352 if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
3353 return true;
3354 }
3355 else {
3356 return delay(policy._retryTimeout * 1000)
3357 .then(function () { return getRegistrationStatus(policy, url, originalRequest); });
3358 }
3359 });
3360 }
3361
3362 // Copyright (c) Microsoft Corporation. All rights reserved.
3363 function signingPolicy(authenticationProvider) {
3364 return {
3365 create: function (nextPolicy, options) {
3366 return new SigningPolicy(nextPolicy, options, authenticationProvider);
3367 },
3368 };
3369 }
3370 var SigningPolicy = /** @class */ (function (_super) {
3371 __extends(SigningPolicy, _super);
3372 function SigningPolicy(nextPolicy, options, authenticationProvider) {
3373 var _this = _super.call(this, nextPolicy, options) || this;
3374 _this.authenticationProvider = authenticationProvider;
3375 return _this;
3376 }
3377 SigningPolicy.prototype.signRequest = function (request) {
3378 return this.authenticationProvider.signRequest(request);
3379 };
3380 SigningPolicy.prototype.sendRequest = function (request) {
3381 var _this = this;
3382 return this.signRequest(request).then(function (nextRequest) {
3383 return _this._nextPolicy.sendRequest(nextRequest);
3384 });
3385 };
3386 return SigningPolicy;
3387 }(BaseRequestPolicy));
3388
3389 // Copyright (c) Microsoft Corporation. All rights reserved.
3390 function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3391 return {
3392 create: function (nextPolicy, options) {
3393 return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
3394 },
3395 };
3396 }
3397 /**
3398 * @class
3399 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
3400 *
3401 * @constructor
3402 * @param {number} retryCount The client retry count.
3403 * @param {number} retryInterval The client retry interval, in milliseconds.
3404 * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
3405 * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
3406 */
3407 var SystemErrorRetryPolicy = /** @class */ (function (_super) {
3408 __extends(SystemErrorRetryPolicy, _super);
3409 function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3410 var _this = _super.call(this, nextPolicy, options) || this;
3411 _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
3412 _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
3413 _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
3414 _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
3415 _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
3416 _this.retryInterval =
3417 typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
3418 _this.minRetryInterval =
3419 typeof minRetryInterval === "number"
3420 ? minRetryInterval
3421 : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
3422 _this.maxRetryInterval =
3423 typeof maxRetryInterval === "number"
3424 ? maxRetryInterval
3425 : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
3426 return _this;
3427 }
3428 SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
3429 var _this = this;
3430 return this._nextPolicy
3431 .sendRequest(request.clone())
3432 .catch(function (error) { return retry$1(_this, request, error.response, error); });
3433 };
3434 return SystemErrorRetryPolicy;
3435 }(BaseRequestPolicy));
3436 /**
3437 * Determines if the operation should be retried and how long to wait until the next retry.
3438 *
3439 * @param {number} statusCode The HTTP status code.
3440 * @param {RetryData} retryData The retry data.
3441 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
3442 */
3443 function shouldRetry$1(policy, retryData) {
3444 var currentCount;
3445 if (!retryData) {
3446 throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
3447 }
3448 else {
3449 currentCount = retryData && retryData.retryCount;
3450 }
3451 return currentCount < policy.retryCount;
3452 }
3453 /**
3454 * Updates the retry data for the next attempt.
3455 *
3456 * @param {RetryData} retryData The retry data.
3457 * @param {object} err The operation"s error, if any.
3458 */
3459 function updateRetryData$1(policy, retryData, err) {
3460 if (!retryData) {
3461 retryData = {
3462 retryCount: 0,
3463 retryInterval: 0,
3464 };
3465 }
3466 if (err) {
3467 if (retryData.error) {
3468 err.innerError = retryData.error;
3469 }
3470 retryData.error = err;
3471 }
3472 // Adjust retry count
3473 retryData.retryCount++;
3474 // Adjust retry interval
3475 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
3476 var boundedRandDelta = policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 0.4));
3477 incrementDelta *= boundedRandDelta;
3478 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
3479 return retryData;
3480 }
3481 function retry$1(policy, request, operationResponse, err, retryData) {
3482 return __awaiter(this, void 0, void 0, function () {
3483 var error_1;
3484 return __generator(this, function (_a) {
3485 switch (_a.label) {
3486 case 0:
3487 retryData = updateRetryData$1(policy, retryData, err);
3488 if (!(err &&
3489 err.code &&
3490 shouldRetry$1(policy, retryData) &&
3491 (err.code === "ETIMEDOUT" ||
3492 err.code === "ESOCKETTIMEDOUT" ||
3493 err.code === "ECONNREFUSED" ||
3494 err.code === "ECONNRESET" ||
3495 err.code === "ENOENT"))) return [3 /*break*/, 5];
3496 _a.label = 1;
3497 case 1:
3498 _a.trys.push([1, 3, , 4]);
3499 return [4 /*yield*/, delay(retryData.retryInterval)];
3500 case 2:
3501 _a.sent();
3502 return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())];
3503 case 3:
3504 error_1 = _a.sent();
3505 return [2 /*return*/, retry$1(policy, request, operationResponse, error_1, retryData)];
3506 case 4: return [3 /*break*/, 6];
3507 case 5:
3508 if (err) {
3509 // If the operation failed in the end, return all errors instead of just the last one
3510 return [2 /*return*/, Promise.reject(retryData.error)];
3511 }
3512 return [2 /*return*/, operationResponse];
3513 case 6: return [2 /*return*/];
3514 }
3515 });
3516 });
3517 }
3518
3519 // Copyright (c) Microsoft Corporation. All rights reserved.
3520 (function (QueryCollectionFormat) {
3521 QueryCollectionFormat["Csv"] = ",";
3522 QueryCollectionFormat["Ssv"] = " ";
3523 QueryCollectionFormat["Tsv"] = "\t";
3524 QueryCollectionFormat["Pipes"] = "|";
3525 QueryCollectionFormat["Multi"] = "Multi";
3526 })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
3527
3528 // Copyright (c) Microsoft Corporation. All rights reserved.
3529 var agentNotSupportedInBrowser = new Error("AgentPolicy is not supported in browser environment");
3530 function agentPolicy(_agentSettings) {
3531 return {
3532 create: function (_nextPolicy, _options) {
3533 throw agentNotSupportedInBrowser;
3534 },
3535 };
3536 }
3537 var AgentPolicy = /** @class */ (function (_super) {
3538 __extends(AgentPolicy, _super);
3539 function AgentPolicy(nextPolicy, options) {
3540 var _this = _super.call(this, nextPolicy, options) || this;
3541 throw agentNotSupportedInBrowser;
3542 }
3543 AgentPolicy.prototype.sendRequest = function (_request) {
3544 throw agentNotSupportedInBrowser;
3545 };
3546 return AgentPolicy;
3547 }(BaseRequestPolicy));
3548
3549 // Copyright (c) Microsoft Corporation. All rights reserved.
3550 var proxyNotSupportedInBrowser = new Error("ProxyPolicy is not supported in browser environment");
3551 function getDefaultProxySettings(_proxyUrl) {
3552 return undefined;
3553 }
3554 function proxyPolicy(_proxySettings) {
3555 return {
3556 create: function (_nextPolicy, _options) {
3557 throw proxyNotSupportedInBrowser;
3558 },
3559 };
3560 }
3561 var ProxyPolicy = /** @class */ (function (_super) {
3562 __extends(ProxyPolicy, _super);
3563 function ProxyPolicy(nextPolicy, options) {
3564 var _this = _super.call(this, nextPolicy, options) || this;
3565 throw proxyNotSupportedInBrowser;
3566 }
3567 ProxyPolicy.prototype.sendRequest = function (_request) {
3568 throw proxyNotSupportedInBrowser;
3569 };
3570 return ProxyPolicy;
3571 }(BaseRequestPolicy));
3572
3573 // Copyright (c) Microsoft Corporation. All rights reserved.
3574 var StatusCodes = Constants.HttpConstants.StatusCodes;
3575 var DEFAULT_RETRY_COUNT = 3;
3576 function throttlingRetryPolicy(maxRetries) {
3577 if (maxRetries === void 0) { maxRetries = DEFAULT_RETRY_COUNT; }
3578 return {
3579 create: function (nextPolicy, options) {
3580 return new ThrottlingRetryPolicy(nextPolicy, options, maxRetries);
3581 },
3582 };
3583 }
3584 /**
3585 * To learn more, please refer to
3586 * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
3587 * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
3588 * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
3589 */
3590 var ThrottlingRetryPolicy = /** @class */ (function (_super) {
3591 __extends(ThrottlingRetryPolicy, _super);
3592 function ThrottlingRetryPolicy(nextPolicy, options, retryLimit) {
3593 var _this = _super.call(this, nextPolicy, options) || this;
3594 _this.retryLimit = retryLimit;
3595 return _this;
3596 }
3597 ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
3598 return __awaiter(this, void 0, void 0, function () {
3599 var _this = this;
3600 return __generator(this, function (_a) {
3601 return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
3602 return _this.retry(httpRequest, response, 0);
3603 })];
3604 });
3605 });
3606 };
3607 ThrottlingRetryPolicy.prototype.retry = function (httpRequest, httpResponse, retryCount) {
3608 return __awaiter(this, void 0, void 0, function () {
3609 var retryAfterHeader, delayInMs, res;
3610 return __generator(this, function (_a) {
3611 switch (_a.label) {
3612 case 0:
3613 if (httpResponse.status !== StatusCodes.TooManyRequests) {
3614 return [2 /*return*/, httpResponse];
3615 }
3616 retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
3617 if (!(retryAfterHeader && retryCount < this.retryLimit)) return [3 /*break*/, 3];
3618 delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
3619 if (!delayInMs) return [3 /*break*/, 3];
3620 return [4 /*yield*/, delay(delayInMs)];
3621 case 1:
3622 _a.sent();
3623 return [4 /*yield*/, this._nextPolicy.sendRequest(httpRequest)];
3624 case 2:
3625 res = _a.sent();
3626 return [2 /*return*/, this.retry(httpRequest, res, retryCount + 1)];
3627 case 3: return [2 /*return*/, httpResponse];
3628 }
3629 });
3630 });
3631 };
3632 ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
3633 var retryAfterInSeconds = Number(headerValue);
3634 if (Number.isNaN(retryAfterInSeconds)) {
3635 return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
3636 }
3637 else {
3638 return retryAfterInSeconds * 1000;
3639 }
3640 };
3641 ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
3642 try {
3643 var now = Date.now();
3644 var date = Date.parse(headerValue);
3645 var diff = date - now;
3646 return Number.isNaN(diff) ? undefined : diff;
3647 }
3648 catch (error) {
3649 return undefined;
3650 }
3651 };
3652 return ThrottlingRetryPolicy;
3653 }(BaseRequestPolicy));
3654
3655 // Copyright (c) Microsoft Corporation. All rights reserved.
3656 var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
3657 /**
3658 * Resource manager endpoints to match in order to specify a valid scope to the AzureIdentityCredentialAdapter.
3659 */
3660 var azureResourceManagerEndpoints = [
3661 "https://management.windows.net",
3662 "https://management.chinacloudapi.cn",
3663 "https://management.usgovcloudapi.net",
3664 "https://management.cloudapi.de",
3665 ];
3666 /**
3667 * This class provides a simple extension to use {@link TokenCredential} from `@azure/identity` library to
3668 * use with legacy Azure SDKs that accept {@link ServiceClientCredentials} family of credentials for authentication.
3669 */
3670 var AzureIdentityCredentialAdapter = /** @class */ (function () {
3671 function AzureIdentityCredentialAdapter(azureTokenCredential, scopes) {
3672 if (scopes === void 0) { scopes = "https://management.azure.com/.default"; }
3673 this.azureTokenCredential = azureTokenCredential;
3674 this.scopes = scopes;
3675 }
3676 AzureIdentityCredentialAdapter.prototype.getToken = function () {
3677 return __awaiter(this, void 0, void 0, function () {
3678 var accessToken, result;
3679 return __generator(this, function (_a) {
3680 switch (_a.label) {
3681 case 0: return [4 /*yield*/, this.azureTokenCredential.getToken(this.scopes)];
3682 case 1:
3683 accessToken = _a.sent();
3684 if (accessToken !== null) {
3685 result = {
3686 accessToken: accessToken.token,
3687 tokenType: DEFAULT_AUTHORIZATION_SCHEME,
3688 expiresOn: accessToken.expiresOnTimestamp,
3689 };
3690 return [2 /*return*/, result];
3691 }
3692 else {
3693 throw new Error("Could find token for scope");
3694 }
3695 }
3696 });
3697 });
3698 };
3699 AzureIdentityCredentialAdapter.prototype.signRequest = function (webResource) {
3700 return __awaiter(this, void 0, void 0, function () {
3701 var tokenResponse;
3702 return __generator(this, function (_a) {
3703 switch (_a.label) {
3704 case 0: return [4 /*yield*/, this.getToken()];
3705 case 1:
3706 tokenResponse = _a.sent();
3707 webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, tokenResponse.tokenType + " " + tokenResponse.accessToken);
3708 return [2 /*return*/, Promise.resolve(webResource)];
3709 }
3710 });
3711 });
3712 };
3713 return AzureIdentityCredentialAdapter;
3714 }());
3715
3716 // Copyright (c) Microsoft Corporation. All rights reserved.
3717 /**
3718 * @class
3719 * Initializes a new instance of the ServiceClient.
3720 */
3721 var ServiceClient = /** @class */ (function () {
3722 /**
3723 * The ServiceClient constructor
3724 * @constructor
3725 * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
3726 * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
3727 */
3728 function ServiceClient(credentials, options) {
3729 if (!options) {
3730 options = {};
3731 }
3732 if (options.baseUri) {
3733 this.baseUri = options.baseUri;
3734 }
3735 var serviceClientCredentials;
3736 if (isTokenCredential(credentials)) {
3737 var scope = undefined;
3738 if ((options === null || options === void 0 ? void 0 : options.baseUri) && azureResourceManagerEndpoints.includes(options === null || options === void 0 ? void 0 : options.baseUri)) {
3739 scope = options.baseUri + "/.default";
3740 }
3741 serviceClientCredentials = new AzureIdentityCredentialAdapter(credentials, scope);
3742 }
3743 else {
3744 serviceClientCredentials = credentials;
3745 }
3746 if (serviceClientCredentials && !serviceClientCredentials.signRequest) {
3747 throw new Error("credentials argument needs to implement signRequest method");
3748 }
3749 this._withCredentials = options.withCredentials || false;
3750 this._httpClient = options.httpClient || new XhrHttpClient();
3751 this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
3752 var requestPolicyFactories;
3753 if (Array.isArray(options.requestPolicyFactories)) {
3754 requestPolicyFactories = options.requestPolicyFactories;
3755 }
3756 else {
3757 requestPolicyFactories = createDefaultRequestPolicyFactories(serviceClientCredentials, options);
3758 if (options.requestPolicyFactories) {
3759 var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
3760 if (newRequestPolicyFactories) {
3761 requestPolicyFactories = newRequestPolicyFactories;
3762 }
3763 }
3764 }
3765 this._requestPolicyFactories = requestPolicyFactories;
3766 }
3767 /**
3768 * Send the provided httpRequest.
3769 */
3770 ServiceClient.prototype.sendRequest = function (options) {
3771 if (options === null || options === undefined || typeof options !== "object") {
3772 throw new Error("options cannot be null or undefined and it must be of type object.");
3773 }
3774 var httpRequest;
3775 try {
3776 if (isWebResourceLike(options)) {
3777 options.validateRequestProperties();
3778 httpRequest = options;
3779 }
3780 else {
3781 httpRequest = new WebResource();
3782 httpRequest = httpRequest.prepare(options);
3783 }
3784 }
3785 catch (error) {
3786 return Promise.reject(error);
3787 }
3788 var httpPipeline = this._httpClient;
3789 if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
3790 for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
3791 httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
3792 }
3793 }
3794 return httpPipeline.sendRequest(httpRequest);
3795 };
3796 /**
3797 * Send an HTTP request that is populated using the provided OperationSpec.
3798 * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
3799 * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
3800 * @param {ServiceCallback} callback The callback to call when the response is received.
3801 */
3802 ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
3803 if (typeof operationArguments.options === "function") {
3804 callback = operationArguments.options;
3805 operationArguments.options = undefined;
3806 }
3807 var httpRequest = new WebResource();
3808 var result;
3809 try {
3810 var baseUri = operationSpec.baseUrl || this.baseUri;
3811 if (!baseUri) {
3812 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.");
3813 }
3814 httpRequest.method = operationSpec.httpMethod;
3815 httpRequest.operationSpec = operationSpec;
3816 var requestUrl = URLBuilder.parse(baseUri);
3817 if (operationSpec.path) {
3818 requestUrl.appendPath(operationSpec.path);
3819 }
3820 if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
3821 for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
3822 var urlParameter = _a[_i];
3823 var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
3824 urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
3825 if (!urlParameter.skipEncoding) {
3826 urlParameterValue = encodeURIComponent(urlParameterValue);
3827 }
3828 requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
3829 }
3830 }
3831 if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
3832 for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
3833 var queryParameter = _c[_b];
3834 var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
3835 if (queryParameterValue != undefined) {
3836 queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
3837 if (queryParameter.collectionFormat != undefined) {
3838 if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
3839 if (queryParameterValue.length === 0) {
3840 queryParameterValue = "";
3841 }
3842 else {
3843 for (var index in queryParameterValue) {
3844 var item = queryParameterValue[index];
3845 queryParameterValue[index] = item == undefined ? "" : item.toString();
3846 }
3847 }
3848 }
3849 else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv ||
3850 queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) {
3851 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
3852 }
3853 }
3854 if (!queryParameter.skipEncoding) {
3855 if (Array.isArray(queryParameterValue)) {
3856 for (var index in queryParameterValue) {
3857 if (queryParameterValue[index] !== undefined &&
3858 queryParameterValue[index] !== null) {
3859 queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
3860 }
3861 }
3862 }
3863 else {
3864 queryParameterValue = encodeURIComponent(queryParameterValue);
3865 }
3866 }
3867 if (queryParameter.collectionFormat != undefined &&
3868 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi &&
3869 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv &&
3870 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) {
3871 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
3872 }
3873 requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
3874 }
3875 }
3876 }
3877 httpRequest.url = requestUrl.toString();
3878 var contentType = operationSpec.contentType || this.requestContentType;
3879 if (contentType) {
3880 httpRequest.headers.set("Content-Type", contentType);
3881 }
3882 if (operationSpec.headerParameters) {
3883 for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
3884 var headerParameter = _e[_d];
3885 var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
3886 if (headerValue != undefined) {
3887 headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
3888 var headerCollectionPrefix = headerParameter.mapper
3889 .headerCollectionPrefix;
3890 if (headerCollectionPrefix) {
3891 for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
3892 var key = _g[_f];
3893 httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
3894 }
3895 }
3896 else {
3897 httpRequest.headers.set(headerParameter.mapper.serializedName ||
3898 getPathStringFromParameter(headerParameter), headerValue);
3899 }
3900 }
3901 }
3902 }
3903 var options = operationArguments.options;
3904 if (options) {
3905 if (options.customHeaders) {
3906 for (var customHeaderName in options.customHeaders) {
3907 httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
3908 }
3909 }
3910 if (options.abortSignal) {
3911 httpRequest.abortSignal = options.abortSignal;
3912 }
3913 if (options.timeout) {
3914 httpRequest.timeout = options.timeout;
3915 }
3916 if (options.onUploadProgress) {
3917 httpRequest.onUploadProgress = options.onUploadProgress;
3918 }
3919 if (options.onDownloadProgress) {
3920 httpRequest.onDownloadProgress = options.onDownloadProgress;
3921 }
3922 }
3923 httpRequest.withCredentials = this._withCredentials;
3924 serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
3925 if (httpRequest.streamResponseBody == undefined) {
3926 httpRequest.streamResponseBody = isStreamOperation(operationSpec);
3927 }
3928 result = this.sendRequest(httpRequest).then(function (res) {
3929 return flattenResponse(res, operationSpec.responses[res.status]);
3930 });
3931 }
3932 catch (error) {
3933 result = Promise.reject(error);
3934 }
3935 var cb = callback;
3936 if (cb) {
3937 result
3938 // tslint:disable-next-line:no-null-keyword
3939 .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
3940 .catch(function (err) { return cb(err); });
3941 }
3942 return result;
3943 };
3944 return ServiceClient;
3945 }());
3946 function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
3947 if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
3948 httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
3949 var bodyMapper = operationSpec.requestBody.mapper;
3950 var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
3951 var typeName = bodyMapper.type.name;
3952 try {
3953 if (httpRequest.body != undefined || required) {
3954 var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
3955 httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
3956 var isStream = typeName === MapperType.Stream;
3957 if (operationSpec.isXML) {
3958 if (typeName === MapperType.Sequence) {
3959 httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
3960 }
3961 else if (!isStream) {
3962 httpRequest.body = stringifyXML(httpRequest.body, {
3963 rootName: xmlName || serializedName,
3964 });
3965 }
3966 }
3967 else if (!isStream) {
3968 httpRequest.body = JSON.stringify(httpRequest.body);
3969 }
3970 }
3971 }
3972 catch (error) {
3973 throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
3974 }
3975 }
3976 else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
3977 httpRequest.formData = {};
3978 for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
3979 var formDataParameter = _a[_i];
3980 var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
3981 if (formDataParameterValue != undefined) {
3982 var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
3983 httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
3984 }
3985 }
3986 }
3987 }
3988 function isRequestPolicyFactory(instance) {
3989 return typeof instance.create === "function";
3990 }
3991 function getValueOrFunctionResult(value, defaultValueCreator) {
3992 var result;
3993 if (typeof value === "string") {
3994 result = value;
3995 }
3996 else {
3997 result = defaultValueCreator();
3998 if (typeof value === "function") {
3999 result = value(result);
4000 }
4001 }
4002 return result;
4003 }
4004 function createDefaultRequestPolicyFactories(credentials, options) {
4005 var factories = [];
4006 if (options.generateClientRequestIdHeader) {
4007 factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
4008 }
4009 if (credentials) {
4010 if (isRequestPolicyFactory(credentials)) {
4011 factories.push(credentials);
4012 }
4013 else {
4014 factories.push(signingPolicy(credentials));
4015 }
4016 }
4017 var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
4018 var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
4019 if (userAgentHeaderName && userAgentHeaderValue) {
4020 factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
4021 }
4022 var redirectOptions = __assign(__assign({}, DefaultRedirectOptions), options.redirectOptions);
4023 if (redirectOptions.handleRedirects) {
4024 factories.push(redirectPolicy(redirectOptions.maxRetries));
4025 }
4026 factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
4027 if (!options.noRetryPolicy) {
4028 factories.push(exponentialRetryPolicy());
4029 factories.push(systemErrorRetryPolicy());
4030 factories.push(throttlingRetryPolicy());
4031 }
4032 factories.push(deserializationPolicy(options.deserializationContentTypes));
4033 var proxySettings = options.proxySettings || getDefaultProxySettings();
4034 if (proxySettings) {
4035 factories.push(proxyPolicy());
4036 }
4037 if (options.agentSettings) {
4038 factories.push(agentPolicy(options.agentSettings));
4039 }
4040 return factories;
4041 }
4042 function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
4043 return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
4044 }
4045 function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
4046 var value;
4047 if (typeof parameterPath === "string") {
4048 parameterPath = [parameterPath];
4049 }
4050 if (Array.isArray(parameterPath)) {
4051 if (parameterPath.length > 0) {
4052 if (parameterMapper.isConstant) {
4053 value = parameterMapper.defaultValue;
4054 }
4055 else {
4056 var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
4057 if (!propertySearchResult.propertyFound) {
4058 propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
4059 }
4060 var useDefaultValue = false;
4061 if (!propertySearchResult.propertyFound) {
4062 useDefaultValue =
4063 parameterMapper.required ||
4064 (parameterPath[0] === "options" && parameterPath.length === 2);
4065 }
4066 value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
4067 }
4068 // Serialize just for validation purposes.
4069 var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
4070 serializer.serialize(parameterMapper, value, parameterPathString);
4071 }
4072 }
4073 else {
4074 if (parameterMapper.required) {
4075 value = {};
4076 }
4077 for (var propertyName in parameterPath) {
4078 var propertyMapper = parameterMapper.type.modelProperties[propertyName];
4079 var propertyPath = parameterPath[propertyName];
4080 var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
4081 // Serialize just for validation purposes.
4082 var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
4083 serializer.serialize(propertyMapper, propertyValue, propertyPathString);
4084 if (propertyValue !== undefined) {
4085 if (!value) {
4086 value = {};
4087 }
4088 value[propertyName] = propertyValue;
4089 }
4090 }
4091 }
4092 return value;
4093 }
4094 function getPropertyFromParameterPath(parent, parameterPath) {
4095 var result = { propertyFound: false };
4096 var i = 0;
4097 for (; i < parameterPath.length; ++i) {
4098 var parameterPathPart = parameterPath[i];
4099 // Make sure to check inherited properties too, so don't use hasOwnProperty().
4100 if (parent != undefined && parameterPathPart in parent) {
4101 parent = parent[parameterPathPart];
4102 }
4103 else {
4104 break;
4105 }
4106 }
4107 if (i === parameterPath.length) {
4108 result.propertyValue = parent;
4109 result.propertyFound = true;
4110 }
4111 return result;
4112 }
4113 function flattenResponse(_response, responseSpec) {
4114 var parsedHeaders = _response.parsedHeaders;
4115 var bodyMapper = responseSpec && responseSpec.bodyMapper;
4116 var addOperationResponse = function (obj) {
4117 return Object.defineProperty(obj, "_response", {
4118 value: _response,
4119 });
4120 };
4121 if (bodyMapper) {
4122 var typeName = bodyMapper.type.name;
4123 if (typeName === "Stream") {
4124 return addOperationResponse(__assign(__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
4125 }
4126 var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {};
4127 var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
4128 if (typeName === "Sequence" || isPageableResponse) {
4129 // We're expecting a sequece(array) make sure that the response body is in the
4130 // correct format, if not make it an empty array []
4131 var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : [];
4132 var arrayResponse = __spreadArrays(parsedBody);
4133 for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
4134 var key = _a[_i];
4135 if (modelProperties_1[key].serializedName) {
4136 arrayResponse[key] = _response.parsedBody[key];
4137 }
4138 }
4139 if (parsedHeaders) {
4140 for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
4141 var key = _c[_b];
4142 arrayResponse[key] = parsedHeaders[key];
4143 }
4144 }
4145 addOperationResponse(arrayResponse);
4146 return arrayResponse;
4147 }
4148 if (typeName === "Composite" || typeName === "Dictionary") {
4149 return addOperationResponse(__assign(__assign({}, parsedHeaders), _response.parsedBody));
4150 }
4151 }
4152 if (bodyMapper ||
4153 _response.request.method === "HEAD" ||
4154 isPrimitiveType(_response.parsedBody)) {
4155 // primitive body types and HEAD booleans
4156 return addOperationResponse(__assign(__assign({}, parsedHeaders), { body: _response.parsedBody }));
4157 }
4158 return addOperationResponse(__assign(__assign({}, parsedHeaders), _response.parsedBody));
4159 }
4160
4161 // Copyright (c) Microsoft Corporation. All rights reserved.
4162 function logPolicy(logger) {
4163 if (logger === void 0) { logger = console.log; }
4164 return {
4165 create: function (nextPolicy, options) {
4166 return new LogPolicy(nextPolicy, options, logger);
4167 },
4168 };
4169 }
4170 var LogPolicy = /** @class */ (function (_super) {
4171 __extends(LogPolicy, _super);
4172 function LogPolicy(nextPolicy, options, logger) {
4173 if (logger === void 0) { logger = console.log; }
4174 var _this = _super.call(this, nextPolicy, options) || this;
4175 _this.logger = logger;
4176 return _this;
4177 }
4178 LogPolicy.prototype.sendRequest = function (request) {
4179 var _this = this;
4180 return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
4181 };
4182 return LogPolicy;
4183 }(BaseRequestPolicy));
4184 function logResponse(policy, response) {
4185 policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
4186 policy.logger(">> Response status code: " + response.status);
4187 var responseBody = response.bodyAsText;
4188 policy.logger(">> Body: " + responseBody);
4189 return Promise.resolve(response);
4190 }
4191
4192 // Copyright (c) Microsoft Corporation. All rights reserved.
4193 var HeaderConstants = Constants.HeaderConstants;
4194 var DEFAULT_AUTHORIZATION_SCHEME$1 = "Bearer";
4195 /**
4196 * A credentials object that uses a token string and a authorzation scheme to authenticate.
4197 */
4198 var TokenCredentials = /** @class */ (function () {
4199 /**
4200 * Creates a new TokenCredentials object.
4201 *
4202 * @constructor
4203 * @param {string} token The token.
4204 * @param {string} [authorizationScheme] The authorization scheme.
4205 */
4206 function TokenCredentials(token, authorizationScheme) {
4207 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
4208 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
4209 if (!token) {
4210 throw new Error("token cannot be null or undefined.");
4211 }
4212 this.token = token;
4213 this.authorizationScheme = authorizationScheme;
4214 }
4215 /**
4216 * Signs a request with the Authentication header.
4217 *
4218 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
4219 * @return {Promise<WebResourceLike>} The signed request object.
4220 */
4221 TokenCredentials.prototype.signRequest = function (webResource) {
4222 if (!webResource.headers)
4223 webResource.headers = new HttpHeaders();
4224 webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
4225 return Promise.resolve(webResource);
4226 };
4227 return TokenCredentials;
4228 }());
4229
4230 // Copyright (c) Microsoft Corporation. All rights reserved.
4231 var HeaderConstants$1 = Constants.HeaderConstants;
4232 var DEFAULT_AUTHORIZATION_SCHEME$2 = "Basic";
4233 var BasicAuthenticationCredentials = /** @class */ (function () {
4234 /**
4235 * Creates a new BasicAuthenticationCredentials object.
4236 *
4237 * @constructor
4238 * @param {string} userName User name.
4239 * @param {string} password Password.
4240 * @param {string} [authorizationScheme] The authorization scheme.
4241 */
4242 function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
4243 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2; }
4244 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2;
4245 if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
4246 throw new Error("userName cannot be null or undefined and must be of type string.");
4247 }
4248 if (password === null || password === undefined || typeof password.valueOf() !== "string") {
4249 throw new Error("password cannot be null or undefined and must be of type string.");
4250 }
4251 this.userName = userName;
4252 this.password = password;
4253 this.authorizationScheme = authorizationScheme;
4254 }
4255 /**
4256 * Signs a request with the Authentication header.
4257 *
4258 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
4259 * @returns {Promise<WebResourceLike>} The signed request object.
4260 */
4261 BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
4262 var credentials = this.userName + ":" + this.password;
4263 var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
4264 if (!webResource.headers)
4265 webResource.headers = new HttpHeaders();
4266 webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
4267 return Promise.resolve(webResource);
4268 };
4269 return BasicAuthenticationCredentials;
4270 }());
4271
4272 // Copyright (c) Microsoft Corporation. All rights reserved.
4273 /**
4274 * Authenticates to a service using an API key.
4275 */
4276 var ApiKeyCredentials = /** @class */ (function () {
4277 /**
4278 * @constructor
4279 * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
4280 */
4281 function ApiKeyCredentials(options) {
4282 if (!options || (options && !options.inHeader && !options.inQuery)) {
4283 throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
4284 }
4285 this.inHeader = options.inHeader;
4286 this.inQuery = options.inQuery;
4287 }
4288 /**
4289 * Signs a request with the values provided in the inHeader and inQuery parameter.
4290 *
4291 * @param {WebResource} webResource The WebResource to be signed.
4292 * @returns {Promise<WebResource>} The signed request object.
4293 */
4294 ApiKeyCredentials.prototype.signRequest = function (webResource) {
4295 if (!webResource) {
4296 return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
4297 }
4298 if (this.inHeader) {
4299 if (!webResource.headers) {
4300 webResource.headers = new HttpHeaders();
4301 }
4302 for (var headerName in this.inHeader) {
4303 webResource.headers.set(headerName, this.inHeader[headerName]);
4304 }
4305 }
4306 if (this.inQuery) {
4307 if (!webResource.url) {
4308 return Promise.reject(new Error("url cannot be null in the request object."));
4309 }
4310 if (webResource.url.indexOf("?") < 0) {
4311 webResource.url += "?";
4312 }
4313 for (var key in this.inQuery) {
4314 if (!webResource.url.endsWith("?")) {
4315 webResource.url += "&";
4316 }
4317 webResource.url += key + "=" + this.inQuery[key];
4318 }
4319 }
4320 return Promise.resolve(webResource);
4321 };
4322 return ApiKeyCredentials;
4323 }());
4324
4325 // Copyright (c) Microsoft Corporation. All rights reserved.
4326 var TopicCredentials = /** @class */ (function (_super) {
4327 __extends(TopicCredentials, _super);
4328 /**
4329 * Creates a new EventGrid TopicCredentials object.
4330 *
4331 * @constructor
4332 * @param {string} topicKey The EventGrid topic key
4333 */
4334 function TopicCredentials(topicKey) {
4335 var _this = this;
4336 if (!topicKey || (topicKey && typeof topicKey !== "string")) {
4337 throw new Error("topicKey cannot be null or undefined and must be of type string.");
4338 }
4339 var options = {
4340 inHeader: {
4341 "aeg-sas-key": topicKey,
4342 },
4343 };
4344 _this = _super.call(this, options) || this;
4345 return _this;
4346 }
4347 return TopicCredentials;
4348 }(ApiKeyCredentials));
4349
4350 // Copyright (c) Microsoft Corporation. All rights reserved.
4351 var DomainCredentials = /** @class */ (function (_super) {
4352 __extends(DomainCredentials, _super);
4353 /**
4354 * Creates a new EventGrid DomainCredentials object.
4355 *
4356 * @constructor
4357 * @param {string} domainKey The EventGrid domain key
4358 */
4359 function DomainCredentials(domainKey) {
4360 var _this = this;
4361 if (!domainKey || (domainKey && typeof domainKey !== "string")) {
4362 throw new Error("domainKey cannot be null or undefined and must be of type string.");
4363 }
4364 var options = {
4365 inHeader: {
4366 "aeg-sas-key": domainKey,
4367 },
4368 };
4369 _this = _super.call(this, options) || this;
4370 return _this;
4371 }
4372 return DomainCredentials;
4373 }(ApiKeyCredentials));
4374
4375 exports.ApiKeyCredentials = ApiKeyCredentials;
4376 exports.AzureIdentityCredentialAdapter = AzureIdentityCredentialAdapter;
4377 exports.BaseRequestPolicy = BaseRequestPolicy;
4378 exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
4379 exports.Constants = Constants;
4380 exports.DefaultHttpClient = XhrHttpClient;
4381 exports.DomainCredentials = DomainCredentials;
4382 exports.HttpHeaders = HttpHeaders;
4383 exports.MapperType = MapperType;
4384 exports.RequestPolicyOptions = RequestPolicyOptions;
4385 exports.RestError = RestError;
4386 exports.Serializer = Serializer;
4387 exports.ServiceClient = ServiceClient;
4388 exports.TokenCredentials = TokenCredentials;
4389 exports.TopicCredentials = TopicCredentials;
4390 exports.URLBuilder = URLBuilder;
4391 exports.URLQuery = URLQuery;
4392 exports.WebResource = WebResource;
4393 exports.agentPolicy = agentPolicy;
4394 exports.applyMixins = applyMixins;
4395 exports.delay = delay;
4396 exports.deserializationPolicy = deserializationPolicy;
4397 exports.deserializeResponseBody = deserializeResponseBody;
4398 exports.encodeUri = encodeUri;
4399 exports.executePromisesSequentially = executePromisesSequentially;
4400 exports.exponentialRetryPolicy = exponentialRetryPolicy;
4401 exports.flattenResponse = flattenResponse;
4402 exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
4403 exports.generateUuid = generateUuid;
4404 exports.getDefaultProxySettings = getDefaultProxySettings;
4405 exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
4406 exports.isDuration = isDuration;
4407 exports.isNode = isNode;
4408 exports.isValidUuid = isValidUuid;
4409 exports.logPolicy = logPolicy;
4410 exports.promiseToCallback = promiseToCallback;
4411 exports.promiseToServiceCallback = promiseToServiceCallback;
4412 exports.proxyPolicy = proxyPolicy;
4413 exports.redirectPolicy = redirectPolicy;
4414 exports.serializeObject = serializeObject;
4415 exports.signingPolicy = signingPolicy;
4416 exports.stripRequest = stripRequest;
4417 exports.stripResponse = stripResponse;
4418 exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
4419 exports.throttlingRetryPolicy = throttlingRetryPolicy;
4420 exports.userAgentPolicy = userAgentPolicy;
4421
4422 Object.defineProperty(exports, '__esModule', { value: true });
4423
4424})));
4425//# sourceMappingURL=msRest.browser.js.map