Project

General

Profile

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