http.js 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { Injectable, InjectionToken, Inject, PLATFORM_ID, Injector, NgModule } from '@angular/core';
  7. import { of, Observable } from 'rxjs';
  8. import { concatMap, filter, map } from 'rxjs/operators';
  9. import { DOCUMENT, ɵparseCookieValue } from '@angular/common';
  10. /**
  11. * @fileoverview added by tsickle
  12. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  13. */
  14. /**
  15. * @license
  16. * Copyright Google Inc. All Rights Reserved.
  17. *
  18. * Use of this source code is governed by an MIT-style license that can be
  19. * found in the LICENSE file at https://angular.io/license
  20. */
  21. /**
  22. * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a
  23. * `HttpResponse`.
  24. *
  25. * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the
  26. * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the
  27. * `HttpBackend`.
  28. *
  29. * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain.
  30. *
  31. * \@publicApi
  32. * @abstract
  33. */
  34. class HttpHandler {
  35. }
  36. /**
  37. * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend.
  38. *
  39. * Interceptors sit between the `HttpClient` interface and the `HttpBackend`.
  40. *
  41. * When injected, `HttpBackend` dispatches requests directly to the backend, without going
  42. * through the interceptor chain.
  43. *
  44. * \@publicApi
  45. * @abstract
  46. */
  47. class HttpBackend {
  48. }
  49. /**
  50. * @fileoverview added by tsickle
  51. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  52. */
  53. /**
  54. * `HttpHeaders` class represents the header configuration options for an HTTP request.
  55. * Instances should be assumed immutable with lazy parsing.
  56. *
  57. * \@publicApi
  58. */
  59. class HttpHeaders {
  60. /**
  61. * Constructs a new HTTP header object with the given values.
  62. * @param {?=} headers
  63. */
  64. constructor(headers) {
  65. /**
  66. * Internal map of lowercased header names to the normalized
  67. * form of the name (the form seen first).
  68. */
  69. this.normalizedNames = new Map();
  70. /**
  71. * Queued updates to be materialized the next initialization.
  72. */
  73. this.lazyUpdate = null;
  74. if (!headers) {
  75. this.headers = new Map();
  76. }
  77. else if (typeof headers === 'string') {
  78. this.lazyInit = (/**
  79. * @return {?}
  80. */
  81. () => {
  82. this.headers = new Map();
  83. headers.split('\n').forEach((/**
  84. * @param {?} line
  85. * @return {?}
  86. */
  87. line => {
  88. /** @type {?} */
  89. const index = line.indexOf(':');
  90. if (index > 0) {
  91. /** @type {?} */
  92. const name = line.slice(0, index);
  93. /** @type {?} */
  94. const key = name.toLowerCase();
  95. /** @type {?} */
  96. const value = line.slice(index + 1).trim();
  97. this.maybeSetNormalizedName(name, key);
  98. if (this.headers.has(key)) {
  99. (/** @type {?} */ (this.headers.get(key))).push(value);
  100. }
  101. else {
  102. this.headers.set(key, [value]);
  103. }
  104. }
  105. }));
  106. });
  107. }
  108. else {
  109. this.lazyInit = (/**
  110. * @return {?}
  111. */
  112. () => {
  113. this.headers = new Map();
  114. Object.keys(headers).forEach((/**
  115. * @param {?} name
  116. * @return {?}
  117. */
  118. name => {
  119. /** @type {?} */
  120. let values = headers[name];
  121. /** @type {?} */
  122. const key = name.toLowerCase();
  123. if (typeof values === 'string') {
  124. values = [values];
  125. }
  126. if (values.length > 0) {
  127. this.headers.set(key, values);
  128. this.maybeSetNormalizedName(name, key);
  129. }
  130. }));
  131. });
  132. }
  133. }
  134. /**
  135. * Checks for existence of a header by a given name.
  136. *
  137. * @param {?} name The header name to check for existence.
  138. *
  139. * @return {?} Whether the header exits.
  140. */
  141. has(name) {
  142. this.init();
  143. return this.headers.has(name.toLowerCase());
  144. }
  145. /**
  146. * Returns the first header value that matches a given name.
  147. *
  148. * @param {?} name The header name to retrieve.
  149. *
  150. * @return {?} A string if the header exists, null otherwise
  151. */
  152. get(name) {
  153. this.init();
  154. /** @type {?} */
  155. const values = this.headers.get(name.toLowerCase());
  156. return values && values.length > 0 ? values[0] : null;
  157. }
  158. /**
  159. * Returns the names of the headers.
  160. *
  161. * @return {?} A list of header names.
  162. */
  163. keys() {
  164. this.init();
  165. return Array.from(this.normalizedNames.values());
  166. }
  167. /**
  168. * Returns a list of header values for a given header name.
  169. *
  170. * @param {?} name The header name from which to retrieve the values.
  171. *
  172. * @return {?} A string of values if the header exists, null otherwise.
  173. */
  174. getAll(name) {
  175. this.init();
  176. return this.headers.get(name.toLowerCase()) || null;
  177. }
  178. /**
  179. * Appends a new header value to the existing set of
  180. * header values.
  181. *
  182. * @param {?} name The header name for which to append the values.
  183. *
  184. * @param {?} value
  185. * @return {?} A clone of the HTTP header object with the value appended.
  186. */
  187. append(name, value) {
  188. return this.clone({ name, value, op: 'a' });
  189. }
  190. /**
  191. * Sets a header value for a given name. If the header name already exists,
  192. * its value is replaced with the given value.
  193. *
  194. * @param {?} name The header name.
  195. * @param {?} value Provides the value to set or overide for a given name.
  196. *
  197. * @return {?} A clone of the HTTP header object with the newly set header value.
  198. */
  199. set(name, value) {
  200. return this.clone({ name, value, op: 's' });
  201. }
  202. /**
  203. * Deletes all header values for a given name.
  204. *
  205. * @param {?} name The header name.
  206. * @param {?=} value The header values to delete for a given name.
  207. *
  208. * @return {?} A clone of the HTTP header object.
  209. */
  210. delete(name, value) {
  211. return this.clone({ name, value, op: 'd' });
  212. }
  213. /**
  214. * @private
  215. * @param {?} name
  216. * @param {?} lcName
  217. * @return {?}
  218. */
  219. maybeSetNormalizedName(name, lcName) {
  220. if (!this.normalizedNames.has(lcName)) {
  221. this.normalizedNames.set(lcName, name);
  222. }
  223. }
  224. /**
  225. * @private
  226. * @return {?}
  227. */
  228. init() {
  229. if (!!this.lazyInit) {
  230. if (this.lazyInit instanceof HttpHeaders) {
  231. this.copyFrom(this.lazyInit);
  232. }
  233. else {
  234. this.lazyInit();
  235. }
  236. this.lazyInit = null;
  237. if (!!this.lazyUpdate) {
  238. this.lazyUpdate.forEach((/**
  239. * @param {?} update
  240. * @return {?}
  241. */
  242. update => this.applyUpdate(update)));
  243. this.lazyUpdate = null;
  244. }
  245. }
  246. }
  247. /**
  248. * @private
  249. * @param {?} other
  250. * @return {?}
  251. */
  252. copyFrom(other) {
  253. other.init();
  254. Array.from(other.headers.keys()).forEach((/**
  255. * @param {?} key
  256. * @return {?}
  257. */
  258. key => {
  259. this.headers.set(key, (/** @type {?} */ (other.headers.get(key))));
  260. this.normalizedNames.set(key, (/** @type {?} */ (other.normalizedNames.get(key))));
  261. }));
  262. }
  263. /**
  264. * @private
  265. * @param {?} update
  266. * @return {?}
  267. */
  268. clone(update) {
  269. /** @type {?} */
  270. const clone = new HttpHeaders();
  271. clone.lazyInit =
  272. (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
  273. clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
  274. return clone;
  275. }
  276. /**
  277. * @private
  278. * @param {?} update
  279. * @return {?}
  280. */
  281. applyUpdate(update) {
  282. /** @type {?} */
  283. const key = update.name.toLowerCase();
  284. switch (update.op) {
  285. case 'a':
  286. case 's':
  287. /** @type {?} */
  288. let value = (/** @type {?} */ (update.value));
  289. if (typeof value === 'string') {
  290. value = [value];
  291. }
  292. if (value.length === 0) {
  293. return;
  294. }
  295. this.maybeSetNormalizedName(update.name, key);
  296. /** @type {?} */
  297. const base = (update.op === 'a' ? this.headers.get(key) : undefined) || [];
  298. base.push(...value);
  299. this.headers.set(key, base);
  300. break;
  301. case 'd':
  302. /** @type {?} */
  303. const toDelete = (/** @type {?} */ (update.value));
  304. if (!toDelete) {
  305. this.headers.delete(key);
  306. this.normalizedNames.delete(key);
  307. }
  308. else {
  309. /** @type {?} */
  310. let existing = this.headers.get(key);
  311. if (!existing) {
  312. return;
  313. }
  314. existing = existing.filter((/**
  315. * @param {?} value
  316. * @return {?}
  317. */
  318. value => toDelete.indexOf(value) === -1));
  319. if (existing.length === 0) {
  320. this.headers.delete(key);
  321. this.normalizedNames.delete(key);
  322. }
  323. else {
  324. this.headers.set(key, existing);
  325. }
  326. }
  327. break;
  328. }
  329. }
  330. /**
  331. * \@internal
  332. * @param {?} fn
  333. * @return {?}
  334. */
  335. forEach(fn) {
  336. this.init();
  337. Array.from(this.normalizedNames.keys())
  338. .forEach((/**
  339. * @param {?} key
  340. * @return {?}
  341. */
  342. key => fn((/** @type {?} */ (this.normalizedNames.get(key))), (/** @type {?} */ (this.headers.get(key))))));
  343. }
  344. }
  345. /**
  346. * @fileoverview added by tsickle
  347. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  348. */
  349. /**
  350. * A class that uses `encodeURIComponent` and `decodeURIComponent` to
  351. * serialize and parse URL parameter keys and values. If you pass URL query parameters
  352. * without encoding, the query parameters can get misinterpreted at the receiving end.
  353. * Use the `HttpParameterCodec` class to encode and decode the query-string values.
  354. *
  355. * \@publicApi
  356. */
  357. class HttpUrlEncodingCodec {
  358. /**
  359. * @param {?} key
  360. * @return {?}
  361. */
  362. encodeKey(key) { return standardEncoding(key); }
  363. /**
  364. * @param {?} value
  365. * @return {?}
  366. */
  367. encodeValue(value) { return standardEncoding(value); }
  368. /**
  369. * @param {?} key
  370. * @return {?}
  371. */
  372. decodeKey(key) { return decodeURIComponent(key); }
  373. /**
  374. * @param {?} value
  375. * @return {?}
  376. */
  377. decodeValue(value) { return decodeURIComponent(value); }
  378. }
  379. /**
  380. * @param {?} rawParams
  381. * @param {?} codec
  382. * @return {?}
  383. */
  384. function paramParser(rawParams, codec) {
  385. /** @type {?} */
  386. const map = new Map();
  387. if (rawParams.length > 0) {
  388. /** @type {?} */
  389. const params = rawParams.split('&');
  390. params.forEach((/**
  391. * @param {?} param
  392. * @return {?}
  393. */
  394. (param) => {
  395. /** @type {?} */
  396. const eqIdx = param.indexOf('=');
  397. const [key, val] = eqIdx == -1 ?
  398. [codec.decodeKey(param), ''] :
  399. [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))];
  400. /** @type {?} */
  401. const list = map.get(key) || [];
  402. list.push(val);
  403. map.set(key, list);
  404. }));
  405. }
  406. return map;
  407. }
  408. /**
  409. * @param {?} v
  410. * @return {?}
  411. */
  412. function standardEncoding(v) {
  413. return encodeURIComponent(v)
  414. .replace(/%40/gi, '@')
  415. .replace(/%3A/gi, ':')
  416. .replace(/%24/gi, '$')
  417. .replace(/%2C/gi, ',')
  418. .replace(/%3B/gi, ';')
  419. .replace(/%2B/gi, '+')
  420. .replace(/%3D/gi, '=')
  421. .replace(/%3F/gi, '?')
  422. .replace(/%2F/gi, '/');
  423. }
  424. /**
  425. * An HTTP request/response body that represents serialized parameters,
  426. * per the MIME type `application/x-www-form-urlencoded`.
  427. *
  428. * This class is immutable - all mutation operations return a new instance.
  429. *
  430. * \@publicApi
  431. */
  432. class HttpParams {
  433. /**
  434. * @param {?=} options
  435. */
  436. constructor(options = (/** @type {?} */ ({}))) {
  437. this.updates = null;
  438. this.cloneFrom = null;
  439. this.encoder = options.encoder || new HttpUrlEncodingCodec();
  440. if (!!options.fromString) {
  441. if (!!options.fromObject) {
  442. throw new Error(`Cannot specify both fromString and fromObject.`);
  443. }
  444. this.map = paramParser(options.fromString, this.encoder);
  445. }
  446. else if (!!options.fromObject) {
  447. this.map = new Map();
  448. Object.keys(options.fromObject).forEach((/**
  449. * @param {?} key
  450. * @return {?}
  451. */
  452. key => {
  453. /** @type {?} */
  454. const value = ((/** @type {?} */ (options.fromObject)))[key];
  455. (/** @type {?} */ (this.map)).set(key, Array.isArray(value) ? value : [value]);
  456. }));
  457. }
  458. else {
  459. this.map = null;
  460. }
  461. }
  462. /**
  463. * Check whether the body has one or more values for the given parameter name.
  464. * @param {?} param
  465. * @return {?}
  466. */
  467. has(param) {
  468. this.init();
  469. return (/** @type {?} */ (this.map)).has(param);
  470. }
  471. /**
  472. * Get the first value for the given parameter name, or `null` if it's not present.
  473. * @param {?} param
  474. * @return {?}
  475. */
  476. get(param) {
  477. this.init();
  478. /** @type {?} */
  479. const res = (/** @type {?} */ (this.map)).get(param);
  480. return !!res ? res[0] : null;
  481. }
  482. /**
  483. * Get all values for the given parameter name, or `null` if it's not present.
  484. * @param {?} param
  485. * @return {?}
  486. */
  487. getAll(param) {
  488. this.init();
  489. return (/** @type {?} */ (this.map)).get(param) || null;
  490. }
  491. /**
  492. * Get all the parameter names for this body.
  493. * @return {?}
  494. */
  495. keys() {
  496. this.init();
  497. return Array.from((/** @type {?} */ (this.map)).keys());
  498. }
  499. /**
  500. * Construct a new body with an appended value for the given parameter name.
  501. * @param {?} param
  502. * @param {?} value
  503. * @return {?}
  504. */
  505. append(param, value) { return this.clone({ param, value, op: 'a' }); }
  506. /**
  507. * Construct a new body with a new value for the given parameter name.
  508. * @param {?} param
  509. * @param {?} value
  510. * @return {?}
  511. */
  512. set(param, value) { return this.clone({ param, value, op: 's' }); }
  513. /**
  514. * Construct a new body with either the given value for the given parameter
  515. * removed, if a value is given, or all values for the given parameter removed
  516. * if not.
  517. * @param {?} param
  518. * @param {?=} value
  519. * @return {?}
  520. */
  521. delete(param, value) { return this.clone({ param, value, op: 'd' }); }
  522. /**
  523. * Serialize the body to an encoded string, where key-value pairs (separated by `=`) are
  524. * separated by `&`s.
  525. * @return {?}
  526. */
  527. toString() {
  528. this.init();
  529. return this.keys()
  530. .map((/**
  531. * @param {?} key
  532. * @return {?}
  533. */
  534. key => {
  535. /** @type {?} */
  536. const eKey = this.encoder.encodeKey(key);
  537. return (/** @type {?} */ ((/** @type {?} */ (this.map)).get(key))).map((/**
  538. * @param {?} value
  539. * @return {?}
  540. */
  541. value => eKey + '=' + this.encoder.encodeValue(value)))
  542. .join('&');
  543. }))
  544. .join('&');
  545. }
  546. /**
  547. * @private
  548. * @param {?} update
  549. * @return {?}
  550. */
  551. clone(update) {
  552. /** @type {?} */
  553. const clone = new HttpParams((/** @type {?} */ ({ encoder: this.encoder })));
  554. clone.cloneFrom = this.cloneFrom || this;
  555. clone.updates = (this.updates || []).concat([update]);
  556. return clone;
  557. }
  558. /**
  559. * @private
  560. * @return {?}
  561. */
  562. init() {
  563. if (this.map === null) {
  564. this.map = new Map();
  565. }
  566. if (this.cloneFrom !== null) {
  567. this.cloneFrom.init();
  568. this.cloneFrom.keys().forEach((/**
  569. * @param {?} key
  570. * @return {?}
  571. */
  572. key => (/** @type {?} */ (this.map)).set(key, (/** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ (this.cloneFrom)).map)).get(key))))));
  573. (/** @type {?} */ (this.updates)).forEach((/**
  574. * @param {?} update
  575. * @return {?}
  576. */
  577. update => {
  578. switch (update.op) {
  579. case 'a':
  580. case 's':
  581. /** @type {?} */
  582. const base = (update.op === 'a' ? (/** @type {?} */ (this.map)).get(update.param) : undefined) || [];
  583. base.push((/** @type {?} */ (update.value)));
  584. (/** @type {?} */ (this.map)).set(update.param, base);
  585. break;
  586. case 'd':
  587. if (update.value !== undefined) {
  588. /** @type {?} */
  589. let base = (/** @type {?} */ (this.map)).get(update.param) || [];
  590. /** @type {?} */
  591. const idx = base.indexOf(update.value);
  592. if (idx !== -1) {
  593. base.splice(idx, 1);
  594. }
  595. if (base.length > 0) {
  596. (/** @type {?} */ (this.map)).set(update.param, base);
  597. }
  598. else {
  599. (/** @type {?} */ (this.map)).delete(update.param);
  600. }
  601. }
  602. else {
  603. (/** @type {?} */ (this.map)).delete(update.param);
  604. break;
  605. }
  606. }
  607. }));
  608. this.cloneFrom = this.updates = null;
  609. }
  610. }
  611. }
  612. /**
  613. * @fileoverview added by tsickle
  614. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  615. */
  616. /**
  617. * Determine whether the given HTTP method may include a body.
  618. * @param {?} method
  619. * @return {?}
  620. */
  621. function mightHaveBody(method) {
  622. switch (method) {
  623. case 'DELETE':
  624. case 'GET':
  625. case 'HEAD':
  626. case 'OPTIONS':
  627. case 'JSONP':
  628. return false;
  629. default:
  630. return true;
  631. }
  632. }
  633. /**
  634. * Safely assert whether the given value is an ArrayBuffer.
  635. *
  636. * In some execution environments ArrayBuffer is not defined.
  637. * @param {?} value
  638. * @return {?}
  639. */
  640. function isArrayBuffer(value) {
  641. return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
  642. }
  643. /**
  644. * Safely assert whether the given value is a Blob.
  645. *
  646. * In some execution environments Blob is not defined.
  647. * @param {?} value
  648. * @return {?}
  649. */
  650. function isBlob(value) {
  651. return typeof Blob !== 'undefined' && value instanceof Blob;
  652. }
  653. /**
  654. * Safely assert whether the given value is a FormData instance.
  655. *
  656. * In some execution environments FormData is not defined.
  657. * @param {?} value
  658. * @return {?}
  659. */
  660. function isFormData(value) {
  661. return typeof FormData !== 'undefined' && value instanceof FormData;
  662. }
  663. /**
  664. * An outgoing HTTP request with an optional typed body.
  665. *
  666. * `HttpRequest` represents an outgoing request, including URL, method,
  667. * headers, body, and other request configuration options. Instances should be
  668. * assumed to be immutable. To modify a `HttpRequest`, the `clone`
  669. * method should be used.
  670. *
  671. * \@publicApi
  672. * @template T
  673. */
  674. class HttpRequest {
  675. /**
  676. * @param {?} method
  677. * @param {?} url
  678. * @param {?=} third
  679. * @param {?=} fourth
  680. */
  681. constructor(method, url, third, fourth) {
  682. this.url = url;
  683. /**
  684. * The request body, or `null` if one isn't set.
  685. *
  686. * Bodies are not enforced to be immutable, as they can include a reference to any
  687. * user-defined data type. However, interceptors should take care to preserve
  688. * idempotence by treating them as such.
  689. */
  690. this.body = null;
  691. /**
  692. * Whether this request should be made in a way that exposes progress events.
  693. *
  694. * Progress events are expensive (change detection runs on each event) and so
  695. * they should only be requested if the consumer intends to monitor them.
  696. */
  697. this.reportProgress = false;
  698. /**
  699. * Whether this request should be sent with outgoing credentials (cookies).
  700. */
  701. this.withCredentials = false;
  702. /**
  703. * The expected response type of the server.
  704. *
  705. * This is used to parse the response appropriately before returning it to
  706. * the requestee.
  707. */
  708. this.responseType = 'json';
  709. this.method = method.toUpperCase();
  710. // Next, need to figure out which argument holds the HttpRequestInit
  711. // options, if any.
  712. /** @type {?} */
  713. let options;
  714. // Check whether a body argument is expected. The only valid way to omit
  715. // the body argument is to use a known no-body method like GET.
  716. if (mightHaveBody(this.method) || !!fourth) {
  717. // Body is the third argument, options are the fourth.
  718. this.body = (third !== undefined) ? (/** @type {?} */ (third)) : null;
  719. options = fourth;
  720. }
  721. else {
  722. // No body required, options are the third argument. The body stays null.
  723. options = (/** @type {?} */ (third));
  724. }
  725. // If options have been passed, interpret them.
  726. if (options) {
  727. // Normalize reportProgress and withCredentials.
  728. this.reportProgress = !!options.reportProgress;
  729. this.withCredentials = !!options.withCredentials;
  730. // Override default response type of 'json' if one is provided.
  731. if (!!options.responseType) {
  732. this.responseType = options.responseType;
  733. }
  734. // Override headers if they're provided.
  735. if (!!options.headers) {
  736. this.headers = options.headers;
  737. }
  738. if (!!options.params) {
  739. this.params = options.params;
  740. }
  741. }
  742. // If no headers have been passed in, construct a new HttpHeaders instance.
  743. if (!this.headers) {
  744. this.headers = new HttpHeaders();
  745. }
  746. // If no parameters have been passed in, construct a new HttpUrlEncodedParams instance.
  747. if (!this.params) {
  748. this.params = new HttpParams();
  749. this.urlWithParams = url;
  750. }
  751. else {
  752. // Encode the parameters to a string in preparation for inclusion in the URL.
  753. /** @type {?} */
  754. const params = this.params.toString();
  755. if (params.length === 0) {
  756. // No parameters, the visible URL is just the URL given at creation time.
  757. this.urlWithParams = url;
  758. }
  759. else {
  760. // Does the URL already have query parameters? Look for '?'.
  761. /** @type {?} */
  762. const qIdx = url.indexOf('?');
  763. // There are 3 cases to handle:
  764. // 1) No existing parameters -> append '?' followed by params.
  765. // 2) '?' exists and is followed by existing query string ->
  766. // append '&' followed by params.
  767. // 3) '?' exists at the end of the url -> append params directly.
  768. // This basically amounts to determining the character, if any, with
  769. // which to join the URL and parameters.
  770. /** @type {?} */
  771. const sep = qIdx === -1 ? '?' : (qIdx < url.length - 1 ? '&' : '');
  772. this.urlWithParams = url + sep + params;
  773. }
  774. }
  775. }
  776. /**
  777. * Transform the free-form body into a serialized format suitable for
  778. * transmission to the server.
  779. * @return {?}
  780. */
  781. serializeBody() {
  782. // If no body is present, no need to serialize it.
  783. if (this.body === null) {
  784. return null;
  785. }
  786. // Check whether the body is already in a serialized form. If so,
  787. // it can just be returned directly.
  788. if (isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) ||
  789. typeof this.body === 'string') {
  790. return this.body;
  791. }
  792. // Check whether the body is an instance of HttpUrlEncodedParams.
  793. if (this.body instanceof HttpParams) {
  794. return this.body.toString();
  795. }
  796. // Check whether the body is an object or array, and serialize with JSON if so.
  797. if (typeof this.body === 'object' || typeof this.body === 'boolean' ||
  798. Array.isArray(this.body)) {
  799. return JSON.stringify(this.body);
  800. }
  801. // Fall back on toString() for everything else.
  802. return ((/** @type {?} */ (this.body))).toString();
  803. }
  804. /**
  805. * Examine the body and attempt to infer an appropriate MIME type
  806. * for it.
  807. *
  808. * If no such type can be inferred, this method will return `null`.
  809. * @return {?}
  810. */
  811. detectContentTypeHeader() {
  812. // An empty body has no content type.
  813. if (this.body === null) {
  814. return null;
  815. }
  816. // FormData bodies rely on the browser's content type assignment.
  817. if (isFormData(this.body)) {
  818. return null;
  819. }
  820. // Blobs usually have their own content type. If it doesn't, then
  821. // no type can be inferred.
  822. if (isBlob(this.body)) {
  823. return this.body.type || null;
  824. }
  825. // Array buffers have unknown contents and thus no type can be inferred.
  826. if (isArrayBuffer(this.body)) {
  827. return null;
  828. }
  829. // Technically, strings could be a form of JSON data, but it's safe enough
  830. // to assume they're plain strings.
  831. if (typeof this.body === 'string') {
  832. return 'text/plain';
  833. }
  834. // `HttpUrlEncodedParams` has its own content-type.
  835. if (this.body instanceof HttpParams) {
  836. return 'application/x-www-form-urlencoded;charset=UTF-8';
  837. }
  838. // Arrays, objects, and numbers will be encoded as JSON.
  839. if (typeof this.body === 'object' || typeof this.body === 'number' ||
  840. Array.isArray(this.body)) {
  841. return 'application/json';
  842. }
  843. // No type could be inferred.
  844. return null;
  845. }
  846. /**
  847. * @param {?=} update
  848. * @return {?}
  849. */
  850. clone(update = {}) {
  851. // For method, url, and responseType, take the current value unless
  852. // it is overridden in the update hash.
  853. /** @type {?} */
  854. const method = update.method || this.method;
  855. /** @type {?} */
  856. const url = update.url || this.url;
  857. /** @type {?} */
  858. const responseType = update.responseType || this.responseType;
  859. // The body is somewhat special - a `null` value in update.body means
  860. // whatever current body is present is being overridden with an empty
  861. // body, whereas an `undefined` value in update.body implies no
  862. // override.
  863. /** @type {?} */
  864. const body = (update.body !== undefined) ? update.body : this.body;
  865. // Carefully handle the boolean options to differentiate between
  866. // `false` and `undefined` in the update args.
  867. /** @type {?} */
  868. const withCredentials = (update.withCredentials !== undefined) ? update.withCredentials : this.withCredentials;
  869. /** @type {?} */
  870. const reportProgress = (update.reportProgress !== undefined) ? update.reportProgress : this.reportProgress;
  871. // Headers and params may be appended to if `setHeaders` or
  872. // `setParams` are used.
  873. /** @type {?} */
  874. let headers = update.headers || this.headers;
  875. /** @type {?} */
  876. let params = update.params || this.params;
  877. // Check whether the caller has asked to add headers.
  878. if (update.setHeaders !== undefined) {
  879. // Set every requested header.
  880. headers =
  881. Object.keys(update.setHeaders)
  882. .reduce((/**
  883. * @param {?} headers
  884. * @param {?} name
  885. * @return {?}
  886. */
  887. (headers, name) => headers.set(name, (/** @type {?} */ (update.setHeaders))[name])), headers);
  888. }
  889. // Check whether the caller has asked to set params.
  890. if (update.setParams) {
  891. // Set every requested param.
  892. params = Object.keys(update.setParams)
  893. .reduce((/**
  894. * @param {?} params
  895. * @param {?} param
  896. * @return {?}
  897. */
  898. (params, param) => params.set(param, (/** @type {?} */ (update.setParams))[param])), params);
  899. }
  900. // Finally, construct the new HttpRequest using the pieces from above.
  901. return new HttpRequest(method, url, body, {
  902. params, headers, reportProgress, responseType, withCredentials,
  903. });
  904. }
  905. }
  906. /**
  907. * @fileoverview added by tsickle
  908. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  909. */
  910. /** @enum {number} */
  911. const HttpEventType = {
  912. /**
  913. * The request was sent out over the wire.
  914. */
  915. Sent: 0,
  916. /**
  917. * An upload progress event was received.
  918. */
  919. UploadProgress: 1,
  920. /**
  921. * The response status code and headers were received.
  922. */
  923. ResponseHeader: 2,
  924. /**
  925. * A download progress event was received.
  926. */
  927. DownloadProgress: 3,
  928. /**
  929. * The full response including the body was received.
  930. */
  931. Response: 4,
  932. /**
  933. * A custom event from an interceptor or a backend.
  934. */
  935. User: 5,
  936. };
  937. HttpEventType[HttpEventType.Sent] = 'Sent';
  938. HttpEventType[HttpEventType.UploadProgress] = 'UploadProgress';
  939. HttpEventType[HttpEventType.ResponseHeader] = 'ResponseHeader';
  940. HttpEventType[HttpEventType.DownloadProgress] = 'DownloadProgress';
  941. HttpEventType[HttpEventType.Response] = 'Response';
  942. HttpEventType[HttpEventType.User] = 'User';
  943. /**
  944. * Base class for both `HttpResponse` and `HttpHeaderResponse`.
  945. *
  946. * \@publicApi
  947. * @abstract
  948. */
  949. class HttpResponseBase {
  950. /**
  951. * Super-constructor for all responses.
  952. *
  953. * The single parameter accepted is an initialization hash. Any properties
  954. * of the response passed there will override the default values.
  955. * @param {?} init
  956. * @param {?=} defaultStatus
  957. * @param {?=} defaultStatusText
  958. */
  959. constructor(init, defaultStatus = 200, defaultStatusText = 'OK') {
  960. // If the hash has values passed, use them to initialize the response.
  961. // Otherwise use the default values.
  962. this.headers = init.headers || new HttpHeaders();
  963. this.status = init.status !== undefined ? init.status : defaultStatus;
  964. this.statusText = init.statusText || defaultStatusText;
  965. this.url = init.url || null;
  966. // Cache the ok value to avoid defining a getter.
  967. this.ok = this.status >= 200 && this.status < 300;
  968. }
  969. }
  970. /**
  971. * A partial HTTP response which only includes the status and header data,
  972. * but no response body.
  973. *
  974. * `HttpHeaderResponse` is a `HttpEvent` available on the response
  975. * event stream, only when progress events are requested.
  976. *
  977. * \@publicApi
  978. */
  979. class HttpHeaderResponse extends HttpResponseBase {
  980. /**
  981. * Create a new `HttpHeaderResponse` with the given parameters.
  982. * @param {?=} init
  983. */
  984. constructor(init = {}) {
  985. super(init);
  986. this.type = HttpEventType.ResponseHeader;
  987. }
  988. /**
  989. * Copy this `HttpHeaderResponse`, overriding its contents with the
  990. * given parameter hash.
  991. * @param {?=} update
  992. * @return {?}
  993. */
  994. clone(update = {}) {
  995. // Perform a straightforward initialization of the new HttpHeaderResponse,
  996. // overriding the current parameters with new ones if given.
  997. return new HttpHeaderResponse({
  998. headers: update.headers || this.headers,
  999. status: update.status !== undefined ? update.status : this.status,
  1000. statusText: update.statusText || this.statusText,
  1001. url: update.url || this.url || undefined,
  1002. });
  1003. }
  1004. }
  1005. /**
  1006. * A full HTTP response, including a typed response body (which may be `null`
  1007. * if one was not returned).
  1008. *
  1009. * `HttpResponse` is a `HttpEvent` available on the response event
  1010. * stream.
  1011. *
  1012. * \@publicApi
  1013. * @template T
  1014. */
  1015. class HttpResponse extends HttpResponseBase {
  1016. /**
  1017. * Construct a new `HttpResponse`.
  1018. * @param {?=} init
  1019. */
  1020. constructor(init = {}) {
  1021. super(init);
  1022. this.type = HttpEventType.Response;
  1023. this.body = init.body !== undefined ? init.body : null;
  1024. }
  1025. /**
  1026. * @param {?=} update
  1027. * @return {?}
  1028. */
  1029. clone(update = {}) {
  1030. return new HttpResponse({
  1031. body: (update.body !== undefined) ? update.body : this.body,
  1032. headers: update.headers || this.headers,
  1033. status: (update.status !== undefined) ? update.status : this.status,
  1034. statusText: update.statusText || this.statusText,
  1035. url: update.url || this.url || undefined,
  1036. });
  1037. }
  1038. }
  1039. /**
  1040. * A response that represents an error or failure, either from a
  1041. * non-successful HTTP status, an error while executing the request,
  1042. * or some other failure which occurred during the parsing of the response.
  1043. *
  1044. * Any error returned on the `Observable` response stream will be
  1045. * wrapped in an `HttpErrorResponse` to provide additional context about
  1046. * the state of the HTTP layer when the error occurred. The error property
  1047. * will contain either a wrapped Error object or the error response returned
  1048. * from the server.
  1049. *
  1050. * \@publicApi
  1051. */
  1052. class HttpErrorResponse extends HttpResponseBase {
  1053. /**
  1054. * @param {?} init
  1055. */
  1056. constructor(init) {
  1057. // Initialize with a default status of 0 / Unknown Error.
  1058. super(init, 0, 'Unknown Error');
  1059. this.name = 'HttpErrorResponse';
  1060. /**
  1061. * Errors are never okay, even when the status code is in the 2xx success range.
  1062. */
  1063. this.ok = false;
  1064. // If the response was successful, then this was a parse error. Otherwise, it was
  1065. // a protocol-level failure of some sort. Either the request failed in transit
  1066. // or the server returned an unsuccessful status code.
  1067. if (this.status >= 200 && this.status < 300) {
  1068. this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`;
  1069. }
  1070. else {
  1071. this.message =
  1072. `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${init.statusText}`;
  1073. }
  1074. this.error = init.error || null;
  1075. }
  1076. }
  1077. /**
  1078. * @fileoverview added by tsickle
  1079. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1080. */
  1081. /**
  1082. * Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
  1083. * the given `body`. This function clones the object and adds the body.
  1084. * @template T
  1085. * @param {?} options
  1086. * @param {?} body
  1087. * @return {?}
  1088. */
  1089. function addBody(options, body) {
  1090. return {
  1091. body,
  1092. headers: options.headers,
  1093. observe: options.observe,
  1094. params: options.params,
  1095. reportProgress: options.reportProgress,
  1096. responseType: options.responseType,
  1097. withCredentials: options.withCredentials,
  1098. };
  1099. }
  1100. /**
  1101. * Performs HTTP requests.
  1102. *
  1103. * `HttpClient` is available as an injectable class, with methods to perform HTTP requests.
  1104. * Each request method has multiple signatures, and the return type varies based on
  1105. * the signature that is called (mainly the values of `observe` and `responseType`).
  1106. *
  1107. *
  1108. * @see [HTTP Guide](guide/http)
  1109. *
  1110. *
  1111. * \@usageNotes
  1112. * Sample HTTP requests for the [Tour of Heroes](/tutorial/toh-pt0) application.
  1113. *
  1114. * ### HTTP Request Example
  1115. *
  1116. * ```
  1117. * // GET heroes whose name contains search term
  1118. * searchHeroes(term: string): observable<Hero[]>{
  1119. *
  1120. * const params = new HttpParams({fromString: 'name=term'});
  1121. * return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params});
  1122. * }
  1123. * ```
  1124. * ### JSONP Example
  1125. * ```
  1126. * requestJsonp(url, callback = 'callback') {
  1127. * return this.httpClient.jsonp(this.heroesURL, callback);
  1128. * }
  1129. * ```
  1130. *
  1131. *
  1132. * ### PATCH Example
  1133. * ```
  1134. * // PATCH one of the heroes' name
  1135. * patchHero (id: number, heroName: string): Observable<{}> {
  1136. * const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42
  1137. * return this.httpClient.patch(url, {name: heroName}, httpOptions)
  1138. * .pipe(catchError(this.handleError('patchHero')));
  1139. * }
  1140. * ```
  1141. *
  1142. * \@publicApi
  1143. */
  1144. class HttpClient {
  1145. /**
  1146. * @param {?} handler
  1147. */
  1148. constructor(handler) {
  1149. this.handler = handler;
  1150. }
  1151. /**
  1152. * Constructs an observable for a generic HTTP request that, when subscribed,
  1153. * fires the request through the chain of registered interceptors and on to the
  1154. * server.
  1155. *
  1156. * You can pass an `HttpRequest` directly as the only parameter. In this case,
  1157. * the call returns an observable of the raw `HttpEvent` stream.
  1158. *
  1159. * Alternatively you can pass an HTTP method as the first parameter,
  1160. * a URL string as the second, and an options hash containing the request body as the third.
  1161. * See `addBody()`. In this case, the specified `responseType` and `observe` options determine the
  1162. * type of returned observable.
  1163. * * The `responseType` value determines how a successful response body is parsed.
  1164. * * If `responseType` is the default `json`, you can pass a type interface for the resulting
  1165. * object as a type parameter to the call.
  1166. *
  1167. * The `observe` value determines the return type, according to what you are interested in
  1168. * observing.
  1169. * * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including
  1170. * progress events by default.
  1171. * * An `observe` value of response returns an observable of `HttpResponse<T>`,
  1172. * where the `T` parameter depends on the `responseType` and any optionally provided type
  1173. * parameter.
  1174. * * An `observe` value of body returns an observable of `<T>` with the same `T` body type.
  1175. *
  1176. * @param {?} first
  1177. * @param {?=} url
  1178. * @param {?=} options
  1179. * @return {?}
  1180. */
  1181. request(first, url, options = {}) {
  1182. /** @type {?} */
  1183. let req;
  1184. // First, check whether the primary argument is an instance of `HttpRequest`.
  1185. if (first instanceof HttpRequest) {
  1186. // It is. The other arguments must be undefined (per the signatures) and can be
  1187. // ignored.
  1188. req = (/** @type {?} */ (first));
  1189. }
  1190. else {
  1191. // It's a string, so it represents a URL. Construct a request based on it,
  1192. // and incorporate the remaining arguments (assuming `GET` unless a method is
  1193. // provided.
  1194. // Figure out the headers.
  1195. /** @type {?} */
  1196. let headers = undefined;
  1197. if (options.headers instanceof HttpHeaders) {
  1198. headers = options.headers;
  1199. }
  1200. else {
  1201. headers = new HttpHeaders(options.headers);
  1202. }
  1203. // Sort out parameters.
  1204. /** @type {?} */
  1205. let params = undefined;
  1206. if (!!options.params) {
  1207. if (options.params instanceof HttpParams) {
  1208. params = options.params;
  1209. }
  1210. else {
  1211. params = new HttpParams((/** @type {?} */ ({ fromObject: options.params })));
  1212. }
  1213. }
  1214. // Construct the request.
  1215. req = new HttpRequest(first, (/** @type {?} */ (url)), (options.body !== undefined ? options.body : null), {
  1216. headers,
  1217. params,
  1218. reportProgress: options.reportProgress,
  1219. // By default, JSON is assumed to be returned for all calls.
  1220. responseType: options.responseType || 'json',
  1221. withCredentials: options.withCredentials,
  1222. });
  1223. }
  1224. // Start with an Observable.of() the initial request, and run the handler (which
  1225. // includes all interceptors) inside a concatMap(). This way, the handler runs
  1226. // inside an Observable chain, which causes interceptors to be re-run on every
  1227. // subscription (this also makes retries re-run the handler, including interceptors).
  1228. /** @type {?} */
  1229. const events$ = of(req).pipe(concatMap((/**
  1230. * @param {?} req
  1231. * @return {?}
  1232. */
  1233. (req) => this.handler.handle(req))));
  1234. // If coming via the API signature which accepts a previously constructed HttpRequest,
  1235. // the only option is to get the event stream. Otherwise, return the event stream if
  1236. // that is what was requested.
  1237. if (first instanceof HttpRequest || options.observe === 'events') {
  1238. return events$;
  1239. }
  1240. // The requested stream contains either the full response or the body. In either
  1241. // case, the first step is to filter the event stream to extract a stream of
  1242. // responses(s).
  1243. /** @type {?} */
  1244. const res$ = (/** @type {?} */ (events$.pipe(filter((/**
  1245. * @param {?} event
  1246. * @return {?}
  1247. */
  1248. (event) => event instanceof HttpResponse)))));
  1249. // Decide which stream to return.
  1250. switch (options.observe || 'body') {
  1251. case 'body':
  1252. // The requested stream is the body. Map the response stream to the response
  1253. // body. This could be done more simply, but a misbehaving interceptor might
  1254. // transform the response body into a different format and ignore the requested
  1255. // responseType. Guard against this by validating that the response is of the
  1256. // requested type.
  1257. switch (req.responseType) {
  1258. case 'arraybuffer':
  1259. return res$.pipe(map((/**
  1260. * @param {?} res
  1261. * @return {?}
  1262. */
  1263. (res) => {
  1264. // Validate that the body is an ArrayBuffer.
  1265. if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
  1266. throw new Error('Response is not an ArrayBuffer.');
  1267. }
  1268. return res.body;
  1269. })));
  1270. case 'blob':
  1271. return res$.pipe(map((/**
  1272. * @param {?} res
  1273. * @return {?}
  1274. */
  1275. (res) => {
  1276. // Validate that the body is a Blob.
  1277. if (res.body !== null && !(res.body instanceof Blob)) {
  1278. throw new Error('Response is not a Blob.');
  1279. }
  1280. return res.body;
  1281. })));
  1282. case 'text':
  1283. return res$.pipe(map((/**
  1284. * @param {?} res
  1285. * @return {?}
  1286. */
  1287. (res) => {
  1288. // Validate that the body is a string.
  1289. if (res.body !== null && typeof res.body !== 'string') {
  1290. throw new Error('Response is not a string.');
  1291. }
  1292. return res.body;
  1293. })));
  1294. case 'json':
  1295. default:
  1296. // No validation needed for JSON responses, as they can be of any type.
  1297. return res$.pipe(map((/**
  1298. * @param {?} res
  1299. * @return {?}
  1300. */
  1301. (res) => res.body)));
  1302. }
  1303. case 'response':
  1304. // The response stream was requested directly, so return it.
  1305. return res$;
  1306. default:
  1307. // Guard against new future observe types being added.
  1308. throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);
  1309. }
  1310. }
  1311. /**
  1312. * Constructs an observable that, when subscribed, causes the configured
  1313. * `DELETE` request to execute on the server. See the individual overloads for
  1314. * details on the return type.
  1315. *
  1316. * @param {?} url The endpoint URL.
  1317. * @param {?=} options The HTTP options to send with the request.
  1318. *
  1319. * @return {?}
  1320. */
  1321. delete(url, options = {}) {
  1322. return this.request('DELETE', url, (/** @type {?} */ (options)));
  1323. }
  1324. /**
  1325. * Constructs an observable that, when subscribed, causes the configured
  1326. * `GET` request to execute on the server. See the individual overloads for
  1327. * details on the return type.
  1328. * @param {?} url
  1329. * @param {?=} options
  1330. * @return {?}
  1331. */
  1332. get(url, options = {}) {
  1333. return this.request('GET', url, (/** @type {?} */ (options)));
  1334. }
  1335. /**
  1336. * Constructs an observable that, when subscribed, causes the configured
  1337. * `HEAD` request to execute on the server. The `HEAD` method returns
  1338. * meta information about the resource without transferring the
  1339. * resource itself. See the individual overloads for
  1340. * details on the return type.
  1341. * @param {?} url
  1342. * @param {?=} options
  1343. * @return {?}
  1344. */
  1345. head(url, options = {}) {
  1346. return this.request('HEAD', url, (/** @type {?} */ (options)));
  1347. }
  1348. /**
  1349. * Constructs an `Observable` that, when subscribed, causes a request with the special method
  1350. * `JSONP` to be dispatched via the interceptor pipeline.
  1351. * The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain
  1352. * API endpoints that don't support newer,
  1353. * and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol.
  1354. * JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the
  1355. * requests even if the API endpoint is not located on the same domain (origin) as the client-side
  1356. * application making the request.
  1357. * The endpoint API must support JSONP callback for JSONP requests to work.
  1358. * The resource API returns the JSON response wrapped in a callback function.
  1359. * You can pass the callback function name as one of the query parameters.
  1360. * Note that JSONP requests can only be used with `GET` requests.
  1361. *
  1362. * @template T
  1363. * @param {?} url The resource URL.
  1364. * @param {?} callbackParam The callback function name.
  1365. *
  1366. * @return {?}
  1367. */
  1368. jsonp(url, callbackParam) {
  1369. return this.request('JSONP', url, {
  1370. params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'),
  1371. observe: 'body',
  1372. responseType: 'json',
  1373. });
  1374. }
  1375. /**
  1376. * Constructs an `Observable` that, when subscribed, causes the configured
  1377. * `OPTIONS` request to execute on the server. This method allows the client
  1378. * to determine the supported HTTP methods and other capabilites of an endpoint,
  1379. * without implying a resource action. See the individual overloads for
  1380. * details on the return type.
  1381. * @param {?} url
  1382. * @param {?=} options
  1383. * @return {?}
  1384. */
  1385. options(url, options = {}) {
  1386. return this.request('OPTIONS', url, (/** @type {?} */ (options)));
  1387. }
  1388. /**
  1389. * Constructs an observable that, when subscribed, causes the configured
  1390. * `PATCH` request to execute on the server. See the individual overloads for
  1391. * details on the return type.
  1392. * @param {?} url
  1393. * @param {?} body
  1394. * @param {?=} options
  1395. * @return {?}
  1396. */
  1397. patch(url, body, options = {}) {
  1398. return this.request('PATCH', url, addBody(options, body));
  1399. }
  1400. /**
  1401. * Constructs an observable that, when subscribed, causes the configured
  1402. * `POST` request to execute on the server. The server responds with the location of
  1403. * the replaced resource. See the individual overloads for
  1404. * details on the return type.
  1405. * @param {?} url
  1406. * @param {?} body
  1407. * @param {?=} options
  1408. * @return {?}
  1409. */
  1410. post(url, body, options = {}) {
  1411. return this.request('POST', url, addBody(options, body));
  1412. }
  1413. /**
  1414. * Constructs an observable that, when subscribed, causes the configured
  1415. * `PUT` request to execute on the server. The `PUT` method replaces an existing resource
  1416. * with a new set of values.
  1417. * See the individual overloads for details on the return type.
  1418. * @param {?} url
  1419. * @param {?} body
  1420. * @param {?=} options
  1421. * @return {?}
  1422. */
  1423. put(url, body, options = {}) {
  1424. return this.request('PUT', url, addBody(options, body));
  1425. }
  1426. }
  1427. HttpClient.decorators = [
  1428. { type: Injectable }
  1429. ];
  1430. /** @nocollapse */
  1431. HttpClient.ctorParameters = () => [
  1432. { type: HttpHandler }
  1433. ];
  1434. /**
  1435. * @fileoverview added by tsickle
  1436. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1437. */
  1438. /**
  1439. * `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`.
  1440. *
  1441. *
  1442. */
  1443. class HttpInterceptorHandler {
  1444. /**
  1445. * @param {?} next
  1446. * @param {?} interceptor
  1447. */
  1448. constructor(next, interceptor) {
  1449. this.next = next;
  1450. this.interceptor = interceptor;
  1451. }
  1452. /**
  1453. * @param {?} req
  1454. * @return {?}
  1455. */
  1456. handle(req) {
  1457. return this.interceptor.intercept(req, this.next);
  1458. }
  1459. }
  1460. /**
  1461. * A multi-provider token which represents the array of `HttpInterceptor`s that
  1462. * are registered.
  1463. *
  1464. * \@publicApi
  1465. * @type {?}
  1466. */
  1467. const HTTP_INTERCEPTORS = new InjectionToken('HTTP_INTERCEPTORS');
  1468. class NoopInterceptor {
  1469. /**
  1470. * @param {?} req
  1471. * @param {?} next
  1472. * @return {?}
  1473. */
  1474. intercept(req, next) {
  1475. return next.handle(req);
  1476. }
  1477. }
  1478. NoopInterceptor.decorators = [
  1479. { type: Injectable }
  1480. ];
  1481. /**
  1482. * @fileoverview added by tsickle
  1483. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1484. */
  1485. // Every request made through JSONP needs a callback name that's unique across the
  1486. // whole page. Each request is assigned an id and the callback name is constructed
  1487. // from that. The next id to be assigned is tracked in a global variable here that
  1488. // is shared among all applications on the page.
  1489. /** @type {?} */
  1490. let nextRequestId = 0;
  1491. // Error text given when a JSONP script is injected, but doesn't invoke the callback
  1492. // passed in its URL.
  1493. /** @type {?} */
  1494. const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
  1495. // Error text given when a request is passed to the JsonpClientBackend that doesn't
  1496. // have a request method JSONP.
  1497. /** @type {?} */
  1498. const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.';
  1499. /** @type {?} */
  1500. const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.';
  1501. /**
  1502. * DI token/abstract type representing a map of JSONP callbacks.
  1503. *
  1504. * In the browser, this should always be the `window` object.
  1505. *
  1506. *
  1507. * @abstract
  1508. */
  1509. class JsonpCallbackContext {
  1510. }
  1511. /**
  1512. * `HttpBackend` that only processes `HttpRequest` with the JSONP method,
  1513. * by performing JSONP style requests.
  1514. *
  1515. * \@publicApi
  1516. */
  1517. class JsonpClientBackend {
  1518. /**
  1519. * @param {?} callbackMap
  1520. * @param {?} document
  1521. */
  1522. constructor(callbackMap, document) {
  1523. this.callbackMap = callbackMap;
  1524. this.document = document;
  1525. }
  1526. /**
  1527. * Get the name of the next callback method, by incrementing the global `nextRequestId`.
  1528. * @private
  1529. * @return {?}
  1530. */
  1531. nextCallback() { return `ng_jsonp_callback_${nextRequestId++}`; }
  1532. /**
  1533. * Process a JSONP request and return an event stream of the results.
  1534. * @param {?} req
  1535. * @return {?}
  1536. */
  1537. handle(req) {
  1538. // Firstly, check both the method and response type. If either doesn't match
  1539. // then the request was improperly routed here and cannot be handled.
  1540. if (req.method !== 'JSONP') {
  1541. throw new Error(JSONP_ERR_WRONG_METHOD);
  1542. }
  1543. else if (req.responseType !== 'json') {
  1544. throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE);
  1545. }
  1546. // Everything else happens inside the Observable boundary.
  1547. return new Observable((/**
  1548. * @param {?} observer
  1549. * @return {?}
  1550. */
  1551. (observer) => {
  1552. // The first step to make a request is to generate the callback name, and replace the
  1553. // callback placeholder in the URL with the name. Care has to be taken here to ensure
  1554. // a trailing &, if matched, gets inserted back into the URL in the correct place.
  1555. /** @type {?} */
  1556. const callback = this.nextCallback();
  1557. /** @type {?} */
  1558. const url = req.urlWithParams.replace(/=JSONP_CALLBACK(&|$)/, `=${callback}$1`);
  1559. // Construct the <script> tag and point it at the URL.
  1560. /** @type {?} */
  1561. const node = this.document.createElement('script');
  1562. node.src = url;
  1563. // A JSONP request requires waiting for multiple callbacks. These variables
  1564. // are closed over and track state across those callbacks.
  1565. // The response object, if one has been received, or null otherwise.
  1566. /** @type {?} */
  1567. let body = null;
  1568. // Whether the response callback has been called.
  1569. /** @type {?} */
  1570. let finished = false;
  1571. // Whether the request has been cancelled (and thus any other callbacks)
  1572. // should be ignored.
  1573. /** @type {?} */
  1574. let cancelled = false;
  1575. // Set the response callback in this.callbackMap (which will be the window
  1576. // object in the browser. The script being loaded via the <script> tag will
  1577. // eventually call this callback.
  1578. this.callbackMap[callback] = (/**
  1579. * @param {?=} data
  1580. * @return {?}
  1581. */
  1582. (data) => {
  1583. // Data has been received from the JSONP script. Firstly, delete this callback.
  1584. delete this.callbackMap[callback];
  1585. // Next, make sure the request wasn't cancelled in the meantime.
  1586. if (cancelled) {
  1587. return;
  1588. }
  1589. // Set state to indicate data was received.
  1590. body = data;
  1591. finished = true;
  1592. });
  1593. // cleanup() is a utility closure that removes the <script> from the page and
  1594. // the response callback from the window. This logic is used in both the
  1595. // success, error, and cancellation paths, so it's extracted out for convenience.
  1596. /** @type {?} */
  1597. const cleanup = (/**
  1598. * @return {?}
  1599. */
  1600. () => {
  1601. // Remove the <script> tag if it's still on the page.
  1602. if (node.parentNode) {
  1603. node.parentNode.removeChild(node);
  1604. }
  1605. // Remove the response callback from the callbackMap (window object in the
  1606. // browser).
  1607. delete this.callbackMap[callback];
  1608. });
  1609. // onLoad() is the success callback which runs after the response callback
  1610. // if the JSONP script loads successfully. The event itself is unimportant.
  1611. // If something went wrong, onLoad() may run without the response callback
  1612. // having been invoked.
  1613. /** @type {?} */
  1614. const onLoad = (/**
  1615. * @param {?} event
  1616. * @return {?}
  1617. */
  1618. (event) => {
  1619. // Do nothing if the request has been cancelled.
  1620. if (cancelled) {
  1621. return;
  1622. }
  1623. // Cleanup the page.
  1624. cleanup();
  1625. // Check whether the response callback has run.
  1626. if (!finished) {
  1627. // It hasn't, something went wrong with the request. Return an error via
  1628. // the Observable error path. All JSONP errors have status 0.
  1629. observer.error(new HttpErrorResponse({
  1630. url,
  1631. status: 0,
  1632. statusText: 'JSONP Error',
  1633. error: new Error(JSONP_ERR_NO_CALLBACK),
  1634. }));
  1635. return;
  1636. }
  1637. // Success. body either contains the response body or null if none was
  1638. // returned.
  1639. observer.next(new HttpResponse({
  1640. body,
  1641. status: 200,
  1642. statusText: 'OK', url,
  1643. }));
  1644. // Complete the stream, the response is over.
  1645. observer.complete();
  1646. });
  1647. // onError() is the error callback, which runs if the script returned generates
  1648. // a Javascript error. It emits the error via the Observable error channel as
  1649. // a HttpErrorResponse.
  1650. /** @type {?} */
  1651. const onError = (/**
  1652. * @param {?} error
  1653. * @return {?}
  1654. */
  1655. (error) => {
  1656. // If the request was already cancelled, no need to emit anything.
  1657. if (cancelled) {
  1658. return;
  1659. }
  1660. cleanup();
  1661. // Wrap the error in a HttpErrorResponse.
  1662. observer.error(new HttpErrorResponse({
  1663. error,
  1664. status: 0,
  1665. statusText: 'JSONP Error', url,
  1666. }));
  1667. });
  1668. // Subscribe to both the success (load) and error events on the <script> tag,
  1669. // and add it to the page.
  1670. node.addEventListener('load', onLoad);
  1671. node.addEventListener('error', onError);
  1672. this.document.body.appendChild(node);
  1673. // The request has now been successfully sent.
  1674. observer.next({ type: HttpEventType.Sent });
  1675. // Cancellation handler.
  1676. return (/**
  1677. * @return {?}
  1678. */
  1679. () => {
  1680. // Track the cancellation so event listeners won't do anything even if already scheduled.
  1681. cancelled = true;
  1682. // Remove the event listeners so they won't run if the events later fire.
  1683. node.removeEventListener('load', onLoad);
  1684. node.removeEventListener('error', onError);
  1685. // And finally, clean up the page.
  1686. cleanup();
  1687. });
  1688. }));
  1689. }
  1690. }
  1691. JsonpClientBackend.decorators = [
  1692. { type: Injectable }
  1693. ];
  1694. /** @nocollapse */
  1695. JsonpClientBackend.ctorParameters = () => [
  1696. { type: JsonpCallbackContext },
  1697. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
  1698. ];
  1699. /**
  1700. * An `HttpInterceptor` which identifies requests with the method JSONP and
  1701. * shifts them to the `JsonpClientBackend`.
  1702. *
  1703. * \@publicApi
  1704. */
  1705. class JsonpInterceptor {
  1706. /**
  1707. * @param {?} jsonp
  1708. */
  1709. constructor(jsonp) {
  1710. this.jsonp = jsonp;
  1711. }
  1712. /**
  1713. * @param {?} req
  1714. * @param {?} next
  1715. * @return {?}
  1716. */
  1717. intercept(req, next) {
  1718. if (req.method === 'JSONP') {
  1719. return this.jsonp.handle((/** @type {?} */ (req)));
  1720. }
  1721. // Fall through for normal HTTP requests.
  1722. return next.handle(req);
  1723. }
  1724. }
  1725. JsonpInterceptor.decorators = [
  1726. { type: Injectable }
  1727. ];
  1728. /** @nocollapse */
  1729. JsonpInterceptor.ctorParameters = () => [
  1730. { type: JsonpClientBackend }
  1731. ];
  1732. /**
  1733. * @fileoverview added by tsickle
  1734. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1735. */
  1736. /** @type {?} */
  1737. const XSSI_PREFIX = /^\)\]\}',?\n/;
  1738. /**
  1739. * Determine an appropriate URL for the response, by checking either
  1740. * XMLHttpRequest.responseURL or the X-Request-URL header.
  1741. * @param {?} xhr
  1742. * @return {?}
  1743. */
  1744. function getResponseUrl(xhr) {
  1745. if ('responseURL' in xhr && xhr.responseURL) {
  1746. return xhr.responseURL;
  1747. }
  1748. if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
  1749. return xhr.getResponseHeader('X-Request-URL');
  1750. }
  1751. return null;
  1752. }
  1753. /**
  1754. * A wrapper around the `XMLHttpRequest` constructor.
  1755. *
  1756. * \@publicApi
  1757. * @abstract
  1758. */
  1759. class XhrFactory {
  1760. }
  1761. /**
  1762. * A factory for \@{link HttpXhrBackend} that uses the `XMLHttpRequest` browser API.
  1763. *
  1764. *
  1765. */
  1766. class BrowserXhr {
  1767. constructor() { }
  1768. /**
  1769. * @return {?}
  1770. */
  1771. build() { return (/** @type {?} */ ((new XMLHttpRequest()))); }
  1772. }
  1773. BrowserXhr.decorators = [
  1774. { type: Injectable }
  1775. ];
  1776. /** @nocollapse */
  1777. BrowserXhr.ctorParameters = () => [];
  1778. /**
  1779. * An `HttpBackend` which uses the XMLHttpRequest API to send
  1780. * requests to a backend server.
  1781. *
  1782. * \@publicApi
  1783. */
  1784. class HttpXhrBackend {
  1785. /**
  1786. * @param {?} xhrFactory
  1787. */
  1788. constructor(xhrFactory) {
  1789. this.xhrFactory = xhrFactory;
  1790. }
  1791. /**
  1792. * Process a request and return a stream of response events.
  1793. * @param {?} req
  1794. * @return {?}
  1795. */
  1796. handle(req) {
  1797. // Quick check to give a better error message when a user attempts to use
  1798. // HttpClient.jsonp() without installing the JsonpClientModule
  1799. if (req.method === 'JSONP') {
  1800. throw new Error(`Attempted to construct Jsonp request without JsonpClientModule installed.`);
  1801. }
  1802. // Everything happens on Observable subscription.
  1803. return new Observable((/**
  1804. * @param {?} observer
  1805. * @return {?}
  1806. */
  1807. (observer) => {
  1808. // Start by setting up the XHR object with request method, URL, and withCredentials flag.
  1809. /** @type {?} */
  1810. const xhr = this.xhrFactory.build();
  1811. xhr.open(req.method, req.urlWithParams);
  1812. if (!!req.withCredentials) {
  1813. xhr.withCredentials = true;
  1814. }
  1815. // Add all the requested headers.
  1816. req.headers.forEach((/**
  1817. * @param {?} name
  1818. * @param {?} values
  1819. * @return {?}
  1820. */
  1821. (name, values) => xhr.setRequestHeader(name, values.join(','))));
  1822. // Add an Accept header if one isn't present already.
  1823. if (!req.headers.has('Accept')) {
  1824. xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
  1825. }
  1826. // Auto-detect the Content-Type header if one isn't present already.
  1827. if (!req.headers.has('Content-Type')) {
  1828. /** @type {?} */
  1829. const detectedType = req.detectContentTypeHeader();
  1830. // Sometimes Content-Type detection fails.
  1831. if (detectedType !== null) {
  1832. xhr.setRequestHeader('Content-Type', detectedType);
  1833. }
  1834. }
  1835. // Set the responseType if one was requested.
  1836. if (req.responseType) {
  1837. /** @type {?} */
  1838. const responseType = req.responseType.toLowerCase();
  1839. // JSON responses need to be processed as text. This is because if the server
  1840. // returns an XSSI-prefixed JSON response, the browser will fail to parse it,
  1841. // xhr.response will be null, and xhr.responseText cannot be accessed to
  1842. // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON
  1843. // is parsed by first requesting text and then applying JSON.parse.
  1844. xhr.responseType = (/** @type {?} */ (((responseType !== 'json') ? responseType : 'text')));
  1845. }
  1846. // Serialize the request body if one is present. If not, this will be set to null.
  1847. /** @type {?} */
  1848. const reqBody = req.serializeBody();
  1849. // If progress events are enabled, response headers will be delivered
  1850. // in two events - the HttpHeaderResponse event and the full HttpResponse
  1851. // event. However, since response headers don't change in between these
  1852. // two events, it doesn't make sense to parse them twice. So headerResponse
  1853. // caches the data extracted from the response whenever it's first parsed,
  1854. // to ensure parsing isn't duplicated.
  1855. /** @type {?} */
  1856. let headerResponse = null;
  1857. // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest
  1858. // state, and memoizes it into headerResponse.
  1859. /** @type {?} */
  1860. const partialFromXhr = (/**
  1861. * @return {?}
  1862. */
  1863. () => {
  1864. if (headerResponse !== null) {
  1865. return headerResponse;
  1866. }
  1867. // Read status and normalize an IE9 bug (http://bugs.jquery.com/ticket/1450).
  1868. /** @type {?} */
  1869. const status = xhr.status === 1223 ? 204 : xhr.status;
  1870. /** @type {?} */
  1871. const statusText = xhr.statusText || 'OK';
  1872. // Parse headers from XMLHttpRequest - this step is lazy.
  1873. /** @type {?} */
  1874. const headers = new HttpHeaders(xhr.getAllResponseHeaders());
  1875. // Read the response URL from the XMLHttpResponse instance and fall back on the
  1876. // request URL.
  1877. /** @type {?} */
  1878. const url = getResponseUrl(xhr) || req.url;
  1879. // Construct the HttpHeaderResponse and memoize it.
  1880. headerResponse = new HttpHeaderResponse({ headers, status, statusText, url });
  1881. return headerResponse;
  1882. });
  1883. // Next, a few closures are defined for the various events which XMLHttpRequest can
  1884. // emit. This allows them to be unregistered as event listeners later.
  1885. // First up is the load event, which represents a response being fully available.
  1886. /** @type {?} */
  1887. const onLoad = (/**
  1888. * @return {?}
  1889. */
  1890. () => {
  1891. // Read response state from the memoized partial data.
  1892. let { headers, status, statusText, url } = partialFromXhr();
  1893. // The body will be read out if present.
  1894. /** @type {?} */
  1895. let body = null;
  1896. if (status !== 204) {
  1897. // Use XMLHttpRequest.response if set, responseText otherwise.
  1898. body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
  1899. }
  1900. // Normalize another potential bug (this one comes from CORS).
  1901. if (status === 0) {
  1902. status = !!body ? 200 : 0;
  1903. }
  1904. // ok determines whether the response will be transmitted on the event or
  1905. // error channel. Unsuccessful status codes (not 2xx) will always be errors,
  1906. // but a successful status code can still result in an error if the user
  1907. // asked for JSON data and the body cannot be parsed as such.
  1908. /** @type {?} */
  1909. let ok = status >= 200 && status < 300;
  1910. // Check whether the body needs to be parsed as JSON (in many cases the browser
  1911. // will have done that already).
  1912. if (req.responseType === 'json' && typeof body === 'string') {
  1913. // Save the original body, before attempting XSSI prefix stripping.
  1914. /** @type {?} */
  1915. const originalBody = body;
  1916. body = body.replace(XSSI_PREFIX, '');
  1917. try {
  1918. // Attempt the parse. If it fails, a parse error should be delivered to the user.
  1919. body = body !== '' ? JSON.parse(body) : null;
  1920. }
  1921. catch (error) {
  1922. // Since the JSON.parse failed, it's reasonable to assume this might not have been a
  1923. // JSON response. Restore the original body (including any XSSI prefix) to deliver
  1924. // a better error response.
  1925. body = originalBody;
  1926. // If this was an error request to begin with, leave it as a string, it probably
  1927. // just isn't JSON. Otherwise, deliver the parsing error to the user.
  1928. if (ok) {
  1929. // Even though the response status was 2xx, this is still an error.
  1930. ok = false;
  1931. // The parse error contains the text of the body that failed to parse.
  1932. body = (/** @type {?} */ ({ error, text: body }));
  1933. }
  1934. }
  1935. }
  1936. if (ok) {
  1937. // A successful response is delivered on the event stream.
  1938. observer.next(new HttpResponse({
  1939. body,
  1940. headers,
  1941. status,
  1942. statusText,
  1943. url: url || undefined,
  1944. }));
  1945. // The full body has been received and delivered, no further events
  1946. // are possible. This request is complete.
  1947. observer.complete();
  1948. }
  1949. else {
  1950. // An unsuccessful request is delivered on the error channel.
  1951. observer.error(new HttpErrorResponse({
  1952. // The error in this case is the response body (error from the server).
  1953. error: body,
  1954. headers,
  1955. status,
  1956. statusText,
  1957. url: url || undefined,
  1958. }));
  1959. }
  1960. });
  1961. // The onError callback is called when something goes wrong at the network level.
  1962. // Connection timeout, DNS error, offline, etc. These are actual errors, and are
  1963. // transmitted on the error channel.
  1964. /** @type {?} */
  1965. const onError = (/**
  1966. * @param {?} error
  1967. * @return {?}
  1968. */
  1969. (error) => {
  1970. const { url } = partialFromXhr();
  1971. /** @type {?} */
  1972. const res = new HttpErrorResponse({
  1973. error,
  1974. status: xhr.status || 0,
  1975. statusText: xhr.statusText || 'Unknown Error',
  1976. url: url || undefined,
  1977. });
  1978. observer.error(res);
  1979. });
  1980. // The sentHeaders flag tracks whether the HttpResponseHeaders event
  1981. // has been sent on the stream. This is necessary to track if progress
  1982. // is enabled since the event will be sent on only the first download
  1983. // progerss event.
  1984. /** @type {?} */
  1985. let sentHeaders = false;
  1986. // The download progress event handler, which is only registered if
  1987. // progress events are enabled.
  1988. /** @type {?} */
  1989. const onDownProgress = (/**
  1990. * @param {?} event
  1991. * @return {?}
  1992. */
  1993. (event) => {
  1994. // Send the HttpResponseHeaders event if it hasn't been sent already.
  1995. if (!sentHeaders) {
  1996. observer.next(partialFromXhr());
  1997. sentHeaders = true;
  1998. }
  1999. // Start building the download progress event to deliver on the response
  2000. // event stream.
  2001. /** @type {?} */
  2002. let progressEvent = {
  2003. type: HttpEventType.DownloadProgress,
  2004. loaded: event.loaded,
  2005. };
  2006. // Set the total number of bytes in the event if it's available.
  2007. if (event.lengthComputable) {
  2008. progressEvent.total = event.total;
  2009. }
  2010. // If the request was for text content and a partial response is
  2011. // available on XMLHttpRequest, include it in the progress event
  2012. // to allow for streaming reads.
  2013. if (req.responseType === 'text' && !!xhr.responseText) {
  2014. progressEvent.partialText = xhr.responseText;
  2015. }
  2016. // Finally, fire the event.
  2017. observer.next(progressEvent);
  2018. });
  2019. // The upload progress event handler, which is only registered if
  2020. // progress events are enabled.
  2021. /** @type {?} */
  2022. const onUpProgress = (/**
  2023. * @param {?} event
  2024. * @return {?}
  2025. */
  2026. (event) => {
  2027. // Upload progress events are simpler. Begin building the progress
  2028. // event.
  2029. /** @type {?} */
  2030. let progress = {
  2031. type: HttpEventType.UploadProgress,
  2032. loaded: event.loaded,
  2033. };
  2034. // If the total number of bytes being uploaded is available, include
  2035. // it.
  2036. if (event.lengthComputable) {
  2037. progress.total = event.total;
  2038. }
  2039. // Send the event.
  2040. observer.next(progress);
  2041. });
  2042. // By default, register for load and error events.
  2043. xhr.addEventListener('load', onLoad);
  2044. xhr.addEventListener('error', onError);
  2045. // Progress events are only enabled if requested.
  2046. if (req.reportProgress) {
  2047. // Download progress is always enabled if requested.
  2048. xhr.addEventListener('progress', onDownProgress);
  2049. // Upload progress depends on whether there is a body to upload.
  2050. if (reqBody !== null && xhr.upload) {
  2051. xhr.upload.addEventListener('progress', onUpProgress);
  2052. }
  2053. }
  2054. // Fire the request, and notify the event stream that it was fired.
  2055. xhr.send((/** @type {?} */ (reqBody)));
  2056. observer.next({ type: HttpEventType.Sent });
  2057. // This is the return from the Observable function, which is the
  2058. // request cancellation handler.
  2059. return (/**
  2060. * @return {?}
  2061. */
  2062. () => {
  2063. // On a cancellation, remove all registered event listeners.
  2064. xhr.removeEventListener('error', onError);
  2065. xhr.removeEventListener('load', onLoad);
  2066. if (req.reportProgress) {
  2067. xhr.removeEventListener('progress', onDownProgress);
  2068. if (reqBody !== null && xhr.upload) {
  2069. xhr.upload.removeEventListener('progress', onUpProgress);
  2070. }
  2071. }
  2072. // Finally, abort the in-flight request.
  2073. xhr.abort();
  2074. });
  2075. }));
  2076. }
  2077. }
  2078. HttpXhrBackend.decorators = [
  2079. { type: Injectable }
  2080. ];
  2081. /** @nocollapse */
  2082. HttpXhrBackend.ctorParameters = () => [
  2083. { type: XhrFactory }
  2084. ];
  2085. /**
  2086. * @fileoverview added by tsickle
  2087. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2088. */
  2089. /** @type {?} */
  2090. const XSRF_COOKIE_NAME = new InjectionToken('XSRF_COOKIE_NAME');
  2091. /** @type {?} */
  2092. const XSRF_HEADER_NAME = new InjectionToken('XSRF_HEADER_NAME');
  2093. /**
  2094. * Retrieves the current XSRF token to use with the next outgoing request.
  2095. *
  2096. * \@publicApi
  2097. * @abstract
  2098. */
  2099. class HttpXsrfTokenExtractor {
  2100. }
  2101. /**
  2102. * `HttpXsrfTokenExtractor` which retrieves the token from a cookie.
  2103. */
  2104. class HttpXsrfCookieExtractor {
  2105. /**
  2106. * @param {?} doc
  2107. * @param {?} platform
  2108. * @param {?} cookieName
  2109. */
  2110. constructor(doc, platform, cookieName) {
  2111. this.doc = doc;
  2112. this.platform = platform;
  2113. this.cookieName = cookieName;
  2114. this.lastCookieString = '';
  2115. this.lastToken = null;
  2116. /**
  2117. * \@internal for testing
  2118. */
  2119. this.parseCount = 0;
  2120. }
  2121. /**
  2122. * @return {?}
  2123. */
  2124. getToken() {
  2125. if (this.platform === 'server') {
  2126. return null;
  2127. }
  2128. /** @type {?} */
  2129. const cookieString = this.doc.cookie || '';
  2130. if (cookieString !== this.lastCookieString) {
  2131. this.parseCount++;
  2132. this.lastToken = ɵparseCookieValue(cookieString, this.cookieName);
  2133. this.lastCookieString = cookieString;
  2134. }
  2135. return this.lastToken;
  2136. }
  2137. }
  2138. HttpXsrfCookieExtractor.decorators = [
  2139. { type: Injectable }
  2140. ];
  2141. /** @nocollapse */
  2142. HttpXsrfCookieExtractor.ctorParameters = () => [
  2143. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
  2144. { type: String, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] },
  2145. { type: String, decorators: [{ type: Inject, args: [XSRF_COOKIE_NAME,] }] }
  2146. ];
  2147. /**
  2148. * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests.
  2149. */
  2150. class HttpXsrfInterceptor {
  2151. /**
  2152. * @param {?} tokenService
  2153. * @param {?} headerName
  2154. */
  2155. constructor(tokenService, headerName) {
  2156. this.tokenService = tokenService;
  2157. this.headerName = headerName;
  2158. }
  2159. /**
  2160. * @param {?} req
  2161. * @param {?} next
  2162. * @return {?}
  2163. */
  2164. intercept(req, next) {
  2165. /** @type {?} */
  2166. const lcUrl = req.url.toLowerCase();
  2167. // Skip both non-mutating requests and absolute URLs.
  2168. // Non-mutating requests don't require a token, and absolute URLs require special handling
  2169. // anyway as the cookie set
  2170. // on our origin is not the same as the token expected by another origin.
  2171. if (req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') ||
  2172. lcUrl.startsWith('https://')) {
  2173. return next.handle(req);
  2174. }
  2175. /** @type {?} */
  2176. const token = this.tokenService.getToken();
  2177. // Be careful not to overwrite an existing header of the same name.
  2178. if (token !== null && !req.headers.has(this.headerName)) {
  2179. req = req.clone({ headers: req.headers.set(this.headerName, token) });
  2180. }
  2181. return next.handle(req);
  2182. }
  2183. }
  2184. HttpXsrfInterceptor.decorators = [
  2185. { type: Injectable }
  2186. ];
  2187. /** @nocollapse */
  2188. HttpXsrfInterceptor.ctorParameters = () => [
  2189. { type: HttpXsrfTokenExtractor },
  2190. { type: String, decorators: [{ type: Inject, args: [XSRF_HEADER_NAME,] }] }
  2191. ];
  2192. /**
  2193. * @fileoverview added by tsickle
  2194. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2195. */
  2196. /**
  2197. * An injectable `HttpHandler` that applies multiple interceptors
  2198. * to a request before passing it to the given `HttpBackend`.
  2199. *
  2200. * The interceptors are loaded lazily from the injector, to allow
  2201. * interceptors to themselves inject classes depending indirectly
  2202. * on `HttpInterceptingHandler` itself.
  2203. * @see `HttpInterceptor`
  2204. */
  2205. class HttpInterceptingHandler {
  2206. /**
  2207. * @param {?} backend
  2208. * @param {?} injector
  2209. */
  2210. constructor(backend, injector) {
  2211. this.backend = backend;
  2212. this.injector = injector;
  2213. this.chain = null;
  2214. }
  2215. /**
  2216. * @param {?} req
  2217. * @return {?}
  2218. */
  2219. handle(req) {
  2220. if (this.chain === null) {
  2221. /** @type {?} */
  2222. const interceptors = this.injector.get(HTTP_INTERCEPTORS, []);
  2223. this.chain = interceptors.reduceRight((/**
  2224. * @param {?} next
  2225. * @param {?} interceptor
  2226. * @return {?}
  2227. */
  2228. (next, interceptor) => new HttpInterceptorHandler(next, interceptor)), this.backend);
  2229. }
  2230. return this.chain.handle(req);
  2231. }
  2232. }
  2233. HttpInterceptingHandler.decorators = [
  2234. { type: Injectable }
  2235. ];
  2236. /** @nocollapse */
  2237. HttpInterceptingHandler.ctorParameters = () => [
  2238. { type: HttpBackend },
  2239. { type: Injector }
  2240. ];
  2241. /**
  2242. * Factory function that determines where to store JSONP callbacks.
  2243. *
  2244. * Ordinarily JSONP callbacks are stored on the `window` object, but this may not exist
  2245. * in test environments. In that case, callbacks are stored on an anonymous object instead.
  2246. *
  2247. *
  2248. * @return {?}
  2249. */
  2250. function jsonpCallbackContext() {
  2251. if (typeof window === 'object') {
  2252. return window;
  2253. }
  2254. return {};
  2255. }
  2256. /**
  2257. * Configures XSRF protection support for outgoing requests.
  2258. *
  2259. * For a server that supports a cookie-based XSRF protection system,
  2260. * use directly to configure XSRF protection with the correct
  2261. * cookie and header names.
  2262. *
  2263. * If no names are supplied, the default cookie name is `XSRF-TOKEN`
  2264. * and the default header name is `X-XSRF-TOKEN`.
  2265. *
  2266. * \@publicApi
  2267. */
  2268. class HttpClientXsrfModule {
  2269. /**
  2270. * Disable the default XSRF protection.
  2271. * @return {?}
  2272. */
  2273. static disable() {
  2274. return {
  2275. ngModule: HttpClientXsrfModule,
  2276. providers: [
  2277. { provide: HttpXsrfInterceptor, useClass: NoopInterceptor },
  2278. ],
  2279. };
  2280. }
  2281. /**
  2282. * Configure XSRF protection.
  2283. * @param {?=} options An object that can specify either or both
  2284. * cookie name or header name.
  2285. * - Cookie name default is `XSRF-TOKEN`.
  2286. * - Header name default is `X-XSRF-TOKEN`.
  2287. *
  2288. * @return {?}
  2289. */
  2290. static withOptions(options = {}) {
  2291. return {
  2292. ngModule: HttpClientXsrfModule,
  2293. providers: [
  2294. options.cookieName ? { provide: XSRF_COOKIE_NAME, useValue: options.cookieName } : [],
  2295. options.headerName ? { provide: XSRF_HEADER_NAME, useValue: options.headerName } : [],
  2296. ],
  2297. };
  2298. }
  2299. }
  2300. HttpClientXsrfModule.decorators = [
  2301. { type: NgModule, args: [{
  2302. providers: [
  2303. HttpXsrfInterceptor,
  2304. { provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true },
  2305. { provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor },
  2306. { provide: XSRF_COOKIE_NAME, useValue: 'XSRF-TOKEN' },
  2307. { provide: XSRF_HEADER_NAME, useValue: 'X-XSRF-TOKEN' },
  2308. ],
  2309. },] }
  2310. ];
  2311. /**
  2312. * Configures the [dependency injector](guide/glossary#injector) for `HttpClient`
  2313. * with supporting services for XSRF. Automatically imported by `HttpClientModule`.
  2314. *
  2315. * You can add interceptors to the chain behind `HttpClient` by binding them to the
  2316. * multiprovider for built-in [DI token](guide/glossary#di-token) `HTTP_INTERCEPTORS`.
  2317. *
  2318. * \@publicApi
  2319. */
  2320. class HttpClientModule {
  2321. }
  2322. HttpClientModule.decorators = [
  2323. { type: NgModule, args: [{
  2324. /**
  2325. * Optional configuration for XSRF protection.
  2326. */
  2327. imports: [
  2328. HttpClientXsrfModule.withOptions({
  2329. cookieName: 'XSRF-TOKEN',
  2330. headerName: 'X-XSRF-TOKEN',
  2331. }),
  2332. ],
  2333. /**
  2334. * Configures the [dependency injector](guide/glossary#injector) where it is imported
  2335. * with supporting services for HTTP communications.
  2336. */
  2337. providers: [
  2338. HttpClient,
  2339. { provide: HttpHandler, useClass: HttpInterceptingHandler },
  2340. HttpXhrBackend,
  2341. { provide: HttpBackend, useExisting: HttpXhrBackend },
  2342. BrowserXhr,
  2343. { provide: XhrFactory, useExisting: BrowserXhr },
  2344. ],
  2345. },] }
  2346. ];
  2347. /**
  2348. * Configures the [dependency injector](guide/glossary#injector) for `HttpClient`
  2349. * with supporting services for JSONP.
  2350. * Without this module, Jsonp requests reach the backend
  2351. * with method JSONP, where they are rejected.
  2352. *
  2353. * You can add interceptors to the chain behind `HttpClient` by binding them to the
  2354. * multiprovider for built-in [DI token](guide/glossary#di-token) `HTTP_INTERCEPTORS`.
  2355. *
  2356. * \@publicApi
  2357. */
  2358. class HttpClientJsonpModule {
  2359. }
  2360. HttpClientJsonpModule.decorators = [
  2361. { type: NgModule, args: [{
  2362. providers: [
  2363. JsonpClientBackend,
  2364. { provide: JsonpCallbackContext, useFactory: jsonpCallbackContext },
  2365. { provide: HTTP_INTERCEPTORS, useClass: JsonpInterceptor, multi: true },
  2366. ],
  2367. },] }
  2368. ];
  2369. /**
  2370. * @fileoverview added by tsickle
  2371. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2372. */
  2373. /**
  2374. * @fileoverview added by tsickle
  2375. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2376. */
  2377. /**
  2378. * Generated bundle index. Do not edit.
  2379. */
  2380. export { NoopInterceptor as ɵangular_packages_common_http_http_a, JsonpCallbackContext as ɵangular_packages_common_http_http_b, jsonpCallbackContext as ɵangular_packages_common_http_http_c, BrowserXhr as ɵangular_packages_common_http_http_d, HttpXsrfCookieExtractor as ɵangular_packages_common_http_http_g, HttpXsrfInterceptor as ɵangular_packages_common_http_http_h, XSRF_COOKIE_NAME as ɵangular_packages_common_http_http_e, XSRF_HEADER_NAME as ɵangular_packages_common_http_http_f, HttpBackend, HttpHandler, HttpClient, HttpHeaders, HTTP_INTERCEPTORS, JsonpClientBackend, JsonpInterceptor, HttpClientJsonpModule, HttpClientModule, HttpClientXsrfModule, HttpInterceptingHandler as ɵHttpInterceptingHandler, HttpParams, HttpUrlEncodingCodec, HttpRequest, HttpErrorResponse, HttpEventType, HttpHeaderResponse, HttpResponse, HttpResponseBase, HttpXhrBackend, XhrFactory, HttpXsrfTokenExtractor };
  2381. //# sourceMappingURL=http.js.map