| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941 |
- /** @license ms-rest-js
- * Copyright (c) Microsoft Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt and ThirdPartyNotices.txt in the project root for license information.
- */
- 'use strict';
- Object.defineProperty(exports, '__esModule', { value: true });
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- var uuidv4 = _interopDefault(require('uuid/v4'));
- var axios = _interopDefault(require('axios'));
- var stream = require('stream');
- var FormData = _interopDefault(require('form-data'));
- var tough = require('tough-cookie');
- var tunnel = require('tunnel');
- var xml2js = require('xml2js');
- var os = require('os');
- var tslib_1 = require('tslib');
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // Licensed under the MIT License. See License.txt in the project root for license information.
- /**
- * A collection of HttpHeaders that can be sent with a HTTP request.
- */
- function getHeaderKey(headerName) {
- return headerName.toLowerCase();
- }
- /**
- * A collection of HTTP header key/value pairs.
- */
- var HttpHeaders = /** @class */ (function () {
- function HttpHeaders(rawHeaders) {
- this._headersMap = {};
- if (rawHeaders) {
- for (var headerName in rawHeaders) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- /**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param headerName The name of the header to set. This value is case-insensitive.
- * @param headerValue The value of the header to set.
- */
- HttpHeaders.prototype.set = function (headerName, headerValue) {
- this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() };
- };
- /**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param headerName The name of the header.
- */
- HttpHeaders.prototype.get = function (headerName) {
- var header = this._headersMap[getHeaderKey(headerName)];
- return !header ? undefined : header.value;
- };
- /**
- * Get whether or not this header collection contains a header entry for the provided header name.
- */
- HttpHeaders.prototype.contains = function (headerName) {
- return !!this._headersMap[getHeaderKey(headerName)];
- };
- /**
- * Remove the header with the provided headerName. Return whether or not the header existed and
- * was removed.
- * @param headerName The name of the header to remove.
- */
- HttpHeaders.prototype.remove = function (headerName) {
- var result = this.contains(headerName);
- delete this._headersMap[getHeaderKey(headerName)];
- return result;
- };
- /**
- * Get the headers that are contained this collection as an object.
- */
- HttpHeaders.prototype.rawHeaders = function () {
- var result = {};
- for (var headerKey in this._headersMap) {
- var header = this._headersMap[headerKey];
- result[header.name.toLowerCase()] = header.value;
- }
- return result;
- };
- /**
- * Get the headers that are contained in this collection as an array.
- */
- HttpHeaders.prototype.headersArray = function () {
- var headers = [];
- for (var headerKey in this._headersMap) {
- headers.push(this._headersMap[headerKey]);
- }
- return headers;
- };
- /**
- * Get the header names that are contained in this collection.
- */
- HttpHeaders.prototype.headerNames = function () {
- var headerNames = [];
- var headers = this.headersArray();
- for (var i = 0; i < headers.length; ++i) {
- headerNames.push(headers[i].name);
- }
- return headerNames;
- };
- /**
- * Get the header names that are contained in this collection.
- */
- HttpHeaders.prototype.headerValues = function () {
- var headerValues = [];
- var headers = this.headersArray();
- for (var i = 0; i < headers.length; ++i) {
- headerValues.push(headers[i].value);
- }
- return headerValues;
- };
- /**
- * Get the JSON object representation of this HTTP header collection.
- */
- HttpHeaders.prototype.toJson = function () {
- return this.rawHeaders();
- };
- /**
- * Get the string representation of this HTTP header collection.
- */
- HttpHeaders.prototype.toString = function () {
- return JSON.stringify(this.toJson());
- };
- /**
- * Create a deep clone/copy of this HttpHeaders collection.
- */
- HttpHeaders.prototype.clone = function () {
- return new HttpHeaders(this.rawHeaders());
- };
- return HttpHeaders;
- }());
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // Licensed under the MIT License. See License.txt in the project root for license information.
- /**
- * Encodes a string in base64 format.
- * @param value the string to encode
- */
- function encodeString(value) {
- return Buffer.from(value).toString("base64");
- }
- /**
- * Encodes a byte array in base64 format.
- * @param value the Uint8Aray to encode
- */
- function encodeByteArray(value) {
- // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here
- // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
- var bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer);
- return bufferValue.toString("base64");
- }
- /**
- * Decodes a base64 string into a byte array.
- * @param value the base64 string to decode
- */
- function decodeString(value) {
- return Buffer.from(value, "base64");
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // Licensed under the MIT License. See License.txt in the project root for license information.
- var Constants = {
- /**
- * The ms-rest version
- * @const
- * @type {string}
- */
- msRestVersion: "1.8.13",
- /**
- * Specifies HTTP.
- *
- * @const
- * @type {string}
- */
- HTTP: "http:",
- /**
- * Specifies HTTPS.
- *
- * @const
- * @type {string}
- */
- HTTPS: "https:",
- /**
- * Specifies HTTP Proxy.
- *
- * @const
- * @type {string}
- */
- HTTP_PROXY: "HTTP_PROXY",
- /**
- * Specifies HTTPS Proxy.
- *
- * @const
- * @type {string}
- */
- HTTPS_PROXY: "HTTPS_PROXY",
- HttpConstants: {
- /**
- * Http Verbs
- *
- * @const
- * @enum {string}
- */
- HttpVerbs: {
- PUT: "PUT",
- GET: "GET",
- DELETE: "DELETE",
- POST: "POST",
- MERGE: "MERGE",
- HEAD: "HEAD",
- PATCH: "PATCH"
- },
- StatusCodes: {
- TooManyRequests: 429
- }
- },
- /**
- * Defines constants for use with HTTP headers.
- */
- HeaderConstants: {
- /**
- * The Authorization header.
- *
- * @const
- * @type {string}
- */
- AUTHORIZATION: "authorization",
- AUTHORIZATION_SCHEME: "Bearer",
- /**
- * The Retry-After response-header field can be used with a 503 (Service
- * Unavailable) or 349 (Too Many Requests) responses to indicate how long
- * the service is expected to be unavailable to the requesting client.
- *
- * @const
- * @type {string}
- */
- RETRY_AFTER: "Retry-After",
- /**
- * The UserAgent header.
- *
- * @const
- * @type {string}
- */
- USER_AGENT: "User-Agent"
- }
- };
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * A constant that indicates whether the environment is node.js or browser based.
- */
- var isNode = (typeof process !== "undefined") && !!process.version && !!process.versions && !!process.versions.node;
- /**
- * Encodes an URI.
- *
- * @param {string} uri The URI to be encoded.
- * @return {string} The encoded URI.
- */
- function encodeUri(uri) {
- return encodeURIComponent(uri)
- .replace(/!/g, "%21")
- .replace(/"/g, "%27")
- .replace(/\(/g, "%28")
- .replace(/\)/g, "%29")
- .replace(/\*/g, "%2A");
- }
- /**
- * Returns a stripped version of the Http Response which only contains body,
- * headers and the status.
- *
- * @param {HttpOperationResponse} response The Http Response
- *
- * @return {object} The stripped version of Http Response.
- */
- function stripResponse(response) {
- var strippedResponse = {};
- strippedResponse.body = response.bodyAsText;
- strippedResponse.headers = response.headers;
- strippedResponse.status = response.status;
- return strippedResponse;
- }
- /**
- * Returns a stripped version of the Http Request that does not contain the
- * Authorization header.
- *
- * @param {WebResource} request The Http Request object
- *
- * @return {WebResource} The stripped version of Http Request.
- */
- function stripRequest(request) {
- var strippedRequest = request.clone();
- if (strippedRequest.headers) {
- strippedRequest.headers.remove("authorization");
- }
- return strippedRequest;
- }
- /**
- * Validates the given uuid as a string
- *
- * @param {string} uuid The uuid as a string that needs to be validated
- *
- * @return {boolean} True if the uuid is valid; false otherwise.
- */
- function isValidUuid(uuid) {
- 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");
- return validUuidRegex.test(uuid);
- }
- /**
- * Generated UUID
- *
- * @return {string} RFC4122 v4 UUID.
- */
- function generateUuid() {
- return uuidv4();
- }
- /**
- * Executes an array of promises sequentially. Inspiration of this method is here:
- * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
- *
- * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
- *
- * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
- * If not provided then the promise chain starts with undefined.
- *
- * @return A chain of resolved or rejected promises
- */
- function executePromisesSequentially(promiseFactories, kickstart) {
- var result = Promise.resolve(kickstart);
- promiseFactories.forEach(function (promiseFactory) {
- result = result.then(promiseFactory);
- });
- return result;
- }
- /**
- * A wrapper for setTimeout that resolves a promise after t milliseconds.
- * @param {number} t The number of milliseconds to be delayed.
- * @param {T} value The value to be resolved with after a timeout of t milliseconds.
- * @returns {Promise<T>} Resolved promise
- */
- function delay(t, value) {
- return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
- }
- /**
- * Converts a Promise to a callback.
- * @param {Promise<any>} promise The Promise to be converted to a callback
- * @returns {Function} A function that takes the callback (cb: Function): void
- * @deprecated generated code should instead depend on responseToBody
- */
- function promiseToCallback(promise) {
- if (typeof promise.then !== "function") {
- throw new Error("The provided input is not a Promise.");
- }
- return function (cb) {
- promise.then(function (data) {
- cb(undefined, data);
- }, function (err) {
- cb(err);
- });
- };
- }
- /**
- * Converts a Promise to a service callback.
- * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
- * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
- */
- function promiseToServiceCallback(promise) {
- if (typeof promise.then !== "function") {
- throw new Error("The provided input is not a Promise.");
- }
- return function (cb) {
- promise.then(function (data) {
- process.nextTick(cb, undefined, data.parsedBody, data.request, data);
- }, function (err) {
- process.nextTick(cb, err);
- });
- };
- }
- function prepareXMLRootList(obj, elementName) {
- var _a;
- if (!Array.isArray(obj)) {
- obj = [obj];
- }
- return _a = {}, _a[elementName] = obj, _a;
- }
- /**
- * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
- * @param {object} targetCtor The target object on which the properties need to be applied.
- * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
- */
- function applyMixins(targetCtor, sourceCtors) {
- sourceCtors.forEach(function (sourceCtors) {
- Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
- targetCtor.prototype[name] = sourceCtors.prototype[name];
- });
- });
- }
- var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
- /**
- * Indicates whether the given string is in ISO 8601 format.
- * @param {string} value The value to be validated for ISO 8601 duration format.
- * @return {boolean} `true` if valid, `false` otherwise.
- */
- function isDuration(value) {
- return validateISODuration.test(value);
- }
- /**
- * Replace all of the instances of searchValue in value with the provided replaceValue.
- * @param {string | undefined} value The value to search and replace in.
- * @param {string} searchValue The value to search for in the value argument.
- * @param {string} replaceValue The value to replace searchValue with in the value argument.
- * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
- */
- function replaceAll(value, searchValue, replaceValue) {
- return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var Serializer = /** @class */ (function () {
- function Serializer(modelMappers, isXML) {
- if (modelMappers === void 0) { modelMappers = {}; }
- this.modelMappers = modelMappers;
- this.isXML = isXML;
- }
- Serializer.prototype.validateConstraints = function (mapper, value, objectName) {
- var failValidation = function (constraintName, constraintValue) {
- throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + ".");
- };
- if (mapper.constraints && (value != undefined)) {
- 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;
- if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {
- failValidation("ExclusiveMaximum", ExclusiveMaximum);
- }
- if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {
- failValidation("ExclusiveMinimum", ExclusiveMinimum);
- }
- if (InclusiveMaximum != undefined && value > InclusiveMaximum) {
- failValidation("InclusiveMaximum", InclusiveMaximum);
- }
- if (InclusiveMinimum != undefined && value < InclusiveMinimum) {
- failValidation("InclusiveMinimum", InclusiveMinimum);
- }
- if (MaxItems != undefined && value.length > MaxItems) {
- failValidation("MaxItems", MaxItems);
- }
- if (MaxLength != undefined && value.length > MaxLength) {
- failValidation("MaxLength", MaxLength);
- }
- if (MinItems != undefined && value.length < MinItems) {
- failValidation("MinItems", MinItems);
- }
- if (MinLength != undefined && value.length < MinLength) {
- failValidation("MinLength", MinLength);
- }
- if (MultipleOf != undefined && value % MultipleOf !== 0) {
- failValidation("MultipleOf", MultipleOf);
- }
- if (Pattern && value.match(Pattern) === null) {
- failValidation("Pattern", Pattern);
- }
- if (UniqueItems && value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {
- failValidation("UniqueItems", UniqueItems);
- }
- }
- };
- /**
- * Serialize the given object based on its metadata defined in the mapper
- *
- * @param {Mapper} mapper The mapper which defines the metadata of the serializable object
- *
- * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized
- *
- * @param {string} objectName Name of the serialized object
- *
- * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object
- */
- Serializer.prototype.serialize = function (mapper, object, objectName) {
- var payload = {};
- var mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Sequence$/ig) !== null) {
- payload = [];
- }
- if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) {
- object = mapper.defaultValue;
- }
- // This table of allowed values should help explain
- // the mapper.required and mapper.nullable properties.
- // X means "neither undefined or null are allowed".
- // || required
- // || true | false
- // nullable || ==========================
- // true || null | undefined/null
- // false || X | undefined
- // undefined || X | undefined/null
- var required = mapper.required, nullable = mapper.nullable;
- if (required && nullable && object === undefined) {
- throw new Error(objectName + " cannot be undefined.");
- }
- if (required && !nullable && object == undefined) {
- throw new Error(objectName + " cannot be null or undefined.");
- }
- if (!required && nullable === false && object === null) {
- throw new Error(objectName + " cannot be null.");
- }
- if (object == undefined) {
- payload = object;
- }
- else {
- // Validate Constraints if any
- this.validateConstraints(mapper, object, objectName);
- if (mapperType.match(/^any$/ig) !== null) {
- payload = object;
- }
- else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) {
- payload = serializeBasicTypes(mapperType, objectName, object);
- }
- else if (mapperType.match(/^Enum$/ig) !== null) {
- var enumMapper = mapper;
- payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
- }
- else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) {
- payload = serializeDateTypes(mapperType, object, objectName);
- }
- else if (mapperType.match(/^ByteArray$/ig) !== null) {
- payload = serializeByteArrayType(objectName, object);
- }
- else if (mapperType.match(/^Base64Url$/ig) !== null) {
- payload = serializeBase64UrlType(objectName, object);
- }
- else if (mapperType.match(/^Sequence$/ig) !== null) {
- payload = serializeSequenceType(this, mapper, object, objectName);
- }
- else if (mapperType.match(/^Dictionary$/ig) !== null) {
- payload = serializeDictionaryType(this, mapper, object, objectName);
- }
- else if (mapperType.match(/^Composite$/ig) !== null) {
- payload = serializeCompositeType(this, mapper, object, objectName);
- }
- }
- return payload;
- };
- /**
- * Deserialize the given object based on its metadata defined in the mapper
- *
- * @param {object} mapper The mapper which defines the metadata of the serializable object
- *
- * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized
- *
- * @param {string} objectName Name of the deserialized object
- *
- * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object
- */
- Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {
- if (responseBody == undefined) {
- if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
- // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
- // between the list being empty versus being missing,
- // so let's do the more user-friendly thing and return an empty list.
- responseBody = [];
- }
- return responseBody;
- }
- var payload;
- var mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Composite$/ig) !== null) {
- payload = deserializeCompositeType(this, mapper, responseBody, objectName);
- }
- else {
- if (this.isXML) {
- /**
- * If the mapper specifies this as a non-composite type value but the responseBody contains
- * both header ("$") and body ("_") properties, then just reduce the responseBody value to
- * the body ("_") property.
- */
- if (responseBody["$"] != undefined && responseBody["_"] != undefined) {
- responseBody = responseBody["_"];
- }
- }
- if (mapperType.match(/^Number$/ig) !== null) {
- payload = parseFloat(responseBody);
- if (isNaN(payload)) {
- payload = responseBody;
- }
- }
- else if (mapperType.match(/^Boolean$/ig) !== null) {
- if (responseBody === "true") {
- payload = true;
- }
- else if (responseBody === "false") {
- payload = false;
- }
- else {
- payload = responseBody;
- }
- }
- else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) {
- payload = responseBody;
- }
- else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) {
- payload = new Date(responseBody);
- }
- else if (mapperType.match(/^UnixTime$/ig) !== null) {
- payload = unixTimeToDate(responseBody);
- }
- else if (mapperType.match(/^ByteArray$/ig) !== null) {
- payload = decodeString(responseBody);
- }
- else if (mapperType.match(/^Base64Url$/ig) !== null) {
- payload = base64UrlToByteArray(responseBody);
- }
- else if (mapperType.match(/^Sequence$/ig) !== null) {
- payload = deserializeSequenceType(this, mapper, responseBody, objectName);
- }
- else if (mapperType.match(/^Dictionary$/ig) !== null) {
- payload = deserializeDictionaryType(this, mapper, responseBody, objectName);
- }
- }
- if (mapper.isConstant) {
- payload = mapper.defaultValue;
- }
- return payload;
- };
- return Serializer;
- }());
- function trimEnd(str, ch) {
- var len = str.length;
- while ((len - 1) >= 0 && str[len - 1] === ch) {
- --len;
- }
- return str.substr(0, len);
- }
- function bufferToBase64Url(buffer) {
- if (!buffer) {
- return undefined;
- }
- if (!(buffer instanceof Uint8Array)) {
- throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");
- }
- // Uint8Array to Base64.
- var str = encodeByteArray(buffer);
- // Base64 to Base64Url.
- return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
- }
- function base64UrlToByteArray(str) {
- if (!str) {
- return undefined;
- }
- if (str && typeof str.valueOf() !== "string") {
- throw new Error("Please provide an input of type string for converting to Uint8Array");
- }
- // Base64Url to Base64.
- str = str.replace(/\-/g, "+").replace(/\_/g, "/");
- // Base64 to Uint8Array.
- return decodeString(str);
- }
- function splitSerializeName(prop) {
- var classes = [];
- var partialclass = "";
- if (prop) {
- var subwords = prop.split(".");
- for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {
- var item = subwords_1[_i];
- if (item.charAt(item.length - 1) === "\\") {
- partialclass += item.substr(0, item.length - 1) + ".";
- }
- else {
- partialclass += item;
- classes.push(partialclass);
- partialclass = "";
- }
- }
- }
- return classes;
- }
- function dateToUnixTime(d) {
- if (!d) {
- return undefined;
- }
- if (typeof d.valueOf() === "string") {
- d = new Date(d);
- }
- return Math.floor(d.getTime() / 1000);
- }
- function unixTimeToDate(n) {
- if (!n) {
- return undefined;
- }
- return new Date(n * 1000);
- }
- function serializeBasicTypes(typeName, objectName, value) {
- if (value !== null && value !== undefined) {
- if (typeName.match(/^Number$/ig) !== null) {
- if (typeof value !== "number") {
- throw new Error(objectName + " with value " + value + " must be of type number.");
- }
- }
- else if (typeName.match(/^String$/ig) !== null) {
- if (typeof value.valueOf() !== "string") {
- throw new Error(objectName + " with value \"" + value + "\" must be of type string.");
- }
- }
- else if (typeName.match(/^Uuid$/ig) !== null) {
- if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
- throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid.");
- }
- }
- else if (typeName.match(/^Boolean$/ig) !== null) {
- if (typeof value !== "boolean") {
- throw new Error(objectName + " with value " + value + " must be of type boolean.");
- }
- }
- else if (typeName.match(/^Stream$/ig) !== null) {
- var objectType = typeof value;
- if (objectType !== "string" &&
- objectType !== "function" &&
- !(value instanceof ArrayBuffer) &&
- !ArrayBuffer.isView(value) &&
- !(typeof Blob === "function" && value instanceof Blob)) {
- throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.");
- }
- }
- }
- return value;
- }
- function serializeEnumType(objectName, allowedValues, value) {
- if (!allowedValues) {
- throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type.");
- }
- var isPresent = allowedValues.some(function (item) {
- if (typeof item.valueOf() === "string") {
- return item.toLowerCase() === value.toLowerCase();
- }
- return item === value;
- });
- if (!isPresent) {
- throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + ".");
- }
- return value;
- }
- function serializeByteArrayType(objectName, value) {
- if (value != undefined) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(objectName + " must be of type Uint8Array.");
- }
- value = encodeByteArray(value);
- }
- return value;
- }
- function serializeBase64UrlType(objectName, value) {
- if (value != undefined) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(objectName + " must be of type Uint8Array.");
- }
- value = bufferToBase64Url(value);
- }
- return value;
- }
- function serializeDateTypes(typeName, value, objectName) {
- if (value != undefined) {
- if (typeName.match(/^Date$/ig) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
- }
- value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10);
- }
- else if (typeName.match(/^DateTime$/ig) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
- }
- value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString();
- }
- else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format.");
- }
- value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString();
- }
- else if (typeName.match(/^UnixTime$/ig) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " +
- "for it to be serialized in UnixTime/Epoch format.");
- }
- value = dateToUnixTime(value);
- }
- else if (typeName.match(/^TimeSpan$/ig) !== null) {
- if (!isDuration(value)) {
- throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\".");
- }
- value = value;
- }
- }
- return value;
- }
- function serializeSequenceType(serializer, mapper, object, objectName) {
- if (!Array.isArray(object)) {
- throw new Error(objectName + " must be of type Array.");
- }
- var elementType = mapper.type.element;
- if (!elementType || typeof elementType !== "object") {
- throw new Error("element\" metadata for an Array must be defined in the " +
- ("mapper and it must of type \"object\" in " + objectName + "."));
- }
- var tempArray = [];
- for (var i = 0; i < object.length; i++) {
- tempArray[i] = serializer.serialize(elementType, object[i], objectName);
- }
- return tempArray;
- }
- function serializeDictionaryType(serializer, mapper, object, objectName) {
- if (typeof object !== "object") {
- throw new Error(objectName + " must be of type object.");
- }
- var valueType = mapper.type.value;
- if (!valueType || typeof valueType !== "object") {
- throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
- ("mapper and it must of type \"object\" in " + objectName + "."));
- }
- var tempDictionary = {};
- for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
- var key = _a[_i];
- tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + "." + key);
- }
- return tempDictionary;
- }
- /**
- * Resolves a composite mapper's modelProperties.
- * @param serializer the serializer containing the entire set of mappers
- * @param mapper the composite mapper to resolve
- */
- function resolveModelProperties(serializer, mapper, objectName) {
- var modelProps = mapper.type.modelProperties;
- if (!modelProps) {
- var className = mapper.type.className;
- if (!className) {
- throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\".");
- }
- var modelMapper = serializer.modelMappers[className];
- if (!modelMapper) {
- throw new Error("mapper() cannot be null or undefined for model \"" + className + "\".");
- }
- modelProps = modelMapper.type.modelProperties;
- if (!modelProps) {
- throw new Error("modelProperties cannot be null or undefined in the " +
- ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + className + "\" for object \"" + objectName + "\"."));
- }
- }
- return modelProps;
- }
- function serializeCompositeType(serializer, mapper, object, objectName) {
- var _a;
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
- }
- if (object != undefined) {
- var payload = {};
- var modelProps = resolveModelProperties(serializer, mapper, objectName);
- for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {
- var key = _b[_i];
- var propertyMapper = modelProps[key];
- if (propertyMapper.readOnly) {
- continue;
- }
- var propName = void 0;
- var parentObject = payload;
- if (serializer.isXML) {
- if (propertyMapper.xmlIsWrapped) {
- propName = propertyMapper.xmlName;
- }
- else {
- propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
- }
- }
- else {
- var paths = splitSerializeName(propertyMapper.serializedName);
- propName = paths.pop();
- for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {
- var pathName = paths_1[_c];
- var childObject = parentObject[pathName];
- if ((childObject == undefined) && (object[key] != undefined)) {
- parentObject[pathName] = {};
- }
- parentObject = parentObject[pathName];
- }
- }
- if (parentObject != undefined) {
- var propertyObjectName = propertyMapper.serializedName !== ""
- ? objectName + "." + propertyMapper.serializedName
- : objectName;
- var toSerialize = object[key];
- var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) {
- toSerialize = mapper.serializedName;
- }
- var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);
- if (serializedValue !== undefined && propName != undefined) {
- if (propertyMapper.xmlIsAttribute) {
- // $ is the key attributes are kept under in xml2js.
- // This keeps things simple while preventing name collision
- // with names in user documents.
- parentObject.$ = parentObject.$ || {};
- parentObject.$[propName] = serializedValue;
- }
- else if (propertyMapper.xmlIsWrapped) {
- parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);
- }
- else {
- parentObject[propName] = serializedValue;
- }
- }
- }
- }
- var additionalPropertiesMapper = mapper.type.additionalProperties;
- if (additionalPropertiesMapper) {
- var propNames = Object.keys(modelProps);
- var _loop_1 = function (clientPropName) {
- var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });
- if (isAdditionalProperty) {
- payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]');
- }
- };
- for (var clientPropName in object) {
- _loop_1(clientPropName);
- }
- }
- return payload;
- }
- return object;
- }
- function isSpecialXmlProperty(propertyName) {
- return ["$", "_"].includes(propertyName);
- }
- function deserializeCompositeType(serializer, mapper, responseBody, objectName) {
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
- }
- var modelProps = resolveModelProperties(serializer, mapper, objectName);
- var instance = {};
- var handledPropertyNames = [];
- for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {
- var key = _a[_i];
- var propertyMapper = modelProps[key];
- var paths = splitSerializeName(modelProps[key].serializedName);
- handledPropertyNames.push(paths[0]);
- var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;
- var propertyObjectName = objectName;
- if (serializedName !== "" && serializedName !== undefined) {
- propertyObjectName = objectName + "." + serializedName;
- }
- var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- var dictionary = {};
- for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {
- var headerKey = _c[_b];
- if (headerKey.startsWith(headerCollectionPrefix)) {
- dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);
- }
- handledPropertyNames.push(headerKey);
- }
- instance[key] = dictionary;
- }
- else if (serializer.isXML) {
- if (propertyMapper.xmlIsAttribute && responseBody.$) {
- instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);
- }
- else {
- var propertyName = xmlElementName || xmlName || serializedName;
- var unwrappedProperty = responseBody[propertyName];
- if (propertyMapper.xmlIsWrapped) {
- unwrappedProperty = responseBody[xmlName];
- unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];
- var isEmptyWrappedList = unwrappedProperty === undefined;
- if (isEmptyWrappedList) {
- unwrappedProperty = [];
- }
- }
- instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);
- }
- }
- else {
- // deserialize the property if it is present in the provided responseBody instance
- var propertyInstance = void 0;
- var res = responseBody;
- // traversing the object step by step.
- for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {
- var item = paths_2[_d];
- if (!res)
- break;
- res = res[item];
- }
- propertyInstance = res;
- var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
- if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) {
- propertyInstance = mapper.serializedName;
- }
- var serializedValue = void 0;
- // paging
- if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
- propertyInstance = responseBody[key];
- instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
- }
- else if (propertyInstance !== undefined) {
- serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
- instance[key] = serializedValue;
- }
- }
- }
- var additionalPropertiesMapper = mapper.type.additionalProperties;
- if (additionalPropertiesMapper) {
- var isAdditionalProperty = function (responsePropName) {
- for (var clientPropName in modelProps) {
- var paths = splitSerializeName(modelProps[clientPropName].serializedName);
- if (paths[0] === responsePropName) {
- return false;
- }
- }
- return true;
- };
- for (var responsePropName in responseBody) {
- if (isAdditionalProperty(responsePropName)) {
- instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]');
- }
- }
- }
- else if (responseBody) {
- for (var _e = 0, _f = Object.keys(responseBody); _e < _f.length; _e++) {
- var key = _f[_e];
- if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) {
- instance[key] = responseBody[key];
- }
- }
- }
- return instance;
- }
- function deserializeDictionaryType(serializer, mapper, responseBody, objectName) {
- /*jshint validthis: true */
- var value = mapper.type.value;
- if (!value || typeof value !== "object") {
- throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
- ("mapper and it must of type \"object\" in " + objectName));
- }
- if (responseBody) {
- var tempDictionary = {};
- for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {
- var key = _a[_i];
- tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);
- }
- return tempDictionary;
- }
- return responseBody;
- }
- function deserializeSequenceType(serializer, mapper, responseBody, objectName) {
- /*jshint validthis: true */
- var element = mapper.type.element;
- if (!element || typeof element !== "object") {
- throw new Error("element\" metadata for an Array must be defined in the " +
- ("mapper and it must of type \"object\" in " + objectName));
- }
- if (responseBody) {
- if (!Array.isArray(responseBody)) {
- // xml2js will interpret a single element array as just the element, so force it to be an array
- responseBody = [responseBody];
- }
- var tempArray = [];
- for (var i = 0; i < responseBody.length; i++) {
- tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]");
- }
- return tempArray;
- }
- return responseBody;
- }
- function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
- var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator) {
- var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
- if (discriminatorName != undefined) {
- var discriminatorValue = object[discriminatorName];
- if (discriminatorValue != undefined) {
- var typeName = mapper.type.uberParent || mapper.type.className;
- var indexDiscriminator = discriminatorValue === typeName
- ? discriminatorValue
- : typeName + "." + discriminatorValue;
- var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];
- if (polymorphicMapper) {
- mapper = polymorphicMapper;
- }
- }
- }
- }
- return mapper;
- }
- function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
- return mapper.type.polymorphicDiscriminator
- || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent)
- || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className);
- }
- function getPolymorphicDiscriminatorSafely(serializer, typeName) {
- return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator);
- }
- // TODO: why is this here?
- function serializeObject(toSerialize) {
- if (toSerialize == undefined)
- return undefined;
- if (toSerialize instanceof Uint8Array) {
- toSerialize = encodeByteArray(toSerialize);
- return toSerialize;
- }
- else if (toSerialize instanceof Date) {
- return toSerialize.toISOString();
- }
- else if (Array.isArray(toSerialize)) {
- var array = [];
- for (var i = 0; i < toSerialize.length; i++) {
- array.push(serializeObject(toSerialize[i]));
- }
- return array;
- }
- else if (typeof toSerialize === "object") {
- var dictionary = {};
- for (var property in toSerialize) {
- dictionary[property] = serializeObject(toSerialize[property]);
- }
- return dictionary;
- }
- return toSerialize;
- }
- /**
- * Utility function to create a K:V from a list of strings
- */
- function strEnum(o) {
- var result = {};
- for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {
- var key = o_1[_i];
- result[key] = key;
- }
- return result;
- }
- var MapperType = strEnum([
- "Base64Url",
- "Boolean",
- "ByteArray",
- "Composite",
- "Date",
- "DateTime",
- "DateTimeRfc1123",
- "Dictionary",
- "Enum",
- "Number",
- "Object",
- "Sequence",
- "String",
- "Stream",
- "TimeSpan",
- "UnixTime"
- ]);
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * Creates a new WebResource object.
- *
- * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
- * properties to initiate a request.
- *
- * @constructor
- */
- var WebResource = /** @class */ (function () {
- function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings) {
- this.streamResponseBody = streamResponseBody;
- this.url = url || "";
- this.method = method || "GET";
- this.headers = (headers instanceof HttpHeaders ? headers : new HttpHeaders(headers));
- this.body = body;
- this.query = query;
- this.formData = undefined;
- this.withCredentials = withCredentials || false;
- this.abortSignal = abortSignal;
- this.timeout = timeout || 0;
- this.onUploadProgress = onUploadProgress;
- this.onDownloadProgress = onDownloadProgress;
- this.proxySettings = proxySettings;
- }
- /**
- * Validates that the required properties such as method, url, headers["Content-Type"],
- * headers["accept-language"] are defined. It will throw an error if one of the above
- * mentioned properties are not defined.
- */
- WebResource.prototype.validateRequestProperties = function () {
- if (!this.method) {
- throw new Error("WebResource.method is required.");
- }
- if (!this.url) {
- throw new Error("WebResource.url is required.");
- }
- };
- /**
- * Prepares the request.
- * @param {RequestPrepareOptions} options Options to provide for preparing the request.
- * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.
- */
- WebResource.prototype.prepare = function (options) {
- if (!options) {
- throw new Error("options object is required");
- }
- if (options.method == undefined || typeof options.method.valueOf() !== "string") {
- throw new Error("options.method must be a string.");
- }
- if (options.url && options.pathTemplate) {
- throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.");
- }
- if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && (options.url == undefined || typeof options.url.valueOf() !== "string")) {
- throw new Error("Please provide exactly one of options.pathTemplate or options.url.");
- }
- // set the url if it is provided.
- if (options.url) {
- if (typeof options.url !== "string") {
- throw new Error("options.url must be of type \"string\".");
- }
- this.url = options.url;
- }
- // set the method
- if (options.method) {
- var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"];
- if (validMethods.indexOf(options.method.toUpperCase()) === -1) {
- throw new Error("The provided method \"" + options.method + "\" is invalid. Supported HTTP methods are: " + JSON.stringify(validMethods));
- }
- }
- this.method = options.method.toUpperCase();
- // construct the url if path template is provided
- if (options.pathTemplate) {
- var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;
- if (typeof pathTemplate_1 !== "string") {
- throw new Error("options.pathTemplate must be of type \"string\".");
- }
- if (!options.baseUrl) {
- options.baseUrl = "https://management.azure.com";
- }
- var baseUrl = options.baseUrl;
- var url_1 = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1);
- var segments = url_1.match(/({\w*\s*\w*})/ig);
- if (segments && segments.length) {
- if (!pathParameters_1) {
- throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided.");
- }
- segments.forEach(function (item) {
- var pathParamName = item.slice(1, -1);
- var pathParam = pathParameters_1[pathParamName];
- if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) {
- throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName +
- (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") +
- ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") +
- ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }."));
- }
- if (typeof pathParam.valueOf() === "string") {
- url_1 = url_1.replace(item, encodeURIComponent(pathParam));
- }
- if (typeof pathParam.valueOf() === "object") {
- if (!pathParam.value) {
- throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
- }
- if (pathParam.skipUrlEncoding) {
- url_1 = url_1.replace(item, pathParam.value);
- }
- else {
- url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));
- }
- }
- });
- }
- this.url = url_1;
- }
- // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.
- if (options.queryParameters) {
- var queryParameters = options.queryParameters;
- if (typeof queryParameters !== "object") {
- throw new Error("options.queryParameters must be of type object. It should be a JSON object " +
- "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " +
- "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }.");
- }
- // append question mark if it is not present in the url
- if (this.url && this.url.indexOf("?") === -1) {
- this.url += "?";
- }
- // construct queryString
- var queryParams = [];
- // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().
- this.query = {};
- for (var queryParamName in queryParameters) {
- var queryParam = queryParameters[queryParamName];
- if (queryParam) {
- if (typeof queryParam === "string") {
- queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam));
- this.query[queryParamName] = encodeURIComponent(queryParam);
- }
- else if (typeof queryParam === "object") {
- if (!queryParam.value) {
- throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
- }
- if (queryParam.skipUrlEncoding) {
- queryParams.push(queryParamName + "=" + queryParam.value);
- this.query[queryParamName] = queryParam.value;
- }
- else {
- queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value));
- this.query[queryParamName] = encodeURIComponent(queryParam.value);
- }
- }
- }
- } // end-of-for
- // append the queryString
- this.url += queryParams.join("&");
- }
- // add headers to the request if they are provided
- if (options.headers) {
- var headers = options.headers;
- for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {
- var headerName = _a[_i];
- this.headers.set(headerName, headers[headerName]);
- }
- }
- // ensure accept-language is set correctly
- if (!this.headers.get("accept-language")) {
- this.headers.set("accept-language", "en-US");
- }
- // ensure the request-id is set correctly
- if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) {
- this.headers.set("x-ms-client-request-id", generateUuid());
- }
- // default
- if (!this.headers.get("Content-Type")) {
- this.headers.set("Content-Type", "application/json; charset=utf-8");
- }
- // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty
- this.body = options.body;
- if (options.body != undefined) {
- // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.
- if (options.bodyIsStream) {
- if (!this.headers.get("Transfer-Encoding")) {
- this.headers.set("Transfer-Encoding", "chunked");
- }
- if (this.headers.get("Content-Type") !== "application/octet-stream") {
- this.headers.set("Content-Type", "application/octet-stream");
- }
- }
- else {
- if (options.serializationMapper) {
- this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody");
- }
- if (!options.disableJsonStringifyOnBody) {
- this.body = JSON.stringify(options.body);
- }
- }
- }
- this.abortSignal = options.abortSignal;
- this.onDownloadProgress = options.onDownloadProgress;
- this.onUploadProgress = options.onUploadProgress;
- return this;
- };
- /**
- * Clone this WebResource HTTP request object.
- * @returns {WebResource} The clone of this WebResource HTTP request object.
- */
- WebResource.prototype.clone = function () {
- 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);
- if (this.formData) {
- result.formData = this.formData;
- }
- if (this.operationSpec) {
- result.operationSpec = this.operationSpec;
- }
- if (this.shouldDeserialize) {
- result.shouldDeserialize = this.shouldDeserialize;
- }
- if (this.operationResponseGetter) {
- result.operationResponseGetter = this.operationResponseGetter;
- }
- return result;
- };
- return WebResource;
- }());
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var RestError = /** @class */ (function (_super) {
- tslib_1.__extends(RestError, _super);
- function RestError(message, code, statusCode, request, response, body) {
- var _this = _super.call(this, message) || this;
- _this.code = code;
- _this.statusCode = statusCode;
- _this.request = request;
- _this.response = response;
- _this.body = body;
- Object.setPrototypeOf(_this, RestError.prototype);
- return _this;
- }
- RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
- RestError.REQUEST_ABORTED_ERROR = "REQUEST_ABORTED_ERROR";
- RestError.PARSE_ERROR = "PARSE_ERROR";
- return RestError;
- }(Error));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * A class that handles the query portion of a URLBuilder.
- */
- var URLQuery = /** @class */ (function () {
- function URLQuery() {
- this._rawQuery = {};
- }
- /**
- * Get whether or not there any query parameters in this URLQuery.
- */
- URLQuery.prototype.any = function () {
- return Object.keys(this._rawQuery).length > 0;
- };
- /**
- * Set a query parameter with the provided name and value. If the parameterValue is undefined or
- * empty, then this will attempt to remove an existing query parameter with the provided
- * parameterName.
- */
- URLQuery.prototype.set = function (parameterName, parameterValue) {
- if (parameterName) {
- if (parameterValue != undefined) {
- var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
- this._rawQuery[parameterName] = newValue;
- }
- else {
- delete this._rawQuery[parameterName];
- }
- }
- };
- /**
- * Get the value of the query parameter with the provided name. If no parameter exists with the
- * provided parameter name, then undefined will be returned.
- */
- URLQuery.prototype.get = function (parameterName) {
- return parameterName ? this._rawQuery[parameterName] : undefined;
- };
- /**
- * Get the string representation of this query. The return value will not start with a "?".
- */
- URLQuery.prototype.toString = function () {
- var result = "";
- for (var parameterName in this._rawQuery) {
- if (result) {
- result += "&";
- }
- var parameterValue = this._rawQuery[parameterName];
- if (Array.isArray(parameterValue)) {
- var parameterStrings = [];
- for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
- var parameterValueElement = parameterValue_1[_i];
- parameterStrings.push(parameterName + "=" + parameterValueElement);
- }
- result += parameterStrings.join("&");
- }
- else {
- result += parameterName + "=" + parameterValue;
- }
- }
- return result;
- };
- /**
- * Parse a URLQuery from the provided text.
- */
- URLQuery.parse = function (text) {
- var result = new URLQuery();
- if (text) {
- if (text.startsWith("?")) {
- text = text.substring(1);
- }
- var currentState = "ParameterName";
- var parameterName = "";
- var parameterValue = "";
- for (var i = 0; i < text.length; ++i) {
- var currentCharacter = text[i];
- switch (currentState) {
- case "ParameterName":
- switch (currentCharacter) {
- case "=":
- currentState = "ParameterValue";
- break;
- case "&":
- parameterName = "";
- parameterValue = "";
- break;
- default:
- parameterName += currentCharacter;
- break;
- }
- break;
- case "ParameterValue":
- switch (currentCharacter) {
- case "=":
- parameterName = "";
- parameterValue = "";
- currentState = "Invalid";
- break;
- case "&":
- result.set(parameterName, parameterValue);
- parameterName = "";
- parameterValue = "";
- currentState = "ParameterName";
- break;
- default:
- parameterValue += currentCharacter;
- break;
- }
- break;
- case "Invalid":
- if (currentCharacter === "&") {
- currentState = "ParameterName";
- }
- break;
- default:
- throw new Error("Unrecognized URLQuery parse state: " + currentState);
- }
- }
- if (currentState === "ParameterValue") {
- result.set(parameterName, parameterValue);
- }
- }
- return result;
- };
- return URLQuery;
- }());
- /**
- * A class that handles creating, modifying, and parsing URLs.
- */
- var URLBuilder = /** @class */ (function () {
- function URLBuilder() {
- }
- /**
- * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
- * (such as a host, port, path, or query), those parts will be added to this URL as well.
- */
- URLBuilder.prototype.setScheme = function (scheme) {
- if (!scheme) {
- this._scheme = undefined;
- }
- else {
- this.set(scheme, "SCHEME");
- }
- };
- /**
- * Get the scheme that has been set in this URL.
- */
- URLBuilder.prototype.getScheme = function () {
- return this._scheme;
- };
- /**
- * Set the host for this URL. If the provided host contains other parts of a URL (such as a
- * port, path, or query), those parts will be added to this URL as well.
- */
- URLBuilder.prototype.setHost = function (host) {
- if (!host) {
- this._host = undefined;
- }
- else {
- this.set(host, "SCHEME_OR_HOST");
- }
- };
- /**
- * Get the host that has been set in this URL.
- */
- URLBuilder.prototype.getHost = function () {
- return this._host;
- };
- /**
- * Set the port for this URL. If the provided port contains other parts of a URL (such as a
- * path or query), those parts will be added to this URL as well.
- */
- URLBuilder.prototype.setPort = function (port) {
- if (port == undefined || port === "") {
- this._port = undefined;
- }
- else {
- this.set(port.toString(), "PORT");
- }
- };
- /**
- * Get the port that has been set in this URL.
- */
- URLBuilder.prototype.getPort = function () {
- return this._port;
- };
- /**
- * Set the path for this URL. If the provided path contains a query, then it will be added to
- * this URL as well.
- */
- URLBuilder.prototype.setPath = function (path) {
- if (!path) {
- this._path = undefined;
- }
- else {
- if (path.indexOf("://") !== -1) {
- this.set(path, "SCHEME");
- }
- else {
- this.set(path, "PATH");
- }
- }
- };
- /**
- * Append the provided path to this URL's existing path. If the provided path contains a query,
- * then it will be added to this URL as well.
- */
- URLBuilder.prototype.appendPath = function (path) {
- if (path) {
- var currentPath = this.getPath();
- if (currentPath) {
- if (!currentPath.endsWith("/")) {
- currentPath += "/";
- }
- if (path.startsWith("/")) {
- path = path.substring(1);
- }
- path = currentPath + path;
- }
- this.set(path, "PATH");
- }
- };
- /**
- * Get the path that has been set in this URL.
- */
- URLBuilder.prototype.getPath = function () {
- return this._path;
- };
- /**
- * Set the query in this URL.
- */
- URLBuilder.prototype.setQuery = function (query) {
- if (!query) {
- this._query = undefined;
- }
- else {
- this._query = URLQuery.parse(query);
- }
- };
- /**
- * Set a query parameter with the provided name and value in this URL's query. If the provided
- * query parameter value is undefined or empty, then the query parameter will be removed if it
- * existed.
- */
- URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
- if (queryParameterName) {
- if (!this._query) {
- this._query = new URLQuery();
- }
- this._query.set(queryParameterName, queryParameterValue);
- }
- };
- /**
- * Get the value of the query parameter with the provided query parameter name. If no query
- * parameter exists with the provided name, then undefined will be returned.
- */
- URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
- return this._query ? this._query.get(queryParameterName) : undefined;
- };
- /**
- * Get the query in this URL.
- */
- URLBuilder.prototype.getQuery = function () {
- return this._query ? this._query.toString() : undefined;
- };
- /**
- * Set the parts of this URL by parsing the provided text using the provided startState.
- */
- URLBuilder.prototype.set = function (text, startState) {
- var tokenizer = new URLTokenizer(text, startState);
- while (tokenizer.next()) {
- var token = tokenizer.current();
- if (token) {
- switch (token.type) {
- case "SCHEME":
- this._scheme = token.text || undefined;
- break;
- case "HOST":
- this._host = token.text || undefined;
- break;
- case "PORT":
- this._port = token.text || undefined;
- break;
- case "PATH":
- var tokenPath = token.text || undefined;
- if (!this._path || this._path === "/" || tokenPath !== "/") {
- this._path = tokenPath;
- }
- break;
- case "QUERY":
- this._query = URLQuery.parse(token.text);
- break;
- default:
- throw new Error("Unrecognized URLTokenType: " + token.type);
- }
- }
- }
- };
- URLBuilder.prototype.toString = function () {
- var result = "";
- if (this._scheme) {
- result += this._scheme + "://";
- }
- if (this._host) {
- result += this._host;
- }
- if (this._port) {
- result += ":" + this._port;
- }
- if (this._path) {
- if (!this._path.startsWith("/")) {
- result += "/";
- }
- result += this._path;
- }
- if (this._query && this._query.any()) {
- result += "?" + this._query.toString();
- }
- return result;
- };
- /**
- * If the provided searchValue is found in this URLBuilder, then replace it with the provided
- * replaceValue.
- */
- URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
- if (searchValue) {
- this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
- this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
- this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
- this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
- this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
- }
- };
- URLBuilder.parse = function (text) {
- var result = new URLBuilder();
- result.set(text, "SCHEME_OR_HOST");
- return result;
- };
- return URLBuilder;
- }());
- var URLToken = /** @class */ (function () {
- function URLToken(text, type) {
- this.text = text;
- this.type = type;
- }
- URLToken.scheme = function (text) {
- return new URLToken(text, "SCHEME");
- };
- URLToken.host = function (text) {
- return new URLToken(text, "HOST");
- };
- URLToken.port = function (text) {
- return new URLToken(text, "PORT");
- };
- URLToken.path = function (text) {
- return new URLToken(text, "PATH");
- };
- URLToken.query = function (text) {
- return new URLToken(text, "QUERY");
- };
- return URLToken;
- }());
- /**
- * Get whether or not the provided character (single character string) is an alphanumeric (letter or
- * digit) character.
- */
- function isAlphaNumericCharacter(character) {
- var characterCode = character.charCodeAt(0);
- return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) ||
- (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) ||
- (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */);
- }
- /**
- * A class that tokenizes URL strings.
- */
- var URLTokenizer = /** @class */ (function () {
- function URLTokenizer(_text, state) {
- this._text = _text;
- this._textLength = _text ? _text.length : 0;
- this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
- this._currentIndex = 0;
- }
- /**
- * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
- * hasn't started or has finished tokenizing.
- */
- URLTokenizer.prototype.current = function () {
- return this._currentToken;
- };
- /**
- * Advance to the next URLToken and return whether or not a URLToken was found.
- */
- URLTokenizer.prototype.next = function () {
- if (!hasCurrentCharacter(this)) {
- this._currentToken = undefined;
- }
- else {
- switch (this._currentState) {
- case "SCHEME":
- nextScheme(this);
- break;
- case "SCHEME_OR_HOST":
- nextSchemeOrHost(this);
- break;
- case "HOST":
- nextHost(this);
- break;
- case "PORT":
- nextPort(this);
- break;
- case "PATH":
- nextPath(this);
- break;
- case "QUERY":
- nextQuery(this);
- break;
- default:
- throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
- }
- }
- return !!this._currentToken;
- };
- return URLTokenizer;
- }());
- /**
- * Read the remaining characters from this Tokenizer's character stream.
- */
- function readRemaining(tokenizer) {
- var result = "";
- if (tokenizer._currentIndex < tokenizer._textLength) {
- result = tokenizer._text.substring(tokenizer._currentIndex);
- tokenizer._currentIndex = tokenizer._textLength;
- }
- return result;
- }
- /**
- * Whether or not this URLTokenizer has a current character.
- */
- function hasCurrentCharacter(tokenizer) {
- return tokenizer._currentIndex < tokenizer._textLength;
- }
- /**
- * Get the character in the text string at the current index.
- */
- function getCurrentCharacter(tokenizer) {
- return tokenizer._text[tokenizer._currentIndex];
- }
- /**
- * Advance to the character in text that is "step" characters ahead. If no step value is provided,
- * then step will default to 1.
- */
- function nextCharacter(tokenizer, step) {
- if (hasCurrentCharacter(tokenizer)) {
- if (!step) {
- step = 1;
- }
- tokenizer._currentIndex += step;
- }
- }
- /**
- * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
- * Tokenizer's stream of characters.
- */
- function peekCharacters(tokenizer, charactersToPeek) {
- var endIndex = tokenizer._currentIndex + charactersToPeek;
- if (tokenizer._textLength < endIndex) {
- endIndex = tokenizer._textLength;
- }
- return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
- }
- /**
- * Read characters from this Tokenizer until the end of the stream or until the provided condition
- * is false when provided the current character.
- */
- function readWhile(tokenizer, condition) {
- var result = "";
- while (hasCurrentCharacter(tokenizer)) {
- var currentCharacter = getCurrentCharacter(tokenizer);
- if (!condition(currentCharacter)) {
- break;
- }
- else {
- result += currentCharacter;
- nextCharacter(tokenizer);
- }
- }
- return result;
- }
- /**
- * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
- * character stream is reached.
- */
- function readWhileLetterOrDigit(tokenizer) {
- return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
- }
- /**
- * Read characters from this Tokenizer until one of the provided terminating characters is read or
- * the end of the character stream is reached.
- */
- function readUntilCharacter(tokenizer) {
- var terminatingCharacters = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- terminatingCharacters[_i - 1] = arguments[_i];
- }
- return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
- }
- function nextScheme(tokenizer) {
- var scheme = readWhileLetterOrDigit(tokenizer);
- tokenizer._currentToken = URLToken.scheme(scheme);
- if (!hasCurrentCharacter(tokenizer)) {
- tokenizer._currentState = "DONE";
- }
- else {
- tokenizer._currentState = "HOST";
- }
- }
- function nextSchemeOrHost(tokenizer) {
- var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
- if (!hasCurrentCharacter(tokenizer)) {
- tokenizer._currentToken = URLToken.host(schemeOrHost);
- tokenizer._currentState = "DONE";
- }
- else if (getCurrentCharacter(tokenizer) === ":") {
- if (peekCharacters(tokenizer, 3) === "://") {
- tokenizer._currentToken = URLToken.scheme(schemeOrHost);
- tokenizer._currentState = "HOST";
- }
- else {
- tokenizer._currentToken = URLToken.host(schemeOrHost);
- tokenizer._currentState = "PORT";
- }
- }
- else {
- tokenizer._currentToken = URLToken.host(schemeOrHost);
- if (getCurrentCharacter(tokenizer) === "/") {
- tokenizer._currentState = "PATH";
- }
- else {
- tokenizer._currentState = "QUERY";
- }
- }
- }
- function nextHost(tokenizer) {
- if (peekCharacters(tokenizer, 3) === "://") {
- nextCharacter(tokenizer, 3);
- }
- var host = readUntilCharacter(tokenizer, ":", "/", "?");
- tokenizer._currentToken = URLToken.host(host);
- if (!hasCurrentCharacter(tokenizer)) {
- tokenizer._currentState = "DONE";
- }
- else if (getCurrentCharacter(tokenizer) === ":") {
- tokenizer._currentState = "PORT";
- }
- else if (getCurrentCharacter(tokenizer) === "/") {
- tokenizer._currentState = "PATH";
- }
- else {
- tokenizer._currentState = "QUERY";
- }
- }
- function nextPort(tokenizer) {
- if (getCurrentCharacter(tokenizer) === ":") {
- nextCharacter(tokenizer);
- }
- var port = readUntilCharacter(tokenizer, "/", "?");
- tokenizer._currentToken = URLToken.port(port);
- if (!hasCurrentCharacter(tokenizer)) {
- tokenizer._currentState = "DONE";
- }
- else if (getCurrentCharacter(tokenizer) === "/") {
- tokenizer._currentState = "PATH";
- }
- else {
- tokenizer._currentState = "QUERY";
- }
- }
- function nextPath(tokenizer) {
- var path = readUntilCharacter(tokenizer, "?");
- tokenizer._currentToken = URLToken.path(path);
- if (!hasCurrentCharacter(tokenizer)) {
- tokenizer._currentState = "DONE";
- }
- else {
- tokenizer._currentState = "QUERY";
- }
- }
- function nextQuery(tokenizer) {
- if (getCurrentCharacter(tokenizer) === "?") {
- nextCharacter(tokenizer);
- }
- var query = readRemaining(tokenizer);
- tokenizer._currentToken = URLToken.query(query);
- tokenizer._currentState = "DONE";
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * A HttpClient implementation that uses axios to send HTTP requests.
- */
- var AxiosHttpClient = /** @class */ (function () {
- function AxiosHttpClient() {
- this.cookieJar = new tough.CookieJar();
- }
- AxiosHttpClient.prototype.sendRequest = function (httpRequest) {
- return tslib_1.__awaiter(this, void 0, void 0, function () {
- var formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, cookieString, abortSignal, abortListener, cancelToken, rawHeaders, httpRequestBody, axiosBody, onUploadProgress, loadedBytes_1, uploadReportStream, res, config, agent, err_1, axiosErr, headers, onDownloadProgress, responseBody, loadedBytes_2, downloadReportStream, length_1, operationResponse, setCookieHeader_1;
- var _this = this;
- return tslib_1.__generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- if (typeof httpRequest !== "object") {
- throw new Error("httpRequest (WebResource) cannot be null or undefined and must be of type object.");
- }
- if (httpRequest.formData) {
- formData = httpRequest.formData;
- requestForm_1 = new FormData();
- appendFormValue = function (key, value) {
- // value function probably returns a stream so we can provide a fresh stream on each retry
- if (typeof value === "function") {
- value = value();
- }
- if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
- requestForm_1.append(key, value.value, value.options);
- }
- else {
- requestForm_1.append(key, value);
- }
- };
- for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {
- formKey = _a[_i];
- formValue = formData[formKey];
- if (Array.isArray(formValue)) {
- for (j = 0; j < formValue.length; j++) {
- appendFormValue(formKey, formValue[j]);
- }
- }
- else {
- appendFormValue(formKey, formValue);
- }
- }
- httpRequest.body = requestForm_1;
- httpRequest.formData = undefined;
- contentType = httpRequest.headers.get("Content-Type");
- if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
- if (typeof requestForm_1.getBoundary === "function") {
- httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary());
- }
- else {
- // browser will automatically apply a suitable content-type header
- httpRequest.headers.remove("Content-Type");
- }
- }
- }
- if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2];
- return [4 /*yield*/, new Promise(function (resolve, reject) {
- _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) {
- if (err) {
- reject(err);
- }
- else {
- resolve(cookie);
- }
- });
- })];
- case 1:
- cookieString = _b.sent();
- httpRequest.headers.set("Cookie", cookieString);
- _b.label = 2;
- case 2:
- abortSignal = httpRequest.abortSignal;
- if (abortSignal && abortSignal.aborted) {
- throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
- }
- cancelToken = abortSignal && new axios.CancelToken(function (canceler) {
- abortListener = function () { return canceler(); };
- abortSignal.addEventListener("abort", abortListener);
- });
- rawHeaders = httpRequest.headers.rawHeaders();
- httpRequestBody = httpRequest.body;
- axiosBody =
- // Workaround for https://github.com/axios/axios/issues/755
- // tslint:disable-next-line:no-null-keyword
- typeof httpRequestBody === "undefined" ? null :
- typeof httpRequestBody === "function" ? httpRequestBody() :
- httpRequestBody;
- onUploadProgress = httpRequest.onUploadProgress;
- if (onUploadProgress && axiosBody) {
- loadedBytes_1 = 0;
- uploadReportStream = new stream.Transform({
- transform: function (chunk, _encoding, callback) {
- loadedBytes_1 += chunk.length;
- onUploadProgress({ loadedBytes: loadedBytes_1 });
- callback(undefined, chunk);
- }
- });
- if (isReadableStream(axiosBody)) {
- axiosBody.pipe(uploadReportStream);
- }
- else {
- uploadReportStream.end(axiosBody);
- }
- axiosBody = uploadReportStream;
- }
- _b.label = 3;
- case 3:
- _b.trys.push([3, 5, 6, 7]);
- config = {
- method: httpRequest.method,
- url: httpRequest.url,
- headers: rawHeaders,
- data: axiosBody,
- transformResponse: function (data) { return data; },
- validateStatus: function () { return true; },
- // Workaround for https://github.com/axios/axios/issues/1362
- maxContentLength: Infinity,
- responseType: httpRequest.streamResponseBody ? "stream" : "text",
- cancelToken: cancelToken,
- timeout: httpRequest.timeout,
- proxy: false
- };
- if (httpRequest.proxySettings) {
- agent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers);
- if (agent.isHttps) {
- config.httpsAgent = agent.agent;
- }
- else {
- config.httpAgent = agent.agent;
- }
- }
- // This hack is still required with 0.19.0 version of axios since axios tries to merge the
- // Content-Type header from it's config["<method name>"] where the method name is lower-case,
- // into the request header. It could be possible that the Content-Type header is not present
- // in the original request and this would create problems while creating the signature for
- // storage data plane sdks.
- axios.interceptors.request.use(function (config) { return (tslib_1.__assign({}, config, { method: config.method && config.method.toUpperCase() })); });
- return [4 /*yield*/, axios.request(config)];
- case 4:
- res = _b.sent();
- return [3 /*break*/, 7];
- case 5:
- err_1 = _b.sent();
- if (err_1 instanceof axios.Cancel) {
- throw new RestError(err_1.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
- }
- else {
- axiosErr = err_1;
- throw new RestError(axiosErr.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
- }
- return [3 /*break*/, 7];
- case 6:
- if (abortSignal && abortListener) {
- abortSignal.removeEventListener("abort", abortListener);
- }
- return [7 /*endfinally*/];
- case 7:
- headers = new HttpHeaders(res.headers);
- onDownloadProgress = httpRequest.onDownloadProgress;
- responseBody = res.data;
- if (onDownloadProgress) {
- if (isReadableStream(responseBody)) {
- loadedBytes_2 = 0;
- downloadReportStream = new stream.Transform({
- transform: function (chunk, _encoding, callback) {
- loadedBytes_2 += chunk.length;
- onDownloadProgress({ loadedBytes: loadedBytes_2 });
- callback(undefined, chunk);
- }
- });
- responseBody.pipe(downloadReportStream);
- responseBody = downloadReportStream;
- }
- else {
- length_1 = parseInt(headers.get("Content-Length")) || responseBody.length || undefined;
- if (length_1) {
- // Calling callback for non-stream response for consistency with browser
- onDownloadProgress({ loadedBytes: length_1 });
- }
- }
- }
- operationResponse = {
- request: httpRequest,
- status: res.status,
- headers: headers,
- readableStreamBody: httpRequest.streamResponseBody ? responseBody : undefined,
- bodyAsText: httpRequest.streamResponseBody ? undefined : responseBody
- };
- if (!this.cookieJar) return [3 /*break*/, 9];
- setCookieHeader_1 = operationResponse.headers.get("Set-Cookie");
- if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 9];
- return [4 /*yield*/, new Promise(function (resolve, reject) {
- _this.cookieJar.setCookie(setCookieHeader_1, httpRequest.url, function (err) {
- if (err) {
- reject(err);
- }
- else {
- resolve();
- }
- });
- })];
- case 8:
- _b.sent();
- _b.label = 9;
- case 9: return [2 /*return*/, operationResponse];
- }
- });
- });
- };
- return AxiosHttpClient;
- }());
- function isReadableStream(body) {
- return typeof body.pipe === "function";
- }
- function createProxyAgent(requestUrl, proxySettings, headers) {
- var tunnelOptions = {
- proxy: {
- host: URLBuilder.parse(proxySettings.host).getHost(),
- port: proxySettings.port,
- headers: (headers && headers.rawHeaders()) || {}
- }
- };
- if ((proxySettings.username && proxySettings.password)) {
- tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password;
- }
- var requestScheme = URLBuilder.parse(requestUrl).getScheme() || "";
- var isRequestHttps = requestScheme.toLowerCase() === "https";
- var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || "";
- var isProxyHttps = proxyScheme.toLowerCase() === "https";
- var proxyAgent = {
- isHttps: isRequestHttps,
- agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions)
- };
- return proxyAgent;
- }
- function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) {
- if (isRequestHttps && isProxyHttps) {
- return tunnel.httpsOverHttps(tunnelOptions);
- }
- else if (isRequestHttps && !isProxyHttps) {
- return tunnel.httpsOverHttp(tunnelOptions);
- }
- else if (!isRequestHttps && isProxyHttps) {
- return tunnel.httpOverHttps(tunnelOptions);
- }
- else {
- return tunnel.httpOverHttp(tunnelOptions);
- }
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // Copyright (c) Microsoft Corporation. All rights reserved.
- (function (HttpPipelineLogLevel) {
- /**
- * A log level that indicates that no logs will be logged.
- */
- HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
- /**
- * An error log.
- */
- HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
- /**
- * A warning log.
- */
- HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
- /**
- * An information log.
- */
- HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
- })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- // Licensed under the MIT License. See License.txt in the project root for license information.
- /**
- * Get the path to this parameter's value as a dotted string (a.b.c).
- * @param parameter The parameter to get the path string for.
- * @returns The path to this parameter's value as a dotted string.
- */
- function getPathStringFromParameter(parameter) {
- return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);
- }
- function getPathStringFromParameterPath(parameterPath, mapper) {
- var result;
- if (typeof parameterPath === "string") {
- result = parameterPath;
- }
- else if (Array.isArray(parameterPath)) {
- result = parameterPath.join(".");
- }
- else {
- result = mapper.serializedName;
- }
- return result;
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function isStreamOperation(operationSpec) {
- var result = false;
- for (var statusCode in operationSpec.responses) {
- var operationResponse = operationSpec.responses[statusCode];
- if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) {
- result = true;
- break;
- }
- }
- return result;
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function stringifyXML(obj, opts) {
- var builder = new xml2js.Builder({
- explicitArray: false,
- explicitCharkey: false,
- rootName: (opts || {}).rootName,
- renderOpts: {
- pretty: false
- }
- });
- return builder.buildObject(obj);
- }
- function parseXML(str) {
- var xmlParser = new xml2js.Parser({
- explicitArray: false,
- explicitCharkey: false,
- explicitRoot: false
- });
- return new Promise(function (resolve, reject) {
- if (!str) {
- reject(new Error("Document is empty"));
- }
- else {
- xmlParser.parseString(str, function (err, res) {
- if (err) {
- reject(err);
- }
- else {
- resolve(res);
- }
- });
- }
- });
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var BaseRequestPolicy = /** @class */ (function () {
- function BaseRequestPolicy(_nextPolicy, _options) {
- this._nextPolicy = _nextPolicy;
- this._options = _options;
- }
- /**
- * Get whether or not a log with the provided log level should be logged.
- * @param logLevel The log level of the log that will be logged.
- * @returns Whether or not a log with the provided log level should be logged.
- */
- BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
- return this._options.shouldLog(logLevel);
- };
- /**
- * Attempt to log the provided message to the provided logger. If no logger was provided or if
- * the log level does not meat the logger's threshold, then nothing will be logged.
- * @param logLevel The log level of this log.
- * @param message The message of this log.
- */
- BaseRequestPolicy.prototype.log = function (logLevel, message) {
- this._options.log(logLevel, message);
- };
- return BaseRequestPolicy;
- }());
- /**
- * Optional properties that can be used when creating a RequestPolicy.
- */
- var RequestPolicyOptions = /** @class */ (function () {
- function RequestPolicyOptions(_logger) {
- this._logger = _logger;
- }
- /**
- * Get whether or not a log with the provided log level should be logged.
- * @param logLevel The log level of the log that will be logged.
- * @returns Whether or not a log with the provided log level should be logged.
- */
- RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
- return !!this._logger &&
- logLevel !== exports.HttpPipelineLogLevel.OFF &&
- logLevel <= this._logger.minimumLogLevel;
- };
- /**
- * Attempt to log the provided message to the provided logger. If no logger was provided or if
- * the log level does not meat the logger's threshold, then nothing will be logged.
- * @param logLevel The log level of this log.
- * @param message The message of this log.
- */
- RequestPolicyOptions.prototype.log = function (logLevel, message) {
- if (this._logger && this.shouldLog(logLevel)) {
- this._logger.log(logLevel, message);
- }
- };
- return RequestPolicyOptions;
- }());
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
- * pass through the HTTP pipeline.
- */
- function deserializationPolicy(deserializationContentTypes) {
- return {
- create: function (nextPolicy, options) {
- return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
- }
- };
- }
- var defaultJsonContentTypes = ["application/json", "text/json"];
- var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
- /**
- * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
- * HTTP pipeline.
- */
- var DeserializationPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(DeserializationPolicy, _super);
- function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
- var _this = _super.call(this, nextPolicy, options) || this;
- _this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes;
- _this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes;
- return _this;
- }
- DeserializationPolicy.prototype.sendRequest = function (request) {
- return tslib_1.__awaiter(this, void 0, void 0, function () {
- var _this = this;
- return tslib_1.__generator(this, function (_a) {
- return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })];
- });
- });
- };
- return DeserializationPolicy;
- }(BaseRequestPolicy));
- function getOperationResponse(parsedResponse) {
- var result;
- var request = parsedResponse.request;
- var operationSpec = request.operationSpec;
- if (operationSpec) {
- var operationResponseGetter = request.operationResponseGetter;
- if (!operationResponseGetter) {
- result = operationSpec.responses[parsedResponse.status];
- }
- else {
- result = operationResponseGetter(operationSpec, parsedResponse);
- }
- }
- return result;
- }
- function shouldDeserializeResponse(parsedResponse) {
- var shouldDeserialize = parsedResponse.request.shouldDeserialize;
- var result;
- if (shouldDeserialize === undefined) {
- result = true;
- }
- else if (typeof shouldDeserialize === "boolean") {
- result = shouldDeserialize;
- }
- else {
- result = shouldDeserialize(parsedResponse);
- }
- return result;
- }
- function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
- return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
- var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
- if (shouldDeserialize) {
- var operationSpec = parsedResponse.request.operationSpec;
- if (operationSpec && operationSpec.responses) {
- var statusCode = parsedResponse.status;
- var expectedStatusCodes = Object.keys(operationSpec.responses);
- var hasNoExpectedStatusCodes = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
- var responseSpec = getOperationResponse(parsedResponse);
- var isExpectedStatusCode = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec;
- if (!isExpectedStatusCode) {
- var defaultResponseSpec = operationSpec.responses.default;
- if (defaultResponseSpec) {
- var initialErrorMessage = isStreamOperation(operationSpec)
- ? "Unexpected status code: " + statusCode
- : parsedResponse.bodyAsText;
- var error = new RestError(initialErrorMessage);
- error.statusCode = statusCode;
- error.request = stripRequest(parsedResponse.request);
- error.response = stripResponse(parsedResponse);
- var parsedErrorResponse = parsedResponse.parsedBody;
- try {
- if (parsedErrorResponse) {
- var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
- if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === "CloudError") {
- if (parsedErrorResponse.error) {
- parsedErrorResponse = parsedErrorResponse.error;
- }
- if (parsedErrorResponse.code) {
- error.code = parsedErrorResponse.code;
- }
- if (parsedErrorResponse.message) {
- error.message = parsedErrorResponse.message;
- }
- }
- else {
- var internalError = parsedErrorResponse;
- if (parsedErrorResponse.error) {
- internalError = parsedErrorResponse.error;
- }
- error.code = internalError.code;
- if (internalError.message) {
- error.message = internalError.message;
- }
- }
- if (defaultResponseBodyMapper) {
- var valueToDeserialize = parsedErrorResponse;
- if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) {
- valueToDeserialize = typeof parsedErrorResponse === "object"
- ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
- : [];
- }
- error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
- }
- }
- }
- catch (defaultError) {
- error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
- }
- return Promise.reject(error);
- }
- }
- else if (responseSpec) {
- if (responseSpec.bodyMapper) {
- var valueToDeserialize = parsedResponse.parsedBody;
- if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
- valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : [];
- }
- try {
- parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
- }
- catch (error) {
- var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
- restError.request = stripRequest(parsedResponse.request);
- restError.response = stripResponse(parsedResponse);
- return Promise.reject(restError);
- }
- }
- else if (operationSpec.httpMethod === "HEAD") {
- // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
- parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
- }
- if (responseSpec.headersMapper) {
- parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
- }
- }
- }
- }
- return Promise.resolve(parsedResponse);
- });
- }
- function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
- var errorHandler = function (err) {
- var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
- var errCode = err.code || RestError.PARSE_ERROR;
- var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
- return Promise.reject(e);
- };
- if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
- var text_1 = operationResponse.bodyAsText;
- var contentType = operationResponse.headers.get("Content-Type") || "";
- var contentComponents = !contentType ? [] : contentType.split(";").map(function (component) { return component.toLowerCase(); });
- if (contentComponents.length === 0 || contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
- return new Promise(function (resolve) {
- operationResponse.parsedBody = JSON.parse(text_1);
- resolve(operationResponse);
- }).catch(errorHandler);
- }
- else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
- return parseXML(text_1)
- .then(function (body) {
- operationResponse.parsedBody = body;
- return operationResponse;
- })
- .catch(errorHandler);
- }
- }
- return Promise.resolve(operationResponse);
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
- return {
- create: function (nextPolicy, options) {
- return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
- }
- };
- }
- var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
- var DEFAULT_CLIENT_RETRY_COUNT = 3;
- var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
- var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
- /**
- * @class
- * Instantiates a new "ExponentialRetryPolicyFilter" instance.
- */
- var ExponentialRetryPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(ExponentialRetryPolicy, _super);
- /**
- * @constructor
- * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
- * @param {RequestPolicyOptions} options The options for this RequestPolicy.
- * @param {number} [retryCount] The client retry count.
- * @param {number} [retryInterval] The client retry interval, in milliseconds.
- * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
- * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
- */
- function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
- var _this = _super.call(this, nextPolicy, options) || this;
- function isNumber(n) { return typeof n === "number"; }
- _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
- _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
- _this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
- _this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
- return _this;
- }
- ExponentialRetryPolicy.prototype.sendRequest = function (request) {
- var _this = this;
- return this._nextPolicy.sendRequest(request.clone())
- .then(function (response) { return retry(_this, request, response); })
- .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
- };
- return ExponentialRetryPolicy;
- }(BaseRequestPolicy));
- /**
- * Determines if the operation should be retried and how long to wait until the next retry.
- *
- * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
- * @param {number} statusCode The HTTP status code.
- * @param {RetryData} retryData The retry data.
- * @return {boolean} True if the operation qualifies for a retry; false otherwise.
- */
- function shouldRetry(policy, statusCode, retryData) {
- if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) {
- return false;
- }
- var currentCount;
- if (!retryData) {
- throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
- }
- else {
- currentCount = (retryData && retryData.retryCount);
- }
- return (currentCount < policy.retryCount);
- }
- /**
- * Updates the retry data for the next attempt.
- *
- * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
- * @param {RetryData} retryData The retry data.
- * @param {RetryError} [err] The operation"s error, if any.
- */
- function updateRetryData(policy, retryData, err) {
- if (!retryData) {
- retryData = {
- retryCount: 0,
- retryInterval: 0
- };
- }
- if (err) {
- if (retryData.error) {
- err.innerError = retryData.error;
- }
- retryData.error = err;
- }
- // Adjust retry count
- retryData.retryCount++;
- // Adjust retry interval
- var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
- var boundedRandDelta = policy.retryInterval * 0.8 +
- Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
- incrementDelta *= boundedRandDelta;
- retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
- return retryData;
- }
- function retry(policy, request, response, retryData, requestError) {
- retryData = updateRetryData(policy, retryData, requestError);
- var isAborted = request.abortSignal && request.abortSignal.aborted;
- if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
- return delay(retryData.retryInterval)
- .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
- .then(function (res) { return retry(policy, request, res, retryData, undefined); })
- .catch(function (err) { return retry(policy, request, response, retryData, err); });
- }
- else if (isAborted || requestError || !response) {
- // If the operation failed in the end, return all errors instead of just the last one
- var err = retryData.error ||
- new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
- return Promise.reject(err);
- }
- else {
- return Promise.resolve(response);
- }
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function generateClientRequestIdPolicy(requestIdHeaderName) {
- if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
- return {
- create: function (nextPolicy, options) {
- return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
- }
- };
- }
- var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(GenerateClientRequestIdPolicy, _super);
- function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
- var _this = _super.call(this, nextPolicy, options) || this;
- _this._requestIdHeaderName = _requestIdHeaderName;
- return _this;
- }
- GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
- if (!request.headers.contains(this._requestIdHeaderName)) {
- request.headers.set(this._requestIdHeaderName, generateUuid());
- }
- return this._nextPolicy.sendRequest(request);
- };
- return GenerateClientRequestIdPolicy;
- }(BaseRequestPolicy));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function getDefaultUserAgentKey() {
- return Constants.HeaderConstants.USER_AGENT;
- }
- function getPlatformSpecificData() {
- var runtimeInfo = {
- key: "Node",
- value: process.version
- };
- var osInfo = {
- key: "OS",
- value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")"
- };
- return [runtimeInfo, osInfo];
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function getRuntimeInfo() {
- var msRestRuntime = {
- key: "ms-rest-js",
- value: Constants.msRestVersion
- };
- return [msRestRuntime];
- }
- function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
- if (keySeparator === void 0) { keySeparator = " "; }
- if (valueSeparator === void 0) { valueSeparator = "/"; }
- return telemetryInfo.map(function (info) {
- var value = info.value ? "" + valueSeparator + info.value : "";
- return "" + info.key + value;
- }).join(keySeparator);
- }
- var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
- function getDefaultUserAgentValue() {
- var runtimeInfo = getRuntimeInfo();
- var platformSpecificData = getPlatformSpecificData();
- var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
- return userAgent;
- }
- function userAgentPolicy(userAgentData) {
- var key = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key;
- var value = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value;
- return {
- create: function (nextPolicy, options) {
- return new UserAgentPolicy(nextPolicy, options, key, value);
- }
- };
- }
- var UserAgentPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(UserAgentPolicy, _super);
- function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
- var _this = _super.call(this, _nextPolicy, _options) || this;
- _this._nextPolicy = _nextPolicy;
- _this._options = _options;
- _this.headerKey = headerKey;
- _this.headerValue = headerValue;
- return _this;
- }
- UserAgentPolicy.prototype.sendRequest = function (request) {
- this.addUserAgentHeader(request);
- return this._nextPolicy.sendRequest(request);
- };
- UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
- if (!request.headers) {
- request.headers = new HttpHeaders();
- }
- if (!request.headers.get(this.headerKey) && this.headerValue) {
- request.headers.set(this.headerKey, this.headerValue);
- }
- };
- return UserAgentPolicy;
- }(BaseRequestPolicy));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function redirectPolicy(maximumRetries) {
- if (maximumRetries === void 0) { maximumRetries = 20; }
- return {
- create: function (nextPolicy, options) {
- return new RedirectPolicy(nextPolicy, options, maximumRetries);
- }
- };
- }
- var RedirectPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(RedirectPolicy, _super);
- function RedirectPolicy(nextPolicy, options, maxRetries) {
- if (maxRetries === void 0) { maxRetries = 20; }
- var _this = _super.call(this, nextPolicy, options) || this;
- _this.maxRetries = maxRetries;
- return _this;
- }
- RedirectPolicy.prototype.sendRequest = function (request) {
- var _this = this;
- return this._nextPolicy.sendRequest(request).then(function (response) { return handleRedirect(_this, response, 0); });
- };
- return RedirectPolicy;
- }(BaseRequestPolicy));
- function handleRedirect(policy, response, currentRetries) {
- var request = response.request, status = response.status;
- var locationHeader = response.headers.get("location");
- if (locationHeader &&
- (status === 300 || status === 307 || (status === 303 && request.method === "POST")) &&
- (!policy.maxRetries || currentRetries < policy.maxRetries)) {
- var builder = URLBuilder.parse(request.url);
- builder.setPath(locationHeader);
- request.url = builder.toString();
- // POST request with Status code 303 should be converted into a
- // redirected GET request if the redirect url is present in the location header
- if (status === 303) {
- request.method = "GET";
- }
- return policy._nextPolicy.sendRequest(request)
- .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); });
- }
- return Promise.resolve(response);
- }
- function rpRegistrationPolicy(retryTimeout) {
- if (retryTimeout === void 0) { retryTimeout = 30; }
- return {
- create: function (nextPolicy, options) {
- return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
- }
- };
- }
- var RPRegistrationPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(RPRegistrationPolicy, _super);
- function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
- if (_retryTimeout === void 0) { _retryTimeout = 30; }
- var _this = _super.call(this, nextPolicy, options) || this;
- _this._retryTimeout = _retryTimeout;
- return _this;
- }
- RPRegistrationPolicy.prototype.sendRequest = function (request) {
- var _this = this;
- return this._nextPolicy.sendRequest(request.clone())
- .then(function (response) { return registerIfNeeded(_this, request, response); });
- };
- return RPRegistrationPolicy;
- }(BaseRequestPolicy));
- function registerIfNeeded(policy, request, response) {
- if (response.status === 409) {
- var rpName = checkRPNotRegisteredError(response.bodyAsText);
- if (rpName) {
- var urlPrefix = extractSubscriptionUrl(request.url);
- return registerRP(policy, urlPrefix, rpName, request)
- // Autoregistration of ${provider} failed for some reason. We will not return this error
- // instead will return the initial response with 409 status code back to the user.
- // do nothing here as we are returning the original response at the end of this method.
- .catch(function () { return false; })
- .then(function (registrationStatus) {
- if (registrationStatus) {
- // Retry the original request. We have to change the x-ms-client-request-id
- // otherwise Azure endpoint will return the initial 409 (cached) response.
- request.headers.set("x-ms-client-request-id", generateUuid());
- return policy._nextPolicy.sendRequest(request.clone());
- }
- return response;
- });
- }
- }
- return Promise.resolve(response);
- }
- /**
- * Reuses the headers of the original request and url (if specified).
- * @param {WebResource} originalRequest The original request
- * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
- * @returns {object} A new request object with desired headers.
- */
- function getRequestEssentials(originalRequest, reuseUrlToo) {
- if (reuseUrlToo === void 0) { reuseUrlToo = false; }
- var reqOptions = originalRequest.clone();
- if (reuseUrlToo) {
- reqOptions.url = originalRequest.url;
- }
- // We have to change the x-ms-client-request-id otherwise Azure endpoint
- // will return the initial 409 (cached) response.
- reqOptions.headers.set("x-ms-client-request-id", generateUuid());
- // Set content-type to application/json
- reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
- return reqOptions;
- }
- /**
- * Validates the error code and message associated with 409 response status code. If it matches to that of
- * RP not registered then it returns the name of the RP else returns undefined.
- * @param {string} body The response body received after making the original request.
- * @returns {string} The name of the RP if condition is satisfied else undefined.
- */
- function checkRPNotRegisteredError(body) {
- var result, responseBody;
- if (body) {
- try {
- responseBody = JSON.parse(body);
- }
- catch (err) {
- // do nothing;
- }
- if (responseBody && responseBody.error && responseBody.error.message &&
- responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") {
- var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
- if (matchRes) {
- result = matchRes.pop();
- }
- }
- }
- return result;
- }
- /**
- * Extracts the first part of the URL, just after subscription:
- * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
- * @param {string} url The original request url
- * @returns {string} The url prefix as explained above.
- */
- function extractSubscriptionUrl(url) {
- var result;
- var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//ig);
- if (matchRes && matchRes[0]) {
- result = matchRes[0];
- }
- else {
- throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
- }
- return result;
- }
- /**
- * Registers the given provider.
- * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
- * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
- * @param {string} provider The provider name to be registered.
- * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response
- * with a message that the provider is not registered.
- * @param {registrationCallback} callback The callback that handles the RP registration
- */
- function registerRP(policy, urlPrefix, provider, originalRequest) {
- var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
- var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
- var reqOptions = getRequestEssentials(originalRequest);
- reqOptions.method = "POST";
- reqOptions.url = postUrl;
- return policy._nextPolicy.sendRequest(reqOptions)
- .then(function (response) {
- if (response.status !== 200) {
- throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
- }
- return getRegistrationStatus(policy, getUrl, originalRequest);
- });
- }
- /**
- * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
- * Polling will happen till the registrationState property of the response body is "Registered".
- * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
- * @param {string} url The request url for polling
- * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response
- * with a message that the provider is not registered.
- * @returns {Promise<boolean>} True if RP Registration is successful.
- */
- function getRegistrationStatus(policy, url, originalRequest) {
- var reqOptions = getRequestEssentials(originalRequest);
- reqOptions.url = url;
- reqOptions.method = "GET";
- return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
- var obj = res.parsedBody;
- if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
- return true;
- }
- else {
- return delay(policy._retryTimeout * 1000).then(function () { return getRegistrationStatus(policy, url, originalRequest); });
- }
- });
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function signingPolicy(authenticationProvider) {
- return {
- create: function (nextPolicy, options) {
- return new SigningPolicy(nextPolicy, options, authenticationProvider);
- }
- };
- }
- var SigningPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(SigningPolicy, _super);
- function SigningPolicy(nextPolicy, options, authenticationProvider) {
- var _this = _super.call(this, nextPolicy, options) || this;
- _this.authenticationProvider = authenticationProvider;
- return _this;
- }
- SigningPolicy.prototype.signRequest = function (request) {
- return this.authenticationProvider.signRequest(request);
- };
- SigningPolicy.prototype.sendRequest = function (request) {
- var _this = this;
- return this.signRequest(request).then(function (nextRequest) { return _this._nextPolicy.sendRequest(nextRequest); });
- };
- return SigningPolicy;
- }(BaseRequestPolicy));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
- return {
- create: function (nextPolicy, options) {
- return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
- }
- };
- }
- /**
- * @class
- * Instantiates a new "ExponentialRetryPolicyFilter" instance.
- *
- * @constructor
- * @param {number} retryCount The client retry count.
- * @param {number} retryInterval The client retry interval, in milliseconds.
- * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
- * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
- */
- var SystemErrorRetryPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(SystemErrorRetryPolicy, _super);
- function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
- var _this = _super.call(this, nextPolicy, options) || this;
- _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
- _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
- _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
- _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
- _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
- _this.retryInterval = typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
- _this.minRetryInterval = typeof minRetryInterval === "number" ? minRetryInterval : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
- _this.maxRetryInterval = typeof maxRetryInterval === "number" ? maxRetryInterval : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
- return _this;
- }
- SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
- var _this = this;
- return this._nextPolicy.sendRequest(request.clone()).then(function (response) { return retry$1(_this, request, response); });
- };
- return SystemErrorRetryPolicy;
- }(BaseRequestPolicy));
- /**
- * Determines if the operation should be retried and how long to wait until the next retry.
- *
- * @param {number} statusCode The HTTP status code.
- * @param {RetryData} retryData The retry data.
- * @return {boolean} True if the operation qualifies for a retry; false otherwise.
- */
- function shouldRetry$1(policy, retryData) {
- var currentCount;
- if (!retryData) {
- throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
- }
- else {
- currentCount = (retryData && retryData.retryCount);
- }
- return (currentCount < policy.retryCount);
- }
- /**
- * Updates the retry data for the next attempt.
- *
- * @param {RetryData} retryData The retry data.
- * @param {object} err The operation"s error, if any.
- */
- function updateRetryData$1(policy, retryData, err) {
- if (!retryData) {
- retryData = {
- retryCount: 0,
- retryInterval: 0
- };
- }
- if (err) {
- if (retryData.error) {
- err.innerError = retryData.error;
- }
- retryData.error = err;
- }
- // Adjust retry count
- retryData.retryCount++;
- // Adjust retry interval
- var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
- var boundedRandDelta = policy.retryInterval * 0.8 +
- Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
- incrementDelta *= boundedRandDelta;
- retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
- return retryData;
- }
- function retry$1(policy, request, operationResponse, retryData, err) {
- retryData = updateRetryData$1(policy, retryData, err);
- if (err && err.code && shouldRetry$1(policy, retryData) &&
- (err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" ||
- err.code === "ECONNRESET" || err.code === "ENOENT")) {
- // If previous operation ended with an error and the policy allows a retry, do that
- return delay(retryData.retryInterval)
- .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
- .then(function (res) { return retry$1(policy, request, res, retryData, err); })
- .catch(function (err) { return retry$1(policy, request, operationResponse, retryData, err); });
- }
- else {
- if (err != undefined) {
- // If the operation failed in the end, return all errors instead of just the last one
- err = retryData.error;
- return Promise.reject(err);
- }
- return Promise.resolve(operationResponse);
- }
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- (function (QueryCollectionFormat) {
- QueryCollectionFormat["Csv"] = ",";
- QueryCollectionFormat["Ssv"] = " ";
- QueryCollectionFormat["Tsv"] = "\t";
- QueryCollectionFormat["Pipes"] = "|";
- QueryCollectionFormat["Multi"] = "Multi";
- })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function loadEnvironmentProxyValue() {
- if (!process) {
- return undefined;
- }
- if (process.env[Constants.HTTPS_PROXY]) {
- return process.env[Constants.HTTPS_PROXY];
- }
- else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) {
- return process.env[Constants.HTTPS_PROXY.toLowerCase()];
- }
- else if (process.env[Constants.HTTP_PROXY]) {
- return process.env[Constants.HTTP_PROXY];
- }
- else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) {
- return process.env[Constants.HTTP_PROXY.toLowerCase()];
- }
- return undefined;
- }
- function getDefaultProxySettings(proxyUrl) {
- if (!proxyUrl) {
- proxyUrl = loadEnvironmentProxyValue();
- if (!proxyUrl) {
- return undefined;
- }
- }
- var parsedUrl = URLBuilder.parse(proxyUrl);
- return {
- host: parsedUrl.getScheme() + "://" + parsedUrl.getHost(),
- port: Number.parseInt(parsedUrl.getPort() || "80")
- };
- }
- function proxyPolicy(proxySettings) {
- return {
- create: function (nextPolicy, options) {
- return new ProxyPolicy(nextPolicy, options, proxySettings);
- }
- };
- }
- var ProxyPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(ProxyPolicy, _super);
- function ProxyPolicy(nextPolicy, options, proxySettings) {
- var _this = _super.call(this, nextPolicy, options) || this;
- _this.proxySettings = proxySettings;
- return _this;
- }
- ProxyPolicy.prototype.sendRequest = function (request) {
- if (!request.proxySettings) {
- request.proxySettings = this.proxySettings;
- }
- return this._nextPolicy.sendRequest(request);
- };
- return ProxyPolicy;
- }(BaseRequestPolicy));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var StatusCodes = Constants.HttpConstants.StatusCodes;
- function throttlingRetryPolicy() {
- return {
- create: function (nextPolicy, options) {
- return new ThrottlingRetryPolicy(nextPolicy, options);
- }
- };
- }
- /**
- * To learn more, please refer to
- * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
- * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
- * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
- */
- var ThrottlingRetryPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(ThrottlingRetryPolicy, _super);
- function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) {
- var _this = _super.call(this, nextPolicy, options) || this;
- _this._handleResponse = _handleResponse || _this._defaultResponseHandler;
- return _this;
- }
- ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
- return tslib_1.__awaiter(this, void 0, void 0, function () {
- var _this = this;
- return tslib_1.__generator(this, function (_a) {
- return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
- if (response.status !== StatusCodes.TooManyRequests) {
- return response;
- }
- else {
- return _this._handleResponse(httpRequest, response);
- }
- })];
- });
- });
- };
- ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) {
- return tslib_1.__awaiter(this, void 0, void 0, function () {
- var retryAfterHeader, delayInMs;
- var _this = this;
- return tslib_1.__generator(this, function (_a) {
- retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
- if (retryAfterHeader) {
- delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
- if (delayInMs) {
- return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })];
- }
- }
- return [2 /*return*/, httpResponse];
- });
- });
- };
- ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
- var retryAfterInSeconds = Number(headerValue);
- if (Number.isNaN(retryAfterInSeconds)) {
- return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
- }
- else {
- return retryAfterInSeconds * 1000;
- }
- };
- ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
- try {
- var now = Date.now();
- var date = Date.parse(headerValue);
- var diff = date - now;
- return Number.isNaN(diff) ? undefined : diff;
- }
- catch (error) {
- return undefined;
- }
- };
- return ThrottlingRetryPolicy;
- }(BaseRequestPolicy));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * @class
- * Initializes a new instance of the ServiceClient.
- */
- var ServiceClient = /** @class */ (function () {
- /**
- * The ServiceClient constructor
- * @constructor
- * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
- * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
- */
- function ServiceClient(credentials, options) {
- if (!options) {
- options = {};
- }
- if (credentials && !credentials.signRequest) {
- throw new Error("credentials argument needs to implement signRequest method");
- }
- this._withCredentials = options.withCredentials || false;
- this._httpClient = options.httpClient || new AxiosHttpClient();
- this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
- var requestPolicyFactories;
- if (Array.isArray(options.requestPolicyFactories)) {
- requestPolicyFactories = options.requestPolicyFactories;
- }
- else {
- requestPolicyFactories = createDefaultRequestPolicyFactories(credentials, options);
- if (options.requestPolicyFactories) {
- var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
- if (newRequestPolicyFactories) {
- requestPolicyFactories = newRequestPolicyFactories;
- }
- }
- }
- this._requestPolicyFactories = requestPolicyFactories;
- }
- /**
- * Send the provided httpRequest.
- */
- ServiceClient.prototype.sendRequest = function (options) {
- if (options === null || options === undefined || typeof options !== "object") {
- throw new Error("options cannot be null or undefined and it must be of type object.");
- }
- var httpRequest;
- try {
- if (options instanceof WebResource) {
- options.validateRequestProperties();
- httpRequest = options;
- }
- else {
- httpRequest = new WebResource();
- httpRequest = httpRequest.prepare(options);
- }
- }
- catch (error) {
- return Promise.reject(error);
- }
- var httpPipeline = this._httpClient;
- if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
- for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
- httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
- }
- }
- return httpPipeline.sendRequest(httpRequest);
- };
- /**
- * Send an HTTP request that is populated using the provided OperationSpec.
- * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
- * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
- * @param {ServiceCallback} callback The callback to call when the response is received.
- */
- ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
- if (typeof operationArguments.options === "function") {
- callback = operationArguments.options;
- operationArguments.options = undefined;
- }
- var httpRequest = new WebResource();
- var result;
- try {
- var baseUri = operationSpec.baseUrl || this.baseUri;
- if (!baseUri) {
- 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.");
- }
- httpRequest.method = operationSpec.httpMethod;
- httpRequest.operationSpec = operationSpec;
- var requestUrl = URLBuilder.parse(baseUri);
- if (operationSpec.path) {
- requestUrl.appendPath(operationSpec.path);
- }
- if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
- for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
- var urlParameter = _a[_i];
- var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
- urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
- if (!urlParameter.skipEncoding) {
- urlParameterValue = encodeURIComponent(urlParameterValue);
- }
- requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
- }
- }
- if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
- for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
- var queryParameter = _c[_b];
- var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
- if (queryParameterValue != undefined) {
- queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
- if (queryParameter.collectionFormat != undefined) {
- if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
- if (queryParameterValue.length === 0) {
- queryParameterValue = "";
- }
- else {
- for (var index in queryParameterValue) {
- var item = queryParameterValue[index];
- queryParameterValue[index] = item == undefined ? "" : item.toString();
- }
- }
- }
- else {
- queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
- }
- }
- if (!queryParameter.skipEncoding) {
- if (Array.isArray(queryParameterValue)) {
- for (var index in queryParameterValue) {
- queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
- }
- }
- else {
- queryParameterValue = encodeURIComponent(queryParameterValue);
- }
- }
- requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
- }
- }
- }
- httpRequest.url = requestUrl.toString();
- var contentType = operationSpec.contentType || this.requestContentType;
- if (contentType) {
- httpRequest.headers.set("Content-Type", contentType);
- }
- if (operationSpec.headerParameters) {
- for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
- var headerParameter = _e[_d];
- var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
- if (headerValue != undefined) {
- headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
- var headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
- var key = _g[_f];
- httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
- }
- }
- else {
- httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
- }
- }
- }
- }
- var options = operationArguments.options;
- if (options) {
- if (options.customHeaders) {
- for (var customHeaderName in options.customHeaders) {
- httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
- }
- }
- if (options.abortSignal) {
- httpRequest.abortSignal = options.abortSignal;
- }
- if (options.timeout) {
- httpRequest.timeout = options.timeout;
- }
- if (options.onUploadProgress) {
- httpRequest.onUploadProgress = options.onUploadProgress;
- }
- if (options.onDownloadProgress) {
- httpRequest.onDownloadProgress = options.onDownloadProgress;
- }
- }
- httpRequest.withCredentials = this._withCredentials;
- serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
- if (httpRequest.streamResponseBody == undefined) {
- httpRequest.streamResponseBody = isStreamOperation(operationSpec);
- }
- result = this.sendRequest(httpRequest)
- .then(function (res) { return flattenResponse(res, operationSpec.responses[res.status]); });
- }
- catch (error) {
- result = Promise.reject(error);
- }
- var cb = callback;
- if (cb) {
- result
- // tslint:disable-next-line:no-null-keyword
- .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
- .catch(function (err) { return cb(err); });
- }
- return result;
- };
- return ServiceClient;
- }());
- function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
- if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
- httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
- var bodyMapper = operationSpec.requestBody.mapper;
- var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
- var typeName = bodyMapper.type.name;
- try {
- if (httpRequest.body != undefined || required) {
- var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
- httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
- var isStream = typeName === MapperType.Stream;
- if (operationSpec.isXML) {
- if (typeName === MapperType.Sequence) {
- httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
- }
- else if (!isStream) {
- httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName });
- }
- }
- else if (!isStream) {
- httpRequest.body = JSON.stringify(httpRequest.body);
- }
- }
- }
- catch (error) {
- throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
- }
- }
- else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
- httpRequest.formData = {};
- for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
- var formDataParameter = _a[_i];
- var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
- if (formDataParameterValue != undefined) {
- var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
- httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
- }
- }
- }
- }
- function isRequestPolicyFactory(instance) {
- return typeof instance.create === "function";
- }
- function getValueOrFunctionResult(value, defaultValueCreator) {
- var result;
- if (typeof value === "string") {
- result = value;
- }
- else {
- result = defaultValueCreator();
- if (typeof value === "function") {
- result = value(result);
- }
- }
- return result;
- }
- function createDefaultRequestPolicyFactories(credentials, options) {
- var factories = [];
- if (options.generateClientRequestIdHeader) {
- factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
- }
- if (credentials) {
- if (isRequestPolicyFactory(credentials)) {
- factories.push(credentials);
- }
- else {
- factories.push(signingPolicy(credentials));
- }
- }
- var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
- var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
- if (userAgentHeaderName && userAgentHeaderValue) {
- factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
- }
- factories.push(redirectPolicy());
- factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
- if (!options.noRetryPolicy) {
- factories.push(exponentialRetryPolicy());
- factories.push(systemErrorRetryPolicy());
- factories.push(throttlingRetryPolicy());
- }
- factories.push(deserializationPolicy(options.deserializationContentTypes));
- var proxySettings = options.proxySettings || getDefaultProxySettings();
- if (proxySettings) {
- factories.push(proxyPolicy(proxySettings));
- }
- return factories;
- }
- function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
- return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
- }
- function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
- var value;
- if (typeof parameterPath === "string") {
- parameterPath = [parameterPath];
- }
- if (Array.isArray(parameterPath)) {
- if (parameterPath.length > 0) {
- if (parameterMapper.isConstant) {
- value = parameterMapper.defaultValue;
- }
- else {
- var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
- if (!propertySearchResult.propertyFound) {
- propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
- }
- var useDefaultValue = false;
- if (!propertySearchResult.propertyFound) {
- useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2);
- }
- value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
- }
- // Serialize just for validation purposes.
- var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
- serializer.serialize(parameterMapper, value, parameterPathString);
- }
- }
- else {
- if (parameterMapper.required) {
- value = {};
- }
- for (var propertyName in parameterPath) {
- var propertyMapper = parameterMapper.type.modelProperties[propertyName];
- var propertyPath = parameterPath[propertyName];
- var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
- // Serialize just for validation purposes.
- var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
- serializer.serialize(propertyMapper, propertyValue, propertyPathString);
- if (propertyValue !== undefined) {
- if (!value) {
- value = {};
- }
- value[propertyName] = propertyValue;
- }
- }
- }
- return value;
- }
- function getPropertyFromParameterPath(parent, parameterPath) {
- var result = { propertyFound: false };
- var i = 0;
- for (; i < parameterPath.length; ++i) {
- var parameterPathPart = parameterPath[i];
- // Make sure to check inherited properties too, so don't use hasOwnProperty().
- if (parent != undefined && parameterPathPart in parent) {
- parent = parent[parameterPathPart];
- }
- else {
- break;
- }
- }
- if (i === parameterPath.length) {
- result.propertyValue = parent;
- result.propertyFound = true;
- }
- return result;
- }
- function flattenResponse(_response, responseSpec) {
- var parsedHeaders = _response.parsedHeaders;
- var bodyMapper = responseSpec && responseSpec.bodyMapper;
- var addOperationResponse = function (obj) {
- return Object.defineProperty(obj, "_response", {
- value: _response
- });
- };
- if (bodyMapper) {
- var typeName = bodyMapper.type.name;
- if (typeName === "Stream") {
- return addOperationResponse(tslib_1.__assign({}, parsedHeaders, { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
- }
- var modelProperties_1 = typeName === "Composite" && bodyMapper.type.modelProperties || {};
- var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
- if (typeName === "Sequence" || isPageableResponse) {
- var arrayResponse = (_response.parsedBody || []).slice();
- for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
- var key = _a[_i];
- if (modelProperties_1[key].serializedName) {
- arrayResponse[key] = _response.parsedBody[key];
- }
- }
- if (parsedHeaders) {
- for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
- var key = _c[_b];
- arrayResponse[key] = parsedHeaders[key];
- }
- }
- addOperationResponse(arrayResponse);
- return arrayResponse;
- }
- if (typeName === "Composite" || typeName === "Dictionary") {
- return addOperationResponse(tslib_1.__assign({}, parsedHeaders, _response.parsedBody));
- }
- }
- if (bodyMapper || _response.request.method === "HEAD") {
- // primitive body types and HEAD booleans
- return addOperationResponse(tslib_1.__assign({}, parsedHeaders, { body: _response.parsedBody }));
- }
- return addOperationResponse(tslib_1.__assign({}, parsedHeaders, _response.parsedBody));
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- function logPolicy(logger) {
- if (logger === void 0) { logger = console.log; }
- return {
- create: function (nextPolicy, options) {
- return new LogPolicy(nextPolicy, options, logger);
- }
- };
- }
- var LogPolicy = /** @class */ (function (_super) {
- tslib_1.__extends(LogPolicy, _super);
- function LogPolicy(nextPolicy, options, logger) {
- if (logger === void 0) { logger = console.log; }
- var _this = _super.call(this, nextPolicy, options) || this;
- _this.logger = logger;
- return _this;
- }
- LogPolicy.prototype.sendRequest = function (request) {
- var _this = this;
- return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
- };
- return LogPolicy;
- }(BaseRequestPolicy));
- function logResponse(policy, response) {
- policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
- policy.logger(">> Response status code: " + response.status);
- var responseBody = response.bodyAsText;
- policy.logger(">> Body: " + responseBody);
- return Promise.resolve(response);
- }
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var HeaderConstants = Constants.HeaderConstants;
- var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
- /**
- * A credentials object that uses a token string and a authorzation scheme to authenticate.
- */
- var TokenCredentials = /** @class */ (function () {
- /**
- * Creates a new TokenCredentials object.
- *
- * @constructor
- * @param {string} token The token.
- * @param {string} [authorizationScheme] The authorization scheme.
- */
- function TokenCredentials(token, authorizationScheme) {
- if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; }
- this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME;
- if (!token) {
- throw new Error("token cannot be null or undefined.");
- }
- this.token = token;
- this.authorizationScheme = authorizationScheme;
- }
- /**
- * Signs a request with the Authentication header.
- *
- * @param {WebResource} webResource The WebResource to be signed.
- * @return {Promise<WebResource>} The signed request object.
- */
- TokenCredentials.prototype.signRequest = function (webResource) {
- if (!webResource.headers)
- webResource.headers = new HttpHeaders();
- webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
- return Promise.resolve(webResource);
- };
- return TokenCredentials;
- }());
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var HeaderConstants$1 = Constants.HeaderConstants;
- var DEFAULT_AUTHORIZATION_SCHEME$1 = "Basic";
- var BasicAuthenticationCredentials = /** @class */ (function () {
- /**
- * Creates a new BasicAuthenticationCredentials object.
- *
- * @constructor
- * @param {string} userName User name.
- * @param {string} password Password.
- * @param {string} [authorizationScheme] The authorization scheme.
- */
- function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
- if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
- this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
- if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
- throw new Error("userName cannot be null or undefined and must be of type string.");
- }
- if (password === null || password === undefined || typeof password.valueOf() !== "string") {
- throw new Error("password cannot be null or undefined and must be of type string.");
- }
- this.userName = userName;
- this.password = password;
- this.authorizationScheme = authorizationScheme;
- }
- /**
- * Signs a request with the Authentication header.
- *
- * @param {WebResource} webResource The WebResource to be signed.
- * @returns {Promise<WebResource>} The signed request object.
- */
- BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
- var credentials = this.userName + ":" + this.password;
- var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
- if (!webResource.headers)
- webResource.headers = new HttpHeaders();
- webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
- return Promise.resolve(webResource);
- };
- return BasicAuthenticationCredentials;
- }());
- // Copyright (c) Microsoft Corporation. All rights reserved.
- /**
- * Authenticates to a service using an API key.
- */
- var ApiKeyCredentials = /** @class */ (function () {
- /**
- * @constructor
- * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
- */
- function ApiKeyCredentials(options) {
- if (!options || (options && !options.inHeader && !options.inQuery)) {
- throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
- }
- this.inHeader = options.inHeader;
- this.inQuery = options.inQuery;
- }
- /**
- * Signs a request with the values provided in the inHeader and inQuery parameter.
- *
- * @param {WebResource} webResource The WebResource to be signed.
- * @returns {Promise<WebResource>} The signed request object.
- */
- ApiKeyCredentials.prototype.signRequest = function (webResource) {
- if (!webResource) {
- return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
- }
- if (this.inHeader) {
- if (!webResource.headers) {
- webResource.headers = new HttpHeaders();
- }
- for (var headerName in this.inHeader) {
- webResource.headers.set(headerName, this.inHeader[headerName]);
- }
- }
- if (this.inQuery) {
- if (!webResource.url) {
- return Promise.reject(new Error("url cannot be null in the request object."));
- }
- if (webResource.url.indexOf("?") < 0) {
- webResource.url += "?";
- }
- for (var key in this.inQuery) {
- if (!webResource.url.endsWith("?")) {
- webResource.url += "&";
- }
- webResource.url += key + "=" + this.inQuery[key];
- }
- }
- return Promise.resolve(webResource);
- };
- return ApiKeyCredentials;
- }());
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var TopicCredentials = /** @class */ (function (_super) {
- tslib_1.__extends(TopicCredentials, _super);
- /**
- * Creates a new EventGrid TopicCredentials object.
- *
- * @constructor
- * @param {string} topicKey The EventGrid topic key
- */
- function TopicCredentials(topicKey) {
- var _this = this;
- if (!topicKey || (topicKey && typeof topicKey !== "string")) {
- throw new Error("topicKey cannot be null or undefined and must be of type string.");
- }
- var options = {
- inHeader: {
- "aeg-sas-key": topicKey
- }
- };
- _this = _super.call(this, options) || this;
- return _this;
- }
- return TopicCredentials;
- }(ApiKeyCredentials));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- var DomainCredentials = /** @class */ (function (_super) {
- tslib_1.__extends(DomainCredentials, _super);
- /**
- * Creates a new EventGrid DomainCredentials object.
- *
- * @constructor
- * @param {string} domainKey The EventGrid domain key
- */
- function DomainCredentials(domainKey) {
- var _this = this;
- if (!domainKey || (domainKey && typeof domainKey !== "string")) {
- throw new Error("domainKey cannot be null or undefined and must be of type string.");
- }
- var options = {
- inHeader: {
- "aeg-sas-key": domainKey
- }
- };
- _this = _super.call(this, options) || this;
- return _this;
- }
- return DomainCredentials;
- }(ApiKeyCredentials));
- // Copyright (c) Microsoft Corporation. All rights reserved.
- exports.WebResource = WebResource;
- exports.DefaultHttpClient = AxiosHttpClient;
- exports.HttpHeaders = HttpHeaders;
- exports.RestError = RestError;
- exports.ServiceClient = ServiceClient;
- exports.flattenResponse = flattenResponse;
- exports.Constants = Constants;
- exports.logPolicy = logPolicy;
- exports.BaseRequestPolicy = BaseRequestPolicy;
- exports.RequestPolicyOptions = RequestPolicyOptions;
- exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
- exports.exponentialRetryPolicy = exponentialRetryPolicy;
- exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
- exports.throttlingRetryPolicy = throttlingRetryPolicy;
- exports.getDefaultProxySettings = getDefaultProxySettings;
- exports.proxyPolicy = proxyPolicy;
- exports.redirectPolicy = redirectPolicy;
- exports.signingPolicy = signingPolicy;
- exports.userAgentPolicy = userAgentPolicy;
- exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
- exports.deserializationPolicy = deserializationPolicy;
- exports.deserializeResponseBody = deserializeResponseBody;
- exports.MapperType = MapperType;
- exports.Serializer = Serializer;
- exports.serializeObject = serializeObject;
- exports.stripRequest = stripRequest;
- exports.stripResponse = stripResponse;
- exports.delay = delay;
- exports.executePromisesSequentially = executePromisesSequentially;
- exports.generateUuid = generateUuid;
- exports.encodeUri = encodeUri;
- exports.promiseToCallback = promiseToCallback;
- exports.promiseToServiceCallback = promiseToServiceCallback;
- exports.isValidUuid = isValidUuid;
- exports.applyMixins = applyMixins;
- exports.isNode = isNode;
- exports.isDuration = isDuration;
- exports.URLBuilder = URLBuilder;
- exports.URLQuery = URLQuery;
- exports.TokenCredentials = TokenCredentials;
- exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
- exports.ApiKeyCredentials = ApiKeyCredentials;
- exports.TopicCredentials = TopicCredentials;
- exports.DomainCredentials = DomainCredentials;
- //# sourceMappingURL=msRest.node.js.map
|