UNPKG

214 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'use strict';
6
7Object.defineProperty(exports, '__esModule', { value: true });
8
9function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
10
11var uuid = require('uuid');
12var tslib = require('tslib');
13var http = require('http');
14var https = require('https');
15var node_fetch = _interopDefault(require('node-fetch'));
16var FormData = _interopDefault(require('form-data'));
17var stream = require('stream');
18var tunnel = require('tunnel');
19var xml2js = require('xml2js');
20var os = require('os');
21
22// Copyright (c) Microsoft Corporation. All rights reserved.
23// Licensed under the MIT License. See License.txt in the project root for license information.
24/**
25 * A collection of HttpHeaders that can be sent with a HTTP request.
26 */
27function getHeaderKey(headerName) {
28 return headerName.toLowerCase();
29}
30function isHttpHeadersLike(object) {
31 if (!object || typeof object !== "object") {
32 return false;
33 }
34 if (typeof object.rawHeaders === "function" &&
35 typeof object.clone === "function" &&
36 typeof object.get === "function" &&
37 typeof object.set === "function" &&
38 typeof object.contains === "function" &&
39 typeof object.remove === "function" &&
40 typeof object.headersArray === "function" &&
41 typeof object.headerValues === "function" &&
42 typeof object.headerNames === "function" &&
43 typeof object.toJson === "function") {
44 return true;
45 }
46 return false;
47}
48/**
49 * A collection of HTTP header key/value pairs.
50 */
51var HttpHeaders = /** @class */ (function () {
52 function HttpHeaders(rawHeaders) {
53 this._headersMap = {};
54 if (rawHeaders) {
55 for (var headerName in rawHeaders) {
56 this.set(headerName, rawHeaders[headerName]);
57 }
58 }
59 }
60 /**
61 * Set a header in this collection with the provided name and value. The name is
62 * case-insensitive.
63 * @param headerName The name of the header to set. This value is case-insensitive.
64 * @param headerValue The value of the header to set.
65 */
66 HttpHeaders.prototype.set = function (headerName, headerValue) {
67 this._headersMap[getHeaderKey(headerName)] = {
68 name: headerName,
69 value: headerValue.toString(),
70 };
71 };
72 /**
73 * Get the header value for the provided header name, or undefined if no header exists in this
74 * collection with the provided name.
75 * @param headerName The name of the header.
76 */
77 HttpHeaders.prototype.get = function (headerName) {
78 var header = this._headersMap[getHeaderKey(headerName)];
79 return !header ? undefined : header.value;
80 };
81 /**
82 * Get whether or not this header collection contains a header entry for the provided header name.
83 */
84 HttpHeaders.prototype.contains = function (headerName) {
85 return !!this._headersMap[getHeaderKey(headerName)];
86 };
87 /**
88 * Remove the header with the provided headerName. Return whether or not the header existed and
89 * was removed.
90 * @param headerName The name of the header to remove.
91 */
92 HttpHeaders.prototype.remove = function (headerName) {
93 var result = this.contains(headerName);
94 delete this._headersMap[getHeaderKey(headerName)];
95 return result;
96 };
97 /**
98 * Get the headers that are contained this collection as an object.
99 */
100 HttpHeaders.prototype.rawHeaders = function () {
101 var result = {};
102 for (var headerKey in this._headersMap) {
103 var header = this._headersMap[headerKey];
104 result[header.name.toLowerCase()] = header.value;
105 }
106 return result;
107 };
108 /**
109 * Get the headers that are contained in this collection as an array.
110 */
111 HttpHeaders.prototype.headersArray = function () {
112 var headers = [];
113 for (var headerKey in this._headersMap) {
114 headers.push(this._headersMap[headerKey]);
115 }
116 return headers;
117 };
118 /**
119 * Get the header names that are contained in this collection.
120 */
121 HttpHeaders.prototype.headerNames = function () {
122 var headerNames = [];
123 var headers = this.headersArray();
124 for (var i = 0; i < headers.length; ++i) {
125 headerNames.push(headers[i].name);
126 }
127 return headerNames;
128 };
129 /**
130 * Get the header names that are contained in this collection.
131 */
132 HttpHeaders.prototype.headerValues = function () {
133 var headerValues = [];
134 var headers = this.headersArray();
135 for (var i = 0; i < headers.length; ++i) {
136 headerValues.push(headers[i].value);
137 }
138 return headerValues;
139 };
140 /**
141 * Get the JSON object representation of this HTTP header collection.
142 */
143 HttpHeaders.prototype.toJson = function () {
144 return this.rawHeaders();
145 };
146 /**
147 * Get the string representation of this HTTP header collection.
148 */
149 HttpHeaders.prototype.toString = function () {
150 return JSON.stringify(this.toJson());
151 };
152 /**
153 * Create a deep clone/copy of this HttpHeaders collection.
154 */
155 HttpHeaders.prototype.clone = function () {
156 return new HttpHeaders(this.rawHeaders());
157 };
158 return HttpHeaders;
159}());
160
161// Copyright (c) Microsoft Corporation. All rights reserved.
162// Licensed under the MIT License. See License.txt in the project root for license information.
163/**
164 * Encodes a string in base64 format.
165 * @param value the string to encode
166 */
167function encodeString(value) {
168 return Buffer.from(value).toString("base64");
169}
170/**
171 * Encodes a byte array in base64 format.
172 * @param value the Uint8Aray to encode
173 */
174function encodeByteArray(value) {
175 // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here
176 // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
177 var bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
178 return bufferValue.toString("base64");
179}
180/**
181 * Decodes a base64 string into a byte array.
182 * @param value the base64 string to decode
183 */
184function decodeString(value) {
185 return Buffer.from(value, "base64");
186}
187
188// Copyright (c) Microsoft Corporation. All rights reserved.
189// Licensed under the MIT License. See License.txt in the project root for license information.
190var Constants = {
191 /**
192 * The ms-rest version
193 * @const
194 * @type {string}
195 */
196 msRestVersion: "2.7.0",
197 /**
198 * Specifies HTTP.
199 *
200 * @const
201 * @type {string}
202 */
203 HTTP: "http:",
204 /**
205 * Specifies HTTPS.
206 *
207 * @const
208 * @type {string}
209 */
210 HTTPS: "https:",
211 /**
212 * Specifies HTTP Proxy.
213 *
214 * @const
215 * @type {string}
216 */
217 HTTP_PROXY: "HTTP_PROXY",
218 /**
219 * Specifies HTTPS Proxy.
220 *
221 * @const
222 * @type {string}
223 */
224 HTTPS_PROXY: "HTTPS_PROXY",
225 /**
226 * Specifies NO Proxy.
227 */
228 NO_PROXY: "NO_PROXY",
229 /**
230 * Specifies ALL Proxy.
231 */
232 ALL_PROXY: "ALL_PROXY",
233 HttpConstants: {
234 /**
235 * Http Verbs
236 *
237 * @const
238 * @enum {string}
239 */
240 HttpVerbs: {
241 PUT: "PUT",
242 GET: "GET",
243 DELETE: "DELETE",
244 POST: "POST",
245 MERGE: "MERGE",
246 HEAD: "HEAD",
247 PATCH: "PATCH",
248 },
249 StatusCodes: {
250 TooManyRequests: 429,
251 },
252 },
253 /**
254 * Defines constants for use with HTTP headers.
255 */
256 HeaderConstants: {
257 /**
258 * The Authorization header.
259 *
260 * @const
261 * @type {string}
262 */
263 AUTHORIZATION: "authorization",
264 AUTHORIZATION_SCHEME: "Bearer",
265 /**
266 * The Retry-After response-header field can be used with a 503 (Service
267 * Unavailable) or 349 (Too Many Requests) responses to indicate how long
268 * the service is expected to be unavailable to the requesting client.
269 *
270 * @const
271 * @type {string}
272 */
273 RETRY_AFTER: "Retry-After",
274 /**
275 * The UserAgent header.
276 *
277 * @const
278 * @type {string}
279 */
280 USER_AGENT: "User-Agent",
281 },
282};
283
284// Copyright (c) Microsoft Corporation. All rights reserved.
285/**
286 * A constant that indicates whether the environment is node.js or browser based.
287 */
288var isNode = typeof process !== "undefined" &&
289 !!process.version &&
290 !!process.versions &&
291 !!process.versions.node;
292/**
293 * Encodes an URI.
294 *
295 * @param {string} uri The URI to be encoded.
296 * @return {string} The encoded URI.
297 */
298function encodeUri(uri) {
299 return encodeURIComponent(uri)
300 .replace(/!/g, "%21")
301 .replace(/"/g, "%27")
302 .replace(/\(/g, "%28")
303 .replace(/\)/g, "%29")
304 .replace(/\*/g, "%2A");
305}
306/**
307 * Returns a stripped version of the Http Response which only contains body,
308 * headers and the status.
309 *
310 * @param {HttpOperationResponse} response The Http Response
311 *
312 * @return {object} The stripped version of Http Response.
313 */
314function stripResponse(response) {
315 var strippedResponse = {};
316 strippedResponse.body = response.bodyAsText;
317 strippedResponse.headers = response.headers;
318 strippedResponse.status = response.status;
319 return strippedResponse;
320}
321/**
322 * Returns a stripped version of the Http Request that does not contain the
323 * Authorization header.
324 *
325 * @param {WebResource} request The Http Request object
326 *
327 * @return {WebResource} The stripped version of Http Request.
328 */
329function stripRequest(request) {
330 var strippedRequest = request.clone();
331 if (strippedRequest.headers) {
332 strippedRequest.headers.remove("authorization");
333 }
334 return strippedRequest;
335}
336/**
337 * Validates the given uuid as a string
338 *
339 * @param {string} uuid The uuid as a string that needs to be validated
340 *
341 * @return {boolean} True if the uuid is valid; false otherwise.
342 */
343function isValidUuid(uuid) {
344 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");
345 return validUuidRegex.test(uuid);
346}
347/**
348 * Generated UUID
349 *
350 * @return {string} RFC4122 v4 UUID.
351 */
352function generateUuid() {
353 return uuid.v4();
354}
355/**
356 * Executes an array of promises sequentially. Inspiration of this method is here:
357 * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
358 *
359 * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
360 *
361 * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
362 * If not provided then the promise chain starts with undefined.
363 *
364 * @return A chain of resolved or rejected promises
365 */
366function executePromisesSequentially(promiseFactories, kickstart) {
367 var result = Promise.resolve(kickstart);
368 promiseFactories.forEach(function (promiseFactory) {
369 result = result.then(promiseFactory);
370 });
371 return result;
372}
373/**
374 * A wrapper for setTimeout that resolves a promise after t milliseconds.
375 * @param {number} t The number of milliseconds to be delayed.
376 * @param {T} value The value to be resolved with after a timeout of t milliseconds.
377 * @returns {Promise<T>} Resolved promise
378 */
379function delay(t, value) {
380 return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
381}
382/**
383 * Converts a Promise to a callback.
384 * @param {Promise<any>} promise The Promise to be converted to a callback
385 * @returns {Function} A function that takes the callback (cb: Function): void
386 * @deprecated generated code should instead depend on responseToBody
387 */
388function promiseToCallback(promise) {
389 if (typeof promise.then !== "function") {
390 throw new Error("The provided input is not a Promise.");
391 }
392 return function (cb) {
393 promise.then(function (data) {
394 cb(undefined, data);
395 }, function (err) {
396 cb(err);
397 });
398 };
399}
400/**
401 * Converts a Promise to a service callback.
402 * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
403 * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
404 */
405function promiseToServiceCallback(promise) {
406 if (typeof promise.then !== "function") {
407 throw new Error("The provided input is not a Promise.");
408 }
409 return function (cb) {
410 promise.then(function (data) {
411 process.nextTick(cb, undefined, data.parsedBody, data.request, data);
412 }, function (err) {
413 process.nextTick(cb, err);
414 });
415 };
416}
417function prepareXMLRootList(obj, elementName) {
418 var _a;
419 if (!Array.isArray(obj)) {
420 obj = [obj];
421 }
422 return _a = {}, _a[elementName] = obj, _a;
423}
424/**
425 * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
426 * @param {object} targetCtor The target object on which the properties need to be applied.
427 * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
428 */
429function applyMixins(targetCtor, sourceCtors) {
430 sourceCtors.forEach(function (sourceCtors) {
431 Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
432 targetCtor.prototype[name] = sourceCtors.prototype[name];
433 });
434 });
435}
436var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
437/**
438 * Indicates whether the given string is in ISO 8601 format.
439 * @param {string} value The value to be validated for ISO 8601 duration format.
440 * @return {boolean} `true` if valid, `false` otherwise.
441 */
442function isDuration(value) {
443 return validateISODuration.test(value);
444}
445/**
446 * Replace all of the instances of searchValue in value with the provided replaceValue.
447 * @param {string | undefined} value The value to search and replace in.
448 * @param {string} searchValue The value to search for in the value argument.
449 * @param {string} replaceValue The value to replace searchValue with in the value argument.
450 * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
451 */
452function replaceAll(value, searchValue, replaceValue) {
453 return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
454}
455/**
456 * Determines whether the given enity is a basic/primitive type
457 * (string, number, boolean, null, undefined).
458 * @param value Any entity
459 * @return boolean - true is it is primitive type, false otherwise.
460 */
461function isPrimitiveType(value) {
462 return (typeof value !== "object" && typeof value !== "function") || value === null;
463}
464
465// Copyright (c) Microsoft Corporation. All rights reserved.
466var Serializer = /** @class */ (function () {
467 function Serializer(modelMappers, isXML) {
468 if (modelMappers === void 0) { modelMappers = {}; }
469 this.modelMappers = modelMappers;
470 this.isXML = isXML;
471 }
472 Serializer.prototype.validateConstraints = function (mapper, value, objectName) {
473 var failValidation = function (constraintName, constraintValue) {
474 throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + ".");
475 };
476 if (mapper.constraints && value != undefined) {
477 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;
478 if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {
479 failValidation("ExclusiveMaximum", ExclusiveMaximum);
480 }
481 if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {
482 failValidation("ExclusiveMinimum", ExclusiveMinimum);
483 }
484 if (InclusiveMaximum != undefined && value > InclusiveMaximum) {
485 failValidation("InclusiveMaximum", InclusiveMaximum);
486 }
487 if (InclusiveMinimum != undefined && value < InclusiveMinimum) {
488 failValidation("InclusiveMinimum", InclusiveMinimum);
489 }
490 if (MaxItems != undefined && value.length > MaxItems) {
491 failValidation("MaxItems", MaxItems);
492 }
493 if (MaxLength != undefined && value.length > MaxLength) {
494 failValidation("MaxLength", MaxLength);
495 }
496 if (MinItems != undefined && value.length < MinItems) {
497 failValidation("MinItems", MinItems);
498 }
499 if (MinLength != undefined && value.length < MinLength) {
500 failValidation("MinLength", MinLength);
501 }
502 if (MultipleOf != undefined && value % MultipleOf !== 0) {
503 failValidation("MultipleOf", MultipleOf);
504 }
505 if (Pattern) {
506 var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
507 if (typeof value !== "string" || value.match(pattern) === null) {
508 failValidation("Pattern", Pattern);
509 }
510 }
511 if (UniqueItems &&
512 value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {
513 failValidation("UniqueItems", UniqueItems);
514 }
515 }
516 };
517 /**
518 * Serialize the given object based on its metadata defined in the mapper
519 *
520 * @param {Mapper} mapper The mapper which defines the metadata of the serializable object
521 *
522 * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized
523 *
524 * @param {string} objectName Name of the serialized object
525 *
526 * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object
527 */
528 Serializer.prototype.serialize = function (mapper, object, objectName) {
529 var payload = {};
530 var mapperType = mapper.type.name;
531 if (!objectName) {
532 objectName = mapper.serializedName;
533 }
534 if (mapperType.match(/^Sequence$/gi) !== null) {
535 payload = [];
536 }
537 if (mapper.isConstant) {
538 object = mapper.defaultValue;
539 }
540 // This table of allowed values should help explain
541 // the mapper.required and mapper.nullable properties.
542 // X means "neither undefined or null are allowed".
543 // || required
544 // || true | false
545 // nullable || ==========================
546 // true || null | undefined/null
547 // false || X | undefined
548 // undefined || X | undefined/null
549 var required = mapper.required, nullable = mapper.nullable;
550 if (required && nullable && object === undefined) {
551 throw new Error(objectName + " cannot be undefined.");
552 }
553 if (required && !nullable && object == undefined) {
554 throw new Error(objectName + " cannot be null or undefined.");
555 }
556 if (!required && nullable === false && object === null) {
557 throw new Error(objectName + " cannot be null.");
558 }
559 if (object == undefined) {
560 payload = object;
561 }
562 else {
563 // Validate Constraints if any
564 this.validateConstraints(mapper, object, objectName);
565 if (mapperType.match(/^any$/gi) !== null) {
566 payload = object;
567 }
568 else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/gi) !== null) {
569 payload = serializeBasicTypes(mapperType, objectName, object);
570 }
571 else if (mapperType.match(/^Enum$/gi) !== null) {
572 var enumMapper = mapper;
573 payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
574 }
575 else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/gi) !== null) {
576 payload = serializeDateTypes(mapperType, object, objectName);
577 }
578 else if (mapperType.match(/^ByteArray$/gi) !== null) {
579 payload = serializeByteArrayType(objectName, object);
580 }
581 else if (mapperType.match(/^Base64Url$/gi) !== null) {
582 payload = serializeBase64UrlType(objectName, object);
583 }
584 else if (mapperType.match(/^Sequence$/gi) !== null) {
585 payload = serializeSequenceType(this, mapper, object, objectName);
586 }
587 else if (mapperType.match(/^Dictionary$/gi) !== null) {
588 payload = serializeDictionaryType(this, mapper, object, objectName);
589 }
590 else if (mapperType.match(/^Composite$/gi) !== null) {
591 payload = serializeCompositeType(this, mapper, object, objectName);
592 }
593 }
594 return payload;
595 };
596 /**
597 * Deserialize the given object based on its metadata defined in the mapper
598 *
599 * @param {object} mapper The mapper which defines the metadata of the serializable object
600 *
601 * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized
602 *
603 * @param {string} objectName Name of the deserialized object
604 *
605 * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object
606 */
607 Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {
608 if (responseBody == undefined) {
609 if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
610 // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
611 // between the list being empty versus being missing,
612 // so let's do the more user-friendly thing and return an empty list.
613 responseBody = [];
614 }
615 // specifically check for undefined as default value can be a falsey value `0, "", false, null`
616 if (mapper.defaultValue !== undefined) {
617 responseBody = mapper.defaultValue;
618 }
619 return responseBody;
620 }
621 var payload;
622 var mapperType = mapper.type.name;
623 if (!objectName) {
624 objectName = mapper.serializedName;
625 }
626 if (mapperType.match(/^Composite$/gi) !== null) {
627 payload = deserializeCompositeType(this, mapper, responseBody, objectName);
628 }
629 else {
630 if (this.isXML) {
631 /**
632 * If the mapper specifies this as a non-composite type value but the responseBody contains
633 * both header ("$") and body ("_") properties, then just reduce the responseBody value to
634 * the body ("_") property.
635 */
636 if (responseBody["$"] != undefined && responseBody["_"] != undefined) {
637 responseBody = responseBody["_"];
638 }
639 }
640 if (mapperType.match(/^Number$/gi) !== null) {
641 payload = parseFloat(responseBody);
642 if (isNaN(payload)) {
643 payload = responseBody;
644 }
645 }
646 else if (mapperType.match(/^Boolean$/gi) !== null) {
647 if (responseBody === "true") {
648 payload = true;
649 }
650 else if (responseBody === "false") {
651 payload = false;
652 }
653 else {
654 payload = responseBody;
655 }
656 }
657 else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/gi) !== null) {
658 payload = responseBody;
659 }
660 else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/gi) !== null) {
661 payload = new Date(responseBody);
662 }
663 else if (mapperType.match(/^UnixTime$/gi) !== null) {
664 payload = unixTimeToDate(responseBody);
665 }
666 else if (mapperType.match(/^ByteArray$/gi) !== null) {
667 payload = decodeString(responseBody);
668 }
669 else if (mapperType.match(/^Base64Url$/gi) !== null) {
670 payload = base64UrlToByteArray(responseBody);
671 }
672 else if (mapperType.match(/^Sequence$/gi) !== null) {
673 payload = deserializeSequenceType(this, mapper, responseBody, objectName);
674 }
675 else if (mapperType.match(/^Dictionary$/gi) !== null) {
676 payload = deserializeDictionaryType(this, mapper, responseBody, objectName);
677 }
678 }
679 if (mapper.isConstant) {
680 payload = mapper.defaultValue;
681 }
682 return payload;
683 };
684 return Serializer;
685}());
686function trimEnd(str, ch) {
687 var len = str.length;
688 while (len - 1 >= 0 && str[len - 1] === ch) {
689 --len;
690 }
691 return str.substr(0, len);
692}
693function bufferToBase64Url(buffer) {
694 if (!buffer) {
695 return undefined;
696 }
697 if (!(buffer instanceof Uint8Array)) {
698 throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");
699 }
700 // Uint8Array to Base64.
701 var str = encodeByteArray(buffer);
702 // Base64 to Base64Url.
703 return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
704}
705function base64UrlToByteArray(str) {
706 if (!str) {
707 return undefined;
708 }
709 if (str && typeof str.valueOf() !== "string") {
710 throw new Error("Please provide an input of type string for converting to Uint8Array");
711 }
712 // Base64Url to Base64.
713 str = str.replace(/\-/g, "+").replace(/\_/g, "/");
714 // Base64 to Uint8Array.
715 return decodeString(str);
716}
717function splitSerializeName(prop) {
718 var classes = [];
719 var partialclass = "";
720 if (prop) {
721 var subwords = prop.split(".");
722 for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {
723 var item = subwords_1[_i];
724 if (item.charAt(item.length - 1) === "\\") {
725 partialclass += item.substr(0, item.length - 1) + ".";
726 }
727 else {
728 partialclass += item;
729 classes.push(partialclass);
730 partialclass = "";
731 }
732 }
733 }
734 return classes;
735}
736function dateToUnixTime(d) {
737 if (!d) {
738 return undefined;
739 }
740 if (typeof d.valueOf() === "string") {
741 d = new Date(d);
742 }
743 return Math.floor(d.getTime() / 1000);
744}
745function unixTimeToDate(n) {
746 if (!n) {
747 return undefined;
748 }
749 return new Date(n * 1000);
750}
751function serializeBasicTypes(typeName, objectName, value) {
752 if (value !== null && value !== undefined) {
753 if (typeName.match(/^Number$/gi) !== null) {
754 if (typeof value !== "number") {
755 throw new Error(objectName + " with value " + value + " must be of type number.");
756 }
757 }
758 else if (typeName.match(/^String$/gi) !== null) {
759 if (typeof value.valueOf() !== "string") {
760 throw new Error(objectName + " with value \"" + value + "\" must be of type string.");
761 }
762 }
763 else if (typeName.match(/^Uuid$/gi) !== null) {
764 if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
765 throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid.");
766 }
767 }
768 else if (typeName.match(/^Boolean$/gi) !== null) {
769 if (typeof value !== "boolean") {
770 throw new Error(objectName + " with value " + value + " must be of type boolean.");
771 }
772 }
773 else if (typeName.match(/^Stream$/gi) !== null) {
774 var objectType = typeof value;
775 if (objectType !== "string" &&
776 objectType !== "function" &&
777 !(value instanceof ArrayBuffer) &&
778 !ArrayBuffer.isView(value) &&
779 !(typeof Blob === "function" && value instanceof Blob)) {
780 throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.");
781 }
782 }
783 }
784 return value;
785}
786function serializeEnumType(objectName, allowedValues, value) {
787 if (!allowedValues) {
788 throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type.");
789 }
790 var isPresent = allowedValues.some(function (item) {
791 if (typeof item.valueOf() === "string") {
792 return item.toLowerCase() === value.toLowerCase();
793 }
794 return item === value;
795 });
796 if (!isPresent) {
797 throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + ".");
798 }
799 return value;
800}
801function serializeByteArrayType(objectName, value) {
802 if (value != undefined) {
803 if (!(value instanceof Uint8Array)) {
804 throw new Error(objectName + " must be of type Uint8Array.");
805 }
806 value = encodeByteArray(value);
807 }
808 return value;
809}
810function serializeBase64UrlType(objectName, value) {
811 if (value != undefined) {
812 if (!(value instanceof Uint8Array)) {
813 throw new Error(objectName + " must be of type Uint8Array.");
814 }
815 value = bufferToBase64Url(value);
816 }
817 return value;
818}
819function serializeDateTypes(typeName, value, objectName) {
820 if (value != undefined) {
821 if (typeName.match(/^Date$/gi) !== null) {
822 if (!(value instanceof Date ||
823 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
824 throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
825 }
826 value =
827 value instanceof Date
828 ? value.toISOString().substring(0, 10)
829 : new Date(value).toISOString().substring(0, 10);
830 }
831 else if (typeName.match(/^DateTime$/gi) !== null) {
832 if (!(value instanceof Date ||
833 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
834 throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
835 }
836 value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
837 }
838 else if (typeName.match(/^DateTimeRfc1123$/gi) !== null) {
839 if (!(value instanceof Date ||
840 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
841 throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format.");
842 }
843 value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
844 }
845 else if (typeName.match(/^UnixTime$/gi) !== null) {
846 if (!(value instanceof Date ||
847 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
848 throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " +
849 "for it to be serialized in UnixTime/Epoch format.");
850 }
851 value = dateToUnixTime(value);
852 }
853 else if (typeName.match(/^TimeSpan$/gi) !== null) {
854 if (!isDuration(value)) {
855 throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\".");
856 }
857 value = value;
858 }
859 }
860 return value;
861}
862function serializeSequenceType(serializer, mapper, object, objectName) {
863 if (!Array.isArray(object)) {
864 throw new Error(objectName + " must be of type Array.");
865 }
866 var elementType = mapper.type.element;
867 if (!elementType || typeof elementType !== "object") {
868 throw new Error("element\" metadata for an Array must be defined in the " +
869 ("mapper and it must of type \"object\" in " + objectName + "."));
870 }
871 var tempArray = [];
872 for (var i = 0; i < object.length; i++) {
873 tempArray[i] = serializer.serialize(elementType, object[i], objectName);
874 }
875 return tempArray;
876}
877function serializeDictionaryType(serializer, mapper, object, objectName) {
878 if (typeof object !== "object") {
879 throw new Error(objectName + " must be of type object.");
880 }
881 var valueType = mapper.type.value;
882 if (!valueType || typeof valueType !== "object") {
883 throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
884 ("mapper and it must of type \"object\" in " + objectName + "."));
885 }
886 var tempDictionary = {};
887 for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
888 var key = _a[_i];
889 tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + "." + key);
890 }
891 return tempDictionary;
892}
893/**
894 * Resolves a composite mapper's modelProperties.
895 * @param serializer the serializer containing the entire set of mappers
896 * @param mapper the composite mapper to resolve
897 */
898function resolveModelProperties(serializer, mapper, objectName) {
899 var modelProps = mapper.type.modelProperties;
900 if (!modelProps) {
901 var className = mapper.type.className;
902 if (!className) {
903 throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\".");
904 }
905 var modelMapper = serializer.modelMappers[className];
906 if (!modelMapper) {
907 throw new Error("mapper() cannot be null or undefined for model \"" + className + "\".");
908 }
909 modelProps = modelMapper.type.modelProperties;
910 if (!modelProps) {
911 throw new Error("modelProperties cannot be null or undefined in the " +
912 ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + className + "\" for object \"" + objectName + "\"."));
913 }
914 }
915 return modelProps;
916}
917function serializeCompositeType(serializer, mapper, object, objectName) {
918 var _a;
919 if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
920 mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
921 }
922 if (object != undefined) {
923 var payload = {};
924 var modelProps = resolveModelProperties(serializer, mapper, objectName);
925 for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {
926 var key = _b[_i];
927 var propertyMapper = modelProps[key];
928 if (propertyMapper.readOnly) {
929 continue;
930 }
931 var propName = void 0;
932 var parentObject = payload;
933 if (serializer.isXML) {
934 if (propertyMapper.xmlIsWrapped) {
935 propName = propertyMapper.xmlName;
936 }
937 else {
938 propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
939 }
940 }
941 else {
942 var paths = splitSerializeName(propertyMapper.serializedName);
943 propName = paths.pop();
944 for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {
945 var pathName = paths_1[_c];
946 var childObject = parentObject[pathName];
947 if (childObject == undefined && object[key] != undefined) {
948 parentObject[pathName] = {};
949 }
950 parentObject = parentObject[pathName];
951 }
952 }
953 if (parentObject != undefined) {
954 var propertyObjectName = propertyMapper.serializedName !== ""
955 ? objectName + "." + propertyMapper.serializedName
956 : objectName;
957 var toSerialize = object[key];
958 var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
959 if (polymorphicDiscriminator &&
960 polymorphicDiscriminator.clientName === key &&
961 toSerialize == undefined) {
962 toSerialize = mapper.serializedName;
963 }
964 var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);
965 if (serializedValue !== undefined && propName != undefined) {
966 if (propertyMapper.xmlIsAttribute) {
967 // $ is the key attributes are kept under in xml2js.
968 // This keeps things simple while preventing name collision
969 // with names in user documents.
970 parentObject.$ = parentObject.$ || {};
971 parentObject.$[propName] = serializedValue;
972 }
973 else if (propertyMapper.xmlIsWrapped) {
974 parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);
975 }
976 else {
977 parentObject[propName] = serializedValue;
978 }
979 }
980 }
981 }
982 var additionalPropertiesMapper = mapper.type.additionalProperties;
983 if (additionalPropertiesMapper) {
984 var propNames = Object.keys(modelProps);
985 var _loop_1 = function (clientPropName) {
986 var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });
987 if (isAdditionalProperty) {
988 payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]');
989 }
990 };
991 for (var clientPropName in object) {
992 _loop_1(clientPropName);
993 }
994 }
995 return payload;
996 }
997 return object;
998}
999function isSpecialXmlProperty(propertyName) {
1000 return ["$", "_"].includes(propertyName);
1001}
1002function deserializeCompositeType(serializer, mapper, responseBody, objectName) {
1003 if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
1004 mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
1005 }
1006 var modelProps = resolveModelProperties(serializer, mapper, objectName);
1007 var instance = {};
1008 var handledPropertyNames = [];
1009 for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {
1010 var key = _a[_i];
1011 var propertyMapper = modelProps[key];
1012 var paths = splitSerializeName(modelProps[key].serializedName);
1013 handledPropertyNames.push(paths[0]);
1014 var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;
1015 var propertyObjectName = objectName;
1016 if (serializedName !== "" && serializedName !== undefined) {
1017 propertyObjectName = objectName + "." + serializedName;
1018 }
1019 var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
1020 if (headerCollectionPrefix) {
1021 var dictionary = {};
1022 for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {
1023 var headerKey = _c[_b];
1024 if (headerKey.startsWith(headerCollectionPrefix)) {
1025 dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);
1026 }
1027 handledPropertyNames.push(headerKey);
1028 }
1029 instance[key] = dictionary;
1030 }
1031 else if (serializer.isXML) {
1032 if (propertyMapper.xmlIsAttribute && responseBody.$) {
1033 instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);
1034 }
1035 else {
1036 var propertyName = xmlElementName || xmlName || serializedName;
1037 var unwrappedProperty = responseBody[propertyName];
1038 if (propertyMapper.xmlIsWrapped) {
1039 unwrappedProperty = responseBody[xmlName];
1040 unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];
1041 var isEmptyWrappedList = unwrappedProperty === undefined;
1042 if (isEmptyWrappedList) {
1043 unwrappedProperty = [];
1044 }
1045 }
1046 instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);
1047 }
1048 }
1049 else {
1050 // deserialize the property if it is present in the provided responseBody instance
1051 var propertyInstance = void 0;
1052 var res = responseBody;
1053 // traversing the object step by step.
1054 for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {
1055 var item = paths_2[_d];
1056 if (!res)
1057 break;
1058 res = res[item];
1059 }
1060 propertyInstance = res;
1061 var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
1062 // checking that the model property name (key)(ex: "fishtype") and the
1063 // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
1064 // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
1065 // is a better approach. The generator is not consistent with escaping '\.' in the
1066 // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
1067 // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
1068 // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
1069 // the transformation of model property name (ex: "fishtype") is done consistently.
1070 // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
1071 if (polymorphicDiscriminator &&
1072 key === polymorphicDiscriminator.clientName &&
1073 propertyInstance == undefined) {
1074 propertyInstance = mapper.serializedName;
1075 }
1076 var serializedValue = void 0;
1077 // paging
1078 if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
1079 propertyInstance = responseBody[key];
1080 var arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
1081 // Copy over any properties that have already been added into the instance, where they do
1082 // not exist on the newly de-serialized array
1083 for (var _e = 0, _f = Object.entries(instance); _e < _f.length; _e++) {
1084 var _g = _f[_e], key_1 = _g[0], value = _g[1];
1085 if (!arrayInstance.hasOwnProperty(key_1)) {
1086 arrayInstance[key_1] = value;
1087 }
1088 }
1089 instance = arrayInstance;
1090 }
1091 else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
1092 serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
1093 instance[key] = serializedValue;
1094 }
1095 }
1096 }
1097 var additionalPropertiesMapper = mapper.type.additionalProperties;
1098 if (additionalPropertiesMapper) {
1099 var isAdditionalProperty = function (responsePropName) {
1100 for (var clientPropName in modelProps) {
1101 var paths = splitSerializeName(modelProps[clientPropName].serializedName);
1102 if (paths[0] === responsePropName) {
1103 return false;
1104 }
1105 }
1106 return true;
1107 };
1108 for (var responsePropName in responseBody) {
1109 if (isAdditionalProperty(responsePropName)) {
1110 instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]');
1111 }
1112 }
1113 }
1114 else if (responseBody) {
1115 for (var _h = 0, _j = Object.keys(responseBody); _h < _j.length; _h++) {
1116 var key = _j[_h];
1117 if (instance[key] === undefined &&
1118 !handledPropertyNames.includes(key) &&
1119 !isSpecialXmlProperty(key)) {
1120 instance[key] = responseBody[key];
1121 }
1122 }
1123 }
1124 return instance;
1125}
1126function deserializeDictionaryType(serializer, mapper, responseBody, objectName) {
1127 /*jshint validthis: true */
1128 var value = mapper.type.value;
1129 if (!value || typeof value !== "object") {
1130 throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
1131 ("mapper and it must of type \"object\" in " + objectName));
1132 }
1133 if (responseBody) {
1134 var tempDictionary = {};
1135 for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {
1136 var key = _a[_i];
1137 tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);
1138 }
1139 return tempDictionary;
1140 }
1141 return responseBody;
1142}
1143function deserializeSequenceType(serializer, mapper, responseBody, objectName) {
1144 /*jshint validthis: true */
1145 var element = mapper.type.element;
1146 if (!element || typeof element !== "object") {
1147 throw new Error("element\" metadata for an Array must be defined in the " +
1148 ("mapper and it must of type \"object\" in " + objectName));
1149 }
1150 if (responseBody) {
1151 if (!Array.isArray(responseBody)) {
1152 // xml2js will interpret a single element array as just the element, so force it to be an array
1153 responseBody = [responseBody];
1154 }
1155 var tempArray = [];
1156 for (var i = 0; i < responseBody.length; i++) {
1157 tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]");
1158 }
1159 return tempArray;
1160 }
1161 return responseBody;
1162}
1163function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
1164 var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
1165 if (polymorphicDiscriminator) {
1166 var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
1167 if (discriminatorName != undefined) {
1168 var discriminatorValue = object[discriminatorName];
1169 if (discriminatorValue != undefined) {
1170 var typeName = mapper.type.uberParent || mapper.type.className;
1171 var indexDiscriminator = discriminatorValue === typeName
1172 ? discriminatorValue
1173 : typeName + "." + discriminatorValue;
1174 var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];
1175 if (polymorphicMapper) {
1176 mapper = polymorphicMapper;
1177 }
1178 }
1179 }
1180 }
1181 return mapper;
1182}
1183function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
1184 return (mapper.type.polymorphicDiscriminator ||
1185 getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
1186 getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
1187}
1188function getPolymorphicDiscriminatorSafely(serializer, typeName) {
1189 return (typeName &&
1190 serializer.modelMappers[typeName] &&
1191 serializer.modelMappers[typeName].type.polymorphicDiscriminator);
1192}
1193// TODO: why is this here?
1194function serializeObject(toSerialize) {
1195 if (toSerialize == undefined)
1196 return undefined;
1197 if (toSerialize instanceof Uint8Array) {
1198 toSerialize = encodeByteArray(toSerialize);
1199 return toSerialize;
1200 }
1201 else if (toSerialize instanceof Date) {
1202 return toSerialize.toISOString();
1203 }
1204 else if (Array.isArray(toSerialize)) {
1205 var array = [];
1206 for (var i = 0; i < toSerialize.length; i++) {
1207 array.push(serializeObject(toSerialize[i]));
1208 }
1209 return array;
1210 }
1211 else if (typeof toSerialize === "object") {
1212 var dictionary = {};
1213 for (var property in toSerialize) {
1214 dictionary[property] = serializeObject(toSerialize[property]);
1215 }
1216 return dictionary;
1217 }
1218 return toSerialize;
1219}
1220/**
1221 * Utility function to create a K:V from a list of strings
1222 */
1223function strEnum(o) {
1224 var result = {};
1225 for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {
1226 var key = o_1[_i];
1227 result[key] = key;
1228 }
1229 return result;
1230}
1231var MapperType = strEnum([
1232 "Base64Url",
1233 "Boolean",
1234 "ByteArray",
1235 "Composite",
1236 "Date",
1237 "DateTime",
1238 "DateTimeRfc1123",
1239 "Dictionary",
1240 "Enum",
1241 "Number",
1242 "Object",
1243 "Sequence",
1244 "String",
1245 "Stream",
1246 "TimeSpan",
1247 "UnixTime",
1248]);
1249
1250// Copyright (c) Microsoft Corporation. All rights reserved.
1251function isWebResourceLike(object) {
1252 if (typeof object !== "object") {
1253 return false;
1254 }
1255 if (typeof object.url === "string" &&
1256 typeof object.method === "string" &&
1257 typeof object.headers === "object" &&
1258 isHttpHeadersLike(object.headers) &&
1259 typeof object.validateRequestProperties === "function" &&
1260 typeof object.prepare === "function" &&
1261 typeof object.clone === "function") {
1262 return true;
1263 }
1264 return false;
1265}
1266/**
1267 * Creates a new WebResource object.
1268 *
1269 * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
1270 * properties to initiate a request.
1271 *
1272 * @constructor
1273 */
1274var WebResource = /** @class */ (function () {
1275 function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings, redirectLimit) {
1276 this.streamResponseBody = streamResponseBody;
1277 this.url = url || "";
1278 this.method = method || "GET";
1279 this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers);
1280 this.body = body;
1281 this.query = query;
1282 this.formData = undefined;
1283 this.withCredentials = withCredentials || false;
1284 this.abortSignal = abortSignal;
1285 this.timeout = timeout || 0;
1286 this.onUploadProgress = onUploadProgress;
1287 this.onDownloadProgress = onDownloadProgress;
1288 this.proxySettings = proxySettings;
1289 this.keepAlive = keepAlive;
1290 this.agentSettings = agentSettings;
1291 this.redirectLimit = redirectLimit;
1292 }
1293 /**
1294 * Validates that the required properties such as method, url, headers["Content-Type"],
1295 * headers["accept-language"] are defined. It will throw an error if one of the above
1296 * mentioned properties are not defined.
1297 */
1298 WebResource.prototype.validateRequestProperties = function () {
1299 if (!this.method) {
1300 throw new Error("WebResource.method is required.");
1301 }
1302 if (!this.url) {
1303 throw new Error("WebResource.url is required.");
1304 }
1305 };
1306 /**
1307 * Prepares the request.
1308 * @param {RequestPrepareOptions} options Options to provide for preparing the request.
1309 * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.
1310 */
1311 WebResource.prototype.prepare = function (options) {
1312 if (!options) {
1313 throw new Error("options object is required");
1314 }
1315 if (options.method == undefined || typeof options.method.valueOf() !== "string") {
1316 throw new Error("options.method must be a string.");
1317 }
1318 if (options.url && options.pathTemplate) {
1319 throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.");
1320 }
1321 if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") &&
1322 (options.url == undefined || typeof options.url.valueOf() !== "string")) {
1323 throw new Error("Please provide exactly one of options.pathTemplate or options.url.");
1324 }
1325 // set the url if it is provided.
1326 if (options.url) {
1327 if (typeof options.url !== "string") {
1328 throw new Error('options.url must be of type "string".');
1329 }
1330 this.url = options.url;
1331 }
1332 // set the method
1333 if (options.method) {
1334 var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"];
1335 if (validMethods.indexOf(options.method.toUpperCase()) === -1) {
1336 throw new Error('The provided method "' +
1337 options.method +
1338 '" is invalid. Supported HTTP methods are: ' +
1339 JSON.stringify(validMethods));
1340 }
1341 }
1342 this.method = options.method.toUpperCase();
1343 // construct the url if path template is provided
1344 if (options.pathTemplate) {
1345 var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;
1346 if (typeof pathTemplate_1 !== "string") {
1347 throw new Error('options.pathTemplate must be of type "string".');
1348 }
1349 if (!options.baseUrl) {
1350 options.baseUrl = "https://management.azure.com";
1351 }
1352 var baseUrl = options.baseUrl;
1353 var url_1 = baseUrl +
1354 (baseUrl.endsWith("/") ? "" : "/") +
1355 (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1);
1356 var segments = url_1.match(/({\w*\s*\w*})/gi);
1357 if (segments && segments.length) {
1358 if (!pathParameters_1) {
1359 throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided.");
1360 }
1361 segments.forEach(function (item) {
1362 var pathParamName = item.slice(1, -1);
1363 var pathParam = pathParameters_1[pathParamName];
1364 if (pathParam === null ||
1365 pathParam === undefined ||
1366 !(typeof pathParam === "string" || typeof pathParam === "object")) {
1367 throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName +
1368 (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") +
1369 ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") +
1370 ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }."));
1371 }
1372 if (typeof pathParam.valueOf() === "string") {
1373 url_1 = url_1.replace(item, encodeURIComponent(pathParam));
1374 }
1375 if (typeof pathParam.valueOf() === "object") {
1376 if (!pathParam.value) {
1377 throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
1378 }
1379 if (pathParam.skipUrlEncoding) {
1380 url_1 = url_1.replace(item, pathParam.value);
1381 }
1382 else {
1383 url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));
1384 }
1385 }
1386 });
1387 }
1388 this.url = url_1;
1389 }
1390 // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.
1391 if (options.queryParameters) {
1392 var queryParameters = options.queryParameters;
1393 if (typeof queryParameters !== "object") {
1394 throw new Error("options.queryParameters must be of type object. It should be a JSON object " +
1395 "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " +
1396 "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }.");
1397 }
1398 // append question mark if it is not present in the url
1399 if (this.url && this.url.indexOf("?") === -1) {
1400 this.url += "?";
1401 }
1402 // construct queryString
1403 var queryParams = [];
1404 // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().
1405 this.query = {};
1406 for (var queryParamName in queryParameters) {
1407 var queryParam = queryParameters[queryParamName];
1408 if (queryParam) {
1409 if (typeof queryParam === "string") {
1410 queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam));
1411 this.query[queryParamName] = encodeURIComponent(queryParam);
1412 }
1413 else if (typeof queryParam === "object") {
1414 if (!queryParam.value) {
1415 throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
1416 }
1417 if (queryParam.skipUrlEncoding) {
1418 queryParams.push(queryParamName + "=" + queryParam.value);
1419 this.query[queryParamName] = queryParam.value;
1420 }
1421 else {
1422 queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value));
1423 this.query[queryParamName] = encodeURIComponent(queryParam.value);
1424 }
1425 }
1426 }
1427 } // end-of-for
1428 // append the queryString
1429 this.url += queryParams.join("&");
1430 }
1431 // add headers to the request if they are provided
1432 if (options.headers) {
1433 var headers = options.headers;
1434 for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {
1435 var headerName = _a[_i];
1436 this.headers.set(headerName, headers[headerName]);
1437 }
1438 }
1439 // ensure accept-language is set correctly
1440 if (!this.headers.get("accept-language")) {
1441 this.headers.set("accept-language", "en-US");
1442 }
1443 // ensure the request-id is set correctly
1444 if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) {
1445 this.headers.set("x-ms-client-request-id", generateUuid());
1446 }
1447 // default
1448 if (!this.headers.get("Content-Type")) {
1449 this.headers.set("Content-Type", "application/json; charset=utf-8");
1450 }
1451 // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty
1452 this.body = options.body;
1453 if (options.body != undefined) {
1454 // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.
1455 if (options.bodyIsStream) {
1456 if (!this.headers.get("Transfer-Encoding")) {
1457 this.headers.set("Transfer-Encoding", "chunked");
1458 }
1459 if (this.headers.get("Content-Type") !== "application/octet-stream") {
1460 this.headers.set("Content-Type", "application/octet-stream");
1461 }
1462 }
1463 else {
1464 if (options.serializationMapper) {
1465 this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody");
1466 }
1467 if (!options.disableJsonStringifyOnBody) {
1468 this.body = JSON.stringify(options.body);
1469 }
1470 }
1471 }
1472 this.abortSignal = options.abortSignal;
1473 this.onDownloadProgress = options.onDownloadProgress;
1474 this.onUploadProgress = options.onUploadProgress;
1475 this.redirectLimit = options.redirectLimit;
1476 this.streamResponseBody = options.streamResponseBody;
1477 return this;
1478 };
1479 /**
1480 * Clone this WebResource HTTP request object.
1481 * @returns {WebResource} The clone of this WebResource HTTP request object.
1482 */
1483 WebResource.prototype.clone = function () {
1484 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);
1485 if (this.formData) {
1486 result.formData = this.formData;
1487 }
1488 if (this.operationSpec) {
1489 result.operationSpec = this.operationSpec;
1490 }
1491 if (this.shouldDeserialize) {
1492 result.shouldDeserialize = this.shouldDeserialize;
1493 }
1494 if (this.operationResponseGetter) {
1495 result.operationResponseGetter = this.operationResponseGetter;
1496 }
1497 return result;
1498 };
1499 return WebResource;
1500}());
1501
1502/**
1503 * @author Toru Nagashima <https://github.com/mysticatea>
1504 * @copyright 2015 Toru Nagashima. All rights reserved.
1505 * See LICENSE file in root directory for full license.
1506 */
1507/**
1508 * @typedef {object} PrivateData
1509 * @property {EventTarget} eventTarget The event target.
1510 * @property {{type:string}} event The original event object.
1511 * @property {number} eventPhase The current event phase.
1512 * @property {EventTarget|null} currentTarget The current event target.
1513 * @property {boolean} canceled The flag to prevent default.
1514 * @property {boolean} stopped The flag to stop propagation.
1515 * @property {boolean} immediateStopped The flag to stop propagation immediately.
1516 * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
1517 * @property {number} timeStamp The unix time.
1518 * @private
1519 */
1520
1521/**
1522 * Private data for event wrappers.
1523 * @type {WeakMap<Event, PrivateData>}
1524 * @private
1525 */
1526const privateData = new WeakMap();
1527
1528/**
1529 * Cache for wrapper classes.
1530 * @type {WeakMap<Object, Function>}
1531 * @private
1532 */
1533const wrappers = new WeakMap();
1534
1535/**
1536 * Get private data.
1537 * @param {Event} event The event object to get private data.
1538 * @returns {PrivateData} The private data of the event.
1539 * @private
1540 */
1541function pd(event) {
1542 const retv = privateData.get(event);
1543 console.assert(
1544 retv != null,
1545 "'this' is expected an Event object, but got",
1546 event
1547 );
1548 return retv
1549}
1550
1551/**
1552 * https://dom.spec.whatwg.org/#set-the-canceled-flag
1553 * @param data {PrivateData} private data.
1554 */
1555function setCancelFlag(data) {
1556 if (data.passiveListener != null) {
1557 if (
1558 typeof console !== "undefined" &&
1559 typeof console.error === "function"
1560 ) {
1561 console.error(
1562 "Unable to preventDefault inside passive event listener invocation.",
1563 data.passiveListener
1564 );
1565 }
1566 return
1567 }
1568 if (!data.event.cancelable) {
1569 return
1570 }
1571
1572 data.canceled = true;
1573 if (typeof data.event.preventDefault === "function") {
1574 data.event.preventDefault();
1575 }
1576}
1577
1578/**
1579 * @see https://dom.spec.whatwg.org/#interface-event
1580 * @private
1581 */
1582/**
1583 * The event wrapper.
1584 * @constructor
1585 * @param {EventTarget} eventTarget The event target of this dispatching.
1586 * @param {Event|{type:string}} event The original event to wrap.
1587 */
1588function Event(eventTarget, event) {
1589 privateData.set(this, {
1590 eventTarget,
1591 event,
1592 eventPhase: 2,
1593 currentTarget: eventTarget,
1594 canceled: false,
1595 stopped: false,
1596 immediateStopped: false,
1597 passiveListener: null,
1598 timeStamp: event.timeStamp || Date.now(),
1599 });
1600
1601 // https://heycam.github.io/webidl/#Unforgeable
1602 Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
1603
1604 // Define accessors
1605 const keys = Object.keys(event);
1606 for (let i = 0; i < keys.length; ++i) {
1607 const key = keys[i];
1608 if (!(key in this)) {
1609 Object.defineProperty(this, key, defineRedirectDescriptor(key));
1610 }
1611 }
1612}
1613
1614// Should be enumerable, but class methods are not enumerable.
1615Event.prototype = {
1616 /**
1617 * The type of this event.
1618 * @type {string}
1619 */
1620 get type() {
1621 return pd(this).event.type
1622 },
1623
1624 /**
1625 * The target of this event.
1626 * @type {EventTarget}
1627 */
1628 get target() {
1629 return pd(this).eventTarget
1630 },
1631
1632 /**
1633 * The target of this event.
1634 * @type {EventTarget}
1635 */
1636 get currentTarget() {
1637 return pd(this).currentTarget
1638 },
1639
1640 /**
1641 * @returns {EventTarget[]} The composed path of this event.
1642 */
1643 composedPath() {
1644 const currentTarget = pd(this).currentTarget;
1645 if (currentTarget == null) {
1646 return []
1647 }
1648 return [currentTarget]
1649 },
1650
1651 /**
1652 * Constant of NONE.
1653 * @type {number}
1654 */
1655 get NONE() {
1656 return 0
1657 },
1658
1659 /**
1660 * Constant of CAPTURING_PHASE.
1661 * @type {number}
1662 */
1663 get CAPTURING_PHASE() {
1664 return 1
1665 },
1666
1667 /**
1668 * Constant of AT_TARGET.
1669 * @type {number}
1670 */
1671 get AT_TARGET() {
1672 return 2
1673 },
1674
1675 /**
1676 * Constant of BUBBLING_PHASE.
1677 * @type {number}
1678 */
1679 get BUBBLING_PHASE() {
1680 return 3
1681 },
1682
1683 /**
1684 * The target of this event.
1685 * @type {number}
1686 */
1687 get eventPhase() {
1688 return pd(this).eventPhase
1689 },
1690
1691 /**
1692 * Stop event bubbling.
1693 * @returns {void}
1694 */
1695 stopPropagation() {
1696 const data = pd(this);
1697
1698 data.stopped = true;
1699 if (typeof data.event.stopPropagation === "function") {
1700 data.event.stopPropagation();
1701 }
1702 },
1703
1704 /**
1705 * Stop event bubbling.
1706 * @returns {void}
1707 */
1708 stopImmediatePropagation() {
1709 const data = pd(this);
1710
1711 data.stopped = true;
1712 data.immediateStopped = true;
1713 if (typeof data.event.stopImmediatePropagation === "function") {
1714 data.event.stopImmediatePropagation();
1715 }
1716 },
1717
1718 /**
1719 * The flag to be bubbling.
1720 * @type {boolean}
1721 */
1722 get bubbles() {
1723 return Boolean(pd(this).event.bubbles)
1724 },
1725
1726 /**
1727 * The flag to be cancelable.
1728 * @type {boolean}
1729 */
1730 get cancelable() {
1731 return Boolean(pd(this).event.cancelable)
1732 },
1733
1734 /**
1735 * Cancel this event.
1736 * @returns {void}
1737 */
1738 preventDefault() {
1739 setCancelFlag(pd(this));
1740 },
1741
1742 /**
1743 * The flag to indicate cancellation state.
1744 * @type {boolean}
1745 */
1746 get defaultPrevented() {
1747 return pd(this).canceled
1748 },
1749
1750 /**
1751 * The flag to be composed.
1752 * @type {boolean}
1753 */
1754 get composed() {
1755 return Boolean(pd(this).event.composed)
1756 },
1757
1758 /**
1759 * The unix time of this event.
1760 * @type {number}
1761 */
1762 get timeStamp() {
1763 return pd(this).timeStamp
1764 },
1765
1766 /**
1767 * The target of this event.
1768 * @type {EventTarget}
1769 * @deprecated
1770 */
1771 get srcElement() {
1772 return pd(this).eventTarget
1773 },
1774
1775 /**
1776 * The flag to stop event bubbling.
1777 * @type {boolean}
1778 * @deprecated
1779 */
1780 get cancelBubble() {
1781 return pd(this).stopped
1782 },
1783 set cancelBubble(value) {
1784 if (!value) {
1785 return
1786 }
1787 const data = pd(this);
1788
1789 data.stopped = true;
1790 if (typeof data.event.cancelBubble === "boolean") {
1791 data.event.cancelBubble = true;
1792 }
1793 },
1794
1795 /**
1796 * The flag to indicate cancellation state.
1797 * @type {boolean}
1798 * @deprecated
1799 */
1800 get returnValue() {
1801 return !pd(this).canceled
1802 },
1803 set returnValue(value) {
1804 if (!value) {
1805 setCancelFlag(pd(this));
1806 }
1807 },
1808
1809 /**
1810 * Initialize this event object. But do nothing under event dispatching.
1811 * @param {string} type The event type.
1812 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
1813 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
1814 * @deprecated
1815 */
1816 initEvent() {
1817 // Do nothing.
1818 },
1819};
1820
1821// `constructor` is not enumerable.
1822Object.defineProperty(Event.prototype, "constructor", {
1823 value: Event,
1824 configurable: true,
1825 writable: true,
1826});
1827
1828// Ensure `event instanceof window.Event` is `true`.
1829if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
1830 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
1831
1832 // Make association for wrappers.
1833 wrappers.set(window.Event.prototype, Event);
1834}
1835
1836/**
1837 * Get the property descriptor to redirect a given property.
1838 * @param {string} key Property name to define property descriptor.
1839 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
1840 * @private
1841 */
1842function defineRedirectDescriptor(key) {
1843 return {
1844 get() {
1845 return pd(this).event[key]
1846 },
1847 set(value) {
1848 pd(this).event[key] = value;
1849 },
1850 configurable: true,
1851 enumerable: true,
1852 }
1853}
1854
1855/**
1856 * Get the property descriptor to call a given method property.
1857 * @param {string} key Property name to define property descriptor.
1858 * @returns {PropertyDescriptor} The property descriptor to call the method property.
1859 * @private
1860 */
1861function defineCallDescriptor(key) {
1862 return {
1863 value() {
1864 const event = pd(this).event;
1865 return event[key].apply(event, arguments)
1866 },
1867 configurable: true,
1868 enumerable: true,
1869 }
1870}
1871
1872/**
1873 * Define new wrapper class.
1874 * @param {Function} BaseEvent The base wrapper class.
1875 * @param {Object} proto The prototype of the original event.
1876 * @returns {Function} The defined wrapper class.
1877 * @private
1878 */
1879function defineWrapper(BaseEvent, proto) {
1880 const keys = Object.keys(proto);
1881 if (keys.length === 0) {
1882 return BaseEvent
1883 }
1884
1885 /** CustomEvent */
1886 function CustomEvent(eventTarget, event) {
1887 BaseEvent.call(this, eventTarget, event);
1888 }
1889
1890 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
1891 constructor: { value: CustomEvent, configurable: true, writable: true },
1892 });
1893
1894 // Define accessors.
1895 for (let i = 0; i < keys.length; ++i) {
1896 const key = keys[i];
1897 if (!(key in BaseEvent.prototype)) {
1898 const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1899 const isFunc = typeof descriptor.value === "function";
1900 Object.defineProperty(
1901 CustomEvent.prototype,
1902 key,
1903 isFunc
1904 ? defineCallDescriptor(key)
1905 : defineRedirectDescriptor(key)
1906 );
1907 }
1908 }
1909
1910 return CustomEvent
1911}
1912
1913/**
1914 * Get the wrapper class of a given prototype.
1915 * @param {Object} proto The prototype of the original event to get its wrapper.
1916 * @returns {Function} The wrapper class.
1917 * @private
1918 */
1919function getWrapper(proto) {
1920 if (proto == null || proto === Object.prototype) {
1921 return Event
1922 }
1923
1924 let wrapper = wrappers.get(proto);
1925 if (wrapper == null) {
1926 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
1927 wrappers.set(proto, wrapper);
1928 }
1929 return wrapper
1930}
1931
1932/**
1933 * Wrap a given event to management a dispatching.
1934 * @param {EventTarget} eventTarget The event target of this dispatching.
1935 * @param {Object} event The event to wrap.
1936 * @returns {Event} The wrapper instance.
1937 * @private
1938 */
1939function wrapEvent(eventTarget, event) {
1940 const Wrapper = getWrapper(Object.getPrototypeOf(event));
1941 return new Wrapper(eventTarget, event)
1942}
1943
1944/**
1945 * Get the immediateStopped flag of a given event.
1946 * @param {Event} event The event to get.
1947 * @returns {boolean} The flag to stop propagation immediately.
1948 * @private
1949 */
1950function isStopped(event) {
1951 return pd(event).immediateStopped
1952}
1953
1954/**
1955 * Set the current event phase of a given event.
1956 * @param {Event} event The event to set current target.
1957 * @param {number} eventPhase New event phase.
1958 * @returns {void}
1959 * @private
1960 */
1961function setEventPhase(event, eventPhase) {
1962 pd(event).eventPhase = eventPhase;
1963}
1964
1965/**
1966 * Set the current target of a given event.
1967 * @param {Event} event The event to set current target.
1968 * @param {EventTarget|null} currentTarget New current target.
1969 * @returns {void}
1970 * @private
1971 */
1972function setCurrentTarget(event, currentTarget) {
1973 pd(event).currentTarget = currentTarget;
1974}
1975
1976/**
1977 * Set a passive listener of a given event.
1978 * @param {Event} event The event to set current target.
1979 * @param {Function|null} passiveListener New passive listener.
1980 * @returns {void}
1981 * @private
1982 */
1983function setPassiveListener(event, passiveListener) {
1984 pd(event).passiveListener = passiveListener;
1985}
1986
1987/**
1988 * @typedef {object} ListenerNode
1989 * @property {Function} listener
1990 * @property {1|2|3} listenerType
1991 * @property {boolean} passive
1992 * @property {boolean} once
1993 * @property {ListenerNode|null} next
1994 * @private
1995 */
1996
1997/**
1998 * @type {WeakMap<object, Map<string, ListenerNode>>}
1999 * @private
2000 */
2001const listenersMap = new WeakMap();
2002
2003// Listener types
2004const CAPTURE = 1;
2005const BUBBLE = 2;
2006const ATTRIBUTE = 3;
2007
2008/**
2009 * Check whether a given value is an object or not.
2010 * @param {any} x The value to check.
2011 * @returns {boolean} `true` if the value is an object.
2012 */
2013function isObject(x) {
2014 return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
2015}
2016
2017/**
2018 * Get listeners.
2019 * @param {EventTarget} eventTarget The event target to get.
2020 * @returns {Map<string, ListenerNode>} The listeners.
2021 * @private
2022 */
2023function getListeners(eventTarget) {
2024 const listeners = listenersMap.get(eventTarget);
2025 if (listeners == null) {
2026 throw new TypeError(
2027 "'this' is expected an EventTarget object, but got another value."
2028 )
2029 }
2030 return listeners
2031}
2032
2033/**
2034 * Get the property descriptor for the event attribute of a given event.
2035 * @param {string} eventName The event name to get property descriptor.
2036 * @returns {PropertyDescriptor} The property descriptor.
2037 * @private
2038 */
2039function defineEventAttributeDescriptor(eventName) {
2040 return {
2041 get() {
2042 const listeners = getListeners(this);
2043 let node = listeners.get(eventName);
2044 while (node != null) {
2045 if (node.listenerType === ATTRIBUTE) {
2046 return node.listener
2047 }
2048 node = node.next;
2049 }
2050 return null
2051 },
2052
2053 set(listener) {
2054 if (typeof listener !== "function" && !isObject(listener)) {
2055 listener = null; // eslint-disable-line no-param-reassign
2056 }
2057 const listeners = getListeners(this);
2058
2059 // Traverse to the tail while removing old value.
2060 let prev = null;
2061 let node = listeners.get(eventName);
2062 while (node != null) {
2063 if (node.listenerType === ATTRIBUTE) {
2064 // Remove old value.
2065 if (prev !== null) {
2066 prev.next = node.next;
2067 } else if (node.next !== null) {
2068 listeners.set(eventName, node.next);
2069 } else {
2070 listeners.delete(eventName);
2071 }
2072 } else {
2073 prev = node;
2074 }
2075
2076 node = node.next;
2077 }
2078
2079 // Add new value.
2080 if (listener !== null) {
2081 const newNode = {
2082 listener,
2083 listenerType: ATTRIBUTE,
2084 passive: false,
2085 once: false,
2086 next: null,
2087 };
2088 if (prev === null) {
2089 listeners.set(eventName, newNode);
2090 } else {
2091 prev.next = newNode;
2092 }
2093 }
2094 },
2095 configurable: true,
2096 enumerable: true,
2097 }
2098}
2099
2100/**
2101 * Define an event attribute (e.g. `eventTarget.onclick`).
2102 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
2103 * @param {string} eventName The event name to define.
2104 * @returns {void}
2105 */
2106function defineEventAttribute(eventTargetPrototype, eventName) {
2107 Object.defineProperty(
2108 eventTargetPrototype,
2109 `on${eventName}`,
2110 defineEventAttributeDescriptor(eventName)
2111 );
2112}
2113
2114/**
2115 * Define a custom EventTarget with event attributes.
2116 * @param {string[]} eventNames Event names for event attributes.
2117 * @returns {EventTarget} The custom EventTarget.
2118 * @private
2119 */
2120function defineCustomEventTarget(eventNames) {
2121 /** CustomEventTarget */
2122 function CustomEventTarget() {
2123 EventTarget.call(this);
2124 }
2125
2126 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
2127 constructor: {
2128 value: CustomEventTarget,
2129 configurable: true,
2130 writable: true,
2131 },
2132 });
2133
2134 for (let i = 0; i < eventNames.length; ++i) {
2135 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
2136 }
2137
2138 return CustomEventTarget
2139}
2140
2141/**
2142 * EventTarget.
2143 *
2144 * - This is constructor if no arguments.
2145 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
2146 *
2147 * For example:
2148 *
2149 * class A extends EventTarget {}
2150 * class B extends EventTarget("message") {}
2151 * class C extends EventTarget("message", "error") {}
2152 * class D extends EventTarget(["message", "error"]) {}
2153 */
2154function EventTarget() {
2155 /*eslint-disable consistent-return */
2156 if (this instanceof EventTarget) {
2157 listenersMap.set(this, new Map());
2158 return
2159 }
2160 if (arguments.length === 1 && Array.isArray(arguments[0])) {
2161 return defineCustomEventTarget(arguments[0])
2162 }
2163 if (arguments.length > 0) {
2164 const types = new Array(arguments.length);
2165 for (let i = 0; i < arguments.length; ++i) {
2166 types[i] = arguments[i];
2167 }
2168 return defineCustomEventTarget(types)
2169 }
2170 throw new TypeError("Cannot call a class as a function")
2171 /*eslint-enable consistent-return */
2172}
2173
2174// Should be enumerable, but class methods are not enumerable.
2175EventTarget.prototype = {
2176 /**
2177 * Add a given listener to this event target.
2178 * @param {string} eventName The event name to add.
2179 * @param {Function} listener The listener to add.
2180 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
2181 * @returns {void}
2182 */
2183 addEventListener(eventName, listener, options) {
2184 if (listener == null) {
2185 return
2186 }
2187 if (typeof listener !== "function" && !isObject(listener)) {
2188 throw new TypeError("'listener' should be a function or an object.")
2189 }
2190
2191 const listeners = getListeners(this);
2192 const optionsIsObj = isObject(options);
2193 const capture = optionsIsObj
2194 ? Boolean(options.capture)
2195 : Boolean(options);
2196 const listenerType = capture ? CAPTURE : BUBBLE;
2197 const newNode = {
2198 listener,
2199 listenerType,
2200 passive: optionsIsObj && Boolean(options.passive),
2201 once: optionsIsObj && Boolean(options.once),
2202 next: null,
2203 };
2204
2205 // Set it as the first node if the first node is null.
2206 let node = listeners.get(eventName);
2207 if (node === undefined) {
2208 listeners.set(eventName, newNode);
2209 return
2210 }
2211
2212 // Traverse to the tail while checking duplication..
2213 let prev = null;
2214 while (node != null) {
2215 if (
2216 node.listener === listener &&
2217 node.listenerType === listenerType
2218 ) {
2219 // Should ignore duplication.
2220 return
2221 }
2222 prev = node;
2223 node = node.next;
2224 }
2225
2226 // Add it.
2227 prev.next = newNode;
2228 },
2229
2230 /**
2231 * Remove a given listener from this event target.
2232 * @param {string} eventName The event name to remove.
2233 * @param {Function} listener The listener to remove.
2234 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
2235 * @returns {void}
2236 */
2237 removeEventListener(eventName, listener, options) {
2238 if (listener == null) {
2239 return
2240 }
2241
2242 const listeners = getListeners(this);
2243 const capture = isObject(options)
2244 ? Boolean(options.capture)
2245 : Boolean(options);
2246 const listenerType = capture ? CAPTURE : BUBBLE;
2247
2248 let prev = null;
2249 let node = listeners.get(eventName);
2250 while (node != null) {
2251 if (
2252 node.listener === listener &&
2253 node.listenerType === listenerType
2254 ) {
2255 if (prev !== null) {
2256 prev.next = node.next;
2257 } else if (node.next !== null) {
2258 listeners.set(eventName, node.next);
2259 } else {
2260 listeners.delete(eventName);
2261 }
2262 return
2263 }
2264
2265 prev = node;
2266 node = node.next;
2267 }
2268 },
2269
2270 /**
2271 * Dispatch a given event.
2272 * @param {Event|{type:string}} event The event to dispatch.
2273 * @returns {boolean} `false` if canceled.
2274 */
2275 dispatchEvent(event) {
2276 if (event == null || typeof event.type !== "string") {
2277 throw new TypeError('"event.type" should be a string.')
2278 }
2279
2280 // If listeners aren't registered, terminate.
2281 const listeners = getListeners(this);
2282 const eventName = event.type;
2283 let node = listeners.get(eventName);
2284 if (node == null) {
2285 return true
2286 }
2287
2288 // Since we cannot rewrite several properties, so wrap object.
2289 const wrappedEvent = wrapEvent(this, event);
2290
2291 // This doesn't process capturing phase and bubbling phase.
2292 // This isn't participating in a tree.
2293 let prev = null;
2294 while (node != null) {
2295 // Remove this listener if it's once
2296 if (node.once) {
2297 if (prev !== null) {
2298 prev.next = node.next;
2299 } else if (node.next !== null) {
2300 listeners.set(eventName, node.next);
2301 } else {
2302 listeners.delete(eventName);
2303 }
2304 } else {
2305 prev = node;
2306 }
2307
2308 // Call this listener
2309 setPassiveListener(
2310 wrappedEvent,
2311 node.passive ? node.listener : null
2312 );
2313 if (typeof node.listener === "function") {
2314 try {
2315 node.listener.call(this, wrappedEvent);
2316 } catch (err) {
2317 if (
2318 typeof console !== "undefined" &&
2319 typeof console.error === "function"
2320 ) {
2321 console.error(err);
2322 }
2323 }
2324 } else if (
2325 node.listenerType !== ATTRIBUTE &&
2326 typeof node.listener.handleEvent === "function"
2327 ) {
2328 node.listener.handleEvent(wrappedEvent);
2329 }
2330
2331 // Break if `event.stopImmediatePropagation` was called.
2332 if (isStopped(wrappedEvent)) {
2333 break
2334 }
2335
2336 node = node.next;
2337 }
2338 setPassiveListener(wrappedEvent, null);
2339 setEventPhase(wrappedEvent, 0);
2340 setCurrentTarget(wrappedEvent, null);
2341
2342 return !wrappedEvent.defaultPrevented
2343 },
2344};
2345
2346// `constructor` is not enumerable.
2347Object.defineProperty(EventTarget.prototype, "constructor", {
2348 value: EventTarget,
2349 configurable: true,
2350 writable: true,
2351});
2352
2353// Ensure `eventTarget instanceof window.EventTarget` is `true`.
2354if (
2355 typeof window !== "undefined" &&
2356 typeof window.EventTarget !== "undefined"
2357) {
2358 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
2359}
2360
2361/**
2362 * @author Toru Nagashima <https://github.com/mysticatea>
2363 * See LICENSE file in root directory for full license.
2364 */
2365
2366/**
2367 * The signal class.
2368 * @see https://dom.spec.whatwg.org/#abortsignal
2369 */
2370class AbortSignal extends EventTarget {
2371 /**
2372 * AbortSignal cannot be constructed directly.
2373 */
2374 constructor() {
2375 super();
2376 throw new TypeError("AbortSignal cannot be constructed directly");
2377 }
2378 /**
2379 * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
2380 */
2381 get aborted() {
2382 const aborted = abortedFlags.get(this);
2383 if (typeof aborted !== "boolean") {
2384 throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
2385 }
2386 return aborted;
2387 }
2388}
2389defineEventAttribute(AbortSignal.prototype, "abort");
2390/**
2391 * Create an AbortSignal object.
2392 */
2393function createAbortSignal() {
2394 const signal = Object.create(AbortSignal.prototype);
2395 EventTarget.call(signal);
2396 abortedFlags.set(signal, false);
2397 return signal;
2398}
2399/**
2400 * Abort a given signal.
2401 */
2402function abortSignal(signal) {
2403 if (abortedFlags.get(signal) !== false) {
2404 return;
2405 }
2406 abortedFlags.set(signal, true);
2407 signal.dispatchEvent({ type: "abort" });
2408}
2409/**
2410 * Aborted flag for each instances.
2411 */
2412const abortedFlags = new WeakMap();
2413// Properties should be enumerable.
2414Object.defineProperties(AbortSignal.prototype, {
2415 aborted: { enumerable: true },
2416});
2417// `toString()` should return `"[object AbortSignal]"`
2418if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
2419 Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
2420 configurable: true,
2421 value: "AbortSignal",
2422 });
2423}
2424
2425/**
2426 * The AbortController.
2427 * @see https://dom.spec.whatwg.org/#abortcontroller
2428 */
2429class AbortController {
2430 /**
2431 * Initialize this controller.
2432 */
2433 constructor() {
2434 signals.set(this, createAbortSignal());
2435 }
2436 /**
2437 * Returns the `AbortSignal` object associated with this object.
2438 */
2439 get signal() {
2440 return getSignal(this);
2441 }
2442 /**
2443 * Abort and signal to any observers that the associated activity is to be aborted.
2444 */
2445 abort() {
2446 abortSignal(getSignal(this));
2447 }
2448}
2449/**
2450 * Associated signals.
2451 */
2452const signals = new WeakMap();
2453/**
2454 * Get the associated signal of a given controller.
2455 */
2456function getSignal(controller) {
2457 const signal = signals.get(controller);
2458 if (signal == null) {
2459 throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
2460 }
2461 return signal;
2462}
2463// Properties should be enumerable.
2464Object.defineProperties(AbortController.prototype, {
2465 signal: { enumerable: true },
2466 abort: { enumerable: true },
2467});
2468if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
2469 Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
2470 configurable: true,
2471 value: "AbortController",
2472 });
2473}
2474
2475// Copyright (c) Microsoft Corporation. All rights reserved.
2476var RestError = /** @class */ (function (_super) {
2477 tslib.__extends(RestError, _super);
2478 function RestError(message, code, statusCode, request, response, body) {
2479 var _this = _super.call(this, message) || this;
2480 _this.code = code;
2481 _this.statusCode = statusCode;
2482 _this.request = request;
2483 _this.response = response;
2484 _this.body = body;
2485 Object.setPrototypeOf(_this, RestError.prototype);
2486 return _this;
2487 }
2488 RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
2489 RestError.REQUEST_ABORTED_ERROR = "REQUEST_ABORTED_ERROR";
2490 RestError.PARSE_ERROR = "PARSE_ERROR";
2491 return RestError;
2492}(Error));
2493
2494// Copyright (c) Microsoft Corporation. All rights reserved.
2495var FetchHttpClient = /** @class */ (function () {
2496 function FetchHttpClient() {
2497 }
2498 FetchHttpClient.prototype.sendRequest = function (httpRequest) {
2499 return tslib.__awaiter(this, void 0, void 0, function () {
2500 var abortController, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, loadedBytes_1, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, _b, _c, onDownloadProgress_1, responseBody, loadedBytes_2, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone;
2501 return tslib.__generator(this, function (_d) {
2502 switch (_d.label) {
2503 case 0:
2504 if (!httpRequest && typeof httpRequest !== "object") {
2505 throw new Error("'httpRequest' (WebResource) cannot be null or undefined and must be of type object.");
2506 }
2507 abortController = new AbortController();
2508 if (httpRequest.abortSignal) {
2509 if (httpRequest.abortSignal.aborted) {
2510 throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
2511 }
2512 abortListener = function (event) {
2513 if (event.type === "abort") {
2514 abortController.abort();
2515 }
2516 };
2517 httpRequest.abortSignal.addEventListener("abort", abortListener);
2518 }
2519 if (httpRequest.timeout) {
2520 setTimeout(function () {
2521 abortController.abort();
2522 }, httpRequest.timeout);
2523 }
2524 if (httpRequest.formData) {
2525 formData = httpRequest.formData;
2526 requestForm_1 = new FormData();
2527 appendFormValue = function (key, value) {
2528 // value function probably returns a stream so we can provide a fresh stream on each retry
2529 if (typeof value === "function") {
2530 value = value();
2531 }
2532 if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
2533 requestForm_1.append(key, value.value, value.options);
2534 }
2535 else {
2536 requestForm_1.append(key, value);
2537 }
2538 };
2539 for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {
2540 formKey = _a[_i];
2541 formValue = formData[formKey];
2542 if (Array.isArray(formValue)) {
2543 for (j = 0; j < formValue.length; j++) {
2544 appendFormValue(formKey, formValue[j]);
2545 }
2546 }
2547 else {
2548 appendFormValue(formKey, formValue);
2549 }
2550 }
2551 httpRequest.body = requestForm_1;
2552 httpRequest.formData = undefined;
2553 contentType = httpRequest.headers.get("Content-Type");
2554 if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
2555 if (typeof requestForm_1.getBoundary === "function") {
2556 httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary());
2557 }
2558 else {
2559 // browser will automatically apply a suitable content-type header
2560 httpRequest.headers.remove("Content-Type");
2561 }
2562 }
2563 }
2564 body = httpRequest.body
2565 ? typeof httpRequest.body === "function"
2566 ? httpRequest.body()
2567 : httpRequest.body
2568 : undefined;
2569 if (httpRequest.onUploadProgress && httpRequest.body) {
2570 loadedBytes_1 = 0;
2571 uploadReportStream = new stream.Transform({
2572 transform: function (chunk, _encoding, callback) {
2573 loadedBytes_1 += chunk.length;
2574 httpRequest.onUploadProgress({ loadedBytes: loadedBytes_1 });
2575 callback(undefined, chunk);
2576 },
2577 });
2578 if (isReadableStream(body)) {
2579 body.pipe(uploadReportStream);
2580 }
2581 else {
2582 uploadReportStream.end(body);
2583 }
2584 body = uploadReportStream;
2585 }
2586 return [4 /*yield*/, this.prepareRequest(httpRequest)];
2587 case 1:
2588 platformSpecificRequestInit = _d.sent();
2589 requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController.signal, redirect: "manual" }, platformSpecificRequestInit);
2590 _d.label = 2;
2591 case 2:
2592 _d.trys.push([2, 8, 9, 10]);
2593 return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)];
2594 case 3:
2595 response = _d.sent();
2596 headers = parseHeaders(response.headers);
2597 _b = {
2598 headers: headers,
2599 request: httpRequest,
2600 status: response.status,
2601 readableStreamBody: httpRequest.streamResponseBody
2602 ? response.body
2603 : undefined
2604 };
2605 if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5];
2606 return [4 /*yield*/, response.text()];
2607 case 4:
2608 _c = _d.sent();
2609 return [3 /*break*/, 6];
2610 case 5:
2611 _c = undefined;
2612 _d.label = 6;
2613 case 6:
2614 operationResponse = (_b.bodyAsText = _c,
2615 _b.redirected = response.redirected,
2616 _b.url = response.url,
2617 _b);
2618 onDownloadProgress_1 = httpRequest.onDownloadProgress;
2619 if (onDownloadProgress_1) {
2620 responseBody = response.body || undefined;
2621 if (isReadableStream(responseBody)) {
2622 loadedBytes_2 = 0;
2623 downloadReportStream = new stream.Transform({
2624 transform: function (chunk, _encoding, callback) {
2625 loadedBytes_2 += chunk.length;
2626 onDownloadProgress_1({ loadedBytes: loadedBytes_2 });
2627 callback(undefined, chunk);
2628 },
2629 });
2630 responseBody.pipe(downloadReportStream);
2631 operationResponse.readableStreamBody = downloadReportStream;
2632 }
2633 else {
2634 length_1 = parseInt(headers.get("Content-Length")) || undefined;
2635 if (length_1) {
2636 // Calling callback for non-stream response for consistency with browser
2637 onDownloadProgress_1({ loadedBytes: length_1 });
2638 }
2639 }
2640 }
2641 return [4 /*yield*/, this.processRequest(operationResponse)];
2642 case 7:
2643 _d.sent();
2644 return [2 /*return*/, operationResponse];
2645 case 8:
2646 error_1 = _d.sent();
2647 fetchError = error_1;
2648 if (fetchError.code === "ENOTFOUND") {
2649 throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
2650 }
2651 else if (fetchError.type === "aborted") {
2652 throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
2653 }
2654 throw fetchError;
2655 case 9:
2656 // clean up event listener
2657 if (httpRequest.abortSignal && abortListener) {
2658 uploadStreamDone = Promise.resolve();
2659 if (isReadableStream(body)) {
2660 uploadStreamDone = isStreamComplete(body);
2661 }
2662 downloadStreamDone = Promise.resolve();
2663 if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) {
2664 downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody);
2665 }
2666 Promise.all([uploadStreamDone, downloadStreamDone])
2667 .then(function () {
2668 var _a;
2669 (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
2670 return;
2671 })
2672 .catch(function (_e) { });
2673 }
2674 return [7 /*endfinally*/];
2675 case 10: return [2 /*return*/];
2676 }
2677 });
2678 });
2679 };
2680 return FetchHttpClient;
2681}());
2682function isReadableStream(body) {
2683 return body && typeof body.pipe === "function";
2684}
2685function isStreamComplete(stream) {
2686 return new Promise(function (resolve) {
2687 stream.on("close", resolve);
2688 stream.on("end", resolve);
2689 stream.on("error", resolve);
2690 });
2691}
2692function parseHeaders(headers) {
2693 var httpHeaders = new HttpHeaders();
2694 headers.forEach(function (value, key) {
2695 httpHeaders.set(key, value);
2696 });
2697 return httpHeaders;
2698}
2699
2700// Copyright (c) Microsoft Corporation. All rights reserved.
2701/**
2702 * A class that handles the query portion of a URLBuilder.
2703 */
2704var URLQuery = /** @class */ (function () {
2705 function URLQuery() {
2706 this._rawQuery = {};
2707 }
2708 /**
2709 * Get whether or not there any query parameters in this URLQuery.
2710 */
2711 URLQuery.prototype.any = function () {
2712 return Object.keys(this._rawQuery).length > 0;
2713 };
2714 /**
2715 * Set a query parameter with the provided name and value. If the parameterValue is undefined or
2716 * empty, then this will attempt to remove an existing query parameter with the provided
2717 * parameterName.
2718 */
2719 URLQuery.prototype.set = function (parameterName, parameterValue) {
2720 if (parameterName) {
2721 if (parameterValue != undefined) {
2722 var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
2723 this._rawQuery[parameterName] = newValue;
2724 }
2725 else {
2726 delete this._rawQuery[parameterName];
2727 }
2728 }
2729 };
2730 /**
2731 * Get the value of the query parameter with the provided name. If no parameter exists with the
2732 * provided parameter name, then undefined will be returned.
2733 */
2734 URLQuery.prototype.get = function (parameterName) {
2735 return parameterName ? this._rawQuery[parameterName] : undefined;
2736 };
2737 /**
2738 * Get the string representation of this query. The return value will not start with a "?".
2739 */
2740 URLQuery.prototype.toString = function () {
2741 var result = "";
2742 for (var parameterName in this._rawQuery) {
2743 if (result) {
2744 result += "&";
2745 }
2746 var parameterValue = this._rawQuery[parameterName];
2747 if (Array.isArray(parameterValue)) {
2748 var parameterStrings = [];
2749 for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
2750 var parameterValueElement = parameterValue_1[_i];
2751 parameterStrings.push(parameterName + "=" + parameterValueElement);
2752 }
2753 result += parameterStrings.join("&");
2754 }
2755 else {
2756 result += parameterName + "=" + parameterValue;
2757 }
2758 }
2759 return result;
2760 };
2761 /**
2762 * Parse a URLQuery from the provided text.
2763 */
2764 URLQuery.parse = function (text) {
2765 var result = new URLQuery();
2766 if (text) {
2767 if (text.startsWith("?")) {
2768 text = text.substring(1);
2769 }
2770 var currentState = "ParameterName";
2771 var parameterName = "";
2772 var parameterValue = "";
2773 for (var i = 0; i < text.length; ++i) {
2774 var currentCharacter = text[i];
2775 switch (currentState) {
2776 case "ParameterName":
2777 switch (currentCharacter) {
2778 case "=":
2779 currentState = "ParameterValue";
2780 break;
2781 case "&":
2782 parameterName = "";
2783 parameterValue = "";
2784 break;
2785 default:
2786 parameterName += currentCharacter;
2787 break;
2788 }
2789 break;
2790 case "ParameterValue":
2791 switch (currentCharacter) {
2792 case "&":
2793 result.set(parameterName, parameterValue);
2794 parameterName = "";
2795 parameterValue = "";
2796 currentState = "ParameterName";
2797 break;
2798 default:
2799 parameterValue += currentCharacter;
2800 break;
2801 }
2802 break;
2803 default:
2804 throw new Error("Unrecognized URLQuery parse state: " + currentState);
2805 }
2806 }
2807 if (currentState === "ParameterValue") {
2808 result.set(parameterName, parameterValue);
2809 }
2810 }
2811 return result;
2812 };
2813 return URLQuery;
2814}());
2815/**
2816 * A class that handles creating, modifying, and parsing URLs.
2817 */
2818var URLBuilder = /** @class */ (function () {
2819 function URLBuilder() {
2820 }
2821 /**
2822 * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
2823 * (such as a host, port, path, or query), those parts will be added to this URL as well.
2824 */
2825 URLBuilder.prototype.setScheme = function (scheme) {
2826 if (!scheme) {
2827 this._scheme = undefined;
2828 }
2829 else {
2830 this.set(scheme, "SCHEME");
2831 }
2832 };
2833 /**
2834 * Get the scheme that has been set in this URL.
2835 */
2836 URLBuilder.prototype.getScheme = function () {
2837 return this._scheme;
2838 };
2839 /**
2840 * Set the host for this URL. If the provided host contains other parts of a URL (such as a
2841 * port, path, or query), those parts will be added to this URL as well.
2842 */
2843 URLBuilder.prototype.setHost = function (host) {
2844 if (!host) {
2845 this._host = undefined;
2846 }
2847 else {
2848 this.set(host, "SCHEME_OR_HOST");
2849 }
2850 };
2851 /**
2852 * Get the host that has been set in this URL.
2853 */
2854 URLBuilder.prototype.getHost = function () {
2855 return this._host;
2856 };
2857 /**
2858 * Set the port for this URL. If the provided port contains other parts of a URL (such as a
2859 * path or query), those parts will be added to this URL as well.
2860 */
2861 URLBuilder.prototype.setPort = function (port) {
2862 if (port == undefined || port === "") {
2863 this._port = undefined;
2864 }
2865 else {
2866 this.set(port.toString(), "PORT");
2867 }
2868 };
2869 /**
2870 * Get the port that has been set in this URL.
2871 */
2872 URLBuilder.prototype.getPort = function () {
2873 return this._port;
2874 };
2875 /**
2876 * Set the path for this URL. If the provided path contains a query, then it will be added to
2877 * this URL as well.
2878 */
2879 URLBuilder.prototype.setPath = function (path) {
2880 if (!path) {
2881 this._path = undefined;
2882 }
2883 else {
2884 var schemeIndex = path.indexOf("://");
2885 if (schemeIndex !== -1) {
2886 var schemeStart = path.lastIndexOf("/", schemeIndex);
2887 // Make sure to only grab the URL part of the path before setting the state back to SCHEME
2888 // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com"
2889 this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME");
2890 }
2891 else {
2892 this.set(path, "PATH");
2893 }
2894 }
2895 };
2896 /**
2897 * Append the provided path to this URL's existing path. If the provided path contains a query,
2898 * then it will be added to this URL as well.
2899 */
2900 URLBuilder.prototype.appendPath = function (path) {
2901 if (path) {
2902 var currentPath = this.getPath();
2903 if (currentPath) {
2904 if (!currentPath.endsWith("/")) {
2905 currentPath += "/";
2906 }
2907 if (path.startsWith("/")) {
2908 path = path.substring(1);
2909 }
2910 path = currentPath + path;
2911 }
2912 this.set(path, "PATH");
2913 }
2914 };
2915 /**
2916 * Get the path that has been set in this URL.
2917 */
2918 URLBuilder.prototype.getPath = function () {
2919 return this._path;
2920 };
2921 /**
2922 * Set the query in this URL.
2923 */
2924 URLBuilder.prototype.setQuery = function (query) {
2925 if (!query) {
2926 this._query = undefined;
2927 }
2928 else {
2929 this._query = URLQuery.parse(query);
2930 }
2931 };
2932 /**
2933 * Set a query parameter with the provided name and value in this URL's query. If the provided
2934 * query parameter value is undefined or empty, then the query parameter will be removed if it
2935 * existed.
2936 */
2937 URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
2938 if (queryParameterName) {
2939 if (!this._query) {
2940 this._query = new URLQuery();
2941 }
2942 this._query.set(queryParameterName, queryParameterValue);
2943 }
2944 };
2945 /**
2946 * Get the value of the query parameter with the provided query parameter name. If no query
2947 * parameter exists with the provided name, then undefined will be returned.
2948 */
2949 URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
2950 return this._query ? this._query.get(queryParameterName) : undefined;
2951 };
2952 /**
2953 * Get the query in this URL.
2954 */
2955 URLBuilder.prototype.getQuery = function () {
2956 return this._query ? this._query.toString() : undefined;
2957 };
2958 /**
2959 * Set the parts of this URL by parsing the provided text using the provided startState.
2960 */
2961 URLBuilder.prototype.set = function (text, startState) {
2962 var tokenizer = new URLTokenizer(text, startState);
2963 while (tokenizer.next()) {
2964 var token = tokenizer.current();
2965 if (token) {
2966 switch (token.type) {
2967 case "SCHEME":
2968 this._scheme = token.text || undefined;
2969 break;
2970 case "HOST":
2971 this._host = token.text || undefined;
2972 break;
2973 case "PORT":
2974 this._port = token.text || undefined;
2975 break;
2976 case "PATH":
2977 var tokenPath = token.text || undefined;
2978 if (!this._path || this._path === "/" || tokenPath !== "/") {
2979 this._path = tokenPath;
2980 }
2981 break;
2982 case "QUERY":
2983 this._query = URLQuery.parse(token.text);
2984 break;
2985 default:
2986 throw new Error("Unrecognized URLTokenType: " + token.type);
2987 }
2988 }
2989 }
2990 };
2991 URLBuilder.prototype.toString = function () {
2992 var result = "";
2993 if (this._scheme) {
2994 result += this._scheme + "://";
2995 }
2996 if (this._host) {
2997 result += this._host;
2998 }
2999 if (this._port) {
3000 result += ":" + this._port;
3001 }
3002 if (this._path) {
3003 if (!this._path.startsWith("/")) {
3004 result += "/";
3005 }
3006 result += this._path;
3007 }
3008 if (this._query && this._query.any()) {
3009 result += "?" + this._query.toString();
3010 }
3011 return result;
3012 };
3013 /**
3014 * If the provided searchValue is found in this URLBuilder, then replace it with the provided
3015 * replaceValue.
3016 */
3017 URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
3018 if (searchValue) {
3019 this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
3020 this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
3021 this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
3022 this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
3023 this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
3024 }
3025 };
3026 URLBuilder.parse = function (text) {
3027 var result = new URLBuilder();
3028 result.set(text, "SCHEME_OR_HOST");
3029 return result;
3030 };
3031 return URLBuilder;
3032}());
3033var URLToken = /** @class */ (function () {
3034 function URLToken(text, type) {
3035 this.text = text;
3036 this.type = type;
3037 }
3038 URLToken.scheme = function (text) {
3039 return new URLToken(text, "SCHEME");
3040 };
3041 URLToken.host = function (text) {
3042 return new URLToken(text, "HOST");
3043 };
3044 URLToken.port = function (text) {
3045 return new URLToken(text, "PORT");
3046 };
3047 URLToken.path = function (text) {
3048 return new URLToken(text, "PATH");
3049 };
3050 URLToken.query = function (text) {
3051 return new URLToken(text, "QUERY");
3052 };
3053 return URLToken;
3054}());
3055/**
3056 * Get whether or not the provided character (single character string) is an alphanumeric (letter or
3057 * digit) character.
3058 */
3059function isAlphaNumericCharacter(character) {
3060 var characterCode = character.charCodeAt(0);
3061 return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ ||
3062 (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ ||
3063 (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */);
3064}
3065/**
3066 * A class that tokenizes URL strings.
3067 */
3068var URLTokenizer = /** @class */ (function () {
3069 function URLTokenizer(_text, state) {
3070 this._text = _text;
3071 this._textLength = _text ? _text.length : 0;
3072 this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
3073 this._currentIndex = 0;
3074 }
3075 /**
3076 * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
3077 * hasn't started or has finished tokenizing.
3078 */
3079 URLTokenizer.prototype.current = function () {
3080 return this._currentToken;
3081 };
3082 /**
3083 * Advance to the next URLToken and return whether or not a URLToken was found.
3084 */
3085 URLTokenizer.prototype.next = function () {
3086 if (!hasCurrentCharacter(this)) {
3087 this._currentToken = undefined;
3088 }
3089 else {
3090 switch (this._currentState) {
3091 case "SCHEME":
3092 nextScheme(this);
3093 break;
3094 case "SCHEME_OR_HOST":
3095 nextSchemeOrHost(this);
3096 break;
3097 case "HOST":
3098 nextHost(this);
3099 break;
3100 case "PORT":
3101 nextPort(this);
3102 break;
3103 case "PATH":
3104 nextPath(this);
3105 break;
3106 case "QUERY":
3107 nextQuery(this);
3108 break;
3109 default:
3110 throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
3111 }
3112 }
3113 return !!this._currentToken;
3114 };
3115 return URLTokenizer;
3116}());
3117/**
3118 * Read the remaining characters from this Tokenizer's character stream.
3119 */
3120function readRemaining(tokenizer) {
3121 var result = "";
3122 if (tokenizer._currentIndex < tokenizer._textLength) {
3123 result = tokenizer._text.substring(tokenizer._currentIndex);
3124 tokenizer._currentIndex = tokenizer._textLength;
3125 }
3126 return result;
3127}
3128/**
3129 * Whether or not this URLTokenizer has a current character.
3130 */
3131function hasCurrentCharacter(tokenizer) {
3132 return tokenizer._currentIndex < tokenizer._textLength;
3133}
3134/**
3135 * Get the character in the text string at the current index.
3136 */
3137function getCurrentCharacter(tokenizer) {
3138 return tokenizer._text[tokenizer._currentIndex];
3139}
3140/**
3141 * Advance to the character in text that is "step" characters ahead. If no step value is provided,
3142 * then step will default to 1.
3143 */
3144function nextCharacter(tokenizer, step) {
3145 if (hasCurrentCharacter(tokenizer)) {
3146 if (!step) {
3147 step = 1;
3148 }
3149 tokenizer._currentIndex += step;
3150 }
3151}
3152/**
3153 * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
3154 * Tokenizer's stream of characters.
3155 */
3156function peekCharacters(tokenizer, charactersToPeek) {
3157 var endIndex = tokenizer._currentIndex + charactersToPeek;
3158 if (tokenizer._textLength < endIndex) {
3159 endIndex = tokenizer._textLength;
3160 }
3161 return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
3162}
3163/**
3164 * Read characters from this Tokenizer until the end of the stream or until the provided condition
3165 * is false when provided the current character.
3166 */
3167function readWhile(tokenizer, condition) {
3168 var result = "";
3169 while (hasCurrentCharacter(tokenizer)) {
3170 var currentCharacter = getCurrentCharacter(tokenizer);
3171 if (!condition(currentCharacter)) {
3172 break;
3173 }
3174 else {
3175 result += currentCharacter;
3176 nextCharacter(tokenizer);
3177 }
3178 }
3179 return result;
3180}
3181/**
3182 * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
3183 * character stream is reached.
3184 */
3185function readWhileLetterOrDigit(tokenizer) {
3186 return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
3187}
3188/**
3189 * Read characters from this Tokenizer until one of the provided terminating characters is read or
3190 * the end of the character stream is reached.
3191 */
3192function readUntilCharacter(tokenizer) {
3193 var terminatingCharacters = [];
3194 for (var _i = 1; _i < arguments.length; _i++) {
3195 terminatingCharacters[_i - 1] = arguments[_i];
3196 }
3197 return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
3198}
3199function nextScheme(tokenizer) {
3200 var scheme = readWhileLetterOrDigit(tokenizer);
3201 tokenizer._currentToken = URLToken.scheme(scheme);
3202 if (!hasCurrentCharacter(tokenizer)) {
3203 tokenizer._currentState = "DONE";
3204 }
3205 else {
3206 tokenizer._currentState = "HOST";
3207 }
3208}
3209function nextSchemeOrHost(tokenizer) {
3210 var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
3211 if (!hasCurrentCharacter(tokenizer)) {
3212 tokenizer._currentToken = URLToken.host(schemeOrHost);
3213 tokenizer._currentState = "DONE";
3214 }
3215 else if (getCurrentCharacter(tokenizer) === ":") {
3216 if (peekCharacters(tokenizer, 3) === "://") {
3217 tokenizer._currentToken = URLToken.scheme(schemeOrHost);
3218 tokenizer._currentState = "HOST";
3219 }
3220 else {
3221 tokenizer._currentToken = URLToken.host(schemeOrHost);
3222 tokenizer._currentState = "PORT";
3223 }
3224 }
3225 else {
3226 tokenizer._currentToken = URLToken.host(schemeOrHost);
3227 if (getCurrentCharacter(tokenizer) === "/") {
3228 tokenizer._currentState = "PATH";
3229 }
3230 else {
3231 tokenizer._currentState = "QUERY";
3232 }
3233 }
3234}
3235function nextHost(tokenizer) {
3236 if (peekCharacters(tokenizer, 3) === "://") {
3237 nextCharacter(tokenizer, 3);
3238 }
3239 var host = readUntilCharacter(tokenizer, ":", "/", "?");
3240 tokenizer._currentToken = URLToken.host(host);
3241 if (!hasCurrentCharacter(tokenizer)) {
3242 tokenizer._currentState = "DONE";
3243 }
3244 else if (getCurrentCharacter(tokenizer) === ":") {
3245 tokenizer._currentState = "PORT";
3246 }
3247 else if (getCurrentCharacter(tokenizer) === "/") {
3248 tokenizer._currentState = "PATH";
3249 }
3250 else {
3251 tokenizer._currentState = "QUERY";
3252 }
3253}
3254function nextPort(tokenizer) {
3255 if (getCurrentCharacter(tokenizer) === ":") {
3256 nextCharacter(tokenizer);
3257 }
3258 var port = readUntilCharacter(tokenizer, "/", "?");
3259 tokenizer._currentToken = URLToken.port(port);
3260 if (!hasCurrentCharacter(tokenizer)) {
3261 tokenizer._currentState = "DONE";
3262 }
3263 else if (getCurrentCharacter(tokenizer) === "/") {
3264 tokenizer._currentState = "PATH";
3265 }
3266 else {
3267 tokenizer._currentState = "QUERY";
3268 }
3269}
3270function nextPath(tokenizer) {
3271 var path = readUntilCharacter(tokenizer, "?");
3272 tokenizer._currentToken = URLToken.path(path);
3273 if (!hasCurrentCharacter(tokenizer)) {
3274 tokenizer._currentState = "DONE";
3275 }
3276 else {
3277 tokenizer._currentState = "QUERY";
3278 }
3279}
3280function nextQuery(tokenizer) {
3281 if (getCurrentCharacter(tokenizer) === "?") {
3282 nextCharacter(tokenizer);
3283 }
3284 var query = readRemaining(tokenizer);
3285 tokenizer._currentToken = URLToken.query(query);
3286 tokenizer._currentState = "DONE";
3287}
3288
3289// Copyright (c) Microsoft Corporation. All rights reserved.
3290function createProxyAgent(requestUrl, proxySettings, headers) {
3291 var tunnelOptions = {
3292 proxy: {
3293 host: URLBuilder.parse(proxySettings.host).getHost(),
3294 port: proxySettings.port,
3295 headers: (headers && headers.rawHeaders()) || {},
3296 },
3297 };
3298 if (proxySettings.username && proxySettings.password) {
3299 tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password;
3300 }
3301 else if (proxySettings.username) {
3302 tunnelOptions.proxy.proxyAuth = "" + proxySettings.username;
3303 }
3304 var requestScheme = URLBuilder.parse(requestUrl).getScheme() || "";
3305 var isRequestHttps = requestScheme.toLowerCase() === "https";
3306 var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || "";
3307 var isProxyHttps = proxyScheme.toLowerCase() === "https";
3308 var proxyAgent = {
3309 isHttps: isRequestHttps,
3310 agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions),
3311 };
3312 return proxyAgent;
3313}
3314function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) {
3315 if (isRequestHttps && isProxyHttps) {
3316 return tunnel.httpsOverHttps(tunnelOptions);
3317 }
3318 else if (isRequestHttps && !isProxyHttps) {
3319 return tunnel.httpsOverHttp(tunnelOptions);
3320 }
3321 else if (!isRequestHttps && isProxyHttps) {
3322 return tunnel.httpOverHttps(tunnelOptions);
3323 }
3324 else {
3325 return tunnel.httpOverHttp(tunnelOptions);
3326 }
3327}
3328
3329// Copyright (c) Microsoft Corporation. All rights reserved.
3330var NodeFetchHttpClient = /** @class */ (function (_super) {
3331 tslib.__extends(NodeFetchHttpClient, _super);
3332 function NodeFetchHttpClient() {
3333 return _super !== null && _super.apply(this, arguments) || this;
3334 }
3335 NodeFetchHttpClient.prototype.fetch = function (input, init) {
3336 return tslib.__awaiter(this, void 0, void 0, function () {
3337 return tslib.__generator(this, function (_a) {
3338 return [2 /*return*/, node_fetch(input, init)];
3339 });
3340 });
3341 };
3342 NodeFetchHttpClient.prototype.prepareRequest = function (httpRequest) {
3343 return tslib.__awaiter(this, void 0, void 0, function () {
3344 var requestInit, _a, httpAgent, httpsAgent, tunnel, options, agent;
3345 return tslib.__generator(this, function (_b) {
3346 requestInit = {};
3347 if (httpRequest.agentSettings) {
3348 _a = httpRequest.agentSettings, httpAgent = _a.http, httpsAgent = _a.https;
3349 if (httpsAgent && httpRequest.url.startsWith("https")) {
3350 requestInit.agent = httpsAgent;
3351 }
3352 else if (httpAgent) {
3353 requestInit.agent = httpAgent;
3354 }
3355 }
3356 else if (httpRequest.proxySettings) {
3357 tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers);
3358 requestInit.agent = tunnel.agent;
3359 }
3360 if (httpRequest.keepAlive === true) {
3361 if (requestInit.agent) {
3362 requestInit.agent.keepAlive = true;
3363 }
3364 else {
3365 options = { keepAlive: true };
3366 agent = httpRequest.url.startsWith("https")
3367 ? new https.Agent(options)
3368 : new http.Agent(options);
3369 requestInit.agent = agent;
3370 }
3371 }
3372 return [2 /*return*/, requestInit];
3373 });
3374 });
3375 };
3376 NodeFetchHttpClient.prototype.processRequest = function (_operationResponse) {
3377 return tslib.__awaiter(this, void 0, void 0, function () {
3378 return tslib.__generator(this, function (_a) {
3379 /* no_op */
3380 return [2 /*return*/];
3381 });
3382 });
3383 };
3384 return NodeFetchHttpClient;
3385}(FetchHttpClient));
3386
3387// Copyright (c) Microsoft Corporation. All rights reserved.
3388(function (HttpPipelineLogLevel) {
3389 /**
3390 * A log level that indicates that no logs will be logged.
3391 */
3392 HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
3393 /**
3394 * An error log.
3395 */
3396 HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
3397 /**
3398 * A warning log.
3399 */
3400 HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
3401 /**
3402 * An information log.
3403 */
3404 HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
3405})(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));
3406
3407// Copyright (c) Microsoft Corporation.
3408// Licensed under the MIT license.
3409/**
3410 * Tests an object to determine whether it implements TokenCredential.
3411 *
3412 * @param credential - The assumed TokenCredential to be tested.
3413 */
3414function isTokenCredential(credential) {
3415 // Check for an object with a 'getToken' function and possibly with
3416 // a 'signRequest' function. We do this check to make sure that
3417 // a ServiceClientCredentials implementor (like TokenClientCredentials
3418 // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
3419 // it doesn't actually implement TokenCredential also.
3420 const castCredential = credential;
3421 return (castCredential &&
3422 typeof castCredential.getToken === "function" &&
3423 (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
3424}
3425
3426// Copyright (c) Microsoft Corporation. All rights reserved.
3427// Licensed under the MIT License. See License.txt in the project root for license information.
3428/**
3429 * Get the path to this parameter's value as a dotted string (a.b.c).
3430 * @param parameter The parameter to get the path string for.
3431 * @returns The path to this parameter's value as a dotted string.
3432 */
3433function getPathStringFromParameter(parameter) {
3434 return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);
3435}
3436function getPathStringFromParameterPath(parameterPath, mapper) {
3437 var result;
3438 if (typeof parameterPath === "string") {
3439 result = parameterPath;
3440 }
3441 else if (Array.isArray(parameterPath)) {
3442 result = parameterPath.join(".");
3443 }
3444 else {
3445 result = mapper.serializedName;
3446 }
3447 return result;
3448}
3449
3450// Copyright (c) Microsoft Corporation. All rights reserved.
3451function isStreamOperation(operationSpec) {
3452 var result = false;
3453 for (var statusCode in operationSpec.responses) {
3454 var operationResponse = operationSpec.responses[statusCode];
3455 if (operationResponse.bodyMapper &&
3456 operationResponse.bodyMapper.type.name === MapperType.Stream) {
3457 result = true;
3458 break;
3459 }
3460 }
3461 return result;
3462}
3463
3464// Copyright (c) Microsoft Corporation. All rights reserved.
3465function stringifyXML(obj, opts) {
3466 var builder = new xml2js.Builder({
3467 rootName: (opts || {}).rootName,
3468 renderOpts: {
3469 pretty: false,
3470 },
3471 });
3472 return builder.buildObject(obj);
3473}
3474function parseXML(str) {
3475 var xmlParser = new xml2js.Parser({
3476 explicitArray: false,
3477 explicitCharkey: false,
3478 explicitRoot: false,
3479 });
3480 return new Promise(function (resolve, reject) {
3481 if (!str) {
3482 reject(new Error("Document is empty"));
3483 }
3484 else {
3485 xmlParser.parseString(str, function (err, res) {
3486 if (err) {
3487 reject(err);
3488 }
3489 else {
3490 resolve(res);
3491 }
3492 });
3493 }
3494 });
3495}
3496
3497// Copyright (c) Microsoft Corporation. All rights reserved.
3498var BaseRequestPolicy = /** @class */ (function () {
3499 function BaseRequestPolicy(_nextPolicy, _options) {
3500 this._nextPolicy = _nextPolicy;
3501 this._options = _options;
3502 }
3503 /**
3504 * Get whether or not a log with the provided log level should be logged.
3505 * @param logLevel The log level of the log that will be logged.
3506 * @returns Whether or not a log with the provided log level should be logged.
3507 */
3508 BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
3509 return this._options.shouldLog(logLevel);
3510 };
3511 /**
3512 * Attempt to log the provided message to the provided logger. If no logger was provided or if
3513 * the log level does not meat the logger's threshold, then nothing will be logged.
3514 * @param logLevel The log level of this log.
3515 * @param message The message of this log.
3516 */
3517 BaseRequestPolicy.prototype.log = function (logLevel, message) {
3518 this._options.log(logLevel, message);
3519 };
3520 return BaseRequestPolicy;
3521}());
3522/**
3523 * Optional properties that can be used when creating a RequestPolicy.
3524 */
3525var RequestPolicyOptions = /** @class */ (function () {
3526 function RequestPolicyOptions(_logger) {
3527 this._logger = _logger;
3528 }
3529 /**
3530 * Get whether or not a log with the provided log level should be logged.
3531 * @param logLevel The log level of the log that will be logged.
3532 * @returns Whether or not a log with the provided log level should be logged.
3533 */
3534 RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
3535 return (!!this._logger &&
3536 logLevel !== exports.HttpPipelineLogLevel.OFF &&
3537 logLevel <= this._logger.minimumLogLevel);
3538 };
3539 /**
3540 * Attempt to log the provided message to the provided logger. If no logger was provided or if
3541 * the log level does not meat the logger's threshold, then nothing will be logged.
3542 * @param logLevel The log level of this log.
3543 * @param message The message of this log.
3544 */
3545 RequestPolicyOptions.prototype.log = function (logLevel, message) {
3546 if (this._logger && this.shouldLog(logLevel)) {
3547 this._logger.log(logLevel, message);
3548 }
3549 };
3550 return RequestPolicyOptions;
3551}());
3552
3553// Copyright (c) Microsoft Corporation. All rights reserved.
3554/**
3555 * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
3556 * pass through the HTTP pipeline.
3557 */
3558function deserializationPolicy(deserializationContentTypes) {
3559 return {
3560 create: function (nextPolicy, options) {
3561 return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
3562 },
3563 };
3564}
3565var defaultJsonContentTypes = ["application/json", "text/json"];
3566var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
3567/**
3568 * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
3569 * HTTP pipeline.
3570 */
3571var DeserializationPolicy = /** @class */ (function (_super) {
3572 tslib.__extends(DeserializationPolicy, _super);
3573 function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
3574 var _this = _super.call(this, nextPolicy, options) || this;
3575 _this.jsonContentTypes =
3576 (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes;
3577 _this.xmlContentTypes =
3578 (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes;
3579 return _this;
3580 }
3581 DeserializationPolicy.prototype.sendRequest = function (request) {
3582 return tslib.__awaiter(this, void 0, void 0, function () {
3583 var _this = this;
3584 return tslib.__generator(this, function (_a) {
3585 return [2 /*return*/, this._nextPolicy
3586 .sendRequest(request)
3587 .then(function (response) {
3588 return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response);
3589 })];
3590 });
3591 });
3592 };
3593 return DeserializationPolicy;
3594}(BaseRequestPolicy));
3595function getOperationResponse(parsedResponse) {
3596 var result;
3597 var request = parsedResponse.request;
3598 var operationSpec = request.operationSpec;
3599 if (operationSpec) {
3600 var operationResponseGetter = request.operationResponseGetter;
3601 if (!operationResponseGetter) {
3602 result = operationSpec.responses[parsedResponse.status];
3603 }
3604 else {
3605 result = operationResponseGetter(operationSpec, parsedResponse);
3606 }
3607 }
3608 return result;
3609}
3610function shouldDeserializeResponse(parsedResponse) {
3611 var shouldDeserialize = parsedResponse.request.shouldDeserialize;
3612 var result;
3613 if (shouldDeserialize === undefined) {
3614 result = true;
3615 }
3616 else if (typeof shouldDeserialize === "boolean") {
3617 result = shouldDeserialize;
3618 }
3619 else {
3620 result = shouldDeserialize(parsedResponse);
3621 }
3622 return result;
3623}
3624function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
3625 return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
3626 var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
3627 if (shouldDeserialize) {
3628 var operationSpec = parsedResponse.request.operationSpec;
3629 if (operationSpec && operationSpec.responses) {
3630 var statusCode = parsedResponse.status;
3631 var expectedStatusCodes = Object.keys(operationSpec.responses);
3632 var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 ||
3633 (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default");
3634 var responseSpec = getOperationResponse(parsedResponse);
3635 var isExpectedStatusCode = hasNoExpectedStatusCodes
3636 ? 200 <= statusCode && statusCode < 300
3637 : !!responseSpec;
3638 if (!isExpectedStatusCode) {
3639 var defaultResponseSpec = operationSpec.responses.default;
3640 if (defaultResponseSpec) {
3641 var initialErrorMessage = isStreamOperation(operationSpec)
3642 ? "Unexpected status code: " + statusCode
3643 : parsedResponse.bodyAsText;
3644 var error = new RestError(initialErrorMessage);
3645 error.statusCode = statusCode;
3646 error.request = stripRequest(parsedResponse.request);
3647 error.response = stripResponse(parsedResponse);
3648 var parsedErrorResponse = parsedResponse.parsedBody;
3649 try {
3650 if (parsedErrorResponse) {
3651 var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
3652 if (defaultResponseBodyMapper &&
3653 defaultResponseBodyMapper.serializedName === "CloudError") {
3654 if (parsedErrorResponse.error) {
3655 parsedErrorResponse = parsedErrorResponse.error;
3656 }
3657 if (parsedErrorResponse.code) {
3658 error.code = parsedErrorResponse.code;
3659 }
3660 if (parsedErrorResponse.message) {
3661 error.message = parsedErrorResponse.message;
3662 }
3663 }
3664 else {
3665 var internalError = parsedErrorResponse;
3666 if (parsedErrorResponse.error) {
3667 internalError = parsedErrorResponse.error;
3668 }
3669 error.code = internalError.code;
3670 if (internalError.message) {
3671 error.message = internalError.message;
3672 }
3673 }
3674 if (defaultResponseBodyMapper) {
3675 var valueToDeserialize = parsedErrorResponse;
3676 if (operationSpec.isXML &&
3677 defaultResponseBodyMapper.type.name === MapperType.Sequence) {
3678 valueToDeserialize =
3679 typeof parsedErrorResponse === "object"
3680 ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
3681 : [];
3682 }
3683 error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
3684 }
3685 }
3686 }
3687 catch (defaultError) {
3688 error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
3689 }
3690 return Promise.reject(error);
3691 }
3692 }
3693 else if (responseSpec) {
3694 if (responseSpec.bodyMapper) {
3695 var valueToDeserialize = parsedResponse.parsedBody;
3696 if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
3697 valueToDeserialize =
3698 typeof valueToDeserialize === "object"
3699 ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
3700 : [];
3701 }
3702 try {
3703 parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
3704 }
3705 catch (error) {
3706 var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
3707 restError.request = stripRequest(parsedResponse.request);
3708 restError.response = stripResponse(parsedResponse);
3709 return Promise.reject(restError);
3710 }
3711 }
3712 else if (operationSpec.httpMethod === "HEAD") {
3713 // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
3714 parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
3715 }
3716 if (responseSpec.headersMapper) {
3717 parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
3718 }
3719 }
3720 }
3721 }
3722 return Promise.resolve(parsedResponse);
3723 });
3724}
3725function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
3726 var errorHandler = function (err) {
3727 var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
3728 var errCode = err.code || RestError.PARSE_ERROR;
3729 var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
3730 return Promise.reject(e);
3731 };
3732 if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
3733 var text_1 = operationResponse.bodyAsText;
3734 var contentType = operationResponse.headers.get("Content-Type") || "";
3735 var contentComponents = !contentType
3736 ? []
3737 : contentType.split(";").map(function (component) { return component.toLowerCase(); });
3738 if (contentComponents.length === 0 ||
3739 contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
3740 return new Promise(function (resolve) {
3741 operationResponse.parsedBody = JSON.parse(text_1);
3742 resolve(operationResponse);
3743 }).catch(errorHandler);
3744 }
3745 else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
3746 return parseXML(text_1)
3747 .then(function (body) {
3748 operationResponse.parsedBody = body;
3749 return operationResponse;
3750 })
3751 .catch(errorHandler);
3752 }
3753 }
3754 return Promise.resolve(operationResponse);
3755}
3756
3757// Copyright (c) Microsoft Corporation. All rights reserved.
3758function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3759 return {
3760 create: function (nextPolicy, options) {
3761 return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
3762 },
3763 };
3764}
3765var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
3766var DEFAULT_CLIENT_RETRY_COUNT = 3;
3767var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
3768var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
3769/**
3770 * @class
3771 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
3772 */
3773var ExponentialRetryPolicy = /** @class */ (function (_super) {
3774 tslib.__extends(ExponentialRetryPolicy, _super);
3775 /**
3776 * @constructor
3777 * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
3778 * @param {RequestPolicyOptionsLike} options The options for this RequestPolicy.
3779 * @param {number} [retryCount] The client retry count.
3780 * @param {number} [retryInterval] The client retry interval, in milliseconds.
3781 * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
3782 * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
3783 */
3784 function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3785 var _this = _super.call(this, nextPolicy, options) || this;
3786 function isNumber(n) {
3787 return typeof n === "number";
3788 }
3789 _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
3790 _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
3791 _this.minRetryInterval = isNumber(minRetryInterval)
3792 ? minRetryInterval
3793 : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
3794 _this.maxRetryInterval = isNumber(maxRetryInterval)
3795 ? maxRetryInterval
3796 : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
3797 return _this;
3798 }
3799 ExponentialRetryPolicy.prototype.sendRequest = function (request) {
3800 var _this = this;
3801 return this._nextPolicy
3802 .sendRequest(request.clone())
3803 .then(function (response) { return retry(_this, request, response); })
3804 .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
3805 };
3806 return ExponentialRetryPolicy;
3807}(BaseRequestPolicy));
3808/**
3809 * Determines if the operation should be retried and how long to wait until the next retry.
3810 *
3811 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
3812 * @param {number} statusCode The HTTP status code.
3813 * @param {RetryData} retryData The retry data.
3814 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
3815 */
3816function shouldRetry(policy, statusCode, retryData) {
3817 if (statusCode == undefined ||
3818 (statusCode < 500 && statusCode !== 408) ||
3819 statusCode === 501 ||
3820 statusCode === 505) {
3821 return false;
3822 }
3823 var currentCount;
3824 if (!retryData) {
3825 throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
3826 }
3827 else {
3828 currentCount = retryData && retryData.retryCount;
3829 }
3830 return currentCount < policy.retryCount;
3831}
3832/**
3833 * Updates the retry data for the next attempt.
3834 *
3835 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
3836 * @param {RetryData} retryData The retry data.
3837 * @param {RetryError} [err] The operation"s error, if any.
3838 */
3839function updateRetryData(policy, retryData, err) {
3840 if (!retryData) {
3841 retryData = {
3842 retryCount: 0,
3843 retryInterval: 0,
3844 };
3845 }
3846 if (err) {
3847 if (retryData.error) {
3848 err.innerError = retryData.error;
3849 }
3850 retryData.error = err;
3851 }
3852 // Adjust retry count
3853 retryData.retryCount++;
3854 // Adjust retry interval
3855 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
3856 var boundedRandDelta = policy.retryInterval * 0.8 +
3857 Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
3858 incrementDelta *= boundedRandDelta;
3859 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
3860 return retryData;
3861}
3862function retry(policy, request, response, retryData, requestError) {
3863 retryData = updateRetryData(policy, retryData, requestError);
3864 var isAborted = request.abortSignal && request.abortSignal.aborted;
3865 if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
3866 return delay(retryData.retryInterval)
3867 .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
3868 .then(function (res) { return retry(policy, request, res, retryData, undefined); })
3869 .catch(function (err) { return retry(policy, request, response, retryData, err); });
3870 }
3871 else if (isAborted || requestError || !response) {
3872 // If the operation failed in the end, return all errors instead of just the last one
3873 var err = retryData.error ||
3874 new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
3875 return Promise.reject(err);
3876 }
3877 else {
3878 return Promise.resolve(response);
3879 }
3880}
3881
3882// Copyright (c) Microsoft Corporation. All rights reserved.
3883function generateClientRequestIdPolicy(requestIdHeaderName) {
3884 if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
3885 return {
3886 create: function (nextPolicy, options) {
3887 return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
3888 },
3889 };
3890}
3891var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
3892 tslib.__extends(GenerateClientRequestIdPolicy, _super);
3893 function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
3894 var _this = _super.call(this, nextPolicy, options) || this;
3895 _this._requestIdHeaderName = _requestIdHeaderName;
3896 return _this;
3897 }
3898 GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
3899 if (!request.headers.contains(this._requestIdHeaderName)) {
3900 request.headers.set(this._requestIdHeaderName, generateUuid());
3901 }
3902 return this._nextPolicy.sendRequest(request);
3903 };
3904 return GenerateClientRequestIdPolicy;
3905}(BaseRequestPolicy));
3906
3907// Copyright (c) Microsoft Corporation. All rights reserved.
3908function getDefaultUserAgentKey() {
3909 return Constants.HeaderConstants.USER_AGENT;
3910}
3911function getPlatformSpecificData() {
3912 var runtimeInfo = {
3913 key: "Node",
3914 value: process.version,
3915 };
3916 var osInfo = {
3917 key: "OS",
3918 value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")",
3919 };
3920 return [runtimeInfo, osInfo];
3921}
3922
3923// Copyright (c) Microsoft Corporation. All rights reserved.
3924function getRuntimeInfo() {
3925 var msRestRuntime = {
3926 key: "ms-rest-js",
3927 value: Constants.msRestVersion,
3928 };
3929 return [msRestRuntime];
3930}
3931function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
3932 if (keySeparator === void 0) { keySeparator = " "; }
3933 if (valueSeparator === void 0) { valueSeparator = "/"; }
3934 return telemetryInfo
3935 .map(function (info) {
3936 var value = info.value ? "" + valueSeparator + info.value : "";
3937 return "" + info.key + value;
3938 })
3939 .join(keySeparator);
3940}
3941var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
3942function getDefaultUserAgentValue() {
3943 var runtimeInfo = getRuntimeInfo();
3944 var platformSpecificData = getPlatformSpecificData();
3945 var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
3946 return userAgent;
3947}
3948function userAgentPolicy(userAgentData) {
3949 var key = !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key;
3950 var value = !userAgentData || userAgentData.value == undefined
3951 ? getDefaultUserAgentValue()
3952 : userAgentData.value;
3953 return {
3954 create: function (nextPolicy, options) {
3955 return new UserAgentPolicy(nextPolicy, options, key, value);
3956 },
3957 };
3958}
3959var UserAgentPolicy = /** @class */ (function (_super) {
3960 tslib.__extends(UserAgentPolicy, _super);
3961 function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
3962 var _this = _super.call(this, _nextPolicy, _options) || this;
3963 _this._nextPolicy = _nextPolicy;
3964 _this._options = _options;
3965 _this.headerKey = headerKey;
3966 _this.headerValue = headerValue;
3967 return _this;
3968 }
3969 UserAgentPolicy.prototype.sendRequest = function (request) {
3970 this.addUserAgentHeader(request);
3971 return this._nextPolicy.sendRequest(request);
3972 };
3973 UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
3974 if (!request.headers) {
3975 request.headers = new HttpHeaders();
3976 }
3977 if (!request.headers.get(this.headerKey) && this.headerValue) {
3978 request.headers.set(this.headerKey, this.headerValue);
3979 }
3980 };
3981 return UserAgentPolicy;
3982}(BaseRequestPolicy));
3983
3984// Copyright (c) Microsoft Corporation. All rights reserved.
3985var DefaultRedirectOptions = {
3986 handleRedirects: true,
3987 maxRetries: 20,
3988};
3989function redirectPolicy(maximumRetries) {
3990 if (maximumRetries === void 0) { maximumRetries = 20; }
3991 return {
3992 create: function (nextPolicy, options) {
3993 return new RedirectPolicy(nextPolicy, options, maximumRetries);
3994 },
3995 };
3996}
3997var RedirectPolicy = /** @class */ (function (_super) {
3998 tslib.__extends(RedirectPolicy, _super);
3999 function RedirectPolicy(nextPolicy, options, maxRetries) {
4000 if (maxRetries === void 0) { maxRetries = 20; }
4001 var _this = _super.call(this, nextPolicy, options) || this;
4002 _this.maxRetries = maxRetries;
4003 return _this;
4004 }
4005 RedirectPolicy.prototype.sendRequest = function (request) {
4006 var _this = this;
4007 return this._nextPolicy
4008 .sendRequest(request)
4009 .then(function (response) { return handleRedirect(_this, response, 0); });
4010 };
4011 return RedirectPolicy;
4012}(BaseRequestPolicy));
4013function handleRedirect(policy, response, currentRetries) {
4014 var request = response.request, status = response.status;
4015 var locationHeader = response.headers.get("location");
4016 if (locationHeader &&
4017 (status === 300 ||
4018 (status === 301 && ["GET", "HEAD"].includes(request.method)) ||
4019 (status === 302 && ["GET", "POST", "HEAD"].includes(request.method)) ||
4020 (status === 303 && "POST" === request.method) ||
4021 status === 307) &&
4022 ((request.redirectLimit !== undefined && currentRetries < request.redirectLimit) ||
4023 (request.redirectLimit === undefined && currentRetries < policy.maxRetries))) {
4024 var builder = URLBuilder.parse(request.url);
4025 builder.setPath(locationHeader);
4026 request.url = builder.toString();
4027 // POST request with Status code 302 and 303 should be converted into a
4028 // redirected GET request if the redirect url is present in the location header
4029 // reference: https://tools.ietf.org/html/rfc7231#page-57 && https://fetch.spec.whatwg.org/#http-redirect-fetch
4030 if ((status === 302 || status === 303) && request.method === "POST") {
4031 request.method = "GET";
4032 delete request.body;
4033 }
4034 return policy._nextPolicy
4035 .sendRequest(request)
4036 .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); })
4037 .then(function (res) { return recordRedirect(res, request.url); });
4038 }
4039 return Promise.resolve(response);
4040}
4041function recordRedirect(response, redirect) {
4042 // This is called as the recursive calls to handleRedirect() unwind,
4043 // only record the deepest/last redirect
4044 if (!response.redirected) {
4045 response.redirected = true;
4046 response.url = redirect;
4047 }
4048 return response;
4049}
4050
4051function rpRegistrationPolicy(retryTimeout) {
4052 if (retryTimeout === void 0) { retryTimeout = 30; }
4053 return {
4054 create: function (nextPolicy, options) {
4055 return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
4056 },
4057 };
4058}
4059var RPRegistrationPolicy = /** @class */ (function (_super) {
4060 tslib.__extends(RPRegistrationPolicy, _super);
4061 function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
4062 if (_retryTimeout === void 0) { _retryTimeout = 30; }
4063 var _this = _super.call(this, nextPolicy, options) || this;
4064 _this._retryTimeout = _retryTimeout;
4065 return _this;
4066 }
4067 RPRegistrationPolicy.prototype.sendRequest = function (request) {
4068 var _this = this;
4069 return this._nextPolicy
4070 .sendRequest(request.clone())
4071 .then(function (response) { return registerIfNeeded(_this, request, response); });
4072 };
4073 return RPRegistrationPolicy;
4074}(BaseRequestPolicy));
4075function registerIfNeeded(policy, request, response) {
4076 if (response.status === 409) {
4077 var rpName = checkRPNotRegisteredError(response.bodyAsText);
4078 if (rpName) {
4079 var urlPrefix = extractSubscriptionUrl(request.url);
4080 return (registerRP(policy, urlPrefix, rpName, request)
4081 // Autoregistration of ${provider} failed for some reason. We will not return this error
4082 // instead will return the initial response with 409 status code back to the user.
4083 // do nothing here as we are returning the original response at the end of this method.
4084 .catch(function () { return false; })
4085 .then(function (registrationStatus) {
4086 if (registrationStatus) {
4087 // Retry the original request. We have to change the x-ms-client-request-id
4088 // otherwise Azure endpoint will return the initial 409 (cached) response.
4089 request.headers.set("x-ms-client-request-id", generateUuid());
4090 return policy._nextPolicy.sendRequest(request.clone());
4091 }
4092 return response;
4093 }));
4094 }
4095 }
4096 return Promise.resolve(response);
4097}
4098/**
4099 * Reuses the headers of the original request and url (if specified).
4100 * @param {WebResourceLike} originalRequest The original request
4101 * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
4102 * @returns {object} A new request object with desired headers.
4103 */
4104function getRequestEssentials(originalRequest, reuseUrlToo) {
4105 if (reuseUrlToo === void 0) { reuseUrlToo = false; }
4106 var reqOptions = originalRequest.clone();
4107 if (reuseUrlToo) {
4108 reqOptions.url = originalRequest.url;
4109 }
4110 // We have to change the x-ms-client-request-id otherwise Azure endpoint
4111 // will return the initial 409 (cached) response.
4112 reqOptions.headers.set("x-ms-client-request-id", generateUuid());
4113 // Set content-type to application/json
4114 reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
4115 return reqOptions;
4116}
4117/**
4118 * Validates the error code and message associated with 409 response status code. If it matches to that of
4119 * RP not registered then it returns the name of the RP else returns undefined.
4120 * @param {string} body The response body received after making the original request.
4121 * @returns {string} The name of the RP if condition is satisfied else undefined.
4122 */
4123function checkRPNotRegisteredError(body) {
4124 var result, responseBody;
4125 if (body) {
4126 try {
4127 responseBody = JSON.parse(body);
4128 }
4129 catch (err) {
4130 // do nothing;
4131 }
4132 if (responseBody &&
4133 responseBody.error &&
4134 responseBody.error.message &&
4135 responseBody.error.code &&
4136 responseBody.error.code === "MissingSubscriptionRegistration") {
4137 var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
4138 if (matchRes) {
4139 result = matchRes.pop();
4140 }
4141 }
4142 }
4143 return result;
4144}
4145/**
4146 * Extracts the first part of the URL, just after subscription:
4147 * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
4148 * @param {string} url The original request url
4149 * @returns {string} The url prefix as explained above.
4150 */
4151function extractSubscriptionUrl(url) {
4152 var result;
4153 var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi);
4154 if (matchRes && matchRes[0]) {
4155 result = matchRes[0];
4156 }
4157 else {
4158 throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
4159 }
4160 return result;
4161}
4162/**
4163 * Registers the given provider.
4164 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
4165 * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
4166 * @param {string} provider The provider name to be registered.
4167 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
4168 * with a message that the provider is not registered.
4169 * @param {registrationCallback} callback The callback that handles the RP registration
4170 */
4171function registerRP(policy, urlPrefix, provider, originalRequest) {
4172 var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
4173 var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
4174 var reqOptions = getRequestEssentials(originalRequest);
4175 reqOptions.method = "POST";
4176 reqOptions.url = postUrl;
4177 return policy._nextPolicy.sendRequest(reqOptions).then(function (response) {
4178 if (response.status !== 200) {
4179 throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
4180 }
4181 return getRegistrationStatus(policy, getUrl, originalRequest);
4182 });
4183}
4184/**
4185 * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
4186 * Polling will happen till the registrationState property of the response body is "Registered".
4187 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
4188 * @param {string} url The request url for polling
4189 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
4190 * with a message that the provider is not registered.
4191 * @returns {Promise<boolean>} True if RP Registration is successful.
4192 */
4193function getRegistrationStatus(policy, url, originalRequest) {
4194 var reqOptions = getRequestEssentials(originalRequest);
4195 reqOptions.url = url;
4196 reqOptions.method = "GET";
4197 return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
4198 var obj = res.parsedBody;
4199 if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
4200 return true;
4201 }
4202 else {
4203 return delay(policy._retryTimeout * 1000)
4204 .then(function () { return getRegistrationStatus(policy, url, originalRequest); });
4205 }
4206 });
4207}
4208
4209// Copyright (c) Microsoft Corporation. All rights reserved.
4210function signingPolicy(authenticationProvider) {
4211 return {
4212 create: function (nextPolicy, options) {
4213 return new SigningPolicy(nextPolicy, options, authenticationProvider);
4214 },
4215 };
4216}
4217var SigningPolicy = /** @class */ (function (_super) {
4218 tslib.__extends(SigningPolicy, _super);
4219 function SigningPolicy(nextPolicy, options, authenticationProvider) {
4220 var _this = _super.call(this, nextPolicy, options) || this;
4221 _this.authenticationProvider = authenticationProvider;
4222 return _this;
4223 }
4224 SigningPolicy.prototype.signRequest = function (request) {
4225 return this.authenticationProvider.signRequest(request);
4226 };
4227 SigningPolicy.prototype.sendRequest = function (request) {
4228 var _this = this;
4229 return this.signRequest(request).then(function (nextRequest) {
4230 return _this._nextPolicy.sendRequest(nextRequest);
4231 });
4232 };
4233 return SigningPolicy;
4234}(BaseRequestPolicy));
4235
4236// Copyright (c) Microsoft Corporation. All rights reserved.
4237function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
4238 return {
4239 create: function (nextPolicy, options) {
4240 return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
4241 },
4242 };
4243}
4244/**
4245 * @class
4246 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
4247 *
4248 * @constructor
4249 * @param {number} retryCount The client retry count.
4250 * @param {number} retryInterval The client retry interval, in milliseconds.
4251 * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
4252 * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
4253 */
4254var SystemErrorRetryPolicy = /** @class */ (function (_super) {
4255 tslib.__extends(SystemErrorRetryPolicy, _super);
4256 function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
4257 var _this = _super.call(this, nextPolicy, options) || this;
4258 _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
4259 _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
4260 _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
4261 _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
4262 _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
4263 _this.retryInterval =
4264 typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
4265 _this.minRetryInterval =
4266 typeof minRetryInterval === "number"
4267 ? minRetryInterval
4268 : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
4269 _this.maxRetryInterval =
4270 typeof maxRetryInterval === "number"
4271 ? maxRetryInterval
4272 : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
4273 return _this;
4274 }
4275 SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
4276 var _this = this;
4277 return this._nextPolicy
4278 .sendRequest(request.clone())
4279 .catch(function (error) { return retry$1(_this, request, error.response, error); });
4280 };
4281 return SystemErrorRetryPolicy;
4282}(BaseRequestPolicy));
4283/**
4284 * Determines if the operation should be retried and how long to wait until the next retry.
4285 *
4286 * @param {number} statusCode The HTTP status code.
4287 * @param {RetryData} retryData The retry data.
4288 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
4289 */
4290function shouldRetry$1(policy, retryData) {
4291 var currentCount;
4292 if (!retryData) {
4293 throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
4294 }
4295 else {
4296 currentCount = retryData && retryData.retryCount;
4297 }
4298 return currentCount < policy.retryCount;
4299}
4300/**
4301 * Updates the retry data for the next attempt.
4302 *
4303 * @param {RetryData} retryData The retry data.
4304 * @param {object} err The operation"s error, if any.
4305 */
4306function updateRetryData$1(policy, retryData, err) {
4307 if (!retryData) {
4308 retryData = {
4309 retryCount: 0,
4310 retryInterval: 0,
4311 };
4312 }
4313 if (err) {
4314 if (retryData.error) {
4315 err.innerError = retryData.error;
4316 }
4317 retryData.error = err;
4318 }
4319 // Adjust retry count
4320 retryData.retryCount++;
4321 // Adjust retry interval
4322 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
4323 var boundedRandDelta = policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 0.4));
4324 incrementDelta *= boundedRandDelta;
4325 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
4326 return retryData;
4327}
4328function retry$1(policy, request, operationResponse, err, retryData) {
4329 return tslib.__awaiter(this, void 0, void 0, function () {
4330 var error_1;
4331 return tslib.__generator(this, function (_a) {
4332 switch (_a.label) {
4333 case 0:
4334 retryData = updateRetryData$1(policy, retryData, err);
4335 if (!(err &&
4336 err.code &&
4337 shouldRetry$1(policy, retryData) &&
4338 (err.code === "ETIMEDOUT" ||
4339 err.code === "ESOCKETTIMEDOUT" ||
4340 err.code === "ECONNREFUSED" ||
4341 err.code === "ECONNRESET" ||
4342 err.code === "ENOENT"))) return [3 /*break*/, 5];
4343 _a.label = 1;
4344 case 1:
4345 _a.trys.push([1, 3, , 4]);
4346 return [4 /*yield*/, delay(retryData.retryInterval)];
4347 case 2:
4348 _a.sent();
4349 return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())];
4350 case 3:
4351 error_1 = _a.sent();
4352 return [2 /*return*/, retry$1(policy, request, operationResponse, error_1, retryData)];
4353 case 4: return [3 /*break*/, 6];
4354 case 5:
4355 if (err) {
4356 // If the operation failed in the end, return all errors instead of just the last one
4357 return [2 /*return*/, Promise.reject(retryData.error)];
4358 }
4359 return [2 /*return*/, operationResponse];
4360 case 6: return [2 /*return*/];
4361 }
4362 });
4363 });
4364}
4365
4366// Copyright (c) Microsoft Corporation. All rights reserved.
4367(function (QueryCollectionFormat) {
4368 QueryCollectionFormat["Csv"] = ",";
4369 QueryCollectionFormat["Ssv"] = " ";
4370 QueryCollectionFormat["Tsv"] = "\t";
4371 QueryCollectionFormat["Pipes"] = "|";
4372 QueryCollectionFormat["Multi"] = "Multi";
4373})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
4374
4375// Copyright (c) Microsoft Corporation. All rights reserved.
4376function agentPolicy(agentSettings) {
4377 return {
4378 create: function (nextPolicy, options) {
4379 return new AgentPolicy(nextPolicy, options, agentSettings);
4380 },
4381 };
4382}
4383var AgentPolicy = /** @class */ (function (_super) {
4384 tslib.__extends(AgentPolicy, _super);
4385 function AgentPolicy(nextPolicy, options, agentSettings) {
4386 var _this = _super.call(this, nextPolicy, options) || this;
4387 _this.agentSettings = agentSettings;
4388 return _this;
4389 }
4390 AgentPolicy.prototype.sendRequest = function (request) {
4391 if (!request.agentSettings) {
4392 request.agentSettings = this.agentSettings;
4393 }
4394 return this._nextPolicy.sendRequest(request);
4395 };
4396 return AgentPolicy;
4397}(BaseRequestPolicy));
4398
4399// Copyright (c) Microsoft Corporation. All rights reserved.
4400/**
4401 * @internal
4402 */
4403var noProxyList = loadNoProxy();
4404var byPassedList = new Map();
4405/**
4406 * @internal
4407 */
4408function getEnvironmentValue(name) {
4409 if (process.env[name]) {
4410 return process.env[name];
4411 }
4412 else if (process.env[name.toLowerCase()]) {
4413 return process.env[name.toLowerCase()];
4414 }
4415 return undefined;
4416}
4417function loadEnvironmentProxyValue() {
4418 if (!process) {
4419 return undefined;
4420 }
4421 var httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY);
4422 var allProxy = getEnvironmentValue(Constants.ALL_PROXY);
4423 var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY);
4424 return httpsProxy || allProxy || httpProxy;
4425}
4426// Check whether the host of a given `uri` is in the noProxyList.
4427// If there's a match, any request sent to the same host won't have the proxy settings set.
4428// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
4429function isBypassed(uri) {
4430 if (noProxyList.length === 0) {
4431 return false;
4432 }
4433 var host = URLBuilder.parse(uri).getHost();
4434 if (byPassedList.has(host)) {
4435 return byPassedList.get(host);
4436 }
4437 var isBypassedFlag = false;
4438 for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) {
4439 var pattern = noProxyList_1[_i];
4440 if (pattern[0] === ".") {
4441 // This should match either domain it self or any subdomain or host
4442 // .foo.com will match foo.com it self or *.foo.com
4443 if (host.endsWith(pattern)) {
4444 isBypassedFlag = true;
4445 }
4446 else {
4447 if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
4448 isBypassedFlag = true;
4449 }
4450 }
4451 }
4452 else {
4453 if (host === pattern) {
4454 isBypassedFlag = true;
4455 }
4456 }
4457 }
4458 byPassedList.set(host, isBypassedFlag);
4459 return isBypassedFlag;
4460}
4461/**
4462 * @internal
4463 */
4464function loadNoProxy() {
4465 var noProxy = getEnvironmentValue(Constants.NO_PROXY);
4466 if (noProxy) {
4467 return noProxy
4468 .split(",")
4469 .map(function (item) { return item.trim(); })
4470 .filter(function (item) { return item.length; });
4471 }
4472 return [];
4473}
4474/**
4475 * @internal
4476 */
4477function extractAuthFromUrl(url) {
4478 var atIndex = url.indexOf("@");
4479 if (atIndex === -1) {
4480 return { urlWithoutAuth: url };
4481 }
4482 var schemeIndex = url.indexOf("://");
4483 var authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0;
4484 var auth = url.substring(authStart, atIndex);
4485 var colonIndex = auth.indexOf(":");
4486 var hasPassword = colonIndex !== -1;
4487 var username = hasPassword ? auth.substring(0, colonIndex) : auth;
4488 var password = hasPassword ? auth.substring(colonIndex + 1) : undefined;
4489 var urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1);
4490 return {
4491 username: username,
4492 password: password,
4493 urlWithoutAuth: urlWithoutAuth,
4494 };
4495}
4496function getDefaultProxySettings(proxyUrl) {
4497 if (!proxyUrl) {
4498 proxyUrl = loadEnvironmentProxyValue();
4499 if (!proxyUrl) {
4500 return undefined;
4501 }
4502 }
4503 var _a = extractAuthFromUrl(proxyUrl), username = _a.username, password = _a.password, urlWithoutAuth = _a.urlWithoutAuth;
4504 var parsedUrl = URLBuilder.parse(urlWithoutAuth);
4505 var schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : "";
4506 return {
4507 host: schema + parsedUrl.getHost(),
4508 port: Number.parseInt(parsedUrl.getPort() || "80"),
4509 username: username,
4510 password: password,
4511 };
4512}
4513function proxyPolicy(proxySettings) {
4514 if (!proxySettings) {
4515 proxySettings = getDefaultProxySettings();
4516 }
4517 return {
4518 create: function (nextPolicy, options) {
4519 return new ProxyPolicy(nextPolicy, options, proxySettings);
4520 },
4521 };
4522}
4523var ProxyPolicy = /** @class */ (function (_super) {
4524 tslib.__extends(ProxyPolicy, _super);
4525 function ProxyPolicy(nextPolicy, options, proxySettings) {
4526 var _this = _super.call(this, nextPolicy, options) || this;
4527 _this.proxySettings = proxySettings;
4528 return _this;
4529 }
4530 ProxyPolicy.prototype.sendRequest = function (request) {
4531 if (!request.proxySettings && !isBypassed(request.url)) {
4532 request.proxySettings = this.proxySettings;
4533 }
4534 return this._nextPolicy.sendRequest(request);
4535 };
4536 return ProxyPolicy;
4537}(BaseRequestPolicy));
4538
4539// Copyright (c) Microsoft Corporation. All rights reserved.
4540var StatusCodes = Constants.HttpConstants.StatusCodes;
4541var DEFAULT_RETRY_COUNT = 3;
4542function throttlingRetryPolicy(maxRetries) {
4543 if (maxRetries === void 0) { maxRetries = DEFAULT_RETRY_COUNT; }
4544 return {
4545 create: function (nextPolicy, options) {
4546 return new ThrottlingRetryPolicy(nextPolicy, options, maxRetries);
4547 },
4548 };
4549}
4550/**
4551 * To learn more, please refer to
4552 * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
4553 * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
4554 * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
4555 */
4556var ThrottlingRetryPolicy = /** @class */ (function (_super) {
4557 tslib.__extends(ThrottlingRetryPolicy, _super);
4558 function ThrottlingRetryPolicy(nextPolicy, options, retryLimit) {
4559 var _this = _super.call(this, nextPolicy, options) || this;
4560 _this.retryLimit = retryLimit;
4561 return _this;
4562 }
4563 ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
4564 return tslib.__awaiter(this, void 0, void 0, function () {
4565 var _this = this;
4566 return tslib.__generator(this, function (_a) {
4567 return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
4568 return _this.retry(httpRequest, response, 0);
4569 })];
4570 });
4571 });
4572 };
4573 ThrottlingRetryPolicy.prototype.retry = function (httpRequest, httpResponse, retryCount) {
4574 return tslib.__awaiter(this, void 0, void 0, function () {
4575 var retryAfterHeader, delayInMs, res;
4576 return tslib.__generator(this, function (_a) {
4577 switch (_a.label) {
4578 case 0:
4579 if (httpResponse.status !== StatusCodes.TooManyRequests) {
4580 return [2 /*return*/, httpResponse];
4581 }
4582 retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
4583 if (!(retryAfterHeader && retryCount < this.retryLimit)) return [3 /*break*/, 3];
4584 delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
4585 if (!delayInMs) return [3 /*break*/, 3];
4586 return [4 /*yield*/, delay(delayInMs)];
4587 case 1:
4588 _a.sent();
4589 return [4 /*yield*/, this._nextPolicy.sendRequest(httpRequest)];
4590 case 2:
4591 res = _a.sent();
4592 return [2 /*return*/, this.retry(httpRequest, res, retryCount + 1)];
4593 case 3: return [2 /*return*/, httpResponse];
4594 }
4595 });
4596 });
4597 };
4598 ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
4599 var retryAfterInSeconds = Number(headerValue);
4600 if (Number.isNaN(retryAfterInSeconds)) {
4601 return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
4602 }
4603 else {
4604 return retryAfterInSeconds * 1000;
4605 }
4606 };
4607 ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
4608 try {
4609 var now = Date.now();
4610 var date = Date.parse(headerValue);
4611 var diff = date - now;
4612 return Number.isNaN(diff) ? undefined : diff;
4613 }
4614 catch (error) {
4615 return undefined;
4616 }
4617 };
4618 return ThrottlingRetryPolicy;
4619}(BaseRequestPolicy));
4620
4621// Copyright (c) Microsoft Corporation. All rights reserved.
4622var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
4623/**
4624 * Resource manager endpoints to match in order to specify a valid scope to the AzureIdentityCredentialAdapter.
4625 */
4626var azureResourceManagerEndpoints = [
4627 "https://management.windows.net",
4628 "https://management.chinacloudapi.cn",
4629 "https://management.usgovcloudapi.net",
4630 "https://management.cloudapi.de",
4631];
4632/**
4633 * This class provides a simple extension to use {@link TokenCredential} from `@azure/identity` library to
4634 * use with legacy Azure SDKs that accept {@link ServiceClientCredentials} family of credentials for authentication.
4635 */
4636var AzureIdentityCredentialAdapter = /** @class */ (function () {
4637 function AzureIdentityCredentialAdapter(azureTokenCredential, scopes) {
4638 if (scopes === void 0) { scopes = "https://management.azure.com/.default"; }
4639 this.azureTokenCredential = azureTokenCredential;
4640 this.scopes = scopes;
4641 }
4642 AzureIdentityCredentialAdapter.prototype.getToken = function () {
4643 return tslib.__awaiter(this, void 0, void 0, function () {
4644 var accessToken, result;
4645 return tslib.__generator(this, function (_a) {
4646 switch (_a.label) {
4647 case 0: return [4 /*yield*/, this.azureTokenCredential.getToken(this.scopes)];
4648 case 1:
4649 accessToken = _a.sent();
4650 if (accessToken !== null) {
4651 result = {
4652 accessToken: accessToken.token,
4653 tokenType: DEFAULT_AUTHORIZATION_SCHEME,
4654 expiresOn: accessToken.expiresOnTimestamp,
4655 };
4656 return [2 /*return*/, result];
4657 }
4658 else {
4659 throw new Error("Could find token for scope");
4660 }
4661 }
4662 });
4663 });
4664 };
4665 AzureIdentityCredentialAdapter.prototype.signRequest = function (webResource) {
4666 return tslib.__awaiter(this, void 0, void 0, function () {
4667 var tokenResponse;
4668 return tslib.__generator(this, function (_a) {
4669 switch (_a.label) {
4670 case 0: return [4 /*yield*/, this.getToken()];
4671 case 1:
4672 tokenResponse = _a.sent();
4673 webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, tokenResponse.tokenType + " " + tokenResponse.accessToken);
4674 return [2 /*return*/, Promise.resolve(webResource)];
4675 }
4676 });
4677 });
4678 };
4679 return AzureIdentityCredentialAdapter;
4680}());
4681
4682// Copyright (c) Microsoft Corporation. All rights reserved.
4683/**
4684 * @class
4685 * Initializes a new instance of the ServiceClient.
4686 */
4687var ServiceClient = /** @class */ (function () {
4688 /**
4689 * The ServiceClient constructor
4690 * @constructor
4691 * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
4692 * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
4693 */
4694 function ServiceClient(credentials, options) {
4695 if (!options) {
4696 options = {};
4697 }
4698 if (options.baseUri) {
4699 this.baseUri = options.baseUri;
4700 }
4701 var serviceClientCredentials;
4702 if (isTokenCredential(credentials)) {
4703 var scope = undefined;
4704 if ((options === null || options === void 0 ? void 0 : options.baseUri) && azureResourceManagerEndpoints.includes(options === null || options === void 0 ? void 0 : options.baseUri)) {
4705 scope = options.baseUri + "/.default";
4706 }
4707 serviceClientCredentials = new AzureIdentityCredentialAdapter(credentials, scope);
4708 }
4709 else {
4710 serviceClientCredentials = credentials;
4711 }
4712 if (serviceClientCredentials && !serviceClientCredentials.signRequest) {
4713 throw new Error("credentials argument needs to implement signRequest method");
4714 }
4715 this._withCredentials = options.withCredentials || false;
4716 this._httpClient = options.httpClient || new NodeFetchHttpClient();
4717 this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
4718 var requestPolicyFactories;
4719 if (Array.isArray(options.requestPolicyFactories)) {
4720 requestPolicyFactories = options.requestPolicyFactories;
4721 }
4722 else {
4723 requestPolicyFactories = createDefaultRequestPolicyFactories(serviceClientCredentials, options);
4724 if (options.requestPolicyFactories) {
4725 var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
4726 if (newRequestPolicyFactories) {
4727 requestPolicyFactories = newRequestPolicyFactories;
4728 }
4729 }
4730 }
4731 this._requestPolicyFactories = requestPolicyFactories;
4732 }
4733 /**
4734 * Send the provided httpRequest.
4735 */
4736 ServiceClient.prototype.sendRequest = function (options) {
4737 if (options === null || options === undefined || typeof options !== "object") {
4738 throw new Error("options cannot be null or undefined and it must be of type object.");
4739 }
4740 var httpRequest;
4741 try {
4742 if (isWebResourceLike(options)) {
4743 options.validateRequestProperties();
4744 httpRequest = options;
4745 }
4746 else {
4747 httpRequest = new WebResource();
4748 httpRequest = httpRequest.prepare(options);
4749 }
4750 }
4751 catch (error) {
4752 return Promise.reject(error);
4753 }
4754 var httpPipeline = this._httpClient;
4755 if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
4756 for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
4757 httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
4758 }
4759 }
4760 return httpPipeline.sendRequest(httpRequest);
4761 };
4762 /**
4763 * Send an HTTP request that is populated using the provided OperationSpec.
4764 * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
4765 * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
4766 * @param {ServiceCallback} callback The callback to call when the response is received.
4767 */
4768 ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
4769 if (typeof operationArguments.options === "function") {
4770 callback = operationArguments.options;
4771 operationArguments.options = undefined;
4772 }
4773 var httpRequest = new WebResource();
4774 var result;
4775 try {
4776 var baseUri = operationSpec.baseUrl || this.baseUri;
4777 if (!baseUri) {
4778 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.");
4779 }
4780 httpRequest.method = operationSpec.httpMethod;
4781 httpRequest.operationSpec = operationSpec;
4782 var requestUrl = URLBuilder.parse(baseUri);
4783 if (operationSpec.path) {
4784 requestUrl.appendPath(operationSpec.path);
4785 }
4786 if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
4787 for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
4788 var urlParameter = _a[_i];
4789 var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
4790 urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
4791 if (!urlParameter.skipEncoding) {
4792 urlParameterValue = encodeURIComponent(urlParameterValue);
4793 }
4794 requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
4795 }
4796 }
4797 if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
4798 for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
4799 var queryParameter = _c[_b];
4800 var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
4801 if (queryParameterValue != undefined) {
4802 queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
4803 if (queryParameter.collectionFormat != undefined) {
4804 if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
4805 if (queryParameterValue.length === 0) {
4806 queryParameterValue = "";
4807 }
4808 else {
4809 for (var index in queryParameterValue) {
4810 var item = queryParameterValue[index];
4811 queryParameterValue[index] = item == undefined ? "" : item.toString();
4812 }
4813 }
4814 }
4815 else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv ||
4816 queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) {
4817 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
4818 }
4819 }
4820 if (!queryParameter.skipEncoding) {
4821 if (Array.isArray(queryParameterValue)) {
4822 for (var index in queryParameterValue) {
4823 if (queryParameterValue[index] !== undefined &&
4824 queryParameterValue[index] !== null) {
4825 queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
4826 }
4827 }
4828 }
4829 else {
4830 queryParameterValue = encodeURIComponent(queryParameterValue);
4831 }
4832 }
4833 if (queryParameter.collectionFormat != undefined &&
4834 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi &&
4835 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv &&
4836 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) {
4837 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
4838 }
4839 requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
4840 }
4841 }
4842 }
4843 httpRequest.url = requestUrl.toString();
4844 var contentType = operationSpec.contentType || this.requestContentType;
4845 if (contentType) {
4846 httpRequest.headers.set("Content-Type", contentType);
4847 }
4848 if (operationSpec.headerParameters) {
4849 for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
4850 var headerParameter = _e[_d];
4851 var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
4852 if (headerValue != undefined) {
4853 headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
4854 var headerCollectionPrefix = headerParameter.mapper
4855 .headerCollectionPrefix;
4856 if (headerCollectionPrefix) {
4857 for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
4858 var key = _g[_f];
4859 httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
4860 }
4861 }
4862 else {
4863 httpRequest.headers.set(headerParameter.mapper.serializedName ||
4864 getPathStringFromParameter(headerParameter), headerValue);
4865 }
4866 }
4867 }
4868 }
4869 var options = operationArguments.options;
4870 if (options) {
4871 if (options.customHeaders) {
4872 for (var customHeaderName in options.customHeaders) {
4873 httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
4874 }
4875 }
4876 if (options.abortSignal) {
4877 httpRequest.abortSignal = options.abortSignal;
4878 }
4879 if (options.timeout) {
4880 httpRequest.timeout = options.timeout;
4881 }
4882 if (options.onUploadProgress) {
4883 httpRequest.onUploadProgress = options.onUploadProgress;
4884 }
4885 if (options.onDownloadProgress) {
4886 httpRequest.onDownloadProgress = options.onDownloadProgress;
4887 }
4888 }
4889 httpRequest.withCredentials = this._withCredentials;
4890 serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
4891 if (httpRequest.streamResponseBody == undefined) {
4892 httpRequest.streamResponseBody = isStreamOperation(operationSpec);
4893 }
4894 result = this.sendRequest(httpRequest).then(function (res) {
4895 return flattenResponse(res, operationSpec.responses[res.status]);
4896 });
4897 }
4898 catch (error) {
4899 result = Promise.reject(error);
4900 }
4901 var cb = callback;
4902 if (cb) {
4903 result
4904 // tslint:disable-next-line:no-null-keyword
4905 .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
4906 .catch(function (err) { return cb(err); });
4907 }
4908 return result;
4909 };
4910 return ServiceClient;
4911}());
4912function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
4913 if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
4914 httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
4915 var bodyMapper = operationSpec.requestBody.mapper;
4916 var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
4917 var typeName = bodyMapper.type.name;
4918 try {
4919 if (httpRequest.body != undefined || required) {
4920 var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
4921 httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
4922 var isStream = typeName === MapperType.Stream;
4923 if (operationSpec.isXML) {
4924 if (typeName === MapperType.Sequence) {
4925 httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
4926 }
4927 else if (!isStream) {
4928 httpRequest.body = stringifyXML(httpRequest.body, {
4929 rootName: xmlName || serializedName,
4930 });
4931 }
4932 }
4933 else if (!isStream) {
4934 httpRequest.body = JSON.stringify(httpRequest.body);
4935 }
4936 }
4937 }
4938 catch (error) {
4939 throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
4940 }
4941 }
4942 else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
4943 httpRequest.formData = {};
4944 for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
4945 var formDataParameter = _a[_i];
4946 var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
4947 if (formDataParameterValue != undefined) {
4948 var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
4949 httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
4950 }
4951 }
4952 }
4953}
4954function isRequestPolicyFactory(instance) {
4955 return typeof instance.create === "function";
4956}
4957function getValueOrFunctionResult(value, defaultValueCreator) {
4958 var result;
4959 if (typeof value === "string") {
4960 result = value;
4961 }
4962 else {
4963 result = defaultValueCreator();
4964 if (typeof value === "function") {
4965 result = value(result);
4966 }
4967 }
4968 return result;
4969}
4970function createDefaultRequestPolicyFactories(credentials, options) {
4971 var factories = [];
4972 if (options.generateClientRequestIdHeader) {
4973 factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
4974 }
4975 if (credentials) {
4976 if (isRequestPolicyFactory(credentials)) {
4977 factories.push(credentials);
4978 }
4979 else {
4980 factories.push(signingPolicy(credentials));
4981 }
4982 }
4983 var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
4984 var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
4985 if (userAgentHeaderName && userAgentHeaderValue) {
4986 factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
4987 }
4988 var redirectOptions = tslib.__assign(tslib.__assign({}, DefaultRedirectOptions), options.redirectOptions);
4989 if (redirectOptions.handleRedirects) {
4990 factories.push(redirectPolicy(redirectOptions.maxRetries));
4991 }
4992 factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
4993 if (!options.noRetryPolicy) {
4994 factories.push(exponentialRetryPolicy());
4995 factories.push(systemErrorRetryPolicy());
4996 factories.push(throttlingRetryPolicy());
4997 }
4998 factories.push(deserializationPolicy(options.deserializationContentTypes));
4999 var proxySettings = options.proxySettings || getDefaultProxySettings();
5000 if (proxySettings) {
5001 factories.push(proxyPolicy(proxySettings));
5002 }
5003 if (options.agentSettings) {
5004 factories.push(agentPolicy(options.agentSettings));
5005 }
5006 return factories;
5007}
5008function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
5009 return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
5010}
5011function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
5012 var value;
5013 if (typeof parameterPath === "string") {
5014 parameterPath = [parameterPath];
5015 }
5016 if (Array.isArray(parameterPath)) {
5017 if (parameterPath.length > 0) {
5018 if (parameterMapper.isConstant) {
5019 value = parameterMapper.defaultValue;
5020 }
5021 else {
5022 var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
5023 if (!propertySearchResult.propertyFound) {
5024 propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
5025 }
5026 var useDefaultValue = false;
5027 if (!propertySearchResult.propertyFound) {
5028 useDefaultValue =
5029 parameterMapper.required ||
5030 (parameterPath[0] === "options" && parameterPath.length === 2);
5031 }
5032 value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
5033 }
5034 // Serialize just for validation purposes.
5035 var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
5036 serializer.serialize(parameterMapper, value, parameterPathString);
5037 }
5038 }
5039 else {
5040 if (parameterMapper.required) {
5041 value = {};
5042 }
5043 for (var propertyName in parameterPath) {
5044 var propertyMapper = parameterMapper.type.modelProperties[propertyName];
5045 var propertyPath = parameterPath[propertyName];
5046 var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
5047 // Serialize just for validation purposes.
5048 var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
5049 serializer.serialize(propertyMapper, propertyValue, propertyPathString);
5050 if (propertyValue !== undefined) {
5051 if (!value) {
5052 value = {};
5053 }
5054 value[propertyName] = propertyValue;
5055 }
5056 }
5057 }
5058 return value;
5059}
5060function getPropertyFromParameterPath(parent, parameterPath) {
5061 var result = { propertyFound: false };
5062 var i = 0;
5063 for (; i < parameterPath.length; ++i) {
5064 var parameterPathPart = parameterPath[i];
5065 // Make sure to check inherited properties too, so don't use hasOwnProperty().
5066 if (parent != undefined && parameterPathPart in parent) {
5067 parent = parent[parameterPathPart];
5068 }
5069 else {
5070 break;
5071 }
5072 }
5073 if (i === parameterPath.length) {
5074 result.propertyValue = parent;
5075 result.propertyFound = true;
5076 }
5077 return result;
5078}
5079function flattenResponse(_response, responseSpec) {
5080 var parsedHeaders = _response.parsedHeaders;
5081 var bodyMapper = responseSpec && responseSpec.bodyMapper;
5082 var addOperationResponse = function (obj) {
5083 return Object.defineProperty(obj, "_response", {
5084 value: _response,
5085 });
5086 };
5087 if (bodyMapper) {
5088 var typeName = bodyMapper.type.name;
5089 if (typeName === "Stream") {
5090 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
5091 }
5092 var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {};
5093 var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
5094 if (typeName === "Sequence" || isPageableResponse) {
5095 // We're expecting a sequece(array) make sure that the response body is in the
5096 // correct format, if not make it an empty array []
5097 var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : [];
5098 var arrayResponse = tslib.__spreadArrays(parsedBody);
5099 for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
5100 var key = _a[_i];
5101 if (modelProperties_1[key].serializedName) {
5102 arrayResponse[key] = _response.parsedBody[key];
5103 }
5104 }
5105 if (parsedHeaders) {
5106 for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
5107 var key = _c[_b];
5108 arrayResponse[key] = parsedHeaders[key];
5109 }
5110 }
5111 addOperationResponse(arrayResponse);
5112 return arrayResponse;
5113 }
5114 if (typeName === "Composite" || typeName === "Dictionary") {
5115 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody));
5116 }
5117 }
5118 if (bodyMapper ||
5119 _response.request.method === "HEAD" ||
5120 isPrimitiveType(_response.parsedBody)) {
5121 // primitive body types and HEAD booleans
5122 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody }));
5123 }
5124 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody));
5125}
5126
5127// Copyright (c) Microsoft Corporation. All rights reserved.
5128function logPolicy(logger) {
5129 if (logger === void 0) { logger = console.log; }
5130 return {
5131 create: function (nextPolicy, options) {
5132 return new LogPolicy(nextPolicy, options, logger);
5133 },
5134 };
5135}
5136var LogPolicy = /** @class */ (function (_super) {
5137 tslib.__extends(LogPolicy, _super);
5138 function LogPolicy(nextPolicy, options, logger) {
5139 if (logger === void 0) { logger = console.log; }
5140 var _this = _super.call(this, nextPolicy, options) || this;
5141 _this.logger = logger;
5142 return _this;
5143 }
5144 LogPolicy.prototype.sendRequest = function (request) {
5145 var _this = this;
5146 return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
5147 };
5148 return LogPolicy;
5149}(BaseRequestPolicy));
5150function logResponse(policy, response) {
5151 policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
5152 policy.logger(">> Response status code: " + response.status);
5153 var responseBody = response.bodyAsText;
5154 policy.logger(">> Body: " + responseBody);
5155 return Promise.resolve(response);
5156}
5157
5158// Copyright (c) Microsoft Corporation. All rights reserved.
5159var HeaderConstants = Constants.HeaderConstants;
5160var DEFAULT_AUTHORIZATION_SCHEME$1 = "Bearer";
5161/**
5162 * A credentials object that uses a token string and a authorzation scheme to authenticate.
5163 */
5164var TokenCredentials = /** @class */ (function () {
5165 /**
5166 * Creates a new TokenCredentials object.
5167 *
5168 * @constructor
5169 * @param {string} token The token.
5170 * @param {string} [authorizationScheme] The authorization scheme.
5171 */
5172 function TokenCredentials(token, authorizationScheme) {
5173 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
5174 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
5175 if (!token) {
5176 throw new Error("token cannot be null or undefined.");
5177 }
5178 this.token = token;
5179 this.authorizationScheme = authorizationScheme;
5180 }
5181 /**
5182 * Signs a request with the Authentication header.
5183 *
5184 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
5185 * @return {Promise<WebResourceLike>} The signed request object.
5186 */
5187 TokenCredentials.prototype.signRequest = function (webResource) {
5188 if (!webResource.headers)
5189 webResource.headers = new HttpHeaders();
5190 webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
5191 return Promise.resolve(webResource);
5192 };
5193 return TokenCredentials;
5194}());
5195
5196// Copyright (c) Microsoft Corporation. All rights reserved.
5197var HeaderConstants$1 = Constants.HeaderConstants;
5198var DEFAULT_AUTHORIZATION_SCHEME$2 = "Basic";
5199var BasicAuthenticationCredentials = /** @class */ (function () {
5200 /**
5201 * Creates a new BasicAuthenticationCredentials object.
5202 *
5203 * @constructor
5204 * @param {string} userName User name.
5205 * @param {string} password Password.
5206 * @param {string} [authorizationScheme] The authorization scheme.
5207 */
5208 function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
5209 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2; }
5210 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2;
5211 if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
5212 throw new Error("userName cannot be null or undefined and must be of type string.");
5213 }
5214 if (password === null || password === undefined || typeof password.valueOf() !== "string") {
5215 throw new Error("password cannot be null or undefined and must be of type string.");
5216 }
5217 this.userName = userName;
5218 this.password = password;
5219 this.authorizationScheme = authorizationScheme;
5220 }
5221 /**
5222 * Signs a request with the Authentication header.
5223 *
5224 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
5225 * @returns {Promise<WebResourceLike>} The signed request object.
5226 */
5227 BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
5228 var credentials = this.userName + ":" + this.password;
5229 var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
5230 if (!webResource.headers)
5231 webResource.headers = new HttpHeaders();
5232 webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
5233 return Promise.resolve(webResource);
5234 };
5235 return BasicAuthenticationCredentials;
5236}());
5237
5238// Copyright (c) Microsoft Corporation. All rights reserved.
5239/**
5240 * Authenticates to a service using an API key.
5241 */
5242var ApiKeyCredentials = /** @class */ (function () {
5243 /**
5244 * @constructor
5245 * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
5246 */
5247 function ApiKeyCredentials(options) {
5248 if (!options || (options && !options.inHeader && !options.inQuery)) {
5249 throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
5250 }
5251 this.inHeader = options.inHeader;
5252 this.inQuery = options.inQuery;
5253 }
5254 /**
5255 * Signs a request with the values provided in the inHeader and inQuery parameter.
5256 *
5257 * @param {WebResource} webResource The WebResource to be signed.
5258 * @returns {Promise<WebResource>} The signed request object.
5259 */
5260 ApiKeyCredentials.prototype.signRequest = function (webResource) {
5261 if (!webResource) {
5262 return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
5263 }
5264 if (this.inHeader) {
5265 if (!webResource.headers) {
5266 webResource.headers = new HttpHeaders();
5267 }
5268 for (var headerName in this.inHeader) {
5269 webResource.headers.set(headerName, this.inHeader[headerName]);
5270 }
5271 }
5272 if (this.inQuery) {
5273 if (!webResource.url) {
5274 return Promise.reject(new Error("url cannot be null in the request object."));
5275 }
5276 if (webResource.url.indexOf("?") < 0) {
5277 webResource.url += "?";
5278 }
5279 for (var key in this.inQuery) {
5280 if (!webResource.url.endsWith("?")) {
5281 webResource.url += "&";
5282 }
5283 webResource.url += key + "=" + this.inQuery[key];
5284 }
5285 }
5286 return Promise.resolve(webResource);
5287 };
5288 return ApiKeyCredentials;
5289}());
5290
5291// Copyright (c) Microsoft Corporation. All rights reserved.
5292var TopicCredentials = /** @class */ (function (_super) {
5293 tslib.__extends(TopicCredentials, _super);
5294 /**
5295 * Creates a new EventGrid TopicCredentials object.
5296 *
5297 * @constructor
5298 * @param {string} topicKey The EventGrid topic key
5299 */
5300 function TopicCredentials(topicKey) {
5301 var _this = this;
5302 if (!topicKey || (topicKey && typeof topicKey !== "string")) {
5303 throw new Error("topicKey cannot be null or undefined and must be of type string.");
5304 }
5305 var options = {
5306 inHeader: {
5307 "aeg-sas-key": topicKey,
5308 },
5309 };
5310 _this = _super.call(this, options) || this;
5311 return _this;
5312 }
5313 return TopicCredentials;
5314}(ApiKeyCredentials));
5315
5316// Copyright (c) Microsoft Corporation. All rights reserved.
5317var DomainCredentials = /** @class */ (function (_super) {
5318 tslib.__extends(DomainCredentials, _super);
5319 /**
5320 * Creates a new EventGrid DomainCredentials object.
5321 *
5322 * @constructor
5323 * @param {string} domainKey The EventGrid domain key
5324 */
5325 function DomainCredentials(domainKey) {
5326 var _this = this;
5327 if (!domainKey || (domainKey && typeof domainKey !== "string")) {
5328 throw new Error("domainKey cannot be null or undefined and must be of type string.");
5329 }
5330 var options = {
5331 inHeader: {
5332 "aeg-sas-key": domainKey,
5333 },
5334 };
5335 _this = _super.call(this, options) || this;
5336 return _this;
5337 }
5338 return DomainCredentials;
5339}(ApiKeyCredentials));
5340
5341exports.ApiKeyCredentials = ApiKeyCredentials;
5342exports.AzureIdentityCredentialAdapter = AzureIdentityCredentialAdapter;
5343exports.BaseRequestPolicy = BaseRequestPolicy;
5344exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
5345exports.Constants = Constants;
5346exports.DefaultHttpClient = NodeFetchHttpClient;
5347exports.DomainCredentials = DomainCredentials;
5348exports.HttpHeaders = HttpHeaders;
5349exports.MapperType = MapperType;
5350exports.RequestPolicyOptions = RequestPolicyOptions;
5351exports.RestError = RestError;
5352exports.Serializer = Serializer;
5353exports.ServiceClient = ServiceClient;
5354exports.TokenCredentials = TokenCredentials;
5355exports.TopicCredentials = TopicCredentials;
5356exports.URLBuilder = URLBuilder;
5357exports.URLQuery = URLQuery;
5358exports.WebResource = WebResource;
5359exports.agentPolicy = agentPolicy;
5360exports.applyMixins = applyMixins;
5361exports.delay = delay;
5362exports.deserializationPolicy = deserializationPolicy;
5363exports.deserializeResponseBody = deserializeResponseBody;
5364exports.encodeUri = encodeUri;
5365exports.executePromisesSequentially = executePromisesSequentially;
5366exports.exponentialRetryPolicy = exponentialRetryPolicy;
5367exports.flattenResponse = flattenResponse;
5368exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
5369exports.generateUuid = generateUuid;
5370exports.getDefaultProxySettings = getDefaultProxySettings;
5371exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
5372exports.isDuration = isDuration;
5373exports.isNode = isNode;
5374exports.isValidUuid = isValidUuid;
5375exports.logPolicy = logPolicy;
5376exports.promiseToCallback = promiseToCallback;
5377exports.promiseToServiceCallback = promiseToServiceCallback;
5378exports.proxyPolicy = proxyPolicy;
5379exports.redirectPolicy = redirectPolicy;
5380exports.serializeObject = serializeObject;
5381exports.signingPolicy = signingPolicy;
5382exports.stripRequest = stripRequest;
5383exports.stripResponse = stripResponse;
5384exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
5385exports.throttlingRetryPolicy = throttlingRetryPolicy;
5386exports.userAgentPolicy = userAgentPolicy;
5387//# sourceMappingURL=msRest.node.js.map