UNPKG

297 kBJavaScriptView Raw
1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2'use strict';/**
3 * @module
4 * @description
5 * The `di` module provides dependency injection container services.
6 */
7"use strict";
8function __export(m) {
9 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
10}
11var metadata_1 = require('./di/metadata');
12exports.InjectMetadata = metadata_1.InjectMetadata;
13exports.OptionalMetadata = metadata_1.OptionalMetadata;
14exports.InjectableMetadata = metadata_1.InjectableMetadata;
15exports.SelfMetadata = metadata_1.SelfMetadata;
16exports.HostMetadata = metadata_1.HostMetadata;
17exports.SkipSelfMetadata = metadata_1.SkipSelfMetadata;
18exports.DependencyMetadata = metadata_1.DependencyMetadata;
19// we have to reexport * because Dart and TS export two different sets of types
20__export(require('./di/decorators'));
21var forward_ref_1 = require('./di/forward_ref');
22exports.forwardRef = forward_ref_1.forwardRef;
23exports.resolveForwardRef = forward_ref_1.resolveForwardRef;
24var injector_1 = require('./di/injector');
25exports.Injector = injector_1.Injector;
26var reflective_injector_1 = require('./di/reflective_injector');
27exports.ReflectiveInjector = reflective_injector_1.ReflectiveInjector;
28var provider_1 = require('./di/provider');
29exports.Binding = provider_1.Binding;
30exports.ProviderBuilder = provider_1.ProviderBuilder;
31exports.bind = provider_1.bind;
32exports.Provider = provider_1.Provider;
33exports.provide = provider_1.provide;
34var reflective_provider_1 = require('./di/reflective_provider');
35exports.ResolvedReflectiveFactory = reflective_provider_1.ResolvedReflectiveFactory;
36exports.ReflectiveDependency = reflective_provider_1.ReflectiveDependency;
37var reflective_key_1 = require('./di/reflective_key');
38exports.ReflectiveKey = reflective_key_1.ReflectiveKey;
39var reflective_exceptions_1 = require('./di/reflective_exceptions');
40exports.NoProviderError = reflective_exceptions_1.NoProviderError;
41exports.AbstractProviderError = reflective_exceptions_1.AbstractProviderError;
42exports.CyclicDependencyError = reflective_exceptions_1.CyclicDependencyError;
43exports.InstantiationError = reflective_exceptions_1.InstantiationError;
44exports.InvalidProviderError = reflective_exceptions_1.InvalidProviderError;
45exports.NoAnnotationError = reflective_exceptions_1.NoAnnotationError;
46exports.OutOfBoundsError = reflective_exceptions_1.OutOfBoundsError;
47var opaque_token_1 = require('./di/opaque_token');
48exports.OpaqueToken = opaque_token_1.OpaqueToken;
49},{"./di/decorators":2,"./di/forward_ref":3,"./di/injector":4,"./di/metadata":5,"./di/opaque_token":6,"./di/provider":7,"./di/reflective_exceptions":8,"./di/reflective_injector":9,"./di/reflective_key":10,"./di/reflective_provider":11}],2:[function(require,module,exports){
50'use strict';"use strict";
51var metadata_1 = require('./metadata');
52var decorators_1 = require('../util/decorators');
53/**
54 * Factory for creating {@link InjectMetadata}.
55 */
56exports.Inject = decorators_1.makeParamDecorator(metadata_1.InjectMetadata);
57/**
58 * Factory for creating {@link OptionalMetadata}.
59 */
60exports.Optional = decorators_1.makeParamDecorator(metadata_1.OptionalMetadata);
61/**
62 * Factory for creating {@link InjectableMetadata}.
63 */
64exports.Injectable = decorators_1.makeDecorator(metadata_1.InjectableMetadata);
65/**
66 * Factory for creating {@link SelfMetadata}.
67 */
68exports.Self = decorators_1.makeParamDecorator(metadata_1.SelfMetadata);
69/**
70 * Factory for creating {@link HostMetadata}.
71 */
72exports.Host = decorators_1.makeParamDecorator(metadata_1.HostMetadata);
73/**
74 * Factory for creating {@link SkipSelfMetadata}.
75 */
76exports.SkipSelf = decorators_1.makeParamDecorator(metadata_1.SkipSelfMetadata);
77},{"../util/decorators":16,"./metadata":5}],3:[function(require,module,exports){
78'use strict';"use strict";
79var lang_1 = require('angular2/src/facade/lang');
80/**
81 * Allows to refer to references which are not yet defined.
82 *
83 * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
84 * DI is declared,
85 * but not yet defined. It is also used when the `token` which we use when creating a query is not
86 * yet defined.
87 *
88 * ### Example
89 * {@example core/di/ts/forward_ref/forward_ref.ts region='forward_ref'}
90 */
91function forwardRef(forwardRefFn) {
92 forwardRefFn.__forward_ref__ = forwardRef;
93 forwardRefFn.toString = function () { return lang_1.stringify(this()); };
94 return forwardRefFn;
95}
96exports.forwardRef = forwardRef;
97/**
98 * Lazily retrieves the reference value from a forwardRef.
99 *
100 * Acts as the identity function when given a non-forward-ref value.
101 *
102 * ### Example ([live demo](http://plnkr.co/edit/GU72mJrk1fiodChcmiDR?p=preview))
103 *
104 * ```typescript
105 * var ref = forwardRef(() => "refValue");
106 * expect(resolveForwardRef(ref)).toEqual("refValue");
107 * expect(resolveForwardRef("regularValue")).toEqual("regularValue");
108 * ```
109 *
110 * See: {@link forwardRef}
111 */
112function resolveForwardRef(type) {
113 if (lang_1.isFunction(type) && type.hasOwnProperty('__forward_ref__') &&
114 type.__forward_ref__ === forwardRef) {
115 return type();
116 }
117 else {
118 return type;
119 }
120}
121exports.resolveForwardRef = resolveForwardRef;
122},{"angular2/src/facade/lang":22}],4:[function(require,module,exports){
123'use strict';"use strict";
124var lang_1 = require('angular2/src/facade/lang');
125var exceptions_1 = require('angular2/src/facade/exceptions');
126var _THROW_IF_NOT_FOUND = lang_1.CONST_EXPR(new Object());
127exports.THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
128var Injector = (function () {
129 function Injector() {
130 }
131 /**
132 * Retrieves an instance from the injector based on the provided token.
133 * If not found:
134 * - Throws {@link NoProviderError} if no `notFoundValue` that is not equal to
135 * Injector.THROW_IF_NOT_FOUND is given
136 * - Returns the `notFoundValue` otherwise
137 *
138 * ### Example ([live demo](http://plnkr.co/edit/HeXSHg?p=preview))
139 *
140 * ```typescript
141 * var injector = ReflectiveInjector.resolveAndCreate([
142 * provide("validToken", {useValue: "Value"})
143 * ]);
144 * expect(injector.get("validToken")).toEqual("Value");
145 * expect(() => injector.get("invalidToken")).toThrowError();
146 * ```
147 *
148 * `Injector` returns itself when given `Injector` as a token.
149 *
150 * ```typescript
151 * var injector = ReflectiveInjector.resolveAndCreate([]);
152 * expect(injector.get(Injector)).toBe(injector);
153 * ```
154 */
155 Injector.prototype.get = function (token, notFoundValue) { return exceptions_1.unimplemented(); };
156 Injector.THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
157 return Injector;
158}());
159exports.Injector = Injector;
160},{"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],5:[function(require,module,exports){
161'use strict';"use strict";
162var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
163 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
164 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
165 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
166 return c > 3 && r && Object.defineProperty(target, key, r), r;
167};
168var __metadata = (this && this.__metadata) || function (k, v) {
169 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
170};
171var lang_1 = require("angular2/src/facade/lang");
172/**
173 * A parameter metadata that specifies a dependency.
174 *
175 * ### Example ([live demo](http://plnkr.co/edit/6uHYJK?p=preview))
176 *
177 * ```typescript
178 * class Engine {}
179 *
180 * @Injectable()
181 * class Car {
182 * engine;
183 * constructor(@Inject("MyEngine") engine:Engine) {
184 * this.engine = engine;
185 * }
186 * }
187 *
188 * var injector = Injector.resolveAndCreate([
189 * provide("MyEngine", {useClass: Engine}),
190 * Car
191 * ]);
192 *
193 * expect(injector.get(Car).engine instanceof Engine).toBe(true);
194 * ```
195 *
196 * When `@Inject()` is not present, {@link Injector} will use the type annotation of the parameter.
197 *
198 * ### Example
199 *
200 * ```typescript
201 * class Engine {}
202 *
203 * @Injectable()
204 * class Car {
205 * constructor(public engine: Engine) {} //same as constructor(@Inject(Engine) engine:Engine)
206 * }
207 *
208 * var injector = Injector.resolveAndCreate([Engine, Car]);
209 * expect(injector.get(Car).engine instanceof Engine).toBe(true);
210 * ```
211 */
212var InjectMetadata = (function () {
213 function InjectMetadata(token) {
214 this.token = token;
215 }
216 InjectMetadata.prototype.toString = function () { return "@Inject(" + lang_1.stringify(this.token) + ")"; };
217 InjectMetadata = __decorate([
218 lang_1.CONST(),
219 __metadata('design:paramtypes', [Object])
220 ], InjectMetadata);
221 return InjectMetadata;
222}());
223exports.InjectMetadata = InjectMetadata;
224/**
225 * A parameter metadata that marks a dependency as optional. {@link Injector} provides `null` if
226 * the dependency is not found.
227 *
228 * ### Example ([live demo](http://plnkr.co/edit/AsryOm?p=preview))
229 *
230 * ```typescript
231 * class Engine {}
232 *
233 * @Injectable()
234 * class Car {
235 * engine;
236 * constructor(@Optional() engine:Engine) {
237 * this.engine = engine;
238 * }
239 * }
240 *
241 * var injector = Injector.resolveAndCreate([Car]);
242 * expect(injector.get(Car).engine).toBeNull();
243 * ```
244 */
245var OptionalMetadata = (function () {
246 function OptionalMetadata() {
247 }
248 OptionalMetadata.prototype.toString = function () { return "@Optional()"; };
249 OptionalMetadata = __decorate([
250 lang_1.CONST(),
251 __metadata('design:paramtypes', [])
252 ], OptionalMetadata);
253 return OptionalMetadata;
254}());
255exports.OptionalMetadata = OptionalMetadata;
256/**
257 * `DependencyMetadata` is used by the framework to extend DI.
258 * This is internal to Angular and should not be used directly.
259 */
260var DependencyMetadata = (function () {
261 function DependencyMetadata() {
262 }
263 Object.defineProperty(DependencyMetadata.prototype, "token", {
264 get: function () { return null; },
265 enumerable: true,
266 configurable: true
267 });
268 DependencyMetadata = __decorate([
269 lang_1.CONST(),
270 __metadata('design:paramtypes', [])
271 ], DependencyMetadata);
272 return DependencyMetadata;
273}());
274exports.DependencyMetadata = DependencyMetadata;
275/**
276 * A marker metadata that marks a class as available to {@link Injector} for creation.
277 *
278 * ### Example ([live demo](http://plnkr.co/edit/Wk4DMQ?p=preview))
279 *
280 * ```typescript
281 * @Injectable()
282 * class UsefulService {}
283 *
284 * @Injectable()
285 * class NeedsService {
286 * constructor(public service:UsefulService) {}
287 * }
288 *
289 * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]);
290 * expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
291 * ```
292 * {@link Injector} will throw {@link NoAnnotationError} when trying to instantiate a class that
293 * does not have `@Injectable` marker, as shown in the example below.
294 *
295 * ```typescript
296 * class UsefulService {}
297 *
298 * class NeedsService {
299 * constructor(public service:UsefulService) {}
300 * }
301 *
302 * var injector = Injector.resolveAndCreate([NeedsService, UsefulService]);
303 * expect(() => injector.get(NeedsService)).toThrowError();
304 * ```
305 */
306var InjectableMetadata = (function () {
307 function InjectableMetadata() {
308 }
309 InjectableMetadata = __decorate([
310 lang_1.CONST(),
311 __metadata('design:paramtypes', [])
312 ], InjectableMetadata);
313 return InjectableMetadata;
314}());
315exports.InjectableMetadata = InjectableMetadata;
316/**
317 * Specifies that an {@link Injector} should retrieve a dependency only from itself.
318 *
319 * ### Example ([live demo](http://plnkr.co/edit/NeagAg?p=preview))
320 *
321 * ```typescript
322 * class Dependency {
323 * }
324 *
325 * @Injectable()
326 * class NeedsDependency {
327 * dependency;
328 * constructor(@Self() dependency:Dependency) {
329 * this.dependency = dependency;
330 * }
331 * }
332 *
333 * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]);
334 * var nd = inj.get(NeedsDependency);
335 *
336 * expect(nd.dependency instanceof Dependency).toBe(true);
337 *
338 * var inj = Injector.resolveAndCreate([Dependency]);
339 * var child = inj.resolveAndCreateChild([NeedsDependency]);
340 * expect(() => child.get(NeedsDependency)).toThrowError();
341 * ```
342 */
343var SelfMetadata = (function () {
344 function SelfMetadata() {
345 }
346 SelfMetadata.prototype.toString = function () { return "@Self()"; };
347 SelfMetadata = __decorate([
348 lang_1.CONST(),
349 __metadata('design:paramtypes', [])
350 ], SelfMetadata);
351 return SelfMetadata;
352}());
353exports.SelfMetadata = SelfMetadata;
354/**
355 * Specifies that the dependency resolution should start from the parent injector.
356 *
357 * ### Example ([live demo](http://plnkr.co/edit/Wchdzb?p=preview))
358 *
359 * ```typescript
360 * class Dependency {
361 * }
362 *
363 * @Injectable()
364 * class NeedsDependency {
365 * dependency;
366 * constructor(@SkipSelf() dependency:Dependency) {
367 * this.dependency = dependency;
368 * }
369 * }
370 *
371 * var parent = Injector.resolveAndCreate([Dependency]);
372 * var child = parent.resolveAndCreateChild([NeedsDependency]);
373 * expect(child.get(NeedsDependency).dependency instanceof Depedency).toBe(true);
374 *
375 * var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]);
376 * expect(() => inj.get(NeedsDependency)).toThrowError();
377 * ```
378 */
379var SkipSelfMetadata = (function () {
380 function SkipSelfMetadata() {
381 }
382 SkipSelfMetadata.prototype.toString = function () { return "@SkipSelf()"; };
383 SkipSelfMetadata = __decorate([
384 lang_1.CONST(),
385 __metadata('design:paramtypes', [])
386 ], SkipSelfMetadata);
387 return SkipSelfMetadata;
388}());
389exports.SkipSelfMetadata = SkipSelfMetadata;
390/**
391 * Specifies that an injector should retrieve a dependency from any injector until reaching the
392 * closest host.
393 *
394 * In Angular, a component element is automatically declared as a host for all the injectors in
395 * its view.
396 *
397 * ### Example ([live demo](http://plnkr.co/edit/GX79pV?p=preview))
398 *
399 * In the following example `App` contains `ParentCmp`, which contains `ChildDirective`.
400 * So `ParentCmp` is the host of `ChildDirective`.
401 *
402 * `ChildDirective` depends on two services: `HostService` and `OtherService`.
403 * `HostService` is defined at `ParentCmp`, and `OtherService` is defined at `App`.
404 *
405 *```typescript
406 * class OtherService {}
407 * class HostService {}
408 *
409 * @Directive({
410 * selector: 'child-directive'
411 * })
412 * class ChildDirective {
413 * constructor(@Optional() @Host() os:OtherService, @Optional() @Host() hs:HostService){
414 * console.log("os is null", os);
415 * console.log("hs is NOT null", hs);
416 * }
417 * }
418 *
419 * @Component({
420 * selector: 'parent-cmp',
421 * providers: [HostService],
422 * template: `
423 * Dir: <child-directive></child-directive>
424 * `,
425 * directives: [ChildDirective]
426 * })
427 * class ParentCmp {
428 * }
429 *
430 * @Component({
431 * selector: 'app',
432 * providers: [OtherService],
433 * template: `
434 * Parent: <parent-cmp></parent-cmp>
435 * `,
436 * directives: [ParentCmp]
437 * })
438 * class App {
439 * }
440 *
441 * bootstrap(App);
442 *```
443 */
444var HostMetadata = (function () {
445 function HostMetadata() {
446 }
447 HostMetadata.prototype.toString = function () { return "@Host()"; };
448 HostMetadata = __decorate([
449 lang_1.CONST(),
450 __metadata('design:paramtypes', [])
451 ], HostMetadata);
452 return HostMetadata;
453}());
454exports.HostMetadata = HostMetadata;
455},{"angular2/src/facade/lang":22}],6:[function(require,module,exports){
456'use strict';"use strict";
457var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
458 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
459 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
460 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
461 return c > 3 && r && Object.defineProperty(target, key, r), r;
462};
463var __metadata = (this && this.__metadata) || function (k, v) {
464 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
465};
466var lang_1 = require('angular2/src/facade/lang');
467/**
468 * Creates a token that can be used in a DI Provider.
469 *
470 * ### Example ([live demo](http://plnkr.co/edit/Ys9ezXpj2Mnoy3Uc8KBp?p=preview))
471 *
472 * ```typescript
473 * var t = new OpaqueToken("value");
474 *
475 * var injector = Injector.resolveAndCreate([
476 * provide(t, {useValue: "bindingValue"})
477 * ]);
478 *
479 * expect(injector.get(t)).toEqual("bindingValue");
480 * ```
481 *
482 * Using an `OpaqueToken` is preferable to using strings as tokens because of possible collisions
483 * caused by multiple providers using the same string as two different tokens.
484 *
485 * Using an `OpaqueToken` is preferable to using an `Object` as tokens because it provides better
486 * error messages.
487 */
488var OpaqueToken = (function () {
489 function OpaqueToken(_desc) {
490 this._desc = _desc;
491 }
492 OpaqueToken.prototype.toString = function () { return "Token " + this._desc; };
493 OpaqueToken = __decorate([
494 lang_1.CONST(),
495 __metadata('design:paramtypes', [String])
496 ], OpaqueToken);
497 return OpaqueToken;
498}());
499exports.OpaqueToken = OpaqueToken;
500},{"angular2/src/facade/lang":22}],7:[function(require,module,exports){
501'use strict';"use strict";
502var __extends = (this && this.__extends) || function (d, b) {
503 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
504 function __() { this.constructor = d; }
505 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
506};
507var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
508 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
509 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
510 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
511 return c > 3 && r && Object.defineProperty(target, key, r), r;
512};
513var __metadata = (this && this.__metadata) || function (k, v) {
514 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
515};
516var lang_1 = require('angular2/src/facade/lang');
517var exceptions_1 = require('angular2/src/facade/exceptions');
518/**
519 * Describes how the {@link Injector} should instantiate a given token.
520 *
521 * See {@link provide}.
522 *
523 * ### Example ([live demo](http://plnkr.co/edit/GNAyj6K6PfYg2NBzgwZ5?p%3Dpreview&p=preview))
524 *
525 * ```javascript
526 * var injector = Injector.resolveAndCreate([
527 * new Provider("message", { useValue: 'Hello' })
528 * ]);
529 *
530 * expect(injector.get("message")).toEqual('Hello');
531 * ```
532 */
533var Provider = (function () {
534 function Provider(token, _a) {
535 var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
536 this.token = token;
537 this.useClass = useClass;
538 this.useValue = useValue;
539 this.useExisting = useExisting;
540 this.useFactory = useFactory;
541 this.dependencies = deps;
542 this._multi = multi;
543 }
544 Object.defineProperty(Provider.prototype, "multi", {
545 // TODO: Provide a full working example after alpha38 is released.
546 /**
547 * Creates multiple providers matching the same token (a multi-provider).
548 *
549 * Multi-providers are used for creating pluggable service, where the system comes
550 * with some default providers, and the user can register additional providers.
551 * The combination of the default providers and the additional providers will be
552 * used to drive the behavior of the system.
553 *
554 * ### Example
555 *
556 * ```typescript
557 * var injector = Injector.resolveAndCreate([
558 * new Provider("Strings", { useValue: "String1", multi: true}),
559 * new Provider("Strings", { useValue: "String2", multi: true})
560 * ]);
561 *
562 * expect(injector.get("Strings")).toEqual(["String1", "String2"]);
563 * ```
564 *
565 * Multi-providers and regular providers cannot be mixed. The following
566 * will throw an exception:
567 *
568 * ```typescript
569 * var injector = Injector.resolveAndCreate([
570 * new Provider("Strings", { useValue: "String1", multi: true }),
571 * new Provider("Strings", { useValue: "String2"})
572 * ]);
573 * ```
574 */
575 get: function () { return lang_1.normalizeBool(this._multi); },
576 enumerable: true,
577 configurable: true
578 });
579 Provider = __decorate([
580 lang_1.CONST(),
581 __metadata('design:paramtypes', [Object, Object])
582 ], Provider);
583 return Provider;
584}());
585exports.Provider = Provider;
586/**
587 * See {@link Provider} instead.
588 *
589 * @deprecated
590 */
591var Binding = (function (_super) {
592 __extends(Binding, _super);
593 function Binding(token, _a) {
594 var toClass = _a.toClass, toValue = _a.toValue, toAlias = _a.toAlias, toFactory = _a.toFactory, deps = _a.deps, multi = _a.multi;
595 _super.call(this, token, {
596 useClass: toClass,
597 useValue: toValue,
598 useExisting: toAlias,
599 useFactory: toFactory,
600 deps: deps,
601 multi: multi
602 });
603 }
604 Object.defineProperty(Binding.prototype, "toClass", {
605 /**
606 * @deprecated
607 */
608 get: function () { return this.useClass; },
609 enumerable: true,
610 configurable: true
611 });
612 Object.defineProperty(Binding.prototype, "toAlias", {
613 /**
614 * @deprecated
615 */
616 get: function () { return this.useExisting; },
617 enumerable: true,
618 configurable: true
619 });
620 Object.defineProperty(Binding.prototype, "toFactory", {
621 /**
622 * @deprecated
623 */
624 get: function () { return this.useFactory; },
625 enumerable: true,
626 configurable: true
627 });
628 Object.defineProperty(Binding.prototype, "toValue", {
629 /**
630 * @deprecated
631 */
632 get: function () { return this.useValue; },
633 enumerable: true,
634 configurable: true
635 });
636 Binding = __decorate([
637 lang_1.CONST(),
638 __metadata('design:paramtypes', [Object, Object])
639 ], Binding);
640 return Binding;
641}(Provider));
642exports.Binding = Binding;
643/**
644 * Creates a {@link Provider}.
645 *
646 * To construct a {@link Provider}, bind a `token` to either a class, a value, a factory function,
647 * or
648 * to an existing `token`.
649 * See {@link ProviderBuilder} for more details.
650 *
651 * The `token` is most commonly a class or {@link OpaqueToken-class.html}.
652 *
653 * @deprecated
654 */
655function bind(token) {
656 return new ProviderBuilder(token);
657}
658exports.bind = bind;
659/**
660 * Helper class for the {@link bind} function.
661 */
662var ProviderBuilder = (function () {
663 function ProviderBuilder(token) {
664 this.token = token;
665 }
666 /**
667 * Binds a DI token to a class.
668 *
669 * ### Example ([live demo](http://plnkr.co/edit/ZpBCSYqv6e2ud5KXLdxQ?p=preview))
670 *
671 * Because `toAlias` and `toClass` are often confused, the example contains
672 * both use cases for easy comparison.
673 *
674 * ```typescript
675 * class Vehicle {}
676 *
677 * class Car extends Vehicle {}
678 *
679 * var injectorClass = Injector.resolveAndCreate([
680 * Car,
681 * provide(Vehicle, {useClass: Car})
682 * ]);
683 * var injectorAlias = Injector.resolveAndCreate([
684 * Car,
685 * provide(Vehicle, {useExisting: Car})
686 * ]);
687 *
688 * expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
689 * expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
690 *
691 * expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
692 * expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
693 * ```
694 */
695 ProviderBuilder.prototype.toClass = function (type) {
696 if (!lang_1.isType(type)) {
697 throw new exceptions_1.BaseException("Trying to create a class provider but \"" + lang_1.stringify(type) + "\" is not a class!");
698 }
699 return new Provider(this.token, { useClass: type });
700 };
701 /**
702 * Binds a DI token to a value.
703 *
704 * ### Example ([live demo](http://plnkr.co/edit/G024PFHmDL0cJFgfZK8O?p=preview))
705 *
706 * ```typescript
707 * var injector = Injector.resolveAndCreate([
708 * provide('message', {useValue: 'Hello'})
709 * ]);
710 *
711 * expect(injector.get('message')).toEqual('Hello');
712 * ```
713 */
714 ProviderBuilder.prototype.toValue = function (value) { return new Provider(this.token, { useValue: value }); };
715 /**
716 * Binds a DI token to an existing token.
717 *
718 * Angular will return the same instance as if the provided token was used. (This is
719 * in contrast to `useClass` where a separate instance of `useClass` will be returned.)
720 *
721 * ### Example ([live demo](http://plnkr.co/edit/uBaoF2pN5cfc5AfZapNw?p=preview))
722 *
723 * Because `toAlias` and `toClass` are often confused, the example contains
724 * both use cases for easy comparison.
725 *
726 * ```typescript
727 * class Vehicle {}
728 *
729 * class Car extends Vehicle {}
730 *
731 * var injectorAlias = Injector.resolveAndCreate([
732 * Car,
733 * provide(Vehicle, {useExisting: Car})
734 * ]);
735 * var injectorClass = Injector.resolveAndCreate([
736 * Car,
737 * provide(Vehicle, {useClass: Car})
738 * ]);
739 *
740 * expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
741 * expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
742 *
743 * expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
744 * expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
745 * ```
746 */
747 ProviderBuilder.prototype.toAlias = function (aliasToken) {
748 if (lang_1.isBlank(aliasToken)) {
749 throw new exceptions_1.BaseException("Can not alias " + lang_1.stringify(this.token) + " to a blank value!");
750 }
751 return new Provider(this.token, { useExisting: aliasToken });
752 };
753 /**
754 * Binds a DI token to a function which computes the value.
755 *
756 * ### Example ([live demo](http://plnkr.co/edit/OejNIfTT3zb1iBxaIYOb?p=preview))
757 *
758 * ```typescript
759 * var injector = Injector.resolveAndCreate([
760 * provide(Number, {useFactory: () => { return 1+2; }}),
761 * provide(String, {useFactory: (v) => { return "Value: " + v; }, deps: [Number]})
762 * ]);
763 *
764 * expect(injector.get(Number)).toEqual(3);
765 * expect(injector.get(String)).toEqual('Value: 3');
766 * ```
767 */
768 ProviderBuilder.prototype.toFactory = function (factory, dependencies) {
769 if (!lang_1.isFunction(factory)) {
770 throw new exceptions_1.BaseException("Trying to create a factory provider but \"" + lang_1.stringify(factory) + "\" is not a function!");
771 }
772 return new Provider(this.token, { useFactory: factory, deps: dependencies });
773 };
774 return ProviderBuilder;
775}());
776exports.ProviderBuilder = ProviderBuilder;
777/**
778 * Creates a {@link Provider}.
779 *
780 * See {@link Provider} for more details.
781 *
782 * <!-- TODO: improve the docs -->
783 */
784function provide(token, _a) {
785 var useClass = _a.useClass, useValue = _a.useValue, useExisting = _a.useExisting, useFactory = _a.useFactory, deps = _a.deps, multi = _a.multi;
786 return new Provider(token, {
787 useClass: useClass,
788 useValue: useValue,
789 useExisting: useExisting,
790 useFactory: useFactory,
791 deps: deps,
792 multi: multi
793 });
794}
795exports.provide = provide;
796},{"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],8:[function(require,module,exports){
797'use strict';"use strict";
798var __extends = (this && this.__extends) || function (d, b) {
799 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
800 function __() { this.constructor = d; }
801 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
802};
803var collection_1 = require('angular2/src/facade/collection');
804var lang_1 = require('angular2/src/facade/lang');
805var exceptions_1 = require('angular2/src/facade/exceptions');
806function findFirstClosedCycle(keys) {
807 var res = [];
808 for (var i = 0; i < keys.length; ++i) {
809 if (collection_1.ListWrapper.contains(res, keys[i])) {
810 res.push(keys[i]);
811 return res;
812 }
813 else {
814 res.push(keys[i]);
815 }
816 }
817 return res;
818}
819function constructResolvingPath(keys) {
820 if (keys.length > 1) {
821 var reversed = findFirstClosedCycle(collection_1.ListWrapper.reversed(keys));
822 var tokenStrs = reversed.map(function (k) { return lang_1.stringify(k.token); });
823 return " (" + tokenStrs.join(' -> ') + ")";
824 }
825 else {
826 return "";
827 }
828}
829/**
830 * Base class for all errors arising from misconfigured providers.
831 */
832var AbstractProviderError = (function (_super) {
833 __extends(AbstractProviderError, _super);
834 function AbstractProviderError(injector, key, constructResolvingMessage) {
835 _super.call(this, "DI Exception");
836 this.keys = [key];
837 this.injectors = [injector];
838 this.constructResolvingMessage = constructResolvingMessage;
839 this.message = this.constructResolvingMessage(this.keys);
840 }
841 AbstractProviderError.prototype.addKey = function (injector, key) {
842 this.injectors.push(injector);
843 this.keys.push(key);
844 this.message = this.constructResolvingMessage(this.keys);
845 };
846 Object.defineProperty(AbstractProviderError.prototype, "context", {
847 get: function () { return this.injectors[this.injectors.length - 1].debugContext(); },
848 enumerable: true,
849 configurable: true
850 });
851 return AbstractProviderError;
852}(exceptions_1.BaseException));
853exports.AbstractProviderError = AbstractProviderError;
854/**
855 * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
856 * {@link Injector} does not have a {@link Provider} for {@link Key}.
857 *
858 * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
859 *
860 * ```typescript
861 * class A {
862 * constructor(b:B) {}
863 * }
864 *
865 * expect(() => Injector.resolveAndCreate([A])).toThrowError();
866 * ```
867 */
868var NoProviderError = (function (_super) {
869 __extends(NoProviderError, _super);
870 function NoProviderError(injector, key) {
871 _super.call(this, injector, key, function (keys) {
872 var first = lang_1.stringify(collection_1.ListWrapper.first(keys).token);
873 return "No provider for " + first + "!" + constructResolvingPath(keys);
874 });
875 }
876 return NoProviderError;
877}(AbstractProviderError));
878exports.NoProviderError = NoProviderError;
879/**
880 * Thrown when dependencies form a cycle.
881 *
882 * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
883 *
884 * ```typescript
885 * var injector = Injector.resolveAndCreate([
886 * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}),
887 * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]})
888 * ]);
889 *
890 * expect(() => injector.get("one")).toThrowError();
891 * ```
892 *
893 * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
894 */
895var CyclicDependencyError = (function (_super) {
896 __extends(CyclicDependencyError, _super);
897 function CyclicDependencyError(injector, key) {
898 _super.call(this, injector, key, function (keys) {
899 return "Cannot instantiate cyclic dependency!" + constructResolvingPath(keys);
900 });
901 }
902 return CyclicDependencyError;
903}(AbstractProviderError));
904exports.CyclicDependencyError = CyclicDependencyError;
905/**
906 * Thrown when a constructing type returns with an Error.
907 *
908 * The `InstantiationError` class contains the original error plus the dependency graph which caused
909 * this object to be instantiated.
910 *
911 * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
912 *
913 * ```typescript
914 * class A {
915 * constructor() {
916 * throw new Error('message');
917 * }
918 * }
919 *
920 * var injector = Injector.resolveAndCreate([A]);
921
922 * try {
923 * injector.get(A);
924 * } catch (e) {
925 * expect(e instanceof InstantiationError).toBe(true);
926 * expect(e.originalException.message).toEqual("message");
927 * expect(e.originalStack).toBeDefined();
928 * }
929 * ```
930 */
931var InstantiationError = (function (_super) {
932 __extends(InstantiationError, _super);
933 function InstantiationError(injector, originalException, originalStack, key) {
934 _super.call(this, "DI Exception", originalException, originalStack, null);
935 this.keys = [key];
936 this.injectors = [injector];
937 }
938 InstantiationError.prototype.addKey = function (injector, key) {
939 this.injectors.push(injector);
940 this.keys.push(key);
941 };
942 Object.defineProperty(InstantiationError.prototype, "wrapperMessage", {
943 get: function () {
944 var first = lang_1.stringify(collection_1.ListWrapper.first(this.keys).token);
945 return "Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + ".";
946 },
947 enumerable: true,
948 configurable: true
949 });
950 Object.defineProperty(InstantiationError.prototype, "causeKey", {
951 get: function () { return this.keys[0]; },
952 enumerable: true,
953 configurable: true
954 });
955 Object.defineProperty(InstantiationError.prototype, "context", {
956 get: function () { return this.injectors[this.injectors.length - 1].debugContext(); },
957 enumerable: true,
958 configurable: true
959 });
960 return InstantiationError;
961}(exceptions_1.WrappedException));
962exports.InstantiationError = InstantiationError;
963/**
964 * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
965 * creation.
966 *
967 * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
968 *
969 * ```typescript
970 * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
971 * ```
972 */
973var InvalidProviderError = (function (_super) {
974 __extends(InvalidProviderError, _super);
975 function InvalidProviderError(provider) {
976 _super.call(this, "Invalid provider - only instances of Provider and Type are allowed, got: " +
977 provider.toString());
978 }
979 return InvalidProviderError;
980}(exceptions_1.BaseException));
981exports.InvalidProviderError = InvalidProviderError;
982/**
983 * Thrown when the class has no annotation information.
984 *
985 * Lack of annotation information prevents the {@link Injector} from determining which dependencies
986 * need to be injected into the constructor.
987 *
988 * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
989 *
990 * ```typescript
991 * class A {
992 * constructor(b) {}
993 * }
994 *
995 * expect(() => Injector.resolveAndCreate([A])).toThrowError();
996 * ```
997 *
998 * This error is also thrown when the class not marked with {@link Injectable} has parameter types.
999 *
1000 * ```typescript
1001 * class B {}
1002 *
1003 * class A {
1004 * constructor(b:B) {} // no information about the parameter types of A is available at runtime.
1005 * }
1006 *
1007 * expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
1008 * ```
1009 */
1010var NoAnnotationError = (function (_super) {
1011 __extends(NoAnnotationError, _super);
1012 function NoAnnotationError(typeOrFunc, params) {
1013 _super.call(this, NoAnnotationError._genMessage(typeOrFunc, params));
1014 }
1015 NoAnnotationError._genMessage = function (typeOrFunc, params) {
1016 var signature = [];
1017 for (var i = 0, ii = params.length; i < ii; i++) {
1018 var parameter = params[i];
1019 if (lang_1.isBlank(parameter) || parameter.length == 0) {
1020 signature.push('?');
1021 }
1022 else {
1023 signature.push(parameter.map(lang_1.stringify).join(' '));
1024 }
1025 }
1026 return "Cannot resolve all parameters for '" + lang_1.stringify(typeOrFunc) + "'(" +
1027 signature.join(', ') + "). " +
1028 "Make sure that all the parameters are decorated with Inject or have valid type annotations and that '" +
1029 lang_1.stringify(typeOrFunc) + "' is decorated with Injectable.";
1030 };
1031 return NoAnnotationError;
1032}(exceptions_1.BaseException));
1033exports.NoAnnotationError = NoAnnotationError;
1034/**
1035 * Thrown when getting an object by index.
1036 *
1037 * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
1038 *
1039 * ```typescript
1040 * class A {}
1041 *
1042 * var injector = Injector.resolveAndCreate([A]);
1043 *
1044 * expect(() => injector.getAt(100)).toThrowError();
1045 * ```
1046 */
1047var OutOfBoundsError = (function (_super) {
1048 __extends(OutOfBoundsError, _super);
1049 function OutOfBoundsError(index) {
1050 _super.call(this, "Index " + index + " is out-of-bounds.");
1051 }
1052 return OutOfBoundsError;
1053}(exceptions_1.BaseException));
1054exports.OutOfBoundsError = OutOfBoundsError;
1055// TODO: add a working example after alpha38 is released
1056/**
1057 * Thrown when a multi provider and a regular provider are bound to the same token.
1058 *
1059 * ### Example
1060 *
1061 * ```typescript
1062 * expect(() => Injector.resolveAndCreate([
1063 * new Provider("Strings", {useValue: "string1", multi: true}),
1064 * new Provider("Strings", {useValue: "string2", multi: false})
1065 * ])).toThrowError();
1066 * ```
1067 */
1068var MixingMultiProvidersWithRegularProvidersError = (function (_super) {
1069 __extends(MixingMultiProvidersWithRegularProvidersError, _super);
1070 function MixingMultiProvidersWithRegularProvidersError(provider1, provider2) {
1071 _super.call(this, "Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
1072 provider2.toString());
1073 }
1074 return MixingMultiProvidersWithRegularProvidersError;
1075}(exceptions_1.BaseException));
1076exports.MixingMultiProvidersWithRegularProvidersError = MixingMultiProvidersWithRegularProvidersError;
1077},{"angular2/src/facade/collection":19,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],9:[function(require,module,exports){
1078'use strict';"use strict";
1079var collection_1 = require('angular2/src/facade/collection');
1080var reflective_provider_1 = require('./reflective_provider');
1081var reflective_exceptions_1 = require('./reflective_exceptions');
1082var lang_1 = require('angular2/src/facade/lang');
1083var exceptions_1 = require('angular2/src/facade/exceptions');
1084var reflective_key_1 = require('./reflective_key');
1085var metadata_1 = require('./metadata');
1086var injector_1 = require('./injector');
1087var __unused; // avoid unused import when Type union types are erased
1088// Threshold for the dynamic version
1089var _MAX_CONSTRUCTION_COUNTER = 10;
1090var UNDEFINED = lang_1.CONST_EXPR(new Object());
1091var ReflectiveProtoInjectorInlineStrategy = (function () {
1092 function ReflectiveProtoInjectorInlineStrategy(protoEI, providers) {
1093 this.provider0 = null;
1094 this.provider1 = null;
1095 this.provider2 = null;
1096 this.provider3 = null;
1097 this.provider4 = null;
1098 this.provider5 = null;
1099 this.provider6 = null;
1100 this.provider7 = null;
1101 this.provider8 = null;
1102 this.provider9 = null;
1103 this.keyId0 = null;
1104 this.keyId1 = null;
1105 this.keyId2 = null;
1106 this.keyId3 = null;
1107 this.keyId4 = null;
1108 this.keyId5 = null;
1109 this.keyId6 = null;
1110 this.keyId7 = null;
1111 this.keyId8 = null;
1112 this.keyId9 = null;
1113 var length = providers.length;
1114 if (length > 0) {
1115 this.provider0 = providers[0];
1116 this.keyId0 = providers[0].key.id;
1117 }
1118 if (length > 1) {
1119 this.provider1 = providers[1];
1120 this.keyId1 = providers[1].key.id;
1121 }
1122 if (length > 2) {
1123 this.provider2 = providers[2];
1124 this.keyId2 = providers[2].key.id;
1125 }
1126 if (length > 3) {
1127 this.provider3 = providers[3];
1128 this.keyId3 = providers[3].key.id;
1129 }
1130 if (length > 4) {
1131 this.provider4 = providers[4];
1132 this.keyId4 = providers[4].key.id;
1133 }
1134 if (length > 5) {
1135 this.provider5 = providers[5];
1136 this.keyId5 = providers[5].key.id;
1137 }
1138 if (length > 6) {
1139 this.provider6 = providers[6];
1140 this.keyId6 = providers[6].key.id;
1141 }
1142 if (length > 7) {
1143 this.provider7 = providers[7];
1144 this.keyId7 = providers[7].key.id;
1145 }
1146 if (length > 8) {
1147 this.provider8 = providers[8];
1148 this.keyId8 = providers[8].key.id;
1149 }
1150 if (length > 9) {
1151 this.provider9 = providers[9];
1152 this.keyId9 = providers[9].key.id;
1153 }
1154 }
1155 ReflectiveProtoInjectorInlineStrategy.prototype.getProviderAtIndex = function (index) {
1156 if (index == 0)
1157 return this.provider0;
1158 if (index == 1)
1159 return this.provider1;
1160 if (index == 2)
1161 return this.provider2;
1162 if (index == 3)
1163 return this.provider3;
1164 if (index == 4)
1165 return this.provider4;
1166 if (index == 5)
1167 return this.provider5;
1168 if (index == 6)
1169 return this.provider6;
1170 if (index == 7)
1171 return this.provider7;
1172 if (index == 8)
1173 return this.provider8;
1174 if (index == 9)
1175 return this.provider9;
1176 throw new reflective_exceptions_1.OutOfBoundsError(index);
1177 };
1178 ReflectiveProtoInjectorInlineStrategy.prototype.createInjectorStrategy = function (injector) {
1179 return new ReflectiveInjectorInlineStrategy(injector, this);
1180 };
1181 return ReflectiveProtoInjectorInlineStrategy;
1182}());
1183exports.ReflectiveProtoInjectorInlineStrategy = ReflectiveProtoInjectorInlineStrategy;
1184var ReflectiveProtoInjectorDynamicStrategy = (function () {
1185 function ReflectiveProtoInjectorDynamicStrategy(protoInj, providers) {
1186 this.providers = providers;
1187 var len = providers.length;
1188 this.keyIds = collection_1.ListWrapper.createFixedSize(len);
1189 for (var i = 0; i < len; i++) {
1190 this.keyIds[i] = providers[i].key.id;
1191 }
1192 }
1193 ReflectiveProtoInjectorDynamicStrategy.prototype.getProviderAtIndex = function (index) {
1194 if (index < 0 || index >= this.providers.length) {
1195 throw new reflective_exceptions_1.OutOfBoundsError(index);
1196 }
1197 return this.providers[index];
1198 };
1199 ReflectiveProtoInjectorDynamicStrategy.prototype.createInjectorStrategy = function (ei) {
1200 return new ReflectiveInjectorDynamicStrategy(this, ei);
1201 };
1202 return ReflectiveProtoInjectorDynamicStrategy;
1203}());
1204exports.ReflectiveProtoInjectorDynamicStrategy = ReflectiveProtoInjectorDynamicStrategy;
1205var ReflectiveProtoInjector = (function () {
1206 function ReflectiveProtoInjector(providers) {
1207 this.numberOfProviders = providers.length;
1208 this._strategy = providers.length > _MAX_CONSTRUCTION_COUNTER ?
1209 new ReflectiveProtoInjectorDynamicStrategy(this, providers) :
1210 new ReflectiveProtoInjectorInlineStrategy(this, providers);
1211 }
1212 ReflectiveProtoInjector.fromResolvedProviders = function (providers) {
1213 return new ReflectiveProtoInjector(providers);
1214 };
1215 ReflectiveProtoInjector.prototype.getProviderAtIndex = function (index) {
1216 return this._strategy.getProviderAtIndex(index);
1217 };
1218 return ReflectiveProtoInjector;
1219}());
1220exports.ReflectiveProtoInjector = ReflectiveProtoInjector;
1221var ReflectiveInjectorInlineStrategy = (function () {
1222 function ReflectiveInjectorInlineStrategy(injector, protoStrategy) {
1223 this.injector = injector;
1224 this.protoStrategy = protoStrategy;
1225 this.obj0 = UNDEFINED;
1226 this.obj1 = UNDEFINED;
1227 this.obj2 = UNDEFINED;
1228 this.obj3 = UNDEFINED;
1229 this.obj4 = UNDEFINED;
1230 this.obj5 = UNDEFINED;
1231 this.obj6 = UNDEFINED;
1232 this.obj7 = UNDEFINED;
1233 this.obj8 = UNDEFINED;
1234 this.obj9 = UNDEFINED;
1235 }
1236 ReflectiveInjectorInlineStrategy.prototype.resetConstructionCounter = function () { this.injector._constructionCounter = 0; };
1237 ReflectiveInjectorInlineStrategy.prototype.instantiateProvider = function (provider) {
1238 return this.injector._new(provider);
1239 };
1240 ReflectiveInjectorInlineStrategy.prototype.getObjByKeyId = function (keyId) {
1241 var p = this.protoStrategy;
1242 var inj = this.injector;
1243 if (p.keyId0 === keyId) {
1244 if (this.obj0 === UNDEFINED) {
1245 this.obj0 = inj._new(p.provider0);
1246 }
1247 return this.obj0;
1248 }
1249 if (p.keyId1 === keyId) {
1250 if (this.obj1 === UNDEFINED) {
1251 this.obj1 = inj._new(p.provider1);
1252 }
1253 return this.obj1;
1254 }
1255 if (p.keyId2 === keyId) {
1256 if (this.obj2 === UNDEFINED) {
1257 this.obj2 = inj._new(p.provider2);
1258 }
1259 return this.obj2;
1260 }
1261 if (p.keyId3 === keyId) {
1262 if (this.obj3 === UNDEFINED) {
1263 this.obj3 = inj._new(p.provider3);
1264 }
1265 return this.obj3;
1266 }
1267 if (p.keyId4 === keyId) {
1268 if (this.obj4 === UNDEFINED) {
1269 this.obj4 = inj._new(p.provider4);
1270 }
1271 return this.obj4;
1272 }
1273 if (p.keyId5 === keyId) {
1274 if (this.obj5 === UNDEFINED) {
1275 this.obj5 = inj._new(p.provider5);
1276 }
1277 return this.obj5;
1278 }
1279 if (p.keyId6 === keyId) {
1280 if (this.obj6 === UNDEFINED) {
1281 this.obj6 = inj._new(p.provider6);
1282 }
1283 return this.obj6;
1284 }
1285 if (p.keyId7 === keyId) {
1286 if (this.obj7 === UNDEFINED) {
1287 this.obj7 = inj._new(p.provider7);
1288 }
1289 return this.obj7;
1290 }
1291 if (p.keyId8 === keyId) {
1292 if (this.obj8 === UNDEFINED) {
1293 this.obj8 = inj._new(p.provider8);
1294 }
1295 return this.obj8;
1296 }
1297 if (p.keyId9 === keyId) {
1298 if (this.obj9 === UNDEFINED) {
1299 this.obj9 = inj._new(p.provider9);
1300 }
1301 return this.obj9;
1302 }
1303 return UNDEFINED;
1304 };
1305 ReflectiveInjectorInlineStrategy.prototype.getObjAtIndex = function (index) {
1306 if (index == 0)
1307 return this.obj0;
1308 if (index == 1)
1309 return this.obj1;
1310 if (index == 2)
1311 return this.obj2;
1312 if (index == 3)
1313 return this.obj3;
1314 if (index == 4)
1315 return this.obj4;
1316 if (index == 5)
1317 return this.obj5;
1318 if (index == 6)
1319 return this.obj6;
1320 if (index == 7)
1321 return this.obj7;
1322 if (index == 8)
1323 return this.obj8;
1324 if (index == 9)
1325 return this.obj9;
1326 throw new reflective_exceptions_1.OutOfBoundsError(index);
1327 };
1328 ReflectiveInjectorInlineStrategy.prototype.getMaxNumberOfObjects = function () { return _MAX_CONSTRUCTION_COUNTER; };
1329 return ReflectiveInjectorInlineStrategy;
1330}());
1331exports.ReflectiveInjectorInlineStrategy = ReflectiveInjectorInlineStrategy;
1332var ReflectiveInjectorDynamicStrategy = (function () {
1333 function ReflectiveInjectorDynamicStrategy(protoStrategy, injector) {
1334 this.protoStrategy = protoStrategy;
1335 this.injector = injector;
1336 this.objs = collection_1.ListWrapper.createFixedSize(protoStrategy.providers.length);
1337 collection_1.ListWrapper.fill(this.objs, UNDEFINED);
1338 }
1339 ReflectiveInjectorDynamicStrategy.prototype.resetConstructionCounter = function () { this.injector._constructionCounter = 0; };
1340 ReflectiveInjectorDynamicStrategy.prototype.instantiateProvider = function (provider) {
1341 return this.injector._new(provider);
1342 };
1343 ReflectiveInjectorDynamicStrategy.prototype.getObjByKeyId = function (keyId) {
1344 var p = this.protoStrategy;
1345 for (var i = 0; i < p.keyIds.length; i++) {
1346 if (p.keyIds[i] === keyId) {
1347 if (this.objs[i] === UNDEFINED) {
1348 this.objs[i] = this.injector._new(p.providers[i]);
1349 }
1350 return this.objs[i];
1351 }
1352 }
1353 return UNDEFINED;
1354 };
1355 ReflectiveInjectorDynamicStrategy.prototype.getObjAtIndex = function (index) {
1356 if (index < 0 || index >= this.objs.length) {
1357 throw new reflective_exceptions_1.OutOfBoundsError(index);
1358 }
1359 return this.objs[index];
1360 };
1361 ReflectiveInjectorDynamicStrategy.prototype.getMaxNumberOfObjects = function () { return this.objs.length; };
1362 return ReflectiveInjectorDynamicStrategy;
1363}());
1364exports.ReflectiveInjectorDynamicStrategy = ReflectiveInjectorDynamicStrategy;
1365/**
1366 * A ReflectiveDependency injection container used for instantiating objects and resolving
1367 * dependencies.
1368 *
1369 * An `Injector` is a replacement for a `new` operator, which can automatically resolve the
1370 * constructor dependencies.
1371 *
1372 * In typical use, application code asks for the dependencies in the constructor and they are
1373 * resolved by the `Injector`.
1374 *
1375 * ### Example ([live demo](http://plnkr.co/edit/jzjec0?p=preview))
1376 *
1377 * The following example creates an `Injector` configured to create `Engine` and `Car`.
1378 *
1379 * ```typescript
1380 * @Injectable()
1381 * class Engine {
1382 * }
1383 *
1384 * @Injectable()
1385 * class Car {
1386 * constructor(public engine:Engine) {}
1387 * }
1388 *
1389 * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
1390 * var car = injector.get(Car);
1391 * expect(car instanceof Car).toBe(true);
1392 * expect(car.engine instanceof Engine).toBe(true);
1393 * ```
1394 *
1395 * Notice, we don't use the `new` operator because we explicitly want to have the `Injector`
1396 * resolve all of the object's dependencies automatically.
1397 */
1398var ReflectiveInjector = (function () {
1399 function ReflectiveInjector() {
1400 }
1401 /**
1402 * Turns an array of provider definitions into an array of resolved providers.
1403 *
1404 * A resolution is a process of flattening multiple nested arrays and converting individual
1405 * providers into an array of {@link ResolvedReflectiveProvider}s.
1406 *
1407 * ### Example ([live demo](http://plnkr.co/edit/AiXTHi?p=preview))
1408 *
1409 * ```typescript
1410 * @Injectable()
1411 * class Engine {
1412 * }
1413 *
1414 * @Injectable()
1415 * class Car {
1416 * constructor(public engine:Engine) {}
1417 * }
1418 *
1419 * var providers = ReflectiveInjector.resolve([Car, [[Engine]]]);
1420 *
1421 * expect(providers.length).toEqual(2);
1422 *
1423 * expect(providers[0] instanceof ResolvedReflectiveProvider).toBe(true);
1424 * expect(providers[0].key.displayName).toBe("Car");
1425 * expect(providers[0].dependencies.length).toEqual(1);
1426 * expect(providers[0].factory).toBeDefined();
1427 *
1428 * expect(providers[1].key.displayName).toBe("Engine");
1429 * });
1430 * ```
1431 *
1432 * See {@link ReflectiveInjector#fromResolvedProviders} for more info.
1433 */
1434 ReflectiveInjector.resolve = function (providers) {
1435 return reflective_provider_1.resolveReflectiveProviders(providers);
1436 };
1437 /**
1438 * Resolves an array of providers and creates an injector from those providers.
1439 *
1440 * The passed-in providers can be an array of `Type`, {@link Provider},
1441 * or a recursive array of more providers.
1442 *
1443 * ### Example ([live demo](http://plnkr.co/edit/ePOccA?p=preview))
1444 *
1445 * ```typescript
1446 * @Injectable()
1447 * class Engine {
1448 * }
1449 *
1450 * @Injectable()
1451 * class Car {
1452 * constructor(public engine:Engine) {}
1453 * }
1454 *
1455 * var injector = ReflectiveInjector.resolveAndCreate([Car, Engine]);
1456 * expect(injector.get(Car) instanceof Car).toBe(true);
1457 * ```
1458 *
1459 * This function is slower than the corresponding `fromResolvedProviders`
1460 * because it needs to resolve the passed-in providers first.
1461 * See {@link Injector#resolve} and {@link Injector#fromResolvedProviders}.
1462 */
1463 ReflectiveInjector.resolveAndCreate = function (providers, parent) {
1464 if (parent === void 0) { parent = null; }
1465 var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
1466 return ReflectiveInjector.fromResolvedProviders(ResolvedReflectiveProviders, parent);
1467 };
1468 /**
1469 * Creates an injector from previously resolved providers.
1470 *
1471 * This API is the recommended way to construct injectors in performance-sensitive parts.
1472 *
1473 * ### Example ([live demo](http://plnkr.co/edit/KrSMci?p=preview))
1474 *
1475 * ```typescript
1476 * @Injectable()
1477 * class Engine {
1478 * }
1479 *
1480 * @Injectable()
1481 * class Car {
1482 * constructor(public engine:Engine) {}
1483 * }
1484 *
1485 * var providers = ReflectiveInjector.resolve([Car, Engine]);
1486 * var injector = ReflectiveInjector.fromResolvedProviders(providers);
1487 * expect(injector.get(Car) instanceof Car).toBe(true);
1488 * ```
1489 */
1490 ReflectiveInjector.fromResolvedProviders = function (providers, parent) {
1491 if (parent === void 0) { parent = null; }
1492 return new ReflectiveInjector_(ReflectiveProtoInjector.fromResolvedProviders(providers), parent);
1493 };
1494 /**
1495 * @deprecated
1496 */
1497 ReflectiveInjector.fromResolvedBindings = function (providers) {
1498 return ReflectiveInjector.fromResolvedProviders(providers);
1499 };
1500 Object.defineProperty(ReflectiveInjector.prototype, "parent", {
1501 /**
1502 * Parent of this injector.
1503 *
1504 * <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
1505 * -->
1506 *
1507 * ### Example ([live demo](http://plnkr.co/edit/eosMGo?p=preview))
1508 *
1509 * ```typescript
1510 * var parent = ReflectiveInjector.resolveAndCreate([]);
1511 * var child = parent.resolveAndCreateChild([]);
1512 * expect(child.parent).toBe(parent);
1513 * ```
1514 */
1515 get: function () { return exceptions_1.unimplemented(); },
1516 enumerable: true,
1517 configurable: true
1518 });
1519 /**
1520 * @internal
1521 */
1522 ReflectiveInjector.prototype.debugContext = function () { return null; };
1523 /**
1524 * Resolves an array of providers and creates a child injector from those providers.
1525 *
1526 * <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
1527 * -->
1528 *
1529 * The passed-in providers can be an array of `Type`, {@link Provider},
1530 * or a recursive array of more providers.
1531 *
1532 * ### Example ([live demo](http://plnkr.co/edit/opB3T4?p=preview))
1533 *
1534 * ```typescript
1535 * class ParentProvider {}
1536 * class ChildProvider {}
1537 *
1538 * var parent = ReflectiveInjector.resolveAndCreate([ParentProvider]);
1539 * var child = parent.resolveAndCreateChild([ChildProvider]);
1540 *
1541 * expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
1542 * expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
1543 * expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
1544 * ```
1545 *
1546 * This function is slower than the corresponding `createChildFromResolved`
1547 * because it needs to resolve the passed-in providers first.
1548 * See {@link Injector#resolve} and {@link Injector#createChildFromResolved}.
1549 */
1550 ReflectiveInjector.prototype.resolveAndCreateChild = function (providers) {
1551 return exceptions_1.unimplemented();
1552 };
1553 /**
1554 * Creates a child injector from previously resolved providers.
1555 *
1556 * <!-- TODO: Add a link to the section of the user guide talking about hierarchical injection.
1557 * -->
1558 *
1559 * This API is the recommended way to construct injectors in performance-sensitive parts.
1560 *
1561 * ### Example ([live demo](http://plnkr.co/edit/VhyfjN?p=preview))
1562 *
1563 * ```typescript
1564 * class ParentProvider {}
1565 * class ChildProvider {}
1566 *
1567 * var parentProviders = ReflectiveInjector.resolve([ParentProvider]);
1568 * var childProviders = ReflectiveInjector.resolve([ChildProvider]);
1569 *
1570 * var parent = ReflectiveInjector.fromResolvedProviders(parentProviders);
1571 * var child = parent.createChildFromResolved(childProviders);
1572 *
1573 * expect(child.get(ParentProvider) instanceof ParentProvider).toBe(true);
1574 * expect(child.get(ChildProvider) instanceof ChildProvider).toBe(true);
1575 * expect(child.get(ParentProvider)).toBe(parent.get(ParentProvider));
1576 * ```
1577 */
1578 ReflectiveInjector.prototype.createChildFromResolved = function (providers) {
1579 return exceptions_1.unimplemented();
1580 };
1581 /**
1582 * Resolves a provider and instantiates an object in the context of the injector.
1583 *
1584 * The created object does not get cached by the injector.
1585 *
1586 * ### Example ([live demo](http://plnkr.co/edit/yvVXoB?p=preview))
1587 *
1588 * ```typescript
1589 * @Injectable()
1590 * class Engine {
1591 * }
1592 *
1593 * @Injectable()
1594 * class Car {
1595 * constructor(public engine:Engine) {}
1596 * }
1597 *
1598 * var injector = ReflectiveInjector.resolveAndCreate([Engine]);
1599 *
1600 * var car = injector.resolveAndInstantiate(Car);
1601 * expect(car.engine).toBe(injector.get(Engine));
1602 * expect(car).not.toBe(injector.resolveAndInstantiate(Car));
1603 * ```
1604 */
1605 ReflectiveInjector.prototype.resolveAndInstantiate = function (provider) { return exceptions_1.unimplemented(); };
1606 /**
1607 * Instantiates an object using a resolved provider in the context of the injector.
1608 *
1609 * The created object does not get cached by the injector.
1610 *
1611 * ### Example ([live demo](http://plnkr.co/edit/ptCImQ?p=preview))
1612 *
1613 * ```typescript
1614 * @Injectable()
1615 * class Engine {
1616 * }
1617 *
1618 * @Injectable()
1619 * class Car {
1620 * constructor(public engine:Engine) {}
1621 * }
1622 *
1623 * var injector = ReflectiveInjector.resolveAndCreate([Engine]);
1624 * var carProvider = ReflectiveInjector.resolve([Car])[0];
1625 * var car = injector.instantiateResolved(carProvider);
1626 * expect(car.engine).toBe(injector.get(Engine));
1627 * expect(car).not.toBe(injector.instantiateResolved(carProvider));
1628 * ```
1629 */
1630 ReflectiveInjector.prototype.instantiateResolved = function (provider) { return exceptions_1.unimplemented(); };
1631 return ReflectiveInjector;
1632}());
1633exports.ReflectiveInjector = ReflectiveInjector;
1634var ReflectiveInjector_ = (function () {
1635 /**
1636 * Private
1637 */
1638 function ReflectiveInjector_(_proto /* ProtoInjector */, _parent, _debugContext) {
1639 if (_parent === void 0) { _parent = null; }
1640 if (_debugContext === void 0) { _debugContext = null; }
1641 this._debugContext = _debugContext;
1642 /** @internal */
1643 this._constructionCounter = 0;
1644 this._proto = _proto;
1645 this._parent = _parent;
1646 this._strategy = _proto._strategy.createInjectorStrategy(this);
1647 }
1648 /**
1649 * @internal
1650 */
1651 ReflectiveInjector_.prototype.debugContext = function () { return this._debugContext(); };
1652 ReflectiveInjector_.prototype.get = function (token, notFoundValue) {
1653 if (notFoundValue === void 0) { notFoundValue = injector_1.THROW_IF_NOT_FOUND; }
1654 return this._getByKey(reflective_key_1.ReflectiveKey.get(token), null, null, notFoundValue);
1655 };
1656 ReflectiveInjector_.prototype.getAt = function (index) { return this._strategy.getObjAtIndex(index); };
1657 Object.defineProperty(ReflectiveInjector_.prototype, "parent", {
1658 get: function () { return this._parent; },
1659 enumerable: true,
1660 configurable: true
1661 });
1662 Object.defineProperty(ReflectiveInjector_.prototype, "internalStrategy", {
1663 /**
1664 * @internal
1665 * Internal. Do not use.
1666 * We return `any` not to export the InjectorStrategy type.
1667 */
1668 get: function () { return this._strategy; },
1669 enumerable: true,
1670 configurable: true
1671 });
1672 ReflectiveInjector_.prototype.resolveAndCreateChild = function (providers) {
1673 var ResolvedReflectiveProviders = ReflectiveInjector.resolve(providers);
1674 return this.createChildFromResolved(ResolvedReflectiveProviders);
1675 };
1676 ReflectiveInjector_.prototype.createChildFromResolved = function (providers) {
1677 var proto = new ReflectiveProtoInjector(providers);
1678 var inj = new ReflectiveInjector_(proto);
1679 inj._parent = this;
1680 return inj;
1681 };
1682 ReflectiveInjector_.prototype.resolveAndInstantiate = function (provider) {
1683 return this.instantiateResolved(ReflectiveInjector.resolve([provider])[0]);
1684 };
1685 ReflectiveInjector_.prototype.instantiateResolved = function (provider) {
1686 return this._instantiateProvider(provider);
1687 };
1688 /** @internal */
1689 ReflectiveInjector_.prototype._new = function (provider) {
1690 if (this._constructionCounter++ > this._strategy.getMaxNumberOfObjects()) {
1691 throw new reflective_exceptions_1.CyclicDependencyError(this, provider.key);
1692 }
1693 return this._instantiateProvider(provider);
1694 };
1695 ReflectiveInjector_.prototype._instantiateProvider = function (provider) {
1696 if (provider.multiProvider) {
1697 var res = collection_1.ListWrapper.createFixedSize(provider.resolvedFactories.length);
1698 for (var i = 0; i < provider.resolvedFactories.length; ++i) {
1699 res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
1700 }
1701 return res;
1702 }
1703 else {
1704 return this._instantiate(provider, provider.resolvedFactories[0]);
1705 }
1706 };
1707 ReflectiveInjector_.prototype._instantiate = function (provider, ResolvedReflectiveFactory) {
1708 var factory = ResolvedReflectiveFactory.factory;
1709 var deps = ResolvedReflectiveFactory.dependencies;
1710 var length = deps.length;
1711 var d0;
1712 var d1;
1713 var d2;
1714 var d3;
1715 var d4;
1716 var d5;
1717 var d6;
1718 var d7;
1719 var d8;
1720 var d9;
1721 var d10;
1722 var d11;
1723 var d12;
1724 var d13;
1725 var d14;
1726 var d15;
1727 var d16;
1728 var d17;
1729 var d18;
1730 var d19;
1731 try {
1732 d0 = length > 0 ? this._getByReflectiveDependency(provider, deps[0]) : null;
1733 d1 = length > 1 ? this._getByReflectiveDependency(provider, deps[1]) : null;
1734 d2 = length > 2 ? this._getByReflectiveDependency(provider, deps[2]) : null;
1735 d3 = length > 3 ? this._getByReflectiveDependency(provider, deps[3]) : null;
1736 d4 = length > 4 ? this._getByReflectiveDependency(provider, deps[4]) : null;
1737 d5 = length > 5 ? this._getByReflectiveDependency(provider, deps[5]) : null;
1738 d6 = length > 6 ? this._getByReflectiveDependency(provider, deps[6]) : null;
1739 d7 = length > 7 ? this._getByReflectiveDependency(provider, deps[7]) : null;
1740 d8 = length > 8 ? this._getByReflectiveDependency(provider, deps[8]) : null;
1741 d9 = length > 9 ? this._getByReflectiveDependency(provider, deps[9]) : null;
1742 d10 = length > 10 ? this._getByReflectiveDependency(provider, deps[10]) : null;
1743 d11 = length > 11 ? this._getByReflectiveDependency(provider, deps[11]) : null;
1744 d12 = length > 12 ? this._getByReflectiveDependency(provider, deps[12]) : null;
1745 d13 = length > 13 ? this._getByReflectiveDependency(provider, deps[13]) : null;
1746 d14 = length > 14 ? this._getByReflectiveDependency(provider, deps[14]) : null;
1747 d15 = length > 15 ? this._getByReflectiveDependency(provider, deps[15]) : null;
1748 d16 = length > 16 ? this._getByReflectiveDependency(provider, deps[16]) : null;
1749 d17 = length > 17 ? this._getByReflectiveDependency(provider, deps[17]) : null;
1750 d18 = length > 18 ? this._getByReflectiveDependency(provider, deps[18]) : null;
1751 d19 = length > 19 ? this._getByReflectiveDependency(provider, deps[19]) : null;
1752 }
1753 catch (e) {
1754 if (e instanceof reflective_exceptions_1.AbstractProviderError || e instanceof reflective_exceptions_1.InstantiationError) {
1755 e.addKey(this, provider.key);
1756 }
1757 throw e;
1758 }
1759 var obj;
1760 try {
1761 switch (length) {
1762 case 0:
1763 obj = factory();
1764 break;
1765 case 1:
1766 obj = factory(d0);
1767 break;
1768 case 2:
1769 obj = factory(d0, d1);
1770 break;
1771 case 3:
1772 obj = factory(d0, d1, d2);
1773 break;
1774 case 4:
1775 obj = factory(d0, d1, d2, d3);
1776 break;
1777 case 5:
1778 obj = factory(d0, d1, d2, d3, d4);
1779 break;
1780 case 6:
1781 obj = factory(d0, d1, d2, d3, d4, d5);
1782 break;
1783 case 7:
1784 obj = factory(d0, d1, d2, d3, d4, d5, d6);
1785 break;
1786 case 8:
1787 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7);
1788 break;
1789 case 9:
1790 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8);
1791 break;
1792 case 10:
1793 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9);
1794 break;
1795 case 11:
1796 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10);
1797 break;
1798 case 12:
1799 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11);
1800 break;
1801 case 13:
1802 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12);
1803 break;
1804 case 14:
1805 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13);
1806 break;
1807 case 15:
1808 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14);
1809 break;
1810 case 16:
1811 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15);
1812 break;
1813 case 17:
1814 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16);
1815 break;
1816 case 18:
1817 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17);
1818 break;
1819 case 19:
1820 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18);
1821 break;
1822 case 20:
1823 obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16, d17, d18, d19);
1824 break;
1825 default:
1826 throw new exceptions_1.BaseException("Cannot instantiate '" + provider.key.displayName + "' because it has more than 20 dependencies");
1827 }
1828 }
1829 catch (e) {
1830 throw new reflective_exceptions_1.InstantiationError(this, e, e.stack, provider.key);
1831 }
1832 return obj;
1833 };
1834 ReflectiveInjector_.prototype._getByReflectiveDependency = function (provider, dep) {
1835 return this._getByKey(dep.key, dep.lowerBoundVisibility, dep.upperBoundVisibility, dep.optional ? null : injector_1.THROW_IF_NOT_FOUND);
1836 };
1837 ReflectiveInjector_.prototype._getByKey = function (key, lowerBoundVisibility, upperBoundVisibility, notFoundValue) {
1838 if (key === INJECTOR_KEY) {
1839 return this;
1840 }
1841 if (upperBoundVisibility instanceof metadata_1.SelfMetadata) {
1842 return this._getByKeySelf(key, notFoundValue);
1843 }
1844 else {
1845 return this._getByKeyDefault(key, notFoundValue, lowerBoundVisibility);
1846 }
1847 };
1848 /** @internal */
1849 ReflectiveInjector_.prototype._throwOrNull = function (key, notFoundValue) {
1850 if (notFoundValue !== injector_1.THROW_IF_NOT_FOUND) {
1851 return notFoundValue;
1852 }
1853 else {
1854 throw new reflective_exceptions_1.NoProviderError(this, key);
1855 }
1856 };
1857 /** @internal */
1858 ReflectiveInjector_.prototype._getByKeySelf = function (key, notFoundValue) {
1859 var obj = this._strategy.getObjByKeyId(key.id);
1860 return (obj !== UNDEFINED) ? obj : this._throwOrNull(key, notFoundValue);
1861 };
1862 /** @internal */
1863 ReflectiveInjector_.prototype._getByKeyDefault = function (key, notFoundValue, lowerBoundVisibility) {
1864 var inj;
1865 if (lowerBoundVisibility instanceof metadata_1.SkipSelfMetadata) {
1866 inj = this._parent;
1867 }
1868 else {
1869 inj = this;
1870 }
1871 while (inj instanceof ReflectiveInjector_) {
1872 var inj_ = inj;
1873 var obj = inj_._strategy.getObjByKeyId(key.id);
1874 if (obj !== UNDEFINED)
1875 return obj;
1876 inj = inj_._parent;
1877 }
1878 if (inj !== null) {
1879 return inj.get(key.token, notFoundValue);
1880 }
1881 else {
1882 return this._throwOrNull(key, notFoundValue);
1883 }
1884 };
1885 Object.defineProperty(ReflectiveInjector_.prototype, "displayName", {
1886 get: function () {
1887 return "ReflectiveInjector(providers: [" + _mapProviders(this, function (b) { return (" \"" + b.key.displayName + "\" "); }).join(", ") + "])";
1888 },
1889 enumerable: true,
1890 configurable: true
1891 });
1892 ReflectiveInjector_.prototype.toString = function () { return this.displayName; };
1893 return ReflectiveInjector_;
1894}());
1895exports.ReflectiveInjector_ = ReflectiveInjector_;
1896var INJECTOR_KEY = reflective_key_1.ReflectiveKey.get(injector_1.Injector);
1897function _mapProviders(injector, fn) {
1898 var res = [];
1899 for (var i = 0; i < injector._proto.numberOfProviders; ++i) {
1900 res.push(fn(injector._proto.getProviderAtIndex(i)));
1901 }
1902 return res;
1903}
1904},{"./injector":4,"./metadata":5,"./reflective_exceptions":8,"./reflective_key":10,"./reflective_provider":11,"angular2/src/facade/collection":19,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],10:[function(require,module,exports){
1905'use strict';"use strict";
1906var lang_1 = require('angular2/src/facade/lang');
1907var exceptions_1 = require('angular2/src/facade/exceptions');
1908var forward_ref_1 = require('./forward_ref');
1909/**
1910 * A unique object used for retrieving items from the {@link ReflectiveInjector}.
1911 *
1912 * Keys have:
1913 * - a system-wide unique `id`.
1914 * - a `token`.
1915 *
1916 * `Key` is used internally by {@link ReflectiveInjector} because its system-wide unique `id` allows
1917 * the
1918 * injector to store created objects in a more efficient way.
1919 *
1920 * `Key` should not be created directly. {@link ReflectiveInjector} creates keys automatically when
1921 * resolving
1922 * providers.
1923 */
1924var ReflectiveKey = (function () {
1925 /**
1926 * Private
1927 */
1928 function ReflectiveKey(token, id) {
1929 this.token = token;
1930 this.id = id;
1931 if (lang_1.isBlank(token)) {
1932 throw new exceptions_1.BaseException('Token must be defined!');
1933 }
1934 }
1935 Object.defineProperty(ReflectiveKey.prototype, "displayName", {
1936 /**
1937 * Returns a stringified token.
1938 */
1939 get: function () { return lang_1.stringify(this.token); },
1940 enumerable: true,
1941 configurable: true
1942 });
1943 /**
1944 * Retrieves a `Key` for a token.
1945 */
1946 ReflectiveKey.get = function (token) {
1947 return _globalKeyRegistry.get(forward_ref_1.resolveForwardRef(token));
1948 };
1949 Object.defineProperty(ReflectiveKey, "numberOfKeys", {
1950 /**
1951 * @returns the number of keys registered in the system.
1952 */
1953 get: function () { return _globalKeyRegistry.numberOfKeys; },
1954 enumerable: true,
1955 configurable: true
1956 });
1957 return ReflectiveKey;
1958}());
1959exports.ReflectiveKey = ReflectiveKey;
1960/**
1961 * @internal
1962 */
1963var KeyRegistry = (function () {
1964 function KeyRegistry() {
1965 this._allKeys = new Map();
1966 }
1967 KeyRegistry.prototype.get = function (token) {
1968 if (token instanceof ReflectiveKey)
1969 return token;
1970 if (this._allKeys.has(token)) {
1971 return this._allKeys.get(token);
1972 }
1973 var newKey = new ReflectiveKey(token, ReflectiveKey.numberOfKeys);
1974 this._allKeys.set(token, newKey);
1975 return newKey;
1976 };
1977 Object.defineProperty(KeyRegistry.prototype, "numberOfKeys", {
1978 get: function () { return this._allKeys.size; },
1979 enumerable: true,
1980 configurable: true
1981 });
1982 return KeyRegistry;
1983}());
1984exports.KeyRegistry = KeyRegistry;
1985var _globalKeyRegistry = new KeyRegistry();
1986},{"./forward_ref":3,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],11:[function(require,module,exports){
1987'use strict';"use strict";
1988var lang_1 = require('angular2/src/facade/lang');
1989var collection_1 = require('angular2/src/facade/collection');
1990var reflection_1 = require('angular2/src/core/reflection/reflection');
1991var reflective_key_1 = require('./reflective_key');
1992var metadata_1 = require('./metadata');
1993var reflective_exceptions_1 = require('./reflective_exceptions');
1994var forward_ref_1 = require('./forward_ref');
1995var provider_1 = require('./provider');
1996/**
1997 * `Dependency` is used by the framework to extend DI.
1998 * This is internal to Angular and should not be used directly.
1999 */
2000var ReflectiveDependency = (function () {
2001 function ReflectiveDependency(key, optional, lowerBoundVisibility, upperBoundVisibility, properties) {
2002 this.key = key;
2003 this.optional = optional;
2004 this.lowerBoundVisibility = lowerBoundVisibility;
2005 this.upperBoundVisibility = upperBoundVisibility;
2006 this.properties = properties;
2007 }
2008 ReflectiveDependency.fromKey = function (key) {
2009 return new ReflectiveDependency(key, false, null, null, []);
2010 };
2011 return ReflectiveDependency;
2012}());
2013exports.ReflectiveDependency = ReflectiveDependency;
2014var _EMPTY_LIST = lang_1.CONST_EXPR([]);
2015var ResolvedReflectiveProvider_ = (function () {
2016 function ResolvedReflectiveProvider_(key, resolvedFactories, multiProvider) {
2017 this.key = key;
2018 this.resolvedFactories = resolvedFactories;
2019 this.multiProvider = multiProvider;
2020 }
2021 Object.defineProperty(ResolvedReflectiveProvider_.prototype, "resolvedFactory", {
2022 get: function () { return this.resolvedFactories[0]; },
2023 enumerable: true,
2024 configurable: true
2025 });
2026 return ResolvedReflectiveProvider_;
2027}());
2028exports.ResolvedReflectiveProvider_ = ResolvedReflectiveProvider_;
2029/**
2030 * An internal resolved representation of a factory function created by resolving {@link Provider}.
2031 */
2032var ResolvedReflectiveFactory = (function () {
2033 function ResolvedReflectiveFactory(
2034 /**
2035 * Factory function which can return an instance of an object represented by a key.
2036 */
2037 factory,
2038 /**
2039 * Arguments (dependencies) to the `factory` function.
2040 */
2041 dependencies) {
2042 this.factory = factory;
2043 this.dependencies = dependencies;
2044 }
2045 return ResolvedReflectiveFactory;
2046}());
2047exports.ResolvedReflectiveFactory = ResolvedReflectiveFactory;
2048/**
2049 * Resolve a single provider.
2050 */
2051function resolveReflectiveFactory(provider) {
2052 var factoryFn;
2053 var resolvedDeps;
2054 if (lang_1.isPresent(provider.useClass)) {
2055 var useClass = forward_ref_1.resolveForwardRef(provider.useClass);
2056 factoryFn = reflection_1.reflector.factory(useClass);
2057 resolvedDeps = _dependenciesFor(useClass);
2058 }
2059 else if (lang_1.isPresent(provider.useExisting)) {
2060 factoryFn = function (aliasInstance) { return aliasInstance; };
2061 resolvedDeps = [ReflectiveDependency.fromKey(reflective_key_1.ReflectiveKey.get(provider.useExisting))];
2062 }
2063 else if (lang_1.isPresent(provider.useFactory)) {
2064 factoryFn = provider.useFactory;
2065 resolvedDeps = constructDependencies(provider.useFactory, provider.dependencies);
2066 }
2067 else {
2068 factoryFn = function () { return provider.useValue; };
2069 resolvedDeps = _EMPTY_LIST;
2070 }
2071 return new ResolvedReflectiveFactory(factoryFn, resolvedDeps);
2072}
2073exports.resolveReflectiveFactory = resolveReflectiveFactory;
2074/**
2075 * Converts the {@link Provider} into {@link ResolvedProvider}.
2076 *
2077 * {@link Injector} internally only uses {@link ResolvedProvider}, {@link Provider} contains
2078 * convenience provider syntax.
2079 */
2080function resolveReflectiveProvider(provider) {
2081 return new ResolvedReflectiveProvider_(reflective_key_1.ReflectiveKey.get(provider.token), [resolveReflectiveFactory(provider)], provider.multi);
2082}
2083exports.resolveReflectiveProvider = resolveReflectiveProvider;
2084/**
2085 * Resolve a list of Providers.
2086 */
2087function resolveReflectiveProviders(providers) {
2088 var normalized = _normalizeProviders(providers, []);
2089 var resolved = normalized.map(resolveReflectiveProvider);
2090 return collection_1.MapWrapper.values(mergeResolvedReflectiveProviders(resolved, new Map()));
2091}
2092exports.resolveReflectiveProviders = resolveReflectiveProviders;
2093/**
2094 * Merges a list of ResolvedProviders into a list where
2095 * each key is contained exactly once and multi providers
2096 * have been merged.
2097 */
2098function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
2099 for (var i = 0; i < providers.length; i++) {
2100 var provider = providers[i];
2101 var existing = normalizedProvidersMap.get(provider.key.id);
2102 if (lang_1.isPresent(existing)) {
2103 if (provider.multiProvider !== existing.multiProvider) {
2104 throw new reflective_exceptions_1.MixingMultiProvidersWithRegularProvidersError(existing, provider);
2105 }
2106 if (provider.multiProvider) {
2107 for (var j = 0; j < provider.resolvedFactories.length; j++) {
2108 existing.resolvedFactories.push(provider.resolvedFactories[j]);
2109 }
2110 }
2111 else {
2112 normalizedProvidersMap.set(provider.key.id, provider);
2113 }
2114 }
2115 else {
2116 var resolvedProvider;
2117 if (provider.multiProvider) {
2118 resolvedProvider = new ResolvedReflectiveProvider_(provider.key, collection_1.ListWrapper.clone(provider.resolvedFactories), provider.multiProvider);
2119 }
2120 else {
2121 resolvedProvider = provider;
2122 }
2123 normalizedProvidersMap.set(provider.key.id, resolvedProvider);
2124 }
2125 }
2126 return normalizedProvidersMap;
2127}
2128exports.mergeResolvedReflectiveProviders = mergeResolvedReflectiveProviders;
2129function _normalizeProviders(providers, res) {
2130 providers.forEach(function (b) {
2131 if (b instanceof lang_1.Type) {
2132 res.push(provider_1.provide(b, { useClass: b }));
2133 }
2134 else if (b instanceof provider_1.Provider) {
2135 res.push(b);
2136 }
2137 else if (b instanceof Array) {
2138 _normalizeProviders(b, res);
2139 }
2140 else if (b instanceof provider_1.ProviderBuilder) {
2141 throw new reflective_exceptions_1.InvalidProviderError(b.token);
2142 }
2143 else {
2144 throw new reflective_exceptions_1.InvalidProviderError(b);
2145 }
2146 });
2147 return res;
2148}
2149function constructDependencies(typeOrFunc, dependencies) {
2150 if (lang_1.isBlank(dependencies)) {
2151 return _dependenciesFor(typeOrFunc);
2152 }
2153 else {
2154 var params = dependencies.map(function (t) { return [t]; });
2155 return dependencies.map(function (t) { return _extractToken(typeOrFunc, t, params); });
2156 }
2157}
2158exports.constructDependencies = constructDependencies;
2159function _dependenciesFor(typeOrFunc) {
2160 var params = reflection_1.reflector.parameters(typeOrFunc);
2161 if (lang_1.isBlank(params))
2162 return [];
2163 if (params.some(lang_1.isBlank)) {
2164 throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params);
2165 }
2166 return params.map(function (p) { return _extractToken(typeOrFunc, p, params); });
2167}
2168function _extractToken(typeOrFunc, metadata /*any[] | any*/, params) {
2169 var depProps = [];
2170 var token = null;
2171 var optional = false;
2172 if (!lang_1.isArray(metadata)) {
2173 if (metadata instanceof metadata_1.InjectMetadata) {
2174 return _createDependency(metadata.token, optional, null, null, depProps);
2175 }
2176 else {
2177 return _createDependency(metadata, optional, null, null, depProps);
2178 }
2179 }
2180 var lowerBoundVisibility = null;
2181 var upperBoundVisibility = null;
2182 for (var i = 0; i < metadata.length; ++i) {
2183 var paramMetadata = metadata[i];
2184 if (paramMetadata instanceof lang_1.Type) {
2185 token = paramMetadata;
2186 }
2187 else if (paramMetadata instanceof metadata_1.InjectMetadata) {
2188 token = paramMetadata.token;
2189 }
2190 else if (paramMetadata instanceof metadata_1.OptionalMetadata) {
2191 optional = true;
2192 }
2193 else if (paramMetadata instanceof metadata_1.SelfMetadata) {
2194 upperBoundVisibility = paramMetadata;
2195 }
2196 else if (paramMetadata instanceof metadata_1.HostMetadata) {
2197 upperBoundVisibility = paramMetadata;
2198 }
2199 else if (paramMetadata instanceof metadata_1.SkipSelfMetadata) {
2200 lowerBoundVisibility = paramMetadata;
2201 }
2202 else if (paramMetadata instanceof metadata_1.DependencyMetadata) {
2203 if (lang_1.isPresent(paramMetadata.token)) {
2204 token = paramMetadata.token;
2205 }
2206 depProps.push(paramMetadata);
2207 }
2208 }
2209 token = forward_ref_1.resolveForwardRef(token);
2210 if (lang_1.isPresent(token)) {
2211 return _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps);
2212 }
2213 else {
2214 throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params);
2215 }
2216}
2217function _createDependency(token, optional, lowerBoundVisibility, upperBoundVisibility, depProps) {
2218 return new ReflectiveDependency(reflective_key_1.ReflectiveKey.get(token), optional, lowerBoundVisibility, upperBoundVisibility, depProps);
2219}
2220},{"./forward_ref":3,"./metadata":5,"./provider":7,"./reflective_exceptions":8,"./reflective_key":10,"angular2/src/core/reflection/reflection":12,"angular2/src/facade/collection":19,"angular2/src/facade/lang":22}],12:[function(require,module,exports){
2221'use strict';"use strict";
2222var reflector_1 = require('./reflector');
2223var reflector_2 = require('./reflector');
2224exports.Reflector = reflector_2.Reflector;
2225exports.ReflectionInfo = reflector_2.ReflectionInfo;
2226var reflection_capabilities_1 = require('./reflection_capabilities');
2227/**
2228 * The {@link Reflector} used internally in Angular to access metadata
2229 * about symbols.
2230 */
2231exports.reflector = new reflector_1.Reflector(new reflection_capabilities_1.ReflectionCapabilities());
2232},{"./reflection_capabilities":13,"./reflector":14}],13:[function(require,module,exports){
2233'use strict';"use strict";
2234var lang_1 = require('angular2/src/facade/lang');
2235var exceptions_1 = require('angular2/src/facade/exceptions');
2236var ReflectionCapabilities = (function () {
2237 function ReflectionCapabilities(reflect) {
2238 this._reflect = lang_1.isPresent(reflect) ? reflect : lang_1.global.Reflect;
2239 }
2240 ReflectionCapabilities.prototype.isReflectionEnabled = function () { return true; };
2241 ReflectionCapabilities.prototype.factory = function (t) {
2242 switch (t.length) {
2243 case 0:
2244 return function () { return new t(); };
2245 case 1:
2246 return function (a1) { return new t(a1); };
2247 case 2:
2248 return function (a1, a2) { return new t(a1, a2); };
2249 case 3:
2250 return function (a1, a2, a3) { return new t(a1, a2, a3); };
2251 case 4:
2252 return function (a1, a2, a3, a4) { return new t(a1, a2, a3, a4); };
2253 case 5:
2254 return function (a1, a2, a3, a4, a5) { return new t(a1, a2, a3, a4, a5); };
2255 case 6:
2256 return function (a1, a2, a3, a4, a5, a6) {
2257 return new t(a1, a2, a3, a4, a5, a6);
2258 };
2259 case 7:
2260 return function (a1, a2, a3, a4, a5, a6, a7) {
2261 return new t(a1, a2, a3, a4, a5, a6, a7);
2262 };
2263 case 8:
2264 return function (a1, a2, a3, a4, a5, a6, a7, a8) {
2265 return new t(a1, a2, a3, a4, a5, a6, a7, a8);
2266 };
2267 case 9:
2268 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9) {
2269 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9);
2270 };
2271 case 10:
2272 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) {
2273 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10);
2274 };
2275 case 11:
2276 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11) {
2277 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11);
2278 };
2279 case 12:
2280 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12) {
2281 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12);
2282 };
2283 case 13:
2284 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13) {
2285 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13);
2286 };
2287 case 14:
2288 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14) {
2289 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14);
2290 };
2291 case 15:
2292 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15) {
2293 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15);
2294 };
2295 case 16:
2296 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) {
2297 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16);
2298 };
2299 case 17:
2300 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17) {
2301 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17);
2302 };
2303 case 18:
2304 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18) {
2305 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18);
2306 };
2307 case 19:
2308 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19) {
2309 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19);
2310 };
2311 case 20:
2312 return function (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) {
2313 return new t(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
2314 };
2315 }
2316 ;
2317 throw new Error("Cannot create a factory for '" + lang_1.stringify(t) + "' because its constructor has more than 20 arguments");
2318 };
2319 /** @internal */
2320 ReflectionCapabilities.prototype._zipTypesAndAnnotations = function (paramTypes, paramAnnotations) {
2321 var result;
2322 if (typeof paramTypes === 'undefined') {
2323 result = new Array(paramAnnotations.length);
2324 }
2325 else {
2326 result = new Array(paramTypes.length);
2327 }
2328 for (var i = 0; i < result.length; i++) {
2329 // TS outputs Object for parameters without types, while Traceur omits
2330 // the annotations. For now we preserve the Traceur behavior to aid
2331 // migration, but this can be revisited.
2332 if (typeof paramTypes === 'undefined') {
2333 result[i] = [];
2334 }
2335 else if (paramTypes[i] != Object) {
2336 result[i] = [paramTypes[i]];
2337 }
2338 else {
2339 result[i] = [];
2340 }
2341 if (lang_1.isPresent(paramAnnotations) && lang_1.isPresent(paramAnnotations[i])) {
2342 result[i] = result[i].concat(paramAnnotations[i]);
2343 }
2344 }
2345 return result;
2346 };
2347 ReflectionCapabilities.prototype.parameters = function (typeOrFunc) {
2348 // Prefer the direct API.
2349 if (lang_1.isPresent(typeOrFunc.parameters)) {
2350 return typeOrFunc.parameters;
2351 }
2352 if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) {
2353 var paramAnnotations = this._reflect.getMetadata('parameters', typeOrFunc);
2354 var paramTypes = this._reflect.getMetadata('design:paramtypes', typeOrFunc);
2355 if (lang_1.isPresent(paramTypes) || lang_1.isPresent(paramAnnotations)) {
2356 return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
2357 }
2358 }
2359 // The array has to be filled with `undefined` because holes would be skipped by `some`
2360 var parameters = new Array(typeOrFunc.length);
2361 parameters.fill(undefined);
2362 return parameters;
2363 };
2364 ReflectionCapabilities.prototype.annotations = function (typeOrFunc) {
2365 // Prefer the direct API.
2366 if (lang_1.isPresent(typeOrFunc.annotations)) {
2367 var annotations = typeOrFunc.annotations;
2368 if (lang_1.isFunction(annotations) && annotations.annotations) {
2369 annotations = annotations.annotations;
2370 }
2371 return annotations;
2372 }
2373 if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) {
2374 var annotations = this._reflect.getMetadata('annotations', typeOrFunc);
2375 if (lang_1.isPresent(annotations))
2376 return annotations;
2377 }
2378 return [];
2379 };
2380 ReflectionCapabilities.prototype.propMetadata = function (typeOrFunc) {
2381 // Prefer the direct API.
2382 if (lang_1.isPresent(typeOrFunc.propMetadata)) {
2383 var propMetadata = typeOrFunc.propMetadata;
2384 if (lang_1.isFunction(propMetadata) && propMetadata.propMetadata) {
2385 propMetadata = propMetadata.propMetadata;
2386 }
2387 return propMetadata;
2388 }
2389 if (lang_1.isPresent(this._reflect) && lang_1.isPresent(this._reflect.getMetadata)) {
2390 var propMetadata = this._reflect.getMetadata('propMetadata', typeOrFunc);
2391 if (lang_1.isPresent(propMetadata))
2392 return propMetadata;
2393 }
2394 return {};
2395 };
2396 ReflectionCapabilities.prototype.interfaces = function (type) {
2397 throw new exceptions_1.BaseException("JavaScript does not support interfaces");
2398 };
2399 ReflectionCapabilities.prototype.getter = function (name) { return new Function('o', 'return o.' + name + ';'); };
2400 ReflectionCapabilities.prototype.setter = function (name) {
2401 return new Function('o', 'v', 'return o.' + name + ' = v;');
2402 };
2403 ReflectionCapabilities.prototype.method = function (name) {
2404 var functionBody = "if (!o." + name + ") throw new Error('\"" + name + "\" is undefined');\n return o." + name + ".apply(o, args);";
2405 return new Function('o', 'args', functionBody);
2406 };
2407 // There is not a concept of import uri in Js, but this is useful in developing Dart applications.
2408 ReflectionCapabilities.prototype.importUri = function (type) { return "./" + lang_1.stringify(type); };
2409 return ReflectionCapabilities;
2410}());
2411exports.ReflectionCapabilities = ReflectionCapabilities;
2412},{"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],14:[function(require,module,exports){
2413'use strict';"use strict";
2414var __extends = (this && this.__extends) || function (d, b) {
2415 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
2416 function __() { this.constructor = d; }
2417 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2418};
2419var lang_1 = require('angular2/src/facade/lang');
2420var exceptions_1 = require('angular2/src/facade/exceptions');
2421var collection_1 = require('angular2/src/facade/collection');
2422var reflector_reader_1 = require('./reflector_reader');
2423/**
2424 * Reflective information about a symbol, including annotations, interfaces, and other metadata.
2425 */
2426var ReflectionInfo = (function () {
2427 function ReflectionInfo(annotations, parameters, factory, interfaces, propMetadata) {
2428 this.annotations = annotations;
2429 this.parameters = parameters;
2430 this.factory = factory;
2431 this.interfaces = interfaces;
2432 this.propMetadata = propMetadata;
2433 }
2434 return ReflectionInfo;
2435}());
2436exports.ReflectionInfo = ReflectionInfo;
2437/**
2438 * Provides access to reflection data about symbols. Used internally by Angular
2439 * to power dependency injection and compilation.
2440 */
2441var Reflector = (function (_super) {
2442 __extends(Reflector, _super);
2443 function Reflector(reflectionCapabilities) {
2444 _super.call(this);
2445 /** @internal */
2446 this._injectableInfo = new collection_1.Map();
2447 /** @internal */
2448 this._getters = new collection_1.Map();
2449 /** @internal */
2450 this._setters = new collection_1.Map();
2451 /** @internal */
2452 this._methods = new collection_1.Map();
2453 this._usedKeys = null;
2454 this.reflectionCapabilities = reflectionCapabilities;
2455 }
2456 Reflector.prototype.isReflectionEnabled = function () { return this.reflectionCapabilities.isReflectionEnabled(); };
2457 /**
2458 * Causes `this` reflector to track keys used to access
2459 * {@link ReflectionInfo} objects.
2460 */
2461 Reflector.prototype.trackUsage = function () { this._usedKeys = new collection_1.Set(); };
2462 /**
2463 * Lists types for which reflection information was not requested since
2464 * {@link #trackUsage} was called. This list could later be audited as
2465 * potential dead code.
2466 */
2467 Reflector.prototype.listUnusedKeys = function () {
2468 var _this = this;
2469 if (this._usedKeys == null) {
2470 throw new exceptions_1.BaseException('Usage tracking is disabled');
2471 }
2472 var allTypes = collection_1.MapWrapper.keys(this._injectableInfo);
2473 return allTypes.filter(function (key) { return !collection_1.SetWrapper.has(_this._usedKeys, key); });
2474 };
2475 Reflector.prototype.registerFunction = function (func, funcInfo) {
2476 this._injectableInfo.set(func, funcInfo);
2477 };
2478 Reflector.prototype.registerType = function (type, typeInfo) {
2479 this._injectableInfo.set(type, typeInfo);
2480 };
2481 Reflector.prototype.registerGetters = function (getters) { _mergeMaps(this._getters, getters); };
2482 Reflector.prototype.registerSetters = function (setters) { _mergeMaps(this._setters, setters); };
2483 Reflector.prototype.registerMethods = function (methods) { _mergeMaps(this._methods, methods); };
2484 Reflector.prototype.factory = function (type) {
2485 if (this._containsReflectionInfo(type)) {
2486 var res = this._getReflectionInfo(type).factory;
2487 return lang_1.isPresent(res) ? res : null;
2488 }
2489 else {
2490 return this.reflectionCapabilities.factory(type);
2491 }
2492 };
2493 Reflector.prototype.parameters = function (typeOrFunc) {
2494 if (this._injectableInfo.has(typeOrFunc)) {
2495 var res = this._getReflectionInfo(typeOrFunc).parameters;
2496 return lang_1.isPresent(res) ? res : [];
2497 }
2498 else {
2499 return this.reflectionCapabilities.parameters(typeOrFunc);
2500 }
2501 };
2502 Reflector.prototype.annotations = function (typeOrFunc) {
2503 if (this._injectableInfo.has(typeOrFunc)) {
2504 var res = this._getReflectionInfo(typeOrFunc).annotations;
2505 return lang_1.isPresent(res) ? res : [];
2506 }
2507 else {
2508 return this.reflectionCapabilities.annotations(typeOrFunc);
2509 }
2510 };
2511 Reflector.prototype.propMetadata = function (typeOrFunc) {
2512 if (this._injectableInfo.has(typeOrFunc)) {
2513 var res = this._getReflectionInfo(typeOrFunc).propMetadata;
2514 return lang_1.isPresent(res) ? res : {};
2515 }
2516 else {
2517 return this.reflectionCapabilities.propMetadata(typeOrFunc);
2518 }
2519 };
2520 Reflector.prototype.interfaces = function (type) {
2521 if (this._injectableInfo.has(type)) {
2522 var res = this._getReflectionInfo(type).interfaces;
2523 return lang_1.isPresent(res) ? res : [];
2524 }
2525 else {
2526 return this.reflectionCapabilities.interfaces(type);
2527 }
2528 };
2529 Reflector.prototype.getter = function (name) {
2530 if (this._getters.has(name)) {
2531 return this._getters.get(name);
2532 }
2533 else {
2534 return this.reflectionCapabilities.getter(name);
2535 }
2536 };
2537 Reflector.prototype.setter = function (name) {
2538 if (this._setters.has(name)) {
2539 return this._setters.get(name);
2540 }
2541 else {
2542 return this.reflectionCapabilities.setter(name);
2543 }
2544 };
2545 Reflector.prototype.method = function (name) {
2546 if (this._methods.has(name)) {
2547 return this._methods.get(name);
2548 }
2549 else {
2550 return this.reflectionCapabilities.method(name);
2551 }
2552 };
2553 /** @internal */
2554 Reflector.prototype._getReflectionInfo = function (typeOrFunc) {
2555 if (lang_1.isPresent(this._usedKeys)) {
2556 this._usedKeys.add(typeOrFunc);
2557 }
2558 return this._injectableInfo.get(typeOrFunc);
2559 };
2560 /** @internal */
2561 Reflector.prototype._containsReflectionInfo = function (typeOrFunc) { return this._injectableInfo.has(typeOrFunc); };
2562 Reflector.prototype.importUri = function (type) { return this.reflectionCapabilities.importUri(type); };
2563 return Reflector;
2564}(reflector_reader_1.ReflectorReader));
2565exports.Reflector = Reflector;
2566function _mergeMaps(target, config) {
2567 collection_1.StringMapWrapper.forEach(config, function (v, k) { return target.set(k, v); });
2568}
2569},{"./reflector_reader":15,"angular2/src/facade/collection":19,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],15:[function(require,module,exports){
2570'use strict';"use strict";
2571/**
2572 * Provides read-only access to reflection data about symbols. Used internally by Angular
2573 * to power dependency injection and compilation.
2574 */
2575var ReflectorReader = (function () {
2576 function ReflectorReader() {
2577 }
2578 return ReflectorReader;
2579}());
2580exports.ReflectorReader = ReflectorReader;
2581},{}],16:[function(require,module,exports){
2582'use strict';"use strict";
2583var lang_1 = require('angular2/src/facade/lang');
2584var _nextClassId = 0;
2585function extractAnnotation(annotation) {
2586 if (lang_1.isFunction(annotation) && annotation.hasOwnProperty('annotation')) {
2587 // it is a decorator, extract annotation
2588 annotation = annotation.annotation;
2589 }
2590 return annotation;
2591}
2592function applyParams(fnOrArray, key) {
2593 if (fnOrArray === Object || fnOrArray === String || fnOrArray === Function ||
2594 fnOrArray === Number || fnOrArray === Array) {
2595 throw new Error("Can not use native " + lang_1.stringify(fnOrArray) + " as constructor");
2596 }
2597 if (lang_1.isFunction(fnOrArray)) {
2598 return fnOrArray;
2599 }
2600 else if (fnOrArray instanceof Array) {
2601 var annotations = fnOrArray;
2602 var fn = fnOrArray[fnOrArray.length - 1];
2603 if (!lang_1.isFunction(fn)) {
2604 throw new Error("Last position of Class method array must be Function in key " + key + " was '" + lang_1.stringify(fn) + "'");
2605 }
2606 var annoLength = annotations.length - 1;
2607 if (annoLength != fn.length) {
2608 throw new Error("Number of annotations (" + annoLength + ") does not match number of arguments (" + fn.length + ") in the function: " + lang_1.stringify(fn));
2609 }
2610 var paramsAnnotations = [];
2611 for (var i = 0, ii = annotations.length - 1; i < ii; i++) {
2612 var paramAnnotations = [];
2613 paramsAnnotations.push(paramAnnotations);
2614 var annotation = annotations[i];
2615 if (annotation instanceof Array) {
2616 for (var j = 0; j < annotation.length; j++) {
2617 paramAnnotations.push(extractAnnotation(annotation[j]));
2618 }
2619 }
2620 else if (lang_1.isFunction(annotation)) {
2621 paramAnnotations.push(extractAnnotation(annotation));
2622 }
2623 else {
2624 paramAnnotations.push(annotation);
2625 }
2626 }
2627 Reflect.defineMetadata('parameters', paramsAnnotations, fn);
2628 return fn;
2629 }
2630 else {
2631 throw new Error("Only Function or Array is supported in Class definition for key '" + key + "' is '" + lang_1.stringify(fnOrArray) + "'");
2632 }
2633}
2634/**
2635 * Provides a way for expressing ES6 classes with parameter annotations in ES5.
2636 *
2637 * ## Basic Example
2638 *
2639 * ```
2640 * var Greeter = ng.Class({
2641 * constructor: function(name) {
2642 * this.name = name;
2643 * },
2644 *
2645 * greet: function() {
2646 * alert('Hello ' + this.name + '!');
2647 * }
2648 * });
2649 * ```
2650 *
2651 * is equivalent to ES6:
2652 *
2653 * ```
2654 * class Greeter {
2655 * constructor(name) {
2656 * this.name = name;
2657 * }
2658 *
2659 * greet() {
2660 * alert('Hello ' + this.name + '!');
2661 * }
2662 * }
2663 * ```
2664 *
2665 * or equivalent to ES5:
2666 *
2667 * ```
2668 * var Greeter = function (name) {
2669 * this.name = name;
2670 * }
2671 *
2672 * Greeter.prototype.greet = function () {
2673 * alert('Hello ' + this.name + '!');
2674 * }
2675 * ```
2676 *
2677 * ### Example with parameter annotations
2678 *
2679 * ```
2680 * var MyService = ng.Class({
2681 * constructor: [String, [new Query(), QueryList], function(name, queryList) {
2682 * ...
2683 * }]
2684 * });
2685 * ```
2686 *
2687 * is equivalent to ES6:
2688 *
2689 * ```
2690 * class MyService {
2691 * constructor(name: string, @Query() queryList: QueryList) {
2692 * ...
2693 * }
2694 * }
2695 * ```
2696 *
2697 * ### Example with inheritance
2698 *
2699 * ```
2700 * var Shape = ng.Class({
2701 * constructor: (color) {
2702 * this.color = color;
2703 * }
2704 * });
2705 *
2706 * var Square = ng.Class({
2707 * extends: Shape,
2708 * constructor: function(color, size) {
2709 * Shape.call(this, color);
2710 * this.size = size;
2711 * }
2712 * });
2713 * ```
2714 */
2715function Class(clsDef) {
2716 var constructor = applyParams(clsDef.hasOwnProperty('constructor') ? clsDef.constructor : undefined, 'constructor');
2717 var proto = constructor.prototype;
2718 if (clsDef.hasOwnProperty('extends')) {
2719 if (lang_1.isFunction(clsDef.extends)) {
2720 constructor.prototype = proto =
2721 Object.create(clsDef.extends.prototype);
2722 }
2723 else {
2724 throw new Error("Class definition 'extends' property must be a constructor function was: " + lang_1.stringify(clsDef.extends));
2725 }
2726 }
2727 for (var key in clsDef) {
2728 if (key != 'extends' && key != 'prototype' && clsDef.hasOwnProperty(key)) {
2729 proto[key] = applyParams(clsDef[key], key);
2730 }
2731 }
2732 if (this && this.annotations instanceof Array) {
2733 Reflect.defineMetadata('annotations', this.annotations, constructor);
2734 }
2735 if (!constructor['name']) {
2736 constructor['overriddenName'] = "class" + _nextClassId++;
2737 }
2738 return constructor;
2739}
2740exports.Class = Class;
2741var Reflect = lang_1.global.Reflect;
2742// Throw statement at top-level is disallowed by closure compiler in ES6 input.
2743// Wrap in an IIFE as a work-around.
2744(function checkReflect() {
2745 if (!(Reflect && Reflect.getMetadata)) {
2746 throw 'reflect-metadata shim is required when using class decorators';
2747 }
2748})();
2749function makeDecorator(annotationCls, chainFn) {
2750 if (chainFn === void 0) { chainFn = null; }
2751 function DecoratorFactory(objOrType) {
2752 var annotationInstance = new annotationCls(objOrType);
2753 if (this instanceof annotationCls) {
2754 return annotationInstance;
2755 }
2756 else {
2757 var chainAnnotation = lang_1.isFunction(this) && this.annotations instanceof Array ? this.annotations : [];
2758 chainAnnotation.push(annotationInstance);
2759 var TypeDecorator = function TypeDecorator(cls) {
2760 var annotations = Reflect.getOwnMetadata('annotations', cls);
2761 annotations = annotations || [];
2762 annotations.push(annotationInstance);
2763 Reflect.defineMetadata('annotations', annotations, cls);
2764 return cls;
2765 };
2766 TypeDecorator.annotations = chainAnnotation;
2767 TypeDecorator.Class = Class;
2768 if (chainFn)
2769 chainFn(TypeDecorator);
2770 return TypeDecorator;
2771 }
2772 }
2773 DecoratorFactory.prototype = Object.create(annotationCls.prototype);
2774 return DecoratorFactory;
2775}
2776exports.makeDecorator = makeDecorator;
2777function makeParamDecorator(annotationCls) {
2778 function ParamDecoratorFactory() {
2779 var args = [];
2780 for (var _i = 0; _i < arguments.length; _i++) {
2781 args[_i - 0] = arguments[_i];
2782 }
2783 var annotationInstance = Object.create(annotationCls.prototype);
2784 annotationCls.apply(annotationInstance, args);
2785 if (this instanceof annotationCls) {
2786 return annotationInstance;
2787 }
2788 else {
2789 ParamDecorator.annotation = annotationInstance;
2790 return ParamDecorator;
2791 }
2792 function ParamDecorator(cls, unusedKey, index) {
2793 var parameters = Reflect.getMetadata('parameters', cls);
2794 parameters = parameters || [];
2795 // there might be gaps if some in between parameters do not have annotations.
2796 // we pad with nulls.
2797 while (parameters.length <= index) {
2798 parameters.push(null);
2799 }
2800 parameters[index] = parameters[index] || [];
2801 var annotationsForParam = parameters[index];
2802 annotationsForParam.push(annotationInstance);
2803 Reflect.defineMetadata('parameters', parameters, cls);
2804 return cls;
2805 }
2806 }
2807 ParamDecoratorFactory.prototype = Object.create(annotationCls.prototype);
2808 return ParamDecoratorFactory;
2809}
2810exports.makeParamDecorator = makeParamDecorator;
2811function makePropDecorator(decoratorCls) {
2812 function PropDecoratorFactory() {
2813 var args = [];
2814 for (var _i = 0; _i < arguments.length; _i++) {
2815 args[_i - 0] = arguments[_i];
2816 }
2817 var decoratorInstance = Object.create(decoratorCls.prototype);
2818 decoratorCls.apply(decoratorInstance, args);
2819 if (this instanceof decoratorCls) {
2820 return decoratorInstance;
2821 }
2822 else {
2823 return function PropDecorator(target, name) {
2824 var meta = Reflect.getOwnMetadata('propMetadata', target.constructor);
2825 meta = meta || {};
2826 meta[name] = meta[name] || [];
2827 meta[name].unshift(decoratorInstance);
2828 Reflect.defineMetadata('propMetadata', meta, target.constructor);
2829 };
2830 }
2831 }
2832 PropDecoratorFactory.prototype = Object.create(decoratorCls.prototype);
2833 return PropDecoratorFactory;
2834}
2835exports.makePropDecorator = makePropDecorator;
2836},{"angular2/src/facade/lang":22}],17:[function(require,module,exports){
2837'use strict';"use strict";
2838var __extends = (this && this.__extends) || function (d, b) {
2839 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
2840 function __() { this.constructor = d; }
2841 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2842};
2843var lang_1 = require('angular2/src/facade/lang');
2844var promise_1 = require('angular2/src/facade/promise');
2845exports.PromiseWrapper = promise_1.PromiseWrapper;
2846exports.PromiseCompleter = promise_1.PromiseCompleter;
2847var Subject_1 = require('rxjs/Subject');
2848var PromiseObservable_1 = require('rxjs/observable/PromiseObservable');
2849var toPromise_1 = require('rxjs/operator/toPromise');
2850var Observable_1 = require('rxjs/Observable');
2851exports.Observable = Observable_1.Observable;
2852var Subject_2 = require('rxjs/Subject');
2853exports.Subject = Subject_2.Subject;
2854var TimerWrapper = (function () {
2855 function TimerWrapper() {
2856 }
2857 TimerWrapper.setTimeout = function (fn, millis) {
2858 return lang_1.global.setTimeout(fn, millis);
2859 };
2860 TimerWrapper.clearTimeout = function (id) { lang_1.global.clearTimeout(id); };
2861 TimerWrapper.setInterval = function (fn, millis) {
2862 return lang_1.global.setInterval(fn, millis);
2863 };
2864 TimerWrapper.clearInterval = function (id) { lang_1.global.clearInterval(id); };
2865 return TimerWrapper;
2866}());
2867exports.TimerWrapper = TimerWrapper;
2868var ObservableWrapper = (function () {
2869 function ObservableWrapper() {
2870 }
2871 // TODO(vsavkin): when we use rxnext, try inferring the generic type from the first arg
2872 ObservableWrapper.subscribe = function (emitter, onNext, onError, onComplete) {
2873 if (onComplete === void 0) { onComplete = function () { }; }
2874 onError = (typeof onError === "function") && onError || lang_1.noop;
2875 onComplete = (typeof onComplete === "function") && onComplete || lang_1.noop;
2876 return emitter.subscribe({ next: onNext, error: onError, complete: onComplete });
2877 };
2878 ObservableWrapper.isObservable = function (obs) { return !!obs.subscribe; };
2879 /**
2880 * Returns whether `obs` has any subscribers listening to events.
2881 */
2882 ObservableWrapper.hasSubscribers = function (obs) { return obs.observers.length > 0; };
2883 ObservableWrapper.dispose = function (subscription) { subscription.unsubscribe(); };
2884 /**
2885 * @deprecated - use callEmit() instead
2886 */
2887 ObservableWrapper.callNext = function (emitter, value) { emitter.next(value); };
2888 ObservableWrapper.callEmit = function (emitter, value) { emitter.emit(value); };
2889 ObservableWrapper.callError = function (emitter, error) { emitter.error(error); };
2890 ObservableWrapper.callComplete = function (emitter) { emitter.complete(); };
2891 ObservableWrapper.fromPromise = function (promise) {
2892 return PromiseObservable_1.PromiseObservable.create(promise);
2893 };
2894 ObservableWrapper.toPromise = function (obj) { return toPromise_1.toPromise.call(obj); };
2895 return ObservableWrapper;
2896}());
2897exports.ObservableWrapper = ObservableWrapper;
2898/**
2899 * Use by directives and components to emit custom Events.
2900 *
2901 * ### Examples
2902 *
2903 * In the following example, `Zippy` alternatively emits `open` and `close` events when its
2904 * title gets clicked:
2905 *
2906 * ```
2907 * @Component({
2908 * selector: 'zippy',
2909 * template: `
2910 * <div class="zippy">
2911 * <div (click)="toggle()">Toggle</div>
2912 * <div [hidden]="!visible">
2913 * <ng-content></ng-content>
2914 * </div>
2915 * </div>`})
2916 * export class Zippy {
2917 * visible: boolean = true;
2918 * @Output() open: EventEmitter<any> = new EventEmitter();
2919 * @Output() close: EventEmitter<any> = new EventEmitter();
2920 *
2921 * toggle() {
2922 * this.visible = !this.visible;
2923 * if (this.visible) {
2924 * this.open.emit(null);
2925 * } else {
2926 * this.close.emit(null);
2927 * }
2928 * }
2929 * }
2930 * ```
2931 *
2932 * Use Rx.Observable but provides an adapter to make it work as specified here:
2933 * https://github.com/jhusain/observable-spec
2934 *
2935 * Once a reference implementation of the spec is available, switch to it.
2936 */
2937var EventEmitter = (function (_super) {
2938 __extends(EventEmitter, _super);
2939 /**
2940 * Creates an instance of [EventEmitter], which depending on [isAsync],
2941 * delivers events synchronously or asynchronously.
2942 */
2943 function EventEmitter(isAsync) {
2944 if (isAsync === void 0) { isAsync = true; }
2945 _super.call(this);
2946 this._isAsync = isAsync;
2947 }
2948 EventEmitter.prototype.emit = function (value) { _super.prototype.next.call(this, value); };
2949 /**
2950 * @deprecated - use .emit(value) instead
2951 */
2952 EventEmitter.prototype.next = function (value) { _super.prototype.next.call(this, value); };
2953 EventEmitter.prototype.subscribe = function (generatorOrNext, error, complete) {
2954 var schedulerFn;
2955 var errorFn = function (err) { return null; };
2956 var completeFn = function () { return null; };
2957 if (generatorOrNext && typeof generatorOrNext === 'object') {
2958 schedulerFn = this._isAsync ? function (value) { setTimeout(function () { return generatorOrNext.next(value); }); } :
2959 function (value) { generatorOrNext.next(value); };
2960 if (generatorOrNext.error) {
2961 errorFn = this._isAsync ? function (err) { setTimeout(function () { return generatorOrNext.error(err); }); } :
2962 function (err) { generatorOrNext.error(err); };
2963 }
2964 if (generatorOrNext.complete) {
2965 completeFn = this._isAsync ? function () { setTimeout(function () { return generatorOrNext.complete(); }); } :
2966 function () { generatorOrNext.complete(); };
2967 }
2968 }
2969 else {
2970 schedulerFn = this._isAsync ? function (value) { setTimeout(function () { return generatorOrNext(value); }); } :
2971 function (value) { generatorOrNext(value); };
2972 if (error) {
2973 errorFn =
2974 this._isAsync ? function (err) { setTimeout(function () { return error(err); }); } : function (err) { error(err); };
2975 }
2976 if (complete) {
2977 completeFn =
2978 this._isAsync ? function () { setTimeout(function () { return complete(); }); } : function () { complete(); };
2979 }
2980 }
2981 return _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn);
2982 };
2983 return EventEmitter;
2984}(Subject_1.Subject));
2985exports.EventEmitter = EventEmitter;
2986},{"angular2/src/facade/lang":22,"angular2/src/facade/promise":24,"rxjs/Observable":50,"rxjs/Subject":52,"rxjs/observable/PromiseObservable":56,"rxjs/operator/toPromise":57}],18:[function(require,module,exports){
2987'use strict';"use strict";
2988var __extends = (this && this.__extends) || function (d, b) {
2989 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
2990 function __() { this.constructor = d; }
2991 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2992};
2993/**
2994 * A base class for the WrappedException that can be used to identify
2995 * a WrappedException from ExceptionHandler without adding circular
2996 * dependency.
2997 */
2998var BaseWrappedException = (function (_super) {
2999 __extends(BaseWrappedException, _super);
3000 function BaseWrappedException(message) {
3001 _super.call(this, message);
3002 }
3003 Object.defineProperty(BaseWrappedException.prototype, "wrapperMessage", {
3004 get: function () { return ''; },
3005 enumerable: true,
3006 configurable: true
3007 });
3008 Object.defineProperty(BaseWrappedException.prototype, "wrapperStack", {
3009 get: function () { return null; },
3010 enumerable: true,
3011 configurable: true
3012 });
3013 Object.defineProperty(BaseWrappedException.prototype, "originalException", {
3014 get: function () { return null; },
3015 enumerable: true,
3016 configurable: true
3017 });
3018 Object.defineProperty(BaseWrappedException.prototype, "originalStack", {
3019 get: function () { return null; },
3020 enumerable: true,
3021 configurable: true
3022 });
3023 Object.defineProperty(BaseWrappedException.prototype, "context", {
3024 get: function () { return null; },
3025 enumerable: true,
3026 configurable: true
3027 });
3028 Object.defineProperty(BaseWrappedException.prototype, "message", {
3029 get: function () { return ''; },
3030 enumerable: true,
3031 configurable: true
3032 });
3033 return BaseWrappedException;
3034}(Error));
3035exports.BaseWrappedException = BaseWrappedException;
3036},{}],19:[function(require,module,exports){
3037'use strict';"use strict";
3038var lang_1 = require('angular2/src/facade/lang');
3039exports.Map = lang_1.global.Map;
3040exports.Set = lang_1.global.Set;
3041// Safari and Internet Explorer do not support the iterable parameter to the
3042// Map constructor. We work around that by manually adding the items.
3043var createMapFromPairs = (function () {
3044 try {
3045 if (new exports.Map([[1, 2]]).size === 1) {
3046 return function createMapFromPairs(pairs) { return new exports.Map(pairs); };
3047 }
3048 }
3049 catch (e) {
3050 }
3051 return function createMapAndPopulateFromPairs(pairs) {
3052 var map = new exports.Map();
3053 for (var i = 0; i < pairs.length; i++) {
3054 var pair = pairs[i];
3055 map.set(pair[0], pair[1]);
3056 }
3057 return map;
3058 };
3059})();
3060var createMapFromMap = (function () {
3061 try {
3062 if (new exports.Map(new exports.Map())) {
3063 return function createMapFromMap(m) { return new exports.Map(m); };
3064 }
3065 }
3066 catch (e) {
3067 }
3068 return function createMapAndPopulateFromMap(m) {
3069 var map = new exports.Map();
3070 m.forEach(function (v, k) { map.set(k, v); });
3071 return map;
3072 };
3073})();
3074var _clearValues = (function () {
3075 if ((new exports.Map()).keys().next) {
3076 return function _clearValues(m) {
3077 var keyIterator = m.keys();
3078 var k;
3079 while (!((k = keyIterator.next()).done)) {
3080 m.set(k.value, null);
3081 }
3082 };
3083 }
3084 else {
3085 return function _clearValuesWithForeEach(m) {
3086 m.forEach(function (v, k) { m.set(k, null); });
3087 };
3088 }
3089})();
3090// Safari doesn't implement MapIterator.next(), which is used is Traceur's polyfill of Array.from
3091// TODO(mlaval): remove the work around once we have a working polyfill of Array.from
3092var _arrayFromMap = (function () {
3093 try {
3094 if ((new exports.Map()).values().next) {
3095 return function createArrayFromMap(m, getValues) {
3096 return getValues ? Array.from(m.values()) : Array.from(m.keys());
3097 };
3098 }
3099 }
3100 catch (e) {
3101 }
3102 return function createArrayFromMapWithForeach(m, getValues) {
3103 var res = ListWrapper.createFixedSize(m.size), i = 0;
3104 m.forEach(function (v, k) {
3105 res[i] = getValues ? v : k;
3106 i++;
3107 });
3108 return res;
3109 };
3110})();
3111var MapWrapper = (function () {
3112 function MapWrapper() {
3113 }
3114 MapWrapper.clone = function (m) { return createMapFromMap(m); };
3115 MapWrapper.createFromStringMap = function (stringMap) {
3116 var result = new exports.Map();
3117 for (var prop in stringMap) {
3118 result.set(prop, stringMap[prop]);
3119 }
3120 return result;
3121 };
3122 MapWrapper.toStringMap = function (m) {
3123 var r = {};
3124 m.forEach(function (v, k) { return r[k] = v; });
3125 return r;
3126 };
3127 MapWrapper.createFromPairs = function (pairs) { return createMapFromPairs(pairs); };
3128 MapWrapper.clearValues = function (m) { _clearValues(m); };
3129 MapWrapper.iterable = function (m) { return m; };
3130 MapWrapper.keys = function (m) { return _arrayFromMap(m, false); };
3131 MapWrapper.values = function (m) { return _arrayFromMap(m, true); };
3132 return MapWrapper;
3133}());
3134exports.MapWrapper = MapWrapper;
3135/**
3136 * Wraps Javascript Objects
3137 */
3138var StringMapWrapper = (function () {
3139 function StringMapWrapper() {
3140 }
3141 StringMapWrapper.create = function () {
3142 // Note: We are not using Object.create(null) here due to
3143 // performance!
3144 // http://jsperf.com/ng2-object-create-null
3145 return {};
3146 };
3147 StringMapWrapper.contains = function (map, key) {
3148 return map.hasOwnProperty(key);
3149 };
3150 StringMapWrapper.get = function (map, key) {
3151 return map.hasOwnProperty(key) ? map[key] : undefined;
3152 };
3153 StringMapWrapper.set = function (map, key, value) { map[key] = value; };
3154 StringMapWrapper.keys = function (map) { return Object.keys(map); };
3155 StringMapWrapper.values = function (map) {
3156 return Object.keys(map).reduce(function (r, a) {
3157 r.push(map[a]);
3158 return r;
3159 }, []);
3160 };
3161 StringMapWrapper.isEmpty = function (map) {
3162 for (var prop in map) {
3163 return false;
3164 }
3165 return true;
3166 };
3167 StringMapWrapper.delete = function (map, key) { delete map[key]; };
3168 StringMapWrapper.forEach = function (map, callback) {
3169 for (var prop in map) {
3170 if (map.hasOwnProperty(prop)) {
3171 callback(map[prop], prop);
3172 }
3173 }
3174 };
3175 StringMapWrapper.merge = function (m1, m2) {
3176 var m = {};
3177 for (var attr in m1) {
3178 if (m1.hasOwnProperty(attr)) {
3179 m[attr] = m1[attr];
3180 }
3181 }
3182 for (var attr in m2) {
3183 if (m2.hasOwnProperty(attr)) {
3184 m[attr] = m2[attr];
3185 }
3186 }
3187 return m;
3188 };
3189 StringMapWrapper.equals = function (m1, m2) {
3190 var k1 = Object.keys(m1);
3191 var k2 = Object.keys(m2);
3192 if (k1.length != k2.length) {
3193 return false;
3194 }
3195 var key;
3196 for (var i = 0; i < k1.length; i++) {
3197 key = k1[i];
3198 if (m1[key] !== m2[key]) {
3199 return false;
3200 }
3201 }
3202 return true;
3203 };
3204 return StringMapWrapper;
3205}());
3206exports.StringMapWrapper = StringMapWrapper;
3207var ListWrapper = (function () {
3208 function ListWrapper() {
3209 }
3210 // JS has no way to express a statically fixed size list, but dart does so we
3211 // keep both methods.
3212 ListWrapper.createFixedSize = function (size) { return new Array(size); };
3213 ListWrapper.createGrowableSize = function (size) { return new Array(size); };
3214 ListWrapper.clone = function (array) { return array.slice(0); };
3215 ListWrapper.forEachWithIndex = function (array, fn) {
3216 for (var i = 0; i < array.length; i++) {
3217 fn(array[i], i);
3218 }
3219 };
3220 ListWrapper.first = function (array) {
3221 if (!array)
3222 return null;
3223 return array[0];
3224 };
3225 ListWrapper.last = function (array) {
3226 if (!array || array.length == 0)
3227 return null;
3228 return array[array.length - 1];
3229 };
3230 ListWrapper.indexOf = function (array, value, startIndex) {
3231 if (startIndex === void 0) { startIndex = 0; }
3232 return array.indexOf(value, startIndex);
3233 };
3234 ListWrapper.contains = function (list, el) { return list.indexOf(el) !== -1; };
3235 ListWrapper.reversed = function (array) {
3236 var a = ListWrapper.clone(array);
3237 return a.reverse();
3238 };
3239 ListWrapper.concat = function (a, b) { return a.concat(b); };
3240 ListWrapper.insert = function (list, index, value) { list.splice(index, 0, value); };
3241 ListWrapper.removeAt = function (list, index) {
3242 var res = list[index];
3243 list.splice(index, 1);
3244 return res;
3245 };
3246 ListWrapper.removeAll = function (list, items) {
3247 for (var i = 0; i < items.length; ++i) {
3248 var index = list.indexOf(items[i]);
3249 list.splice(index, 1);
3250 }
3251 };
3252 ListWrapper.remove = function (list, el) {
3253 var index = list.indexOf(el);
3254 if (index > -1) {
3255 list.splice(index, 1);
3256 return true;
3257 }
3258 return false;
3259 };
3260 ListWrapper.clear = function (list) { list.length = 0; };
3261 ListWrapper.isEmpty = function (list) { return list.length == 0; };
3262 ListWrapper.fill = function (list, value, start, end) {
3263 if (start === void 0) { start = 0; }
3264 if (end === void 0) { end = null; }
3265 list.fill(value, start, end === null ? list.length : end);
3266 };
3267 ListWrapper.equals = function (a, b) {
3268 if (a.length != b.length)
3269 return false;
3270 for (var i = 0; i < a.length; ++i) {
3271 if (a[i] !== b[i])
3272 return false;
3273 }
3274 return true;
3275 };
3276 ListWrapper.slice = function (l, from, to) {
3277 if (from === void 0) { from = 0; }
3278 if (to === void 0) { to = null; }
3279 return l.slice(from, to === null ? undefined : to);
3280 };
3281 ListWrapper.splice = function (l, from, length) { return l.splice(from, length); };
3282 ListWrapper.sort = function (l, compareFn) {
3283 if (lang_1.isPresent(compareFn)) {
3284 l.sort(compareFn);
3285 }
3286 else {
3287 l.sort();
3288 }
3289 };
3290 ListWrapper.toString = function (l) { return l.toString(); };
3291 ListWrapper.toJSON = function (l) { return JSON.stringify(l); };
3292 ListWrapper.maximum = function (list, predicate) {
3293 if (list.length == 0) {
3294 return null;
3295 }
3296 var solution = null;
3297 var maxValue = -Infinity;
3298 for (var index = 0; index < list.length; index++) {
3299 var candidate = list[index];
3300 if (lang_1.isBlank(candidate)) {
3301 continue;
3302 }
3303 var candidateValue = predicate(candidate);
3304 if (candidateValue > maxValue) {
3305 solution = candidate;
3306 maxValue = candidateValue;
3307 }
3308 }
3309 return solution;
3310 };
3311 ListWrapper.flatten = function (list) {
3312 var target = [];
3313 _flattenArray(list, target);
3314 return target;
3315 };
3316 ListWrapper.addAll = function (list, source) {
3317 for (var i = 0; i < source.length; i++) {
3318 list.push(source[i]);
3319 }
3320 };
3321 return ListWrapper;
3322}());
3323exports.ListWrapper = ListWrapper;
3324function _flattenArray(source, target) {
3325 if (lang_1.isPresent(source)) {
3326 for (var i = 0; i < source.length; i++) {
3327 var item = source[i];
3328 if (lang_1.isArray(item)) {
3329 _flattenArray(item, target);
3330 }
3331 else {
3332 target.push(item);
3333 }
3334 }
3335 }
3336 return target;
3337}
3338function isListLikeIterable(obj) {
3339 if (!lang_1.isJsObject(obj))
3340 return false;
3341 return lang_1.isArray(obj) ||
3342 (!(obj instanceof exports.Map) &&
3343 lang_1.getSymbolIterator() in obj); // JS Iterable have a Symbol.iterator prop
3344}
3345exports.isListLikeIterable = isListLikeIterable;
3346function areIterablesEqual(a, b, comparator) {
3347 var iterator1 = a[lang_1.getSymbolIterator()]();
3348 var iterator2 = b[lang_1.getSymbolIterator()]();
3349 while (true) {
3350 var item1 = iterator1.next();
3351 var item2 = iterator2.next();
3352 if (item1.done && item2.done)
3353 return true;
3354 if (item1.done || item2.done)
3355 return false;
3356 if (!comparator(item1.value, item2.value))
3357 return false;
3358 }
3359}
3360exports.areIterablesEqual = areIterablesEqual;
3361function iterateListLike(obj, fn) {
3362 if (lang_1.isArray(obj)) {
3363 for (var i = 0; i < obj.length; i++) {
3364 fn(obj[i]);
3365 }
3366 }
3367 else {
3368 var iterator = obj[lang_1.getSymbolIterator()]();
3369 var item;
3370 while (!((item = iterator.next()).done)) {
3371 fn(item.value);
3372 }
3373 }
3374}
3375exports.iterateListLike = iterateListLike;
3376// Safari and Internet Explorer do not support the iterable parameter to the
3377// Set constructor. We work around that by manually adding the items.
3378var createSetFromList = (function () {
3379 var test = new exports.Set([1, 2, 3]);
3380 if (test.size === 3) {
3381 return function createSetFromList(lst) { return new exports.Set(lst); };
3382 }
3383 else {
3384 return function createSetAndPopulateFromList(lst) {
3385 var res = new exports.Set(lst);
3386 if (res.size !== lst.length) {
3387 for (var i = 0; i < lst.length; i++) {
3388 res.add(lst[i]);
3389 }
3390 }
3391 return res;
3392 };
3393 }
3394})();
3395var SetWrapper = (function () {
3396 function SetWrapper() {
3397 }
3398 SetWrapper.createFromList = function (lst) { return createSetFromList(lst); };
3399 SetWrapper.has = function (s, key) { return s.has(key); };
3400 SetWrapper.delete = function (m, k) { m.delete(k); };
3401 return SetWrapper;
3402}());
3403exports.SetWrapper = SetWrapper;
3404},{"angular2/src/facade/lang":22}],20:[function(require,module,exports){
3405'use strict';"use strict";
3406var lang_1 = require('angular2/src/facade/lang');
3407var base_wrapped_exception_1 = require('angular2/src/facade/base_wrapped_exception');
3408var collection_1 = require('angular2/src/facade/collection');
3409var _ArrayLogger = (function () {
3410 function _ArrayLogger() {
3411 this.res = [];
3412 }
3413 _ArrayLogger.prototype.log = function (s) { this.res.push(s); };
3414 _ArrayLogger.prototype.logError = function (s) { this.res.push(s); };
3415 _ArrayLogger.prototype.logGroup = function (s) { this.res.push(s); };
3416 _ArrayLogger.prototype.logGroupEnd = function () { };
3417 ;
3418 return _ArrayLogger;
3419}());
3420/**
3421 * Provides a hook for centralized exception handling.
3422 *
3423 * The default implementation of `ExceptionHandler` prints error messages to the `Console`. To
3424 * intercept error handling,
3425 * write a custom exception handler that replaces this default as appropriate for your app.
3426 *
3427 * ### Example
3428 *
3429 * ```javascript
3430 *
3431 * class MyExceptionHandler implements ExceptionHandler {
3432 * call(error, stackTrace = null, reason = null) {
3433 * // do something with the exception
3434 * }
3435 * }
3436 *
3437 * bootstrap(MyApp, [provide(ExceptionHandler, {useClass: MyExceptionHandler})])
3438 *
3439 * ```
3440 */
3441var ExceptionHandler = (function () {
3442 function ExceptionHandler(_logger, _rethrowException) {
3443 if (_rethrowException === void 0) { _rethrowException = true; }
3444 this._logger = _logger;
3445 this._rethrowException = _rethrowException;
3446 }
3447 ExceptionHandler.exceptionToString = function (exception, stackTrace, reason) {
3448 if (stackTrace === void 0) { stackTrace = null; }
3449 if (reason === void 0) { reason = null; }
3450 var l = new _ArrayLogger();
3451 var e = new ExceptionHandler(l, false);
3452 e.call(exception, stackTrace, reason);
3453 return l.res.join("\n");
3454 };
3455 ExceptionHandler.prototype.call = function (exception, stackTrace, reason) {
3456 if (stackTrace === void 0) { stackTrace = null; }
3457 if (reason === void 0) { reason = null; }
3458 var originalException = this._findOriginalException(exception);
3459 var originalStack = this._findOriginalStack(exception);
3460 var context = this._findContext(exception);
3461 this._logger.logGroup("EXCEPTION: " + this._extractMessage(exception));
3462 if (lang_1.isPresent(stackTrace) && lang_1.isBlank(originalStack)) {
3463 this._logger.logError("STACKTRACE:");
3464 this._logger.logError(this._longStackTrace(stackTrace));
3465 }
3466 if (lang_1.isPresent(reason)) {
3467 this._logger.logError("REASON: " + reason);
3468 }
3469 if (lang_1.isPresent(originalException)) {
3470 this._logger.logError("ORIGINAL EXCEPTION: " + this._extractMessage(originalException));
3471 }
3472 if (lang_1.isPresent(originalStack)) {
3473 this._logger.logError("ORIGINAL STACKTRACE:");
3474 this._logger.logError(this._longStackTrace(originalStack));
3475 }
3476 if (lang_1.isPresent(context)) {
3477 this._logger.logError("ERROR CONTEXT:");
3478 this._logger.logError(context);
3479 }
3480 this._logger.logGroupEnd();
3481 // We rethrow exceptions, so operations like 'bootstrap' will result in an error
3482 // when an exception happens. If we do not rethrow, bootstrap will always succeed.
3483 if (this._rethrowException)
3484 throw exception;
3485 };
3486 /** @internal */
3487 ExceptionHandler.prototype._extractMessage = function (exception) {
3488 return exception instanceof base_wrapped_exception_1.BaseWrappedException ? exception.wrapperMessage :
3489 exception.toString();
3490 };
3491 /** @internal */
3492 ExceptionHandler.prototype._longStackTrace = function (stackTrace) {
3493 return collection_1.isListLikeIterable(stackTrace) ? stackTrace.join("\n\n-----async gap-----\n") :
3494 stackTrace.toString();
3495 };
3496 /** @internal */
3497 ExceptionHandler.prototype._findContext = function (exception) {
3498 try {
3499 if (!(exception instanceof base_wrapped_exception_1.BaseWrappedException))
3500 return null;
3501 return lang_1.isPresent(exception.context) ? exception.context :
3502 this._findContext(exception.originalException);
3503 }
3504 catch (e) {
3505 // exception.context can throw an exception. if it happens, we ignore the context.
3506 return null;
3507 }
3508 };
3509 /** @internal */
3510 ExceptionHandler.prototype._findOriginalException = function (exception) {
3511 if (!(exception instanceof base_wrapped_exception_1.BaseWrappedException))
3512 return null;
3513 var e = exception.originalException;
3514 while (e instanceof base_wrapped_exception_1.BaseWrappedException && lang_1.isPresent(e.originalException)) {
3515 e = e.originalException;
3516 }
3517 return e;
3518 };
3519 /** @internal */
3520 ExceptionHandler.prototype._findOriginalStack = function (exception) {
3521 if (!(exception instanceof base_wrapped_exception_1.BaseWrappedException))
3522 return null;
3523 var e = exception;
3524 var stack = exception.originalStack;
3525 while (e instanceof base_wrapped_exception_1.BaseWrappedException && lang_1.isPresent(e.originalException)) {
3526 e = e.originalException;
3527 if (e instanceof base_wrapped_exception_1.BaseWrappedException && lang_1.isPresent(e.originalException)) {
3528 stack = e.originalStack;
3529 }
3530 }
3531 return stack;
3532 };
3533 return ExceptionHandler;
3534}());
3535exports.ExceptionHandler = ExceptionHandler;
3536},{"angular2/src/facade/base_wrapped_exception":18,"angular2/src/facade/collection":19,"angular2/src/facade/lang":22}],21:[function(require,module,exports){
3537'use strict';"use strict";
3538var __extends = (this && this.__extends) || function (d, b) {
3539 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
3540 function __() { this.constructor = d; }
3541 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
3542};
3543var base_wrapped_exception_1 = require('./base_wrapped_exception');
3544var exception_handler_1 = require('./exception_handler');
3545var exception_handler_2 = require('./exception_handler');
3546exports.ExceptionHandler = exception_handler_2.ExceptionHandler;
3547var BaseException = (function (_super) {
3548 __extends(BaseException, _super);
3549 function BaseException(message) {
3550 if (message === void 0) { message = "--"; }
3551 _super.call(this, message);
3552 this.message = message;
3553 this.stack = (new Error(message)).stack;
3554 }
3555 BaseException.prototype.toString = function () { return this.message; };
3556 return BaseException;
3557}(Error));
3558exports.BaseException = BaseException;
3559/**
3560 * Wraps an exception and provides additional context or information.
3561 */
3562var WrappedException = (function (_super) {
3563 __extends(WrappedException, _super);
3564 function WrappedException(_wrapperMessage, _originalException, _originalStack, _context) {
3565 _super.call(this, _wrapperMessage);
3566 this._wrapperMessage = _wrapperMessage;
3567 this._originalException = _originalException;
3568 this._originalStack = _originalStack;
3569 this._context = _context;
3570 this._wrapperStack = (new Error(_wrapperMessage)).stack;
3571 }
3572 Object.defineProperty(WrappedException.prototype, "wrapperMessage", {
3573 get: function () { return this._wrapperMessage; },
3574 enumerable: true,
3575 configurable: true
3576 });
3577 Object.defineProperty(WrappedException.prototype, "wrapperStack", {
3578 get: function () { return this._wrapperStack; },
3579 enumerable: true,
3580 configurable: true
3581 });
3582 Object.defineProperty(WrappedException.prototype, "originalException", {
3583 get: function () { return this._originalException; },
3584 enumerable: true,
3585 configurable: true
3586 });
3587 Object.defineProperty(WrappedException.prototype, "originalStack", {
3588 get: function () { return this._originalStack; },
3589 enumerable: true,
3590 configurable: true
3591 });
3592 Object.defineProperty(WrappedException.prototype, "context", {
3593 get: function () { return this._context; },
3594 enumerable: true,
3595 configurable: true
3596 });
3597 Object.defineProperty(WrappedException.prototype, "message", {
3598 get: function () { return exception_handler_1.ExceptionHandler.exceptionToString(this); },
3599 enumerable: true,
3600 configurable: true
3601 });
3602 WrappedException.prototype.toString = function () { return this.message; };
3603 return WrappedException;
3604}(base_wrapped_exception_1.BaseWrappedException));
3605exports.WrappedException = WrappedException;
3606function makeTypeError(message) {
3607 return new TypeError(message);
3608}
3609exports.makeTypeError = makeTypeError;
3610function unimplemented() {
3611 throw new BaseException('unimplemented');
3612}
3613exports.unimplemented = unimplemented;
3614},{"./base_wrapped_exception":18,"./exception_handler":20}],22:[function(require,module,exports){
3615'use strict';"use strict";
3616var __extends = (this && this.__extends) || function (d, b) {
3617 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
3618 function __() { this.constructor = d; }
3619 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
3620};
3621var globalScope;
3622if (typeof window === 'undefined') {
3623 if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
3624 // TODO: Replace any with WorkerGlobalScope from lib.webworker.d.ts #3492
3625 globalScope = self;
3626 }
3627 else {
3628 globalScope = global;
3629 }
3630}
3631else {
3632 globalScope = window;
3633}
3634function scheduleMicroTask(fn) {
3635 Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
3636}
3637exports.scheduleMicroTask = scheduleMicroTask;
3638exports.IS_DART = false;
3639// Need to declare a new variable for global here since TypeScript
3640// exports the original value of the symbol.
3641var _global = globalScope;
3642exports.global = _global;
3643exports.Type = Function;
3644function getTypeNameForDebugging(type) {
3645 if (type['name']) {
3646 return type['name'];
3647 }
3648 return typeof type;
3649}
3650exports.getTypeNameForDebugging = getTypeNameForDebugging;
3651exports.Math = _global.Math;
3652exports.Date = _global.Date;
3653var _devMode = true;
3654var _modeLocked = false;
3655function lockMode() {
3656 _modeLocked = true;
3657}
3658exports.lockMode = lockMode;
3659/**
3660 * Disable Angular's development mode, which turns off assertions and other
3661 * checks within the framework.
3662 *
3663 * One important assertion this disables verifies that a change detection pass
3664 * does not result in additional changes to any bindings (also known as
3665 * unidirectional data flow).
3666 */
3667function enableProdMode() {
3668 if (_modeLocked) {
3669 // Cannot use BaseException as that ends up importing from facade/lang.
3670 throw 'Cannot enable prod mode after platform setup.';
3671 }
3672 _devMode = false;
3673}
3674exports.enableProdMode = enableProdMode;
3675function assertionsEnabled() {
3676 return _devMode;
3677}
3678exports.assertionsEnabled = assertionsEnabled;
3679// TODO: remove calls to assert in production environment
3680// Note: Can't just export this and import in in other files
3681// as `assert` is a reserved keyword in Dart
3682_global.assert = function assert(condition) {
3683 // TODO: to be fixed properly via #2830, noop for now
3684};
3685// This function is needed only to properly support Dart's const expressions
3686// see https://github.com/angular/ts2dart/pull/151 for more info
3687function CONST_EXPR(expr) {
3688 return expr;
3689}
3690exports.CONST_EXPR = CONST_EXPR;
3691function CONST() {
3692 return function (target) { return target; };
3693}
3694exports.CONST = CONST;
3695function isPresent(obj) {
3696 return obj !== undefined && obj !== null;
3697}
3698exports.isPresent = isPresent;
3699function isBlank(obj) {
3700 return obj === undefined || obj === null;
3701}
3702exports.isBlank = isBlank;
3703function isBoolean(obj) {
3704 return typeof obj === "boolean";
3705}
3706exports.isBoolean = isBoolean;
3707function isNumber(obj) {
3708 return typeof obj === "number";
3709}
3710exports.isNumber = isNumber;
3711function isString(obj) {
3712 return typeof obj === "string";
3713}
3714exports.isString = isString;
3715function isFunction(obj) {
3716 return typeof obj === "function";
3717}
3718exports.isFunction = isFunction;
3719function isType(obj) {
3720 return isFunction(obj);
3721}
3722exports.isType = isType;
3723function isStringMap(obj) {
3724 return typeof obj === 'object' && obj !== null;
3725}
3726exports.isStringMap = isStringMap;
3727function isPromise(obj) {
3728 return obj instanceof _global.Promise;
3729}
3730exports.isPromise = isPromise;
3731function isArray(obj) {
3732 return Array.isArray(obj);
3733}
3734exports.isArray = isArray;
3735function isDate(obj) {
3736 return obj instanceof exports.Date && !isNaN(obj.valueOf());
3737}
3738exports.isDate = isDate;
3739function noop() { }
3740exports.noop = noop;
3741function stringify(token) {
3742 if (typeof token === 'string') {
3743 return token;
3744 }
3745 if (token === undefined || token === null) {
3746 return '' + token;
3747 }
3748 if (token.name) {
3749 return token.name;
3750 }
3751 if (token.overriddenName) {
3752 return token.overriddenName;
3753 }
3754 var res = token.toString();
3755 var newLineIndex = res.indexOf("\n");
3756 return (newLineIndex === -1) ? res : res.substring(0, newLineIndex);
3757}
3758exports.stringify = stringify;
3759// serialize / deserialize enum exist only for consistency with dart API
3760// enums in typescript don't need to be serialized
3761function serializeEnum(val) {
3762 return val;
3763}
3764exports.serializeEnum = serializeEnum;
3765function deserializeEnum(val, values) {
3766 return val;
3767}
3768exports.deserializeEnum = deserializeEnum;
3769function resolveEnumToken(enumValue, val) {
3770 return enumValue[val];
3771}
3772exports.resolveEnumToken = resolveEnumToken;
3773var StringWrapper = (function () {
3774 function StringWrapper() {
3775 }
3776 StringWrapper.fromCharCode = function (code) { return String.fromCharCode(code); };
3777 StringWrapper.charCodeAt = function (s, index) { return s.charCodeAt(index); };
3778 StringWrapper.split = function (s, regExp) { return s.split(regExp); };
3779 StringWrapper.equals = function (s, s2) { return s === s2; };
3780 StringWrapper.stripLeft = function (s, charVal) {
3781 if (s && s.length) {
3782 var pos = 0;
3783 for (var i = 0; i < s.length; i++) {
3784 if (s[i] != charVal)
3785 break;
3786 pos++;
3787 }
3788 s = s.substring(pos);
3789 }
3790 return s;
3791 };
3792 StringWrapper.stripRight = function (s, charVal) {
3793 if (s && s.length) {
3794 var pos = s.length;
3795 for (var i = s.length - 1; i >= 0; i--) {
3796 if (s[i] != charVal)
3797 break;
3798 pos--;
3799 }
3800 s = s.substring(0, pos);
3801 }
3802 return s;
3803 };
3804 StringWrapper.replace = function (s, from, replace) {
3805 return s.replace(from, replace);
3806 };
3807 StringWrapper.replaceAll = function (s, from, replace) {
3808 return s.replace(from, replace);
3809 };
3810 StringWrapper.slice = function (s, from, to) {
3811 if (from === void 0) { from = 0; }
3812 if (to === void 0) { to = null; }
3813 return s.slice(from, to === null ? undefined : to);
3814 };
3815 StringWrapper.replaceAllMapped = function (s, from, cb) {
3816 return s.replace(from, function () {
3817 var matches = [];
3818 for (var _i = 0; _i < arguments.length; _i++) {
3819 matches[_i - 0] = arguments[_i];
3820 }
3821 // Remove offset & string from the result array
3822 matches.splice(-2, 2);
3823 // The callback receives match, p1, ..., pn
3824 return cb(matches);
3825 });
3826 };
3827 StringWrapper.contains = function (s, substr) { return s.indexOf(substr) != -1; };
3828 StringWrapper.compare = function (a, b) {
3829 if (a < b) {
3830 return -1;
3831 }
3832 else if (a > b) {
3833 return 1;
3834 }
3835 else {
3836 return 0;
3837 }
3838 };
3839 return StringWrapper;
3840}());
3841exports.StringWrapper = StringWrapper;
3842var StringJoiner = (function () {
3843 function StringJoiner(parts) {
3844 if (parts === void 0) { parts = []; }
3845 this.parts = parts;
3846 }
3847 StringJoiner.prototype.add = function (part) { this.parts.push(part); };
3848 StringJoiner.prototype.toString = function () { return this.parts.join(""); };
3849 return StringJoiner;
3850}());
3851exports.StringJoiner = StringJoiner;
3852var NumberParseError = (function (_super) {
3853 __extends(NumberParseError, _super);
3854 function NumberParseError(message) {
3855 _super.call(this);
3856 this.message = message;
3857 }
3858 NumberParseError.prototype.toString = function () { return this.message; };
3859 return NumberParseError;
3860}(Error));
3861exports.NumberParseError = NumberParseError;
3862var NumberWrapper = (function () {
3863 function NumberWrapper() {
3864 }
3865 NumberWrapper.toFixed = function (n, fractionDigits) { return n.toFixed(fractionDigits); };
3866 NumberWrapper.equal = function (a, b) { return a === b; };
3867 NumberWrapper.parseIntAutoRadix = function (text) {
3868 var result = parseInt(text);
3869 if (isNaN(result)) {
3870 throw new NumberParseError("Invalid integer literal when parsing " + text);
3871 }
3872 return result;
3873 };
3874 NumberWrapper.parseInt = function (text, radix) {
3875 if (radix == 10) {
3876 if (/^(\-|\+)?[0-9]+$/.test(text)) {
3877 return parseInt(text, radix);
3878 }
3879 }
3880 else if (radix == 16) {
3881 if (/^(\-|\+)?[0-9ABCDEFabcdef]+$/.test(text)) {
3882 return parseInt(text, radix);
3883 }
3884 }
3885 else {
3886 var result = parseInt(text, radix);
3887 if (!isNaN(result)) {
3888 return result;
3889 }
3890 }
3891 throw new NumberParseError("Invalid integer literal when parsing " + text + " in base " +
3892 radix);
3893 };
3894 // TODO: NaN is a valid literal but is returned by parseFloat to indicate an error.
3895 NumberWrapper.parseFloat = function (text) { return parseFloat(text); };
3896 Object.defineProperty(NumberWrapper, "NaN", {
3897 get: function () { return NaN; },
3898 enumerable: true,
3899 configurable: true
3900 });
3901 NumberWrapper.isNaN = function (value) { return isNaN(value); };
3902 NumberWrapper.isInteger = function (value) { return Number.isInteger(value); };
3903 return NumberWrapper;
3904}());
3905exports.NumberWrapper = NumberWrapper;
3906exports.RegExp = _global.RegExp;
3907var RegExpWrapper = (function () {
3908 function RegExpWrapper() {
3909 }
3910 RegExpWrapper.create = function (regExpStr, flags) {
3911 if (flags === void 0) { flags = ''; }
3912 flags = flags.replace(/g/g, '');
3913 return new _global.RegExp(regExpStr, flags + 'g');
3914 };
3915 RegExpWrapper.firstMatch = function (regExp, input) {
3916 // Reset multimatch regex state
3917 regExp.lastIndex = 0;
3918 return regExp.exec(input);
3919 };
3920 RegExpWrapper.test = function (regExp, input) {
3921 regExp.lastIndex = 0;
3922 return regExp.test(input);
3923 };
3924 RegExpWrapper.matcher = function (regExp, input) {
3925 // Reset regex state for the case
3926 // someone did not loop over all matches
3927 // last time.
3928 regExp.lastIndex = 0;
3929 return { re: regExp, input: input };
3930 };
3931 RegExpWrapper.replaceAll = function (regExp, input, replace) {
3932 var c = regExp.exec(input);
3933 var res = '';
3934 regExp.lastIndex = 0;
3935 var prev = 0;
3936 while (c) {
3937 res += input.substring(prev, c.index);
3938 res += replace(c);
3939 prev = c.index + c[0].length;
3940 regExp.lastIndex = prev;
3941 c = regExp.exec(input);
3942 }
3943 res += input.substring(prev);
3944 return res;
3945 };
3946 return RegExpWrapper;
3947}());
3948exports.RegExpWrapper = RegExpWrapper;
3949var RegExpMatcherWrapper = (function () {
3950 function RegExpMatcherWrapper() {
3951 }
3952 RegExpMatcherWrapper.next = function (matcher) {
3953 return matcher.re.exec(matcher.input);
3954 };
3955 return RegExpMatcherWrapper;
3956}());
3957exports.RegExpMatcherWrapper = RegExpMatcherWrapper;
3958var FunctionWrapper = (function () {
3959 function FunctionWrapper() {
3960 }
3961 FunctionWrapper.apply = function (fn, posArgs) { return fn.apply(null, posArgs); };
3962 return FunctionWrapper;
3963}());
3964exports.FunctionWrapper = FunctionWrapper;
3965// JS has NaN !== NaN
3966function looseIdentical(a, b) {
3967 return a === b || typeof a === "number" && typeof b === "number" && isNaN(a) && isNaN(b);
3968}
3969exports.looseIdentical = looseIdentical;
3970// JS considers NaN is the same as NaN for map Key (while NaN !== NaN otherwise)
3971// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
3972function getMapKey(value) {
3973 return value;
3974}
3975exports.getMapKey = getMapKey;
3976function normalizeBlank(obj) {
3977 return isBlank(obj) ? null : obj;
3978}
3979exports.normalizeBlank = normalizeBlank;
3980function normalizeBool(obj) {
3981 return isBlank(obj) ? false : obj;
3982}
3983exports.normalizeBool = normalizeBool;
3984function isJsObject(o) {
3985 return o !== null && (typeof o === "function" || typeof o === "object");
3986}
3987exports.isJsObject = isJsObject;
3988function print(obj) {
3989 console.log(obj);
3990}
3991exports.print = print;
3992function warn(obj) {
3993 console.warn(obj);
3994}
3995exports.warn = warn;
3996// Can't be all uppercase as our transpiler would think it is a special directive...
3997var Json = (function () {
3998 function Json() {
3999 }
4000 Json.parse = function (s) { return _global.JSON.parse(s); };
4001 Json.stringify = function (data) {
4002 // Dart doesn't take 3 arguments
4003 return _global.JSON.stringify(data, null, 2);
4004 };
4005 return Json;
4006}());
4007exports.Json = Json;
4008var DateWrapper = (function () {
4009 function DateWrapper() {
4010 }
4011 DateWrapper.create = function (year, month, day, hour, minutes, seconds, milliseconds) {
4012 if (month === void 0) { month = 1; }
4013 if (day === void 0) { day = 1; }
4014 if (hour === void 0) { hour = 0; }
4015 if (minutes === void 0) { minutes = 0; }
4016 if (seconds === void 0) { seconds = 0; }
4017 if (milliseconds === void 0) { milliseconds = 0; }
4018 return new exports.Date(year, month - 1, day, hour, minutes, seconds, milliseconds);
4019 };
4020 DateWrapper.fromISOString = function (str) { return new exports.Date(str); };
4021 DateWrapper.fromMillis = function (ms) { return new exports.Date(ms); };
4022 DateWrapper.toMillis = function (date) { return date.getTime(); };
4023 DateWrapper.now = function () { return new exports.Date(); };
4024 DateWrapper.toJson = function (date) { return date.toJSON(); };
4025 return DateWrapper;
4026}());
4027exports.DateWrapper = DateWrapper;
4028function setValueOnPath(global, path, value) {
4029 var parts = path.split('.');
4030 var obj = global;
4031 while (parts.length > 1) {
4032 var name = parts.shift();
4033 if (obj.hasOwnProperty(name) && isPresent(obj[name])) {
4034 obj = obj[name];
4035 }
4036 else {
4037 obj = obj[name] = {};
4038 }
4039 }
4040 if (obj === undefined || obj === null) {
4041 obj = {};
4042 }
4043 obj[parts.shift()] = value;
4044}
4045exports.setValueOnPath = setValueOnPath;
4046var _symbolIterator = null;
4047function getSymbolIterator() {
4048 if (isBlank(_symbolIterator)) {
4049 if (isPresent(globalScope.Symbol) && isPresent(Symbol.iterator)) {
4050 _symbolIterator = Symbol.iterator;
4051 }
4052 else {
4053 // es6-shim specific logic
4054 var keys = Object.getOwnPropertyNames(Map.prototype);
4055 for (var i = 0; i < keys.length; ++i) {
4056 var key = keys[i];
4057 if (key !== 'entries' && key !== 'size' &&
4058 Map.prototype[key] === Map.prototype['entries']) {
4059 _symbolIterator = key;
4060 }
4061 }
4062 }
4063 }
4064 return _symbolIterator;
4065}
4066exports.getSymbolIterator = getSymbolIterator;
4067function evalExpression(sourceUrl, expr, declarations, vars) {
4068 var fnBody = declarations + "\nreturn " + expr + "\n//# sourceURL=" + sourceUrl;
4069 var fnArgNames = [];
4070 var fnArgValues = [];
4071 for (var argName in vars) {
4072 fnArgNames.push(argName);
4073 fnArgValues.push(vars[argName]);
4074 }
4075 return new (Function.bind.apply(Function, [void 0].concat(fnArgNames.concat(fnBody))))().apply(void 0, fnArgValues);
4076}
4077exports.evalExpression = evalExpression;
4078function isPrimitive(obj) {
4079 return !isJsObject(obj);
4080}
4081exports.isPrimitive = isPrimitive;
4082function hasConstructor(value, type) {
4083 return value.constructor === type;
4084}
4085exports.hasConstructor = hasConstructor;
4086function bitWiseOr(values) {
4087 return values.reduce(function (a, b) { return a | b; });
4088}
4089exports.bitWiseOr = bitWiseOr;
4090function bitWiseAnd(values) {
4091 return values.reduce(function (a, b) { return a & b; });
4092}
4093exports.bitWiseAnd = bitWiseAnd;
4094function escape(s) {
4095 return _global.encodeURI(s);
4096}
4097exports.escape = escape;
4098},{}],23:[function(require,module,exports){
4099'use strict';"use strict";
4100var lang_1 = require('angular2/src/facade/lang');
4101exports.Math = lang_1.global.Math;
4102exports.NaN = typeof exports.NaN;
4103},{"angular2/src/facade/lang":22}],24:[function(require,module,exports){
4104'use strict';"use strict";
4105var PromiseCompleter = (function () {
4106 function PromiseCompleter() {
4107 var _this = this;
4108 this.promise = new Promise(function (res, rej) {
4109 _this.resolve = res;
4110 _this.reject = rej;
4111 });
4112 }
4113 return PromiseCompleter;
4114}());
4115exports.PromiseCompleter = PromiseCompleter;
4116var PromiseWrapper = (function () {
4117 function PromiseWrapper() {
4118 }
4119 PromiseWrapper.resolve = function (obj) { return Promise.resolve(obj); };
4120 PromiseWrapper.reject = function (obj, _) { return Promise.reject(obj); };
4121 // Note: We can't rename this method into `catch`, as this is not a valid
4122 // method name in Dart.
4123 PromiseWrapper.catchError = function (promise, onError) {
4124 return promise.catch(onError);
4125 };
4126 PromiseWrapper.all = function (promises) {
4127 if (promises.length == 0)
4128 return Promise.resolve([]);
4129 return Promise.all(promises);
4130 };
4131 PromiseWrapper.then = function (promise, success, rejection) {
4132 return promise.then(success, rejection);
4133 };
4134 PromiseWrapper.wrap = function (computation) {
4135 return new Promise(function (res, rej) {
4136 try {
4137 res(computation());
4138 }
4139 catch (e) {
4140 rej(e);
4141 }
4142 });
4143 };
4144 PromiseWrapper.scheduleMicrotask = function (computation) {
4145 PromiseWrapper.then(PromiseWrapper.resolve(null), computation, function (_) { });
4146 };
4147 PromiseWrapper.isPromise = function (obj) { return obj instanceof Promise; };
4148 PromiseWrapper.completer = function () { return new PromiseCompleter(); };
4149 return PromiseWrapper;
4150}());
4151exports.PromiseWrapper = PromiseWrapper;
4152},{}],25:[function(require,module,exports){
4153'use strict';"use strict";
4154function __export(m) {
4155 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4156}
4157var di_1 = require('angular2/src/core/di');
4158var common_1 = require('./common');
4159__export(require('./common'));
4160var selenium_webdriver_adapter_1 = require('./src/webdriver/selenium_webdriver_adapter');
4161exports.SeleniumWebDriverAdapter = selenium_webdriver_adapter_1.SeleniumWebDriverAdapter;
4162var fs = require('fs');
4163// TODO(tbosch): right now we bind the `writeFile` method
4164// in benchpres/benchpress.es6. This does not work for Dart,
4165// find another way...
4166// Note: Can't do the `require` call in a facade as it can't be loaded into the browser
4167// for our unit tests via karma.
4168common_1.Options.DEFAULT_PROVIDERS.push(di_1.bind(common_1.Options.WRITE_FILE).toValue(writeFile));
4169function writeFile(filename, content) {
4170 return new Promise(function (resolve, reject) {
4171 fs.writeFile(filename, content, function (error) {
4172 if (error) {
4173 reject(error);
4174 }
4175 else {
4176 resolve();
4177 }
4178 });
4179 });
4180}
4181},{"./common":26,"./src/webdriver/selenium_webdriver_adapter":49,"angular2/src/core/di":1,"fs":undefined}],26:[function(require,module,exports){
4182'use strict';"use strict";
4183var sampler_1 = require('./src/sampler');
4184exports.Sampler = sampler_1.Sampler;
4185exports.SampleState = sampler_1.SampleState;
4186var metric_1 = require('./src/metric');
4187exports.Metric = metric_1.Metric;
4188var validator_1 = require('./src/validator');
4189exports.Validator = validator_1.Validator;
4190var reporter_1 = require('./src/reporter');
4191exports.Reporter = reporter_1.Reporter;
4192var web_driver_extension_1 = require('./src/web_driver_extension');
4193exports.WebDriverExtension = web_driver_extension_1.WebDriverExtension;
4194exports.PerfLogFeatures = web_driver_extension_1.PerfLogFeatures;
4195var web_driver_adapter_1 = require('./src/web_driver_adapter');
4196exports.WebDriverAdapter = web_driver_adapter_1.WebDriverAdapter;
4197var size_validator_1 = require('./src/validator/size_validator');
4198exports.SizeValidator = size_validator_1.SizeValidator;
4199var regression_slope_validator_1 = require('./src/validator/regression_slope_validator');
4200exports.RegressionSlopeValidator = regression_slope_validator_1.RegressionSlopeValidator;
4201var console_reporter_1 = require('./src/reporter/console_reporter');
4202exports.ConsoleReporter = console_reporter_1.ConsoleReporter;
4203var json_file_reporter_1 = require('./src/reporter/json_file_reporter');
4204exports.JsonFileReporter = json_file_reporter_1.JsonFileReporter;
4205var sample_description_1 = require('./src/sample_description');
4206exports.SampleDescription = sample_description_1.SampleDescription;
4207var perflog_metric_1 = require('./src/metric/perflog_metric');
4208exports.PerflogMetric = perflog_metric_1.PerflogMetric;
4209var chrome_driver_extension_1 = require('./src/webdriver/chrome_driver_extension');
4210exports.ChromeDriverExtension = chrome_driver_extension_1.ChromeDriverExtension;
4211var firefox_driver_extension_1 = require('./src/webdriver/firefox_driver_extension');
4212exports.FirefoxDriverExtension = firefox_driver_extension_1.FirefoxDriverExtension;
4213var ios_driver_extension_1 = require('./src/webdriver/ios_driver_extension');
4214exports.IOsDriverExtension = ios_driver_extension_1.IOsDriverExtension;
4215var runner_1 = require('./src/runner');
4216exports.Runner = runner_1.Runner;
4217var common_options_1 = require('./src/common_options');
4218exports.Options = common_options_1.Options;
4219var measure_values_1 = require('./src/measure_values');
4220exports.MeasureValues = measure_values_1.MeasureValues;
4221var multi_metric_1 = require('./src/metric/multi_metric');
4222exports.MultiMetric = multi_metric_1.MultiMetric;
4223var multi_reporter_1 = require('./src/reporter/multi_reporter');
4224exports.MultiReporter = multi_reporter_1.MultiReporter;
4225var di_1 = require('angular2/src/core/di');
4226exports.bind = di_1.bind;
4227exports.provide = di_1.provide;
4228exports.Injector = di_1.Injector;
4229exports.ReflectiveInjector = di_1.ReflectiveInjector;
4230exports.OpaqueToken = di_1.OpaqueToken;
4231},{"./src/common_options":28,"./src/measure_values":29,"./src/metric":30,"./src/metric/multi_metric":31,"./src/metric/perflog_metric":32,"./src/reporter":33,"./src/reporter/console_reporter":34,"./src/reporter/json_file_reporter":35,"./src/reporter/multi_reporter":36,"./src/runner":37,"./src/sample_description":38,"./src/sampler":39,"./src/validator":41,"./src/validator/regression_slope_validator":42,"./src/validator/size_validator":43,"./src/web_driver_adapter":44,"./src/web_driver_extension":45,"./src/webdriver/chrome_driver_extension":46,"./src/webdriver/firefox_driver_extension":47,"./src/webdriver/ios_driver_extension":48,"angular2/src/core/di":1}],27:[function(require,module,exports){
4232'use strict';require('reflect-metadata');
4233require('es6-shim');
4234module.exports = require('./benchpress.js');
4235// when bundling benchpress to one file, this is used
4236// for getting exports out of browserify's scope.
4237global.__benchpressExports = module.exports;
4238},{"./benchpress.js":25,"es6-shim":undefined,"reflect-metadata":undefined}],28:[function(require,module,exports){
4239'use strict';"use strict";
4240var di_1 = require('angular2/src/core/di');
4241var lang_1 = require('angular2/src/facade/lang');
4242var Options = (function () {
4243 function Options() {
4244 }
4245 Object.defineProperty(Options, "DEFAULT_PROVIDERS", {
4246 get: function () { return _DEFAULT_PROVIDERS; },
4247 enumerable: true,
4248 configurable: true
4249 });
4250 Object.defineProperty(Options, "SAMPLE_ID", {
4251 // TODO(tbosch): use static initializer when our transpiler supports it
4252 get: function () { return _SAMPLE_ID; },
4253 enumerable: true,
4254 configurable: true
4255 });
4256 Object.defineProperty(Options, "DEFAULT_DESCRIPTION", {
4257 // TODO(tbosch): use static initializer when our transpiler supports it
4258 get: function () { return _DEFAULT_DESCRIPTION; },
4259 enumerable: true,
4260 configurable: true
4261 });
4262 Object.defineProperty(Options, "SAMPLE_DESCRIPTION", {
4263 // TODO(tbosch): use static initializer when our transpiler supports it
4264 get: function () { return _SAMPLE_DESCRIPTION; },
4265 enumerable: true,
4266 configurable: true
4267 });
4268 Object.defineProperty(Options, "FORCE_GC", {
4269 // TODO(tbosch): use static initializer when our transpiler supports it
4270 get: function () { return _FORCE_GC; },
4271 enumerable: true,
4272 configurable: true
4273 });
4274 Object.defineProperty(Options, "PREPARE", {
4275 // TODO(tbosch): use static initializer when our transpiler supports it
4276 get: function () { return _PREPARE; },
4277 enumerable: true,
4278 configurable: true
4279 });
4280 Object.defineProperty(Options, "EXECUTE", {
4281 // TODO(tbosch): use static initializer when our transpiler supports it
4282 get: function () { return _EXECUTE; },
4283 enumerable: true,
4284 configurable: true
4285 });
4286 Object.defineProperty(Options, "CAPABILITIES", {
4287 // TODO(tbosch): use static initializer when our transpiler supports it
4288 get: function () { return _CAPABILITIES; },
4289 enumerable: true,
4290 configurable: true
4291 });
4292 Object.defineProperty(Options, "USER_AGENT", {
4293 // TODO(tbosch): use static initializer when our transpiler supports it
4294 get: function () { return _USER_AGENT; },
4295 enumerable: true,
4296 configurable: true
4297 });
4298 Object.defineProperty(Options, "NOW", {
4299 // TODO(tbosch): use static initializer when our transpiler supports it
4300 get: function () { return _NOW; },
4301 enumerable: true,
4302 configurable: true
4303 });
4304 Object.defineProperty(Options, "WRITE_FILE", {
4305 // TODO(tbosch): use static values when our transpiler supports them
4306 get: function () { return _WRITE_FILE; },
4307 enumerable: true,
4308 configurable: true
4309 });
4310 Object.defineProperty(Options, "MICRO_METRICS", {
4311 // TODO(tbosch): use static values when our transpiler supports them
4312 get: function () { return _MICRO_METRICS; },
4313 enumerable: true,
4314 configurable: true
4315 });
4316 Object.defineProperty(Options, "RECEIVED_DATA", {
4317 // TODO(tbosch): use static values when our transpiler supports them
4318 get: function () { return _RECEIVED_DATA; },
4319 enumerable: true,
4320 configurable: true
4321 });
4322 Object.defineProperty(Options, "REQUEST_COUNT", {
4323 // TODO(tbosch): use static values when our transpiler supports them
4324 get: function () { return _REQUEST_COUNT; },
4325 enumerable: true,
4326 configurable: true
4327 });
4328 Object.defineProperty(Options, "CAPTURE_FRAMES", {
4329 // TODO(tbosch): use static values when our transpiler supports them
4330 get: function () { return _CAPTURE_FRAMES; },
4331 enumerable: true,
4332 configurable: true
4333 });
4334 return Options;
4335}());
4336exports.Options = Options;
4337var _SAMPLE_ID = new di_1.OpaqueToken('Options.sampleId');
4338var _DEFAULT_DESCRIPTION = new di_1.OpaqueToken('Options.defaultDescription');
4339var _SAMPLE_DESCRIPTION = new di_1.OpaqueToken('Options.sampleDescription');
4340var _FORCE_GC = new di_1.OpaqueToken('Options.forceGc');
4341var _PREPARE = new di_1.OpaqueToken('Options.prepare');
4342var _EXECUTE = new di_1.OpaqueToken('Options.execute');
4343var _CAPABILITIES = new di_1.OpaqueToken('Options.capabilities');
4344var _USER_AGENT = new di_1.OpaqueToken('Options.userAgent');
4345var _MICRO_METRICS = new di_1.OpaqueToken('Options.microMetrics');
4346var _NOW = new di_1.OpaqueToken('Options.now');
4347var _WRITE_FILE = new di_1.OpaqueToken('Options.writeFile');
4348var _RECEIVED_DATA = new di_1.OpaqueToken('Options.receivedData');
4349var _REQUEST_COUNT = new di_1.OpaqueToken('Options.requestCount');
4350var _CAPTURE_FRAMES = new di_1.OpaqueToken('Options.frameCapture');
4351var _DEFAULT_PROVIDERS = [
4352 di_1.bind(_DEFAULT_DESCRIPTION)
4353 .toValue({}),
4354 di_1.provide(_SAMPLE_DESCRIPTION, { useValue: {} }),
4355 di_1.provide(_FORCE_GC, { useValue: false }),
4356 di_1.provide(_PREPARE, { useValue: false }),
4357 di_1.provide(_MICRO_METRICS, { useValue: {} }),
4358 di_1.provide(_NOW, { useValue: function () { return lang_1.DateWrapper.now(); } }),
4359 di_1.provide(_RECEIVED_DATA, { useValue: false }),
4360 di_1.provide(_REQUEST_COUNT, { useValue: false }),
4361 di_1.provide(_CAPTURE_FRAMES, { useValue: false })
4362];
4363},{"angular2/src/core/di":1,"angular2/src/facade/lang":22}],29:[function(require,module,exports){
4364'use strict';"use strict";
4365var lang_1 = require('angular2/src/facade/lang');
4366var MeasureValues = (function () {
4367 function MeasureValues(runIndex, timeStamp, values) {
4368 this.runIndex = runIndex;
4369 this.timeStamp = timeStamp;
4370 this.values = values;
4371 }
4372 MeasureValues.prototype.toJson = function () {
4373 return {
4374 'timeStamp': lang_1.DateWrapper.toJson(this.timeStamp),
4375 'runIndex': this.runIndex,
4376 'values': this.values
4377 };
4378 };
4379 return MeasureValues;
4380}());
4381exports.MeasureValues = MeasureValues;
4382},{"angular2/src/facade/lang":22}],30:[function(require,module,exports){
4383'use strict';"use strict";
4384var di_1 = require('angular2/src/core/di');
4385var exceptions_1 = require('angular2/src/facade/exceptions');
4386/**
4387 * A metric is measures values
4388 */
4389var Metric = (function () {
4390 function Metric() {
4391 }
4392 Metric.bindTo = function (delegateToken) {
4393 return [di_1.bind(Metric).toFactory(function (delegate) { return delegate; }, [delegateToken])];
4394 };
4395 /**
4396 * Starts measuring
4397 */
4398 Metric.prototype.beginMeasure = function () { throw new exceptions_1.BaseException('NYI'); };
4399 /**
4400 * Ends measuring and reports the data
4401 * since the begin call.
4402 * @param restart: Whether to restart right after this.
4403 */
4404 Metric.prototype.endMeasure = function (restart) { throw new exceptions_1.BaseException('NYI'); };
4405 /**
4406 * Describes the metrics provided by this metric implementation.
4407 * (e.g. units, ...)
4408 */
4409 Metric.prototype.describe = function () { throw new exceptions_1.BaseException('NYI'); };
4410 return Metric;
4411}());
4412exports.Metric = Metric;
4413},{"angular2/src/core/di":1,"angular2/src/facade/exceptions":21}],31:[function(require,module,exports){
4414'use strict';"use strict";
4415var __extends = (this && this.__extends) || function (d, b) {
4416 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
4417 function __() { this.constructor = d; }
4418 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4419};
4420var di_1 = require('angular2/src/core/di');
4421var collection_1 = require('angular2/src/facade/collection');
4422var async_1 = require('angular2/src/facade/async');
4423var metric_1 = require('../metric');
4424var MultiMetric = (function (_super) {
4425 __extends(MultiMetric, _super);
4426 function MultiMetric(_metrics) {
4427 _super.call(this);
4428 this._metrics = _metrics;
4429 }
4430 MultiMetric.createBindings = function (childTokens) {
4431 return [
4432 di_1.bind(_CHILDREN)
4433 .toFactory(function (injector) { return childTokens.map(function (token) { return injector.get(token); }); }, [di_1.Injector]),
4434 di_1.bind(MultiMetric).toFactory(function (children) { return new MultiMetric(children); }, [_CHILDREN])
4435 ];
4436 };
4437 /**
4438 * Starts measuring
4439 */
4440 MultiMetric.prototype.beginMeasure = function () {
4441 return async_1.PromiseWrapper.all(this._metrics.map(function (metric) { return metric.beginMeasure(); }));
4442 };
4443 /**
4444 * Ends measuring and reports the data
4445 * since the begin call.
4446 * @param restart: Whether to restart right after this.
4447 */
4448 MultiMetric.prototype.endMeasure = function (restart) {
4449 return async_1.PromiseWrapper.all(this._metrics.map(function (metric) { return metric.endMeasure(restart); }))
4450 .then(function (values) { return mergeStringMaps(values); });
4451 };
4452 /**
4453 * Describes the metrics provided by this metric implementation.
4454 * (e.g. units, ...)
4455 */
4456 MultiMetric.prototype.describe = function () {
4457 return mergeStringMaps(this._metrics.map(function (metric) { return metric.describe(); }));
4458 };
4459 return MultiMetric;
4460}(metric_1.Metric));
4461exports.MultiMetric = MultiMetric;
4462function mergeStringMaps(maps) {
4463 var result = {};
4464 maps.forEach(function (map) { collection_1.StringMapWrapper.forEach(map, function (value, prop) { result[prop] = value; }); });
4465 return result;
4466}
4467var _CHILDREN = new di_1.OpaqueToken('MultiMetric.children');
4468},{"../metric":30,"angular2/src/core/di":1,"angular2/src/facade/async":17,"angular2/src/facade/collection":19}],32:[function(require,module,exports){
4469'use strict';"use strict";
4470var __extends = (this && this.__extends) || function (d, b) {
4471 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
4472 function __() { this.constructor = d; }
4473 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4474};
4475var async_1 = require('angular2/src/facade/async');
4476var lang_1 = require('angular2/src/facade/lang');
4477var exceptions_1 = require('angular2/src/facade/exceptions');
4478var collection_1 = require('angular2/src/facade/collection');
4479var di_1 = require('angular2/src/core/di');
4480var web_driver_extension_1 = require('../web_driver_extension');
4481var metric_1 = require('../metric');
4482var common_options_1 = require('../common_options');
4483/**
4484 * A metric that reads out the performance log
4485 */
4486var PerflogMetric = (function (_super) {
4487 __extends(PerflogMetric, _super);
4488 /**
4489 * @param driverExtension
4490 * @param setTimeout
4491 * @param microMetrics Name and description of metrics provided via console.time / console.timeEnd
4492 **/
4493 function PerflogMetric(_driverExtension, _setTimeout, _microMetrics, _forceGc, _captureFrames, _receivedData, _requestCount) {
4494 _super.call(this);
4495 this._driverExtension = _driverExtension;
4496 this._setTimeout = _setTimeout;
4497 this._microMetrics = _microMetrics;
4498 this._forceGc = _forceGc;
4499 this._captureFrames = _captureFrames;
4500 this._receivedData = _receivedData;
4501 this._requestCount = _requestCount;
4502 this._remainingEvents = [];
4503 this._measureCount = 0;
4504 this._perfLogFeatures = _driverExtension.perfLogFeatures();
4505 if (!this._perfLogFeatures.userTiming) {
4506 // User timing is needed for navigationStart.
4507 this._receivedData = false;
4508 this._requestCount = false;
4509 }
4510 }
4511 Object.defineProperty(PerflogMetric, "BINDINGS", {
4512 // TODO(tbosch): use static values when our transpiler supports them
4513 get: function () { return _PROVIDERS; },
4514 enumerable: true,
4515 configurable: true
4516 });
4517 Object.defineProperty(PerflogMetric, "SET_TIMEOUT", {
4518 // TODO(tbosch): use static values when our transpiler supports them
4519 get: function () { return _SET_TIMEOUT; },
4520 enumerable: true,
4521 configurable: true
4522 });
4523 PerflogMetric.prototype.describe = function () {
4524 var res = {
4525 'scriptTime': 'script execution time in ms, including gc and render',
4526 'pureScriptTime': 'script execution time in ms, without gc nor render'
4527 };
4528 if (this._perfLogFeatures.render) {
4529 res['renderTime'] = 'render time in ms';
4530 }
4531 if (this._perfLogFeatures.gc) {
4532 res['gcTime'] = 'gc time in ms';
4533 res['gcAmount'] = 'gc amount in kbytes';
4534 res['majorGcTime'] = 'time of major gcs in ms';
4535 if (this._forceGc) {
4536 res['forcedGcTime'] = 'forced gc time in ms';
4537 res['forcedGcAmount'] = 'forced gc amount in kbytes';
4538 }
4539 }
4540 if (this._receivedData) {
4541 res['receivedData'] = 'encoded bytes received since navigationStart';
4542 }
4543 if (this._requestCount) {
4544 res['requestCount'] = 'count of requests sent since navigationStart';
4545 }
4546 if (this._captureFrames) {
4547 if (!this._perfLogFeatures.frameCapture) {
4548 var warningMsg = 'WARNING: Metric requested, but not supported by driver';
4549 // using dot syntax for metric name to keep them grouped together in console reporter
4550 res['frameTime.mean'] = warningMsg;
4551 res['frameTime.worst'] = warningMsg;
4552 res['frameTime.best'] = warningMsg;
4553 res['frameTime.smooth'] = warningMsg;
4554 }
4555 else {
4556 res['frameTime.mean'] = 'mean frame time in ms (target: 16.6ms for 60fps)';
4557 res['frameTime.worst'] = 'worst frame time in ms';
4558 res['frameTime.best'] = 'best frame time in ms';
4559 res['frameTime.smooth'] = 'percentage of frames that hit 60fps';
4560 }
4561 }
4562 collection_1.StringMapWrapper.forEach(this._microMetrics, function (desc, name) { collection_1.StringMapWrapper.set(res, name, desc); });
4563 return res;
4564 };
4565 PerflogMetric.prototype.beginMeasure = function () {
4566 var _this = this;
4567 var resultPromise = async_1.PromiseWrapper.resolve(null);
4568 if (this._forceGc) {
4569 resultPromise = resultPromise.then(function (_) { return _this._driverExtension.gc(); });
4570 }
4571 return resultPromise.then(function (_) { return _this._beginMeasure(); });
4572 };
4573 PerflogMetric.prototype.endMeasure = function (restart) {
4574 if (this._forceGc) {
4575 return this._endPlainMeasureAndMeasureForceGc(restart);
4576 }
4577 else {
4578 return this._endMeasure(restart);
4579 }
4580 };
4581 PerflogMetric.prototype._endPlainMeasureAndMeasureForceGc = function (restartMeasure) {
4582 var _this = this;
4583 return this._endMeasure(true).then(function (measureValues) {
4584 // disable frame capture for measurements during forced gc
4585 var originalFrameCaptureValue = _this._captureFrames;
4586 _this._captureFrames = false;
4587 return _this._driverExtension.gc()
4588 .then(function (_) { return _this._endMeasure(restartMeasure); })
4589 .then(function (forceGcMeasureValues) {
4590 _this._captureFrames = originalFrameCaptureValue;
4591 collection_1.StringMapWrapper.set(measureValues, 'forcedGcTime', forceGcMeasureValues['gcTime']);
4592 collection_1.StringMapWrapper.set(measureValues, 'forcedGcAmount', forceGcMeasureValues['gcAmount']);
4593 return measureValues;
4594 });
4595 });
4596 };
4597 PerflogMetric.prototype._beginMeasure = function () {
4598 return this._driverExtension.timeBegin(this._markName(this._measureCount++));
4599 };
4600 PerflogMetric.prototype._endMeasure = function (restart) {
4601 var _this = this;
4602 var markName = this._markName(this._measureCount - 1);
4603 var nextMarkName = restart ? this._markName(this._measureCount++) : null;
4604 return this._driverExtension.timeEnd(markName, nextMarkName)
4605 .then(function (_) { return _this._readUntilEndMark(markName); });
4606 };
4607 PerflogMetric.prototype._readUntilEndMark = function (markName, loopCount, startEvent) {
4608 var _this = this;
4609 if (loopCount === void 0) { loopCount = 0; }
4610 if (startEvent === void 0) { startEvent = null; }
4611 if (loopCount > _MAX_RETRY_COUNT) {
4612 throw new exceptions_1.BaseException("Tried too often to get the ending mark: " + loopCount);
4613 }
4614 return this._driverExtension.readPerfLog().then(function (events) {
4615 _this._addEvents(events);
4616 var result = _this._aggregateEvents(_this._remainingEvents, markName);
4617 if (lang_1.isPresent(result)) {
4618 _this._remainingEvents = events;
4619 return result;
4620 }
4621 var completer = async_1.PromiseWrapper.completer();
4622 _this._setTimeout(function () { return completer.resolve(_this._readUntilEndMark(markName, loopCount + 1)); }, 100);
4623 return completer.promise;
4624 });
4625 };
4626 PerflogMetric.prototype._addEvents = function (events) {
4627 var _this = this;
4628 var needSort = false;
4629 events.forEach(function (event) {
4630 if (lang_1.StringWrapper.equals(event['ph'], 'X')) {
4631 needSort = true;
4632 var startEvent = {};
4633 var endEvent = {};
4634 collection_1.StringMapWrapper.forEach(event, function (value, prop) {
4635 startEvent[prop] = value;
4636 endEvent[prop] = value;
4637 });
4638 startEvent['ph'] = 'B';
4639 endEvent['ph'] = 'E';
4640 endEvent['ts'] = startEvent['ts'] + startEvent['dur'];
4641 _this._remainingEvents.push(startEvent);
4642 _this._remainingEvents.push(endEvent);
4643 }
4644 else {
4645 _this._remainingEvents.push(event);
4646 }
4647 });
4648 if (needSort) {
4649 // Need to sort because of the ph==='X' events
4650 collection_1.ListWrapper.sort(this._remainingEvents, function (a, b) {
4651 var diff = a['ts'] - b['ts'];
4652 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
4653 });
4654 }
4655 };
4656 PerflogMetric.prototype._aggregateEvents = function (events, markName) {
4657 var _this = this;
4658 var result = { 'scriptTime': 0, 'pureScriptTime': 0 };
4659 if (this._perfLogFeatures.gc) {
4660 result['gcTime'] = 0;
4661 result['majorGcTime'] = 0;
4662 result['gcAmount'] = 0;
4663 }
4664 if (this._perfLogFeatures.render) {
4665 result['renderTime'] = 0;
4666 }
4667 if (this._captureFrames) {
4668 result['frameTime.mean'] = 0;
4669 result['frameTime.best'] = 0;
4670 result['frameTime.worst'] = 0;
4671 result['frameTime.smooth'] = 0;
4672 }
4673 collection_1.StringMapWrapper.forEach(this._microMetrics, function (desc, name) { result[name] = 0; });
4674 if (this._receivedData) {
4675 result['receivedData'] = 0;
4676 }
4677 if (this._requestCount) {
4678 result['requestCount'] = 0;
4679 }
4680 var markStartEvent = null;
4681 var markEndEvent = null;
4682 var gcTimeInScript = 0;
4683 var renderTimeInScript = 0;
4684 var frameTimestamps = [];
4685 var frameTimes = [];
4686 var frameCaptureStartEvent = null;
4687 var frameCaptureEndEvent = null;
4688 var intervalStarts = {};
4689 var intervalStartCount = {};
4690 events.forEach(function (event) {
4691 var ph = event['ph'];
4692 var name = event['name'];
4693 var microIterations = 1;
4694 var microIterationsMatch = lang_1.RegExpWrapper.firstMatch(_MICRO_ITERATIONS_REGEX, name);
4695 if (lang_1.isPresent(microIterationsMatch)) {
4696 name = microIterationsMatch[1];
4697 microIterations = lang_1.NumberWrapper.parseInt(microIterationsMatch[2], 10);
4698 }
4699 if (lang_1.StringWrapper.equals(ph, 'b') && lang_1.StringWrapper.equals(name, markName)) {
4700 markStartEvent = event;
4701 }
4702 else if (lang_1.StringWrapper.equals(ph, 'e') && lang_1.StringWrapper.equals(name, markName)) {
4703 markEndEvent = event;
4704 }
4705 var isInstant = lang_1.StringWrapper.equals(ph, 'I') || lang_1.StringWrapper.equals(ph, 'i');
4706 if (_this._requestCount && lang_1.StringWrapper.equals(name, 'sendRequest')) {
4707 result['requestCount'] += 1;
4708 }
4709 else if (_this._receivedData && lang_1.StringWrapper.equals(name, 'receivedData') && isInstant) {
4710 result['receivedData'] += event['args']['encodedDataLength'];
4711 }
4712 else if (lang_1.StringWrapper.equals(name, 'navigationStart')) {
4713 // We count data + requests since the last navigationStart
4714 // (there might be chrome extensions loaded by selenium before our page, so there
4715 // will likely be more than one navigationStart).
4716 if (_this._receivedData) {
4717 result['receivedData'] = 0;
4718 }
4719 if (_this._requestCount) {
4720 result['requestCount'] = 0;
4721 }
4722 }
4723 if (lang_1.isPresent(markStartEvent) && lang_1.isBlank(markEndEvent) &&
4724 event['pid'] === markStartEvent['pid']) {
4725 if (lang_1.StringWrapper.equals(ph, 'b') && lang_1.StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) {
4726 if (lang_1.isPresent(frameCaptureStartEvent)) {
4727 throw new exceptions_1.BaseException('can capture frames only once per benchmark run');
4728 }
4729 if (!_this._captureFrames) {
4730 throw new exceptions_1.BaseException('found start event for frame capture, but frame capture was not requested in benchpress');
4731 }
4732 frameCaptureStartEvent = event;
4733 }
4734 else if (lang_1.StringWrapper.equals(ph, 'e') &&
4735 lang_1.StringWrapper.equals(name, _MARK_NAME_FRAME_CAPUTRE)) {
4736 if (lang_1.isBlank(frameCaptureStartEvent)) {
4737 throw new exceptions_1.BaseException('missing start event for frame capture');
4738 }
4739 frameCaptureEndEvent = event;
4740 }
4741 if (isInstant) {
4742 if (lang_1.isPresent(frameCaptureStartEvent) && lang_1.isBlank(frameCaptureEndEvent) &&
4743 lang_1.StringWrapper.equals(name, 'frame')) {
4744 frameTimestamps.push(event['ts']);
4745 if (frameTimestamps.length >= 2) {
4746 frameTimes.push(frameTimestamps[frameTimestamps.length - 1] -
4747 frameTimestamps[frameTimestamps.length - 2]);
4748 }
4749 }
4750 }
4751 if (lang_1.StringWrapper.equals(ph, 'B') || lang_1.StringWrapper.equals(ph, 'b')) {
4752 if (lang_1.isBlank(intervalStarts[name])) {
4753 intervalStartCount[name] = 1;
4754 intervalStarts[name] = event;
4755 }
4756 else {
4757 intervalStartCount[name]++;
4758 }
4759 }
4760 else if ((lang_1.StringWrapper.equals(ph, 'E') || lang_1.StringWrapper.equals(ph, 'e')) &&
4761 lang_1.isPresent(intervalStarts[name])) {
4762 intervalStartCount[name]--;
4763 if (intervalStartCount[name] === 0) {
4764 var startEvent = intervalStarts[name];
4765 var duration = (event['ts'] - startEvent['ts']);
4766 intervalStarts[name] = null;
4767 if (lang_1.StringWrapper.equals(name, 'gc')) {
4768 result['gcTime'] += duration;
4769 var amount = (startEvent['args']['usedHeapSize'] - event['args']['usedHeapSize']) / 1000;
4770 result['gcAmount'] += amount;
4771 var majorGc = event['args']['majorGc'];
4772 if (lang_1.isPresent(majorGc) && majorGc) {
4773 result['majorGcTime'] += duration;
4774 }
4775 if (lang_1.isPresent(intervalStarts['script'])) {
4776 gcTimeInScript += duration;
4777 }
4778 }
4779 else if (lang_1.StringWrapper.equals(name, 'render')) {
4780 result['renderTime'] += duration;
4781 if (lang_1.isPresent(intervalStarts['script'])) {
4782 renderTimeInScript += duration;
4783 }
4784 }
4785 else if (lang_1.StringWrapper.equals(name, 'script')) {
4786 result['scriptTime'] += duration;
4787 }
4788 else if (lang_1.isPresent(_this._microMetrics[name])) {
4789 result[name] += duration / microIterations;
4790 }
4791 }
4792 }
4793 }
4794 });
4795 if (!lang_1.isPresent(markStartEvent) || !lang_1.isPresent(markEndEvent)) {
4796 // not all events have been received, no further processing for now
4797 return null;
4798 }
4799 if (lang_1.isPresent(markEndEvent) && lang_1.isPresent(frameCaptureStartEvent) &&
4800 lang_1.isBlank(frameCaptureEndEvent)) {
4801 throw new exceptions_1.BaseException('missing end event for frame capture');
4802 }
4803 if (this._captureFrames && lang_1.isBlank(frameCaptureStartEvent)) {
4804 throw new exceptions_1.BaseException('frame capture requested in benchpress, but no start event was found');
4805 }
4806 if (frameTimes.length > 0) {
4807 this._addFrameMetrics(result, frameTimes);
4808 }
4809 result['pureScriptTime'] = result['scriptTime'] - gcTimeInScript - renderTimeInScript;
4810 return result;
4811 };
4812 PerflogMetric.prototype._addFrameMetrics = function (result, frameTimes) {
4813 result['frameTime.mean'] = frameTimes.reduce(function (a, b) { return a + b; }, 0) / frameTimes.length;
4814 var firstFrame = frameTimes[0];
4815 result['frameTime.worst'] = frameTimes.reduce(function (a, b) { return a > b ? a : b; }, firstFrame);
4816 result['frameTime.best'] = frameTimes.reduce(function (a, b) { return a < b ? a : b; }, firstFrame);
4817 result['frameTime.smooth'] =
4818 frameTimes.filter(function (t) { return t < _FRAME_TIME_SMOOTH_THRESHOLD; }).length / frameTimes.length;
4819 };
4820 PerflogMetric.prototype._markName = function (index) { return "" + _MARK_NAME_PREFIX + index; };
4821 return PerflogMetric;
4822}(metric_1.Metric));
4823exports.PerflogMetric = PerflogMetric;
4824var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/g;
4825var _MAX_RETRY_COUNT = 20;
4826var _MARK_NAME_PREFIX = 'benchpress';
4827var _SET_TIMEOUT = new di_1.OpaqueToken('PerflogMetric.setTimeout');
4828var _MARK_NAME_FRAME_CAPUTRE = 'frameCapture';
4829// using 17ms as a somewhat looser threshold, instead of 16.6666ms
4830var _FRAME_TIME_SMOOTH_THRESHOLD = 17;
4831var _PROVIDERS = [
4832 di_1.bind(PerflogMetric)
4833 .toFactory(function (driverExtension, setTimeout, microMetrics, forceGc, captureFrames, receivedData, requestCount) {
4834 return new PerflogMetric(driverExtension, setTimeout, microMetrics, forceGc, captureFrames, receivedData, requestCount);
4835 }, [
4836 web_driver_extension_1.WebDriverExtension,
4837 _SET_TIMEOUT,
4838 common_options_1.Options.MICRO_METRICS,
4839 common_options_1.Options.FORCE_GC,
4840 common_options_1.Options.CAPTURE_FRAMES,
4841 common_options_1.Options.RECEIVED_DATA,
4842 common_options_1.Options.REQUEST_COUNT
4843 ]),
4844 di_1.provide(_SET_TIMEOUT, { useValue: function (fn, millis) { return async_1.TimerWrapper.setTimeout(fn, millis); } })
4845];
4846},{"../common_options":28,"../metric":30,"../web_driver_extension":45,"angular2/src/core/di":1,"angular2/src/facade/async":17,"angular2/src/facade/collection":19,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],33:[function(require,module,exports){
4847'use strict';"use strict";
4848var di_1 = require('angular2/src/core/di');
4849var exceptions_1 = require('angular2/src/facade/exceptions');
4850/**
4851 * A reporter reports measure values and the valid sample.
4852 */
4853var Reporter = (function () {
4854 function Reporter() {
4855 }
4856 Reporter.bindTo = function (delegateToken) {
4857 return [di_1.bind(Reporter).toFactory(function (delegate) { return delegate; }, [delegateToken])];
4858 };
4859 Reporter.prototype.reportMeasureValues = function (values) { throw new exceptions_1.BaseException('NYI'); };
4860 Reporter.prototype.reportSample = function (completeSample, validSample) {
4861 throw new exceptions_1.BaseException('NYI');
4862 };
4863 return Reporter;
4864}());
4865exports.Reporter = Reporter;
4866},{"angular2/src/core/di":1,"angular2/src/facade/exceptions":21}],34:[function(require,module,exports){
4867'use strict';"use strict";
4868var __extends = (this && this.__extends) || function (d, b) {
4869 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
4870 function __() { this.constructor = d; }
4871 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4872};
4873var lang_1 = require('angular2/src/facade/lang');
4874var collection_1 = require('angular2/src/facade/collection');
4875var async_1 = require('angular2/src/facade/async');
4876var math_1 = require('angular2/src/facade/math');
4877var di_1 = require('angular2/src/core/di');
4878var statistic_1 = require('../statistic');
4879var reporter_1 = require('../reporter');
4880var sample_description_1 = require('../sample_description');
4881/**
4882 * A reporter for the console
4883 */
4884var ConsoleReporter = (function (_super) {
4885 __extends(ConsoleReporter, _super);
4886 function ConsoleReporter(_columnWidth, sampleDescription, _print) {
4887 _super.call(this);
4888 this._columnWidth = _columnWidth;
4889 this._print = _print;
4890 this._metricNames = ConsoleReporter._sortedProps(sampleDescription.metrics);
4891 this._printDescription(sampleDescription);
4892 }
4893 Object.defineProperty(ConsoleReporter, "PRINT", {
4894 // TODO(tbosch): use static values when our transpiler supports them
4895 get: function () { return _PRINT; },
4896 enumerable: true,
4897 configurable: true
4898 });
4899 Object.defineProperty(ConsoleReporter, "COLUMN_WIDTH", {
4900 // TODO(tbosch): use static values when our transpiler supports them
4901 get: function () { return _COLUMN_WIDTH; },
4902 enumerable: true,
4903 configurable: true
4904 });
4905 Object.defineProperty(ConsoleReporter, "BINDINGS", {
4906 // TODO(tbosch): use static values when our transpiler supports them
4907 get: function () { return _PROVIDERS; },
4908 enumerable: true,
4909 configurable: true
4910 });
4911 ConsoleReporter._lpad = function (value, columnWidth, fill) {
4912 if (fill === void 0) { fill = ' '; }
4913 var result = '';
4914 for (var i = 0; i < columnWidth - value.length; i++) {
4915 result += fill;
4916 }
4917 return result + value;
4918 };
4919 ConsoleReporter._formatNum = function (n) { return lang_1.NumberWrapper.toFixed(n, 2); };
4920 ConsoleReporter._sortedProps = function (obj) {
4921 var props = [];
4922 collection_1.StringMapWrapper.forEach(obj, function (value, prop) { return props.push(prop); });
4923 props.sort();
4924 return props;
4925 };
4926 ConsoleReporter.prototype._printDescription = function (sampleDescription) {
4927 var _this = this;
4928 this._print("BENCHMARK " + sampleDescription.id);
4929 this._print('Description:');
4930 var props = ConsoleReporter._sortedProps(sampleDescription.description);
4931 props.forEach(function (prop) { _this._print("- " + prop + ": " + sampleDescription.description[prop]); });
4932 this._print('Metrics:');
4933 this._metricNames.forEach(function (metricName) {
4934 _this._print("- " + metricName + ": " + sampleDescription.metrics[metricName]);
4935 });
4936 this._print('');
4937 this._printStringRow(this._metricNames);
4938 this._printStringRow(this._metricNames.map(function (_) { return ''; }), '-');
4939 };
4940 ConsoleReporter.prototype.reportMeasureValues = function (measureValues) {
4941 var formattedValues = this._metricNames.map(function (metricName) {
4942 var value = measureValues.values[metricName];
4943 return ConsoleReporter._formatNum(value);
4944 });
4945 this._printStringRow(formattedValues);
4946 return async_1.PromiseWrapper.resolve(null);
4947 };
4948 ConsoleReporter.prototype.reportSample = function (completeSample, validSamples) {
4949 this._printStringRow(this._metricNames.map(function (_) { return ''; }), '=');
4950 this._printStringRow(this._metricNames.map(function (metricName) {
4951 var samples = validSamples.map(function (measureValues) { return measureValues.values[metricName]; });
4952 var mean = statistic_1.Statistic.calculateMean(samples);
4953 var cv = statistic_1.Statistic.calculateCoefficientOfVariation(samples, mean);
4954 var formattedMean = ConsoleReporter._formatNum(mean);
4955 // Note: Don't use the unicode character for +- as it might cause
4956 // hickups for consoles...
4957 return lang_1.NumberWrapper.isNaN(cv) ?
4958 formattedMean :
4959 formattedMean + "+-" + math_1.Math.floor(cv) + "%";
4960 }));
4961 return async_1.PromiseWrapper.resolve(null);
4962 };
4963 ConsoleReporter.prototype._printStringRow = function (parts, fill) {
4964 var _this = this;
4965 if (fill === void 0) { fill = ' '; }
4966 this._print(parts.map(function (part) { return ConsoleReporter._lpad(part, _this._columnWidth, fill); }).join(' | '));
4967 };
4968 return ConsoleReporter;
4969}(reporter_1.Reporter));
4970exports.ConsoleReporter = ConsoleReporter;
4971var _PRINT = new di_1.OpaqueToken('ConsoleReporter.print');
4972var _COLUMN_WIDTH = new di_1.OpaqueToken('ConsoleReporter.columnWidth');
4973var _PROVIDERS = [
4974 di_1.bind(ConsoleReporter)
4975 .toFactory(function (columnWidth, sampleDescription, print) {
4976 return new ConsoleReporter(columnWidth, sampleDescription, print);
4977 }, [_COLUMN_WIDTH, sample_description_1.SampleDescription, _PRINT]),
4978 di_1.provide(_COLUMN_WIDTH, { useValue: 18 }),
4979 di_1.provide(_PRINT, { useValue: lang_1.print })
4980];
4981},{"../reporter":33,"../sample_description":38,"../statistic":40,"angular2/src/core/di":1,"angular2/src/facade/async":17,"angular2/src/facade/collection":19,"angular2/src/facade/lang":22,"angular2/src/facade/math":23}],35:[function(require,module,exports){
4982'use strict';"use strict";
4983var __extends = (this && this.__extends) || function (d, b) {
4984 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
4985 function __() { this.constructor = d; }
4986 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4987};
4988var lang_1 = require('angular2/src/facade/lang');
4989var async_1 = require('angular2/src/facade/async');
4990var di_1 = require('angular2/src/core/di');
4991var reporter_1 = require('../reporter');
4992var sample_description_1 = require('../sample_description');
4993var common_options_1 = require('../common_options');
4994/**
4995 * A reporter that writes results into a json file.
4996 */
4997var JsonFileReporter = (function (_super) {
4998 __extends(JsonFileReporter, _super);
4999 function JsonFileReporter(sampleDescription, path, writeFile, now) {
5000 _super.call(this);
5001 this._description = sampleDescription;
5002 this._path = path;
5003 this._writeFile = writeFile;
5004 this._now = now;
5005 }
5006 Object.defineProperty(JsonFileReporter, "PATH", {
5007 // TODO(tbosch): use static values when our transpiler supports them
5008 get: function () { return _PATH; },
5009 enumerable: true,
5010 configurable: true
5011 });
5012 Object.defineProperty(JsonFileReporter, "BINDINGS", {
5013 // TODO(tbosch): use static values when our transpiler supports them
5014 get: function () { return _PROVIDERS; },
5015 enumerable: true,
5016 configurable: true
5017 });
5018 JsonFileReporter.prototype.reportMeasureValues = function (measureValues) {
5019 return async_1.PromiseWrapper.resolve(null);
5020 };
5021 JsonFileReporter.prototype.reportSample = function (completeSample, validSample) {
5022 var content = lang_1.Json.stringify({
5023 'description': this._description,
5024 'completeSample': completeSample,
5025 'validSample': validSample
5026 });
5027 var filePath = this._path + "/" + this._description.id + "_" + lang_1.DateWrapper.toMillis(this._now()) + ".json";
5028 return this._writeFile(filePath, content);
5029 };
5030 return JsonFileReporter;
5031}(reporter_1.Reporter));
5032exports.JsonFileReporter = JsonFileReporter;
5033var _PATH = new di_1.OpaqueToken('JsonFileReporter.path');
5034var _PROVIDERS = [
5035 di_1.bind(JsonFileReporter)
5036 .toFactory(function (sampleDescription, path, writeFile, now) {
5037 return new JsonFileReporter(sampleDescription, path, writeFile, now);
5038 }, [sample_description_1.SampleDescription, _PATH, common_options_1.Options.WRITE_FILE, common_options_1.Options.NOW]),
5039 di_1.provide(_PATH, { useValue: '.' })
5040];
5041},{"../common_options":28,"../reporter":33,"../sample_description":38,"angular2/src/core/di":1,"angular2/src/facade/async":17,"angular2/src/facade/lang":22}],36:[function(require,module,exports){
5042'use strict';"use strict";
5043var __extends = (this && this.__extends) || function (d, b) {
5044 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5045 function __() { this.constructor = d; }
5046 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5047};
5048var di_1 = require('angular2/src/core/di');
5049var async_1 = require('angular2/src/facade/async');
5050var reporter_1 = require('../reporter');
5051var MultiReporter = (function (_super) {
5052 __extends(MultiReporter, _super);
5053 function MultiReporter(reporters) {
5054 _super.call(this);
5055 this._reporters = reporters;
5056 }
5057 MultiReporter.createBindings = function (childTokens) {
5058 return [
5059 di_1.bind(_CHILDREN)
5060 .toFactory(function (injector) { return childTokens.map(function (token) { return injector.get(token); }); }, [di_1.Injector]),
5061 di_1.bind(MultiReporter).toFactory(function (children) { return new MultiReporter(children); }, [_CHILDREN])
5062 ];
5063 };
5064 MultiReporter.prototype.reportMeasureValues = function (values) {
5065 return async_1.PromiseWrapper.all(this._reporters.map(function (reporter) { return reporter.reportMeasureValues(values); }));
5066 };
5067 MultiReporter.prototype.reportSample = function (completeSample, validSample) {
5068 return async_1.PromiseWrapper.all(this._reporters.map(function (reporter) { return reporter.reportSample(completeSample, validSample); }));
5069 };
5070 return MultiReporter;
5071}(reporter_1.Reporter));
5072exports.MultiReporter = MultiReporter;
5073var _CHILDREN = new di_1.OpaqueToken('MultiReporter.children');
5074},{"../reporter":33,"angular2/src/core/di":1,"angular2/src/facade/async":17}],37:[function(require,module,exports){
5075'use strict';"use strict";
5076var di_1 = require('angular2/src/core/di');
5077var lang_1 = require('angular2/src/facade/lang');
5078var async_1 = require('angular2/src/facade/async');
5079var sampler_1 = require('./sampler');
5080var console_reporter_1 = require('./reporter/console_reporter');
5081var multi_reporter_1 = require('./reporter/multi_reporter');
5082var regression_slope_validator_1 = require('./validator/regression_slope_validator');
5083var size_validator_1 = require('./validator/size_validator');
5084var validator_1 = require('./validator');
5085var perflog_metric_1 = require('./metric/perflog_metric');
5086var multi_metric_1 = require('./metric/multi_metric');
5087var chrome_driver_extension_1 = require('./webdriver/chrome_driver_extension');
5088var firefox_driver_extension_1 = require('./webdriver/firefox_driver_extension');
5089var ios_driver_extension_1 = require('./webdriver/ios_driver_extension');
5090var web_driver_extension_1 = require('./web_driver_extension');
5091var sample_description_1 = require('./sample_description');
5092var web_driver_adapter_1 = require('./web_driver_adapter');
5093var reporter_1 = require('./reporter');
5094var metric_1 = require('./metric');
5095var common_options_1 = require('./common_options');
5096/**
5097 * The Runner is the main entry point for executing a sample run.
5098 * It provides defaults, creates the injector and calls the sampler.
5099 */
5100var Runner = (function () {
5101 function Runner(defaultBindings) {
5102 if (defaultBindings === void 0) { defaultBindings = null; }
5103 if (lang_1.isBlank(defaultBindings)) {
5104 defaultBindings = [];
5105 }
5106 this._defaultBindings = defaultBindings;
5107 }
5108 Runner.prototype.sample = function (_a) {
5109 var id = _a.id, execute = _a.execute, prepare = _a.prepare, microMetrics = _a.microMetrics, bindings = _a.bindings;
5110 var sampleBindings = [
5111 _DEFAULT_PROVIDERS,
5112 this._defaultBindings,
5113 di_1.bind(common_options_1.Options.SAMPLE_ID).toValue(id),
5114 di_1.bind(common_options_1.Options.EXECUTE).toValue(execute)
5115 ];
5116 if (lang_1.isPresent(prepare)) {
5117 sampleBindings.push(di_1.bind(common_options_1.Options.PREPARE).toValue(prepare));
5118 }
5119 if (lang_1.isPresent(microMetrics)) {
5120 sampleBindings.push(di_1.bind(common_options_1.Options.MICRO_METRICS).toValue(microMetrics));
5121 }
5122 if (lang_1.isPresent(bindings)) {
5123 sampleBindings.push(bindings);
5124 }
5125 var inj = di_1.ReflectiveInjector.resolveAndCreate(sampleBindings);
5126 var adapter = inj.get(web_driver_adapter_1.WebDriverAdapter);
5127 return async_1.PromiseWrapper
5128 .all([adapter.capabilities(), adapter.executeScript('return window.navigator.userAgent;')])
5129 .then(function (args) {
5130 var capabilities = args[0];
5131 var userAgent = args[1];
5132 // This might still create instances twice. We are creating a new injector with all the
5133 // providers.
5134 // Only WebDriverAdapter is reused.
5135 // TODO vsavkin consider changing it when toAsyncFactory is added back or when child
5136 // injectors are handled better.
5137 var injector = di_1.ReflectiveInjector.resolveAndCreate([
5138 sampleBindings,
5139 di_1.bind(common_options_1.Options.CAPABILITIES).toValue(capabilities),
5140 di_1.bind(common_options_1.Options.USER_AGENT).toValue(userAgent),
5141 di_1.provide(web_driver_adapter_1.WebDriverAdapter, { useValue: adapter })
5142 ]);
5143 var sampler = injector.get(sampler_1.Sampler);
5144 return sampler.sample();
5145 });
5146 };
5147 return Runner;
5148}());
5149exports.Runner = Runner;
5150var _DEFAULT_PROVIDERS = [
5151 common_options_1.Options.DEFAULT_PROVIDERS,
5152 sampler_1.Sampler.BINDINGS,
5153 console_reporter_1.ConsoleReporter.BINDINGS,
5154 regression_slope_validator_1.RegressionSlopeValidator.BINDINGS,
5155 size_validator_1.SizeValidator.BINDINGS,
5156 chrome_driver_extension_1.ChromeDriverExtension.BINDINGS,
5157 firefox_driver_extension_1.FirefoxDriverExtension.BINDINGS,
5158 ios_driver_extension_1.IOsDriverExtension.BINDINGS,
5159 perflog_metric_1.PerflogMetric.BINDINGS,
5160 sample_description_1.SampleDescription.BINDINGS,
5161 multi_reporter_1.MultiReporter.createBindings([console_reporter_1.ConsoleReporter]),
5162 multi_metric_1.MultiMetric.createBindings([perflog_metric_1.PerflogMetric]),
5163 reporter_1.Reporter.bindTo(multi_reporter_1.MultiReporter),
5164 validator_1.Validator.bindTo(regression_slope_validator_1.RegressionSlopeValidator),
5165 web_driver_extension_1.WebDriverExtension.bindTo([chrome_driver_extension_1.ChromeDriverExtension, firefox_driver_extension_1.FirefoxDriverExtension, ios_driver_extension_1.IOsDriverExtension]),
5166 metric_1.Metric.bindTo(multi_metric_1.MultiMetric),
5167];
5168},{"./common_options":28,"./metric":30,"./metric/multi_metric":31,"./metric/perflog_metric":32,"./reporter":33,"./reporter/console_reporter":34,"./reporter/multi_reporter":36,"./sample_description":38,"./sampler":39,"./validator":41,"./validator/regression_slope_validator":42,"./validator/size_validator":43,"./web_driver_adapter":44,"./web_driver_extension":45,"./webdriver/chrome_driver_extension":46,"./webdriver/firefox_driver_extension":47,"./webdriver/ios_driver_extension":48,"angular2/src/core/di":1,"angular2/src/facade/async":17,"angular2/src/facade/lang":22}],38:[function(require,module,exports){
5169'use strict';"use strict";
5170var collection_1 = require('angular2/src/facade/collection');
5171var di_1 = require('angular2/src/core/di');
5172var validator_1 = require('./validator');
5173var metric_1 = require('./metric');
5174var common_options_1 = require('./common_options');
5175/**
5176 * SampleDescription merges all available descriptions about a sample
5177 */
5178var SampleDescription = (function () {
5179 function SampleDescription(id, descriptions, metrics) {
5180 var _this = this;
5181 this.id = id;
5182 this.metrics = metrics;
5183 this.description = {};
5184 descriptions.forEach(function (description) {
5185 collection_1.StringMapWrapper.forEach(description, function (value, prop) { return _this.description[prop] = value; });
5186 });
5187 }
5188 Object.defineProperty(SampleDescription, "BINDINGS", {
5189 // TODO(tbosch): use static values when our transpiler supports them
5190 get: function () { return _PROVIDERS; },
5191 enumerable: true,
5192 configurable: true
5193 });
5194 SampleDescription.prototype.toJson = function () { return { 'id': this.id, 'description': this.description, 'metrics': this.metrics }; };
5195 return SampleDescription;
5196}());
5197exports.SampleDescription = SampleDescription;
5198var _PROVIDERS = [
5199 di_1.bind(SampleDescription)
5200 .toFactory(function (metric, id, forceGc, userAgent, validator, defaultDesc, userDesc) {
5201 return new SampleDescription(id, [
5202 { 'forceGc': forceGc, 'userAgent': userAgent },
5203 validator.describe(),
5204 defaultDesc,
5205 userDesc
5206 ], metric.describe());
5207 }, [
5208 metric_1.Metric,
5209 common_options_1.Options.SAMPLE_ID,
5210 common_options_1.Options.FORCE_GC,
5211 common_options_1.Options.USER_AGENT,
5212 validator_1.Validator,
5213 common_options_1.Options.DEFAULT_DESCRIPTION,
5214 common_options_1.Options.SAMPLE_DESCRIPTION
5215 ])
5216];
5217},{"./common_options":28,"./metric":30,"./validator":41,"angular2/src/core/di":1,"angular2/src/facade/collection":19}],39:[function(require,module,exports){
5218'use strict';"use strict";
5219var lang_1 = require('angular2/src/facade/lang');
5220var async_1 = require('angular2/src/facade/async');
5221var di_1 = require('angular2/src/core/di');
5222var metric_1 = require('./metric');
5223var validator_1 = require('./validator');
5224var reporter_1 = require('./reporter');
5225var web_driver_adapter_1 = require('./web_driver_adapter');
5226var common_options_1 = require('./common_options');
5227var measure_values_1 = require('./measure_values');
5228/**
5229 * The Sampler owns the sample loop:
5230 * 1. calls the prepare/execute callbacks,
5231 * 2. gets data from the metric
5232 * 3. asks the validator for a valid sample
5233 * 4. reports the new data to the reporter
5234 * 5. loop until there is a valid sample
5235 */
5236var Sampler = (function () {
5237 function Sampler(_a) {
5238 var _b = _a === void 0 ? {} : _a, driver = _b.driver, metric = _b.metric, reporter = _b.reporter, validator = _b.validator, prepare = _b.prepare, execute = _b.execute, now = _b.now;
5239 this._driver = driver;
5240 this._metric = metric;
5241 this._reporter = reporter;
5242 this._validator = validator;
5243 this._prepare = prepare;
5244 this._execute = execute;
5245 this._now = now;
5246 }
5247 Object.defineProperty(Sampler, "BINDINGS", {
5248 // TODO(tbosch): use static values when our transpiler supports them
5249 get: function () { return _PROVIDERS; },
5250 enumerable: true,
5251 configurable: true
5252 });
5253 Sampler.prototype.sample = function () {
5254 var _this = this;
5255 var loop;
5256 loop = function (lastState) {
5257 return _this._iterate(lastState).then(function (newState) {
5258 if (lang_1.isPresent(newState.validSample)) {
5259 return newState;
5260 }
5261 else {
5262 return loop(newState);
5263 }
5264 });
5265 };
5266 return loop(new SampleState([], null));
5267 };
5268 Sampler.prototype._iterate = function (lastState) {
5269 var _this = this;
5270 var resultPromise;
5271 if (lang_1.isPresent(this._prepare)) {
5272 resultPromise = this._driver.waitFor(this._prepare);
5273 }
5274 else {
5275 resultPromise = async_1.PromiseWrapper.resolve(null);
5276 }
5277 if (lang_1.isPresent(this._prepare) || lastState.completeSample.length === 0) {
5278 resultPromise = resultPromise.then(function (_) { return _this._metric.beginMeasure(); });
5279 }
5280 return resultPromise.then(function (_) { return _this._driver.waitFor(_this._execute); })
5281 .then(function (_) { return _this._metric.endMeasure(lang_1.isBlank(_this._prepare)); })
5282 .then(function (measureValues) { return _this._report(lastState, measureValues); });
5283 };
5284 Sampler.prototype._report = function (state, metricValues) {
5285 var _this = this;
5286 var measureValues = new measure_values_1.MeasureValues(state.completeSample.length, this._now(), metricValues);
5287 var completeSample = state.completeSample.concat([measureValues]);
5288 var validSample = this._validator.validate(completeSample);
5289 var resultPromise = this._reporter.reportMeasureValues(measureValues);
5290 if (lang_1.isPresent(validSample)) {
5291 resultPromise =
5292 resultPromise.then(function (_) { return _this._reporter.reportSample(completeSample, validSample); });
5293 }
5294 return resultPromise.then(function (_) { return new SampleState(completeSample, validSample); });
5295 };
5296 return Sampler;
5297}());
5298exports.Sampler = Sampler;
5299var SampleState = (function () {
5300 function SampleState(completeSample, validSample) {
5301 this.completeSample = completeSample;
5302 this.validSample = validSample;
5303 }
5304 return SampleState;
5305}());
5306exports.SampleState = SampleState;
5307var _PROVIDERS = [
5308 di_1.bind(Sampler)
5309 .toFactory(function (driver, metric, reporter, validator, prepare, execute, now) { return new Sampler({
5310 driver: driver,
5311 reporter: reporter,
5312 validator: validator,
5313 metric: metric,
5314 // TODO(tbosch): DI right now does not support null/undefined objects
5315 // Mostly because the cache would have to be initialized with a
5316 // special null object, which is expensive.
5317 prepare: prepare !== false ? prepare : null,
5318 execute: execute,
5319 now: now
5320 }); }, [
5321 web_driver_adapter_1.WebDriverAdapter,
5322 metric_1.Metric,
5323 reporter_1.Reporter,
5324 validator_1.Validator,
5325 common_options_1.Options.PREPARE,
5326 common_options_1.Options.EXECUTE,
5327 common_options_1.Options.NOW
5328 ])
5329];
5330},{"./common_options":28,"./measure_values":29,"./metric":30,"./reporter":33,"./validator":41,"./web_driver_adapter":44,"angular2/src/core/di":1,"angular2/src/facade/async":17,"angular2/src/facade/lang":22}],40:[function(require,module,exports){
5331'use strict';"use strict";
5332var math_1 = require('angular2/src/facade/math');
5333var Statistic = (function () {
5334 function Statistic() {
5335 }
5336 Statistic.calculateCoefficientOfVariation = function (sample, mean) {
5337 return Statistic.calculateStandardDeviation(sample, mean) / mean * 100;
5338 };
5339 Statistic.calculateMean = function (samples) {
5340 var total = 0;
5341 // TODO: use reduce
5342 samples.forEach(function (x) { return total += x; });
5343 return total / samples.length;
5344 };
5345 Statistic.calculateStandardDeviation = function (samples, mean) {
5346 var deviation = 0;
5347 // TODO: use reduce
5348 samples.forEach(function (x) { return deviation += math_1.Math.pow(x - mean, 2); });
5349 deviation = deviation / (samples.length);
5350 deviation = math_1.Math.sqrt(deviation);
5351 return deviation;
5352 };
5353 Statistic.calculateRegressionSlope = function (xValues, xMean, yValues, yMean) {
5354 // See http://en.wikipedia.org/wiki/Simple_linear_regression
5355 var dividendSum = 0;
5356 var divisorSum = 0;
5357 for (var i = 0; i < xValues.length; i++) {
5358 dividendSum += (xValues[i] - xMean) * (yValues[i] - yMean);
5359 divisorSum += math_1.Math.pow(xValues[i] - xMean, 2);
5360 }
5361 return dividendSum / divisorSum;
5362 };
5363 return Statistic;
5364}());
5365exports.Statistic = Statistic;
5366},{"angular2/src/facade/math":23}],41:[function(require,module,exports){
5367'use strict';"use strict";
5368var di_1 = require('angular2/src/core/di');
5369var exceptions_1 = require('angular2/src/facade/exceptions');
5370/**
5371 * A Validator calculates a valid sample out of the complete sample.
5372 * A valid sample is a sample that represents the population that should be observed
5373 * in the correct way.
5374 */
5375var Validator = (function () {
5376 function Validator() {
5377 }
5378 Validator.bindTo = function (delegateToken) {
5379 return [di_1.bind(Validator).toFactory(function (delegate) { return delegate; }, [delegateToken])];
5380 };
5381 /**
5382 * Calculates a valid sample out of the complete sample
5383 */
5384 Validator.prototype.validate = function (completeSample) { throw new exceptions_1.BaseException('NYI'); };
5385 /**
5386 * Returns a Map that describes the properties of the validator
5387 * (e.g. sample size, ...)
5388 */
5389 Validator.prototype.describe = function () { throw new exceptions_1.BaseException('NYI'); };
5390 return Validator;
5391}());
5392exports.Validator = Validator;
5393},{"angular2/src/core/di":1,"angular2/src/facade/exceptions":21}],42:[function(require,module,exports){
5394'use strict';"use strict";
5395var __extends = (this && this.__extends) || function (d, b) {
5396 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5397 function __() { this.constructor = d; }
5398 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5399};
5400var collection_1 = require('angular2/src/facade/collection');
5401var di_1 = require('angular2/src/core/di');
5402var validator_1 = require('../validator');
5403var statistic_1 = require('../statistic');
5404/**
5405 * A validator that checks the regression slope of a specific metric.
5406 * Waits for the regression slope to be >=0.
5407 */
5408var RegressionSlopeValidator = (function (_super) {
5409 __extends(RegressionSlopeValidator, _super);
5410 function RegressionSlopeValidator(sampleSize, metric) {
5411 _super.call(this);
5412 this._sampleSize = sampleSize;
5413 this._metric = metric;
5414 }
5415 Object.defineProperty(RegressionSlopeValidator, "SAMPLE_SIZE", {
5416 // TODO(tbosch): use static values when our transpiler supports them
5417 get: function () { return _SAMPLE_SIZE; },
5418 enumerable: true,
5419 configurable: true
5420 });
5421 Object.defineProperty(RegressionSlopeValidator, "METRIC", {
5422 // TODO(tbosch): use static values when our transpiler supports them
5423 get: function () { return _METRIC; },
5424 enumerable: true,
5425 configurable: true
5426 });
5427 Object.defineProperty(RegressionSlopeValidator, "BINDINGS", {
5428 // TODO(tbosch): use static values when our transpiler supports them
5429 get: function () { return _PROVIDERS; },
5430 enumerable: true,
5431 configurable: true
5432 });
5433 RegressionSlopeValidator.prototype.describe = function () {
5434 return { 'sampleSize': this._sampleSize, 'regressionSlopeMetric': this._metric };
5435 };
5436 RegressionSlopeValidator.prototype.validate = function (completeSample) {
5437 if (completeSample.length >= this._sampleSize) {
5438 var latestSample = collection_1.ListWrapper.slice(completeSample, completeSample.length - this._sampleSize, completeSample.length);
5439 var xValues = [];
5440 var yValues = [];
5441 for (var i = 0; i < latestSample.length; i++) {
5442 // For now, we only use the array index as x value.
5443 // TODO(tbosch): think about whether we should use time here instead
5444 xValues.push(i);
5445 yValues.push(latestSample[i].values[this._metric]);
5446 }
5447 var regressionSlope = statistic_1.Statistic.calculateRegressionSlope(xValues, statistic_1.Statistic.calculateMean(xValues), yValues, statistic_1.Statistic.calculateMean(yValues));
5448 return regressionSlope >= 0 ? latestSample : null;
5449 }
5450 else {
5451 return null;
5452 }
5453 };
5454 return RegressionSlopeValidator;
5455}(validator_1.Validator));
5456exports.RegressionSlopeValidator = RegressionSlopeValidator;
5457var _SAMPLE_SIZE = new di_1.OpaqueToken('RegressionSlopeValidator.sampleSize');
5458var _METRIC = new di_1.OpaqueToken('RegressionSlopeValidator.metric');
5459var _PROVIDERS = [
5460 di_1.bind(RegressionSlopeValidator)
5461 .toFactory(function (sampleSize, metric) { return new RegressionSlopeValidator(sampleSize, metric); }, [_SAMPLE_SIZE, _METRIC]),
5462 di_1.provide(_SAMPLE_SIZE, { useValue: 10 }),
5463 di_1.provide(_METRIC, { useValue: 'scriptTime' })
5464];
5465},{"../statistic":40,"../validator":41,"angular2/src/core/di":1,"angular2/src/facade/collection":19}],43:[function(require,module,exports){
5466'use strict';"use strict";
5467var __extends = (this && this.__extends) || function (d, b) {
5468 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5469 function __() { this.constructor = d; }
5470 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5471};
5472var collection_1 = require('angular2/src/facade/collection');
5473var di_1 = require('angular2/src/core/di');
5474var validator_1 = require('../validator');
5475/**
5476 * A validator that waits for the sample to have a certain size.
5477 */
5478var SizeValidator = (function (_super) {
5479 __extends(SizeValidator, _super);
5480 function SizeValidator(size) {
5481 _super.call(this);
5482 this._sampleSize = size;
5483 }
5484 Object.defineProperty(SizeValidator, "BINDINGS", {
5485 // TODO(tbosch): use static values when our transpiler supports them
5486 get: function () { return _PROVIDERS; },
5487 enumerable: true,
5488 configurable: true
5489 });
5490 Object.defineProperty(SizeValidator, "SAMPLE_SIZE", {
5491 // TODO(tbosch): use static values when our transpiler supports them
5492 get: function () { return _SAMPLE_SIZE; },
5493 enumerable: true,
5494 configurable: true
5495 });
5496 SizeValidator.prototype.describe = function () { return { 'sampleSize': this._sampleSize }; };
5497 SizeValidator.prototype.validate = function (completeSample) {
5498 if (completeSample.length >= this._sampleSize) {
5499 return collection_1.ListWrapper.slice(completeSample, completeSample.length - this._sampleSize, completeSample.length);
5500 }
5501 else {
5502 return null;
5503 }
5504 };
5505 return SizeValidator;
5506}(validator_1.Validator));
5507exports.SizeValidator = SizeValidator;
5508var _SAMPLE_SIZE = new di_1.OpaqueToken('SizeValidator.sampleSize');
5509var _PROVIDERS = [
5510 di_1.bind(SizeValidator)
5511 .toFactory(function (size) { return new SizeValidator(size); }, [_SAMPLE_SIZE]),
5512 di_1.provide(_SAMPLE_SIZE, { useValue: 10 })
5513];
5514},{"../validator":41,"angular2/src/core/di":1,"angular2/src/facade/collection":19}],44:[function(require,module,exports){
5515'use strict';"use strict";
5516var di_1 = require('angular2/src/core/di');
5517var exceptions_1 = require('angular2/src/facade/exceptions');
5518/**
5519 * A WebDriverAdapter bridges API differences between different WebDriver clients,
5520 * e.g. JS vs Dart Async vs Dart Sync webdriver.
5521 * Needs one implementation for every supported WebDriver client.
5522 */
5523var WebDriverAdapter = (function () {
5524 function WebDriverAdapter() {
5525 }
5526 WebDriverAdapter.bindTo = function (delegateToken) {
5527 return [di_1.bind(WebDriverAdapter).toFactory(function (delegate) { return delegate; }, [delegateToken])];
5528 };
5529 WebDriverAdapter.prototype.waitFor = function (callback) { throw new exceptions_1.BaseException('NYI'); };
5530 WebDriverAdapter.prototype.executeScript = function (script) { throw new exceptions_1.BaseException('NYI'); };
5531 WebDriverAdapter.prototype.executeAsyncScript = function (script) { throw new exceptions_1.BaseException('NYI'); };
5532 WebDriverAdapter.prototype.capabilities = function () { throw new exceptions_1.BaseException('NYI'); };
5533 WebDriverAdapter.prototype.logs = function (type) { throw new exceptions_1.BaseException('NYI'); };
5534 return WebDriverAdapter;
5535}());
5536exports.WebDriverAdapter = WebDriverAdapter;
5537},{"angular2/src/core/di":1,"angular2/src/facade/exceptions":21}],45:[function(require,module,exports){
5538'use strict';"use strict";
5539var di_1 = require('angular2/src/core/di');
5540var lang_1 = require('angular2/src/facade/lang');
5541var exceptions_1 = require('angular2/src/facade/exceptions');
5542var common_options_1 = require('./common_options');
5543/**
5544 * A WebDriverExtension implements extended commands of the webdriver protocol
5545 * for a given browser, independent of the WebDriverAdapter.
5546 * Needs one implementation for every supported Browser.
5547 */
5548var WebDriverExtension = (function () {
5549 function WebDriverExtension() {
5550 }
5551 WebDriverExtension.bindTo = function (childTokens) {
5552 var res = [
5553 di_1.bind(_CHILDREN)
5554 .toFactory(function (injector) { return childTokens.map(function (token) { return injector.get(token); }); }, [di_1.Injector]),
5555 di_1.bind(WebDriverExtension)
5556 .toFactory(function (children, capabilities) {
5557 var delegate;
5558 children.forEach(function (extension) {
5559 if (extension.supports(capabilities)) {
5560 delegate = extension;
5561 }
5562 });
5563 if (lang_1.isBlank(delegate)) {
5564 throw new exceptions_1.BaseException('Could not find a delegate for given capabilities!');
5565 }
5566 return delegate;
5567 }, [_CHILDREN, common_options_1.Options.CAPABILITIES])
5568 ];
5569 return res;
5570 };
5571 WebDriverExtension.prototype.gc = function () { throw new exceptions_1.BaseException('NYI'); };
5572 WebDriverExtension.prototype.timeBegin = function (name) { throw new exceptions_1.BaseException('NYI'); };
5573 WebDriverExtension.prototype.timeEnd = function (name, restartName) { throw new exceptions_1.BaseException('NYI'); };
5574 /**
5575 * Format:
5576 * - cat: category of the event
5577 * - name: event name: 'script', 'gc', 'render', ...
5578 * - ph: phase: 'B' (begin), 'E' (end), 'b' (nestable start), 'e' (nestable end), 'X' (Complete
5579 *event)
5580 * - ts: timestamp in ms, e.g. 12345
5581 * - pid: process id
5582 * - args: arguments, e.g. {heapSize: 1234}
5583 *
5584 * Based on [Chrome Trace Event
5585 *Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit)
5586 **/
5587 WebDriverExtension.prototype.readPerfLog = function () { throw new exceptions_1.BaseException('NYI'); };
5588 WebDriverExtension.prototype.perfLogFeatures = function () { throw new exceptions_1.BaseException('NYI'); };
5589 WebDriverExtension.prototype.supports = function (capabilities) { return true; };
5590 return WebDriverExtension;
5591}());
5592exports.WebDriverExtension = WebDriverExtension;
5593var PerfLogFeatures = (function () {
5594 function PerfLogFeatures(_a) {
5595 var _b = _a === void 0 ? {} : _a, _c = _b.render, render = _c === void 0 ? false : _c, _d = _b.gc, gc = _d === void 0 ? false : _d, _e = _b.frameCapture, frameCapture = _e === void 0 ? false : _e, _f = _b.userTiming, userTiming = _f === void 0 ? false : _f;
5596 this.render = render;
5597 this.gc = gc;
5598 this.frameCapture = frameCapture;
5599 this.userTiming = userTiming;
5600 }
5601 return PerfLogFeatures;
5602}());
5603exports.PerfLogFeatures = PerfLogFeatures;
5604var _CHILDREN = new di_1.OpaqueToken('WebDriverExtension.children');
5605},{"./common_options":28,"angular2/src/core/di":1,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],46:[function(require,module,exports){
5606'use strict';"use strict";
5607var __extends = (this && this.__extends) || function (d, b) {
5608 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5609 function __() { this.constructor = d; }
5610 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5611};
5612var di_1 = require('angular2/src/core/di');
5613var collection_1 = require('angular2/src/facade/collection');
5614var lang_1 = require('angular2/src/facade/lang');
5615var exceptions_1 = require('angular2/src/facade/exceptions');
5616var web_driver_extension_1 = require('../web_driver_extension');
5617var web_driver_adapter_1 = require('../web_driver_adapter');
5618var common_options_1 = require('../common_options');
5619/**
5620 * Set the following 'traceCategories' to collect metrics in Chrome:
5621 * 'v8,blink.console,disabled-by-default-devtools.timeline,devtools.timeline'
5622 *
5623 * In order to collect the frame rate related metrics, add 'benchmark'
5624 * to the list above.
5625 */
5626var ChromeDriverExtension = (function (_super) {
5627 __extends(ChromeDriverExtension, _super);
5628 function ChromeDriverExtension(_driver, userAgent) {
5629 _super.call(this);
5630 this._driver = _driver;
5631 this._majorChromeVersion = this._parseChromeVersion(userAgent);
5632 }
5633 Object.defineProperty(ChromeDriverExtension, "BINDINGS", {
5634 // TODO(tbosch): use static values when our transpiler supports them
5635 get: function () { return _PROVIDERS; },
5636 enumerable: true,
5637 configurable: true
5638 });
5639 ChromeDriverExtension.prototype._parseChromeVersion = function (userAgent) {
5640 if (lang_1.isBlank(userAgent)) {
5641 return -1;
5642 }
5643 var v = lang_1.StringWrapper.split(userAgent, /Chrom(e|ium)\//g)[2];
5644 if (lang_1.isBlank(v)) {
5645 return -1;
5646 }
5647 v = v.split('.')[0];
5648 if (lang_1.isBlank(v)) {
5649 return -1;
5650 }
5651 return lang_1.NumberWrapper.parseInt(v, 10);
5652 };
5653 ChromeDriverExtension.prototype.gc = function () { return this._driver.executeScript('window.gc()'); };
5654 ChromeDriverExtension.prototype.timeBegin = function (name) {
5655 return this._driver.executeScript("console.time('" + name + "');");
5656 };
5657 ChromeDriverExtension.prototype.timeEnd = function (name, restartName) {
5658 if (restartName === void 0) { restartName = null; }
5659 var script = "console.timeEnd('" + name + "');";
5660 if (lang_1.isPresent(restartName)) {
5661 script += "console.time('" + restartName + "');";
5662 }
5663 return this._driver.executeScript(script);
5664 };
5665 // See [Chrome Trace Event
5666 // Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit)
5667 ChromeDriverExtension.prototype.readPerfLog = function () {
5668 var _this = this;
5669 // TODO(tbosch): Chromedriver bug https://code.google.com/p/chromedriver/issues/detail?id=1098
5670 // Need to execute at least one command so that the browser logs can be read out!
5671 return this._driver.executeScript('1+1')
5672 .then(function (_) { return _this._driver.logs('performance'); })
5673 .then(function (entries) {
5674 var events = [];
5675 entries.forEach(function (entry) {
5676 var message = lang_1.Json.parse(entry['message'])['message'];
5677 if (lang_1.StringWrapper.equals(message['method'], 'Tracing.dataCollected')) {
5678 events.push(message['params']);
5679 }
5680 if (lang_1.StringWrapper.equals(message['method'], 'Tracing.bufferUsage')) {
5681 throw new exceptions_1.BaseException('The DevTools trace buffer filled during the test!');
5682 }
5683 });
5684 return _this._convertPerfRecordsToEvents(events);
5685 });
5686 };
5687 ChromeDriverExtension.prototype._convertPerfRecordsToEvents = function (chromeEvents, normalizedEvents) {
5688 var _this = this;
5689 if (normalizedEvents === void 0) { normalizedEvents = null; }
5690 if (lang_1.isBlank(normalizedEvents)) {
5691 normalizedEvents = [];
5692 }
5693 var majorGCPids = {};
5694 chromeEvents.forEach(function (event) {
5695 var categories = _this._parseCategories(event['cat']);
5696 var name = event['name'];
5697 if (_this._isEvent(categories, name, ['blink.console'])) {
5698 normalizedEvents.push(normalizeEvent(event, { 'name': name }));
5699 }
5700 else if (_this._isEvent(categories, name, ['benchmark'], 'BenchmarkInstrumentation::ImplThreadRenderingStats')) {
5701 // TODO(goderbauer): Instead of BenchmarkInstrumentation::ImplThreadRenderingStats the
5702 // following events should be used (if available) for more accurate measurments:
5703 // 1st choice: vsync_before - ground truth on Android
5704 // 2nd choice: BenchmarkInstrumentation::DisplayRenderingStats - available on systems with
5705 // new surfaces framework (not broadly enabled yet)
5706 // 3rd choice: BenchmarkInstrumentation::ImplThreadRenderingStats - fallback event that is
5707 // always available if something is rendered
5708 var frameCount = event['args']['data']['frame_count'];
5709 if (frameCount > 1) {
5710 throw new exceptions_1.BaseException('multi-frame render stats not supported');
5711 }
5712 if (frameCount == 1) {
5713 normalizedEvents.push(normalizeEvent(event, { 'name': 'frame' }));
5714 }
5715 }
5716 else if (_this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Rasterize') ||
5717 _this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers')) {
5718 normalizedEvents.push(normalizeEvent(event, { 'name': 'render' }));
5719 }
5720 else if (_this._majorChromeVersion < 45) {
5721 var normalizedEvent = _this._processAsPreChrome45Event(event, categories, majorGCPids);
5722 if (normalizedEvent != null)
5723 normalizedEvents.push(normalizedEvent);
5724 }
5725 else {
5726 var normalizedEvent = _this._processAsPostChrome44Event(event, categories);
5727 if (normalizedEvent != null)
5728 normalizedEvents.push(normalizedEvent);
5729 }
5730 });
5731 return normalizedEvents;
5732 };
5733 ChromeDriverExtension.prototype._processAsPreChrome45Event = function (event, categories, majorGCPids) {
5734 var name = event['name'];
5735 var args = event['args'];
5736 var pid = event['pid'];
5737 var ph = event['ph'];
5738 if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'FunctionCall') &&
5739 (lang_1.isBlank(args) || lang_1.isBlank(args['data']) ||
5740 !lang_1.StringWrapper.equals(args['data']['scriptName'], 'InjectedScript'))) {
5741 return normalizeEvent(event, { 'name': 'script' });
5742 }
5743 else if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'RecalculateStyles') ||
5744 this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Layout') ||
5745 this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'UpdateLayerTree') ||
5746 this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'Paint')) {
5747 return normalizeEvent(event, { 'name': 'render' });
5748 }
5749 else if (this._isEvent(categories, name, ['disabled-by-default-devtools.timeline'], 'GCEvent')) {
5750 var normArgs = {
5751 'usedHeapSize': lang_1.isPresent(args['usedHeapSizeAfter']) ? args['usedHeapSizeAfter'] :
5752 args['usedHeapSizeBefore']
5753 };
5754 if (lang_1.StringWrapper.equals(ph, 'E')) {
5755 normArgs['majorGc'] = lang_1.isPresent(majorGCPids[pid]) && majorGCPids[pid];
5756 }
5757 majorGCPids[pid] = false;
5758 return normalizeEvent(event, { 'name': 'gc', 'args': normArgs });
5759 }
5760 else if (this._isEvent(categories, name, ['v8'], 'majorGC') &&
5761 lang_1.StringWrapper.equals(ph, 'B')) {
5762 majorGCPids[pid] = true;
5763 }
5764 return null; // nothing useful in this event
5765 };
5766 ChromeDriverExtension.prototype._processAsPostChrome44Event = function (event, categories) {
5767 var name = event['name'];
5768 var args = event['args'];
5769 if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MajorGC')) {
5770 var normArgs = {
5771 'majorGc': true,
5772 'usedHeapSize': lang_1.isPresent(args['usedHeapSizeAfter']) ? args['usedHeapSizeAfter'] :
5773 args['usedHeapSizeBefore']
5774 };
5775 return normalizeEvent(event, { 'name': 'gc', 'args': normArgs });
5776 }
5777 else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MinorGC')) {
5778 var normArgs = {
5779 'majorGc': false,
5780 'usedHeapSize': lang_1.isPresent(args['usedHeapSizeAfter']) ? args['usedHeapSizeAfter'] :
5781 args['usedHeapSizeBefore']
5782 };
5783 return normalizeEvent(event, { 'name': 'gc', 'args': normArgs });
5784 }
5785 else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'FunctionCall') &&
5786 (lang_1.isBlank(args) || lang_1.isBlank(args['data']) ||
5787 (!lang_1.StringWrapper.equals(args['data']['scriptName'], 'InjectedScript') &&
5788 !lang_1.StringWrapper.equals(args['data']['scriptName'], '')))) {
5789 return normalizeEvent(event, { 'name': 'script' });
5790 }
5791 else if (this._isEvent(categories, name, ['devtools.timeline', 'blink'], 'UpdateLayoutTree')) {
5792 return normalizeEvent(event, { 'name': 'render' });
5793 }
5794 else if (this._isEvent(categories, name, ['devtools.timeline'], 'UpdateLayerTree') ||
5795 this._isEvent(categories, name, ['devtools.timeline'], 'Layout') ||
5796 this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) {
5797 return normalizeEvent(event, { 'name': 'render' });
5798 }
5799 else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) {
5800 var normArgs_1 = { 'encodedDataLength': args['data']['encodedDataLength'] };
5801 return normalizeEvent(event, { 'name': 'receivedData', 'args': normArgs_1 });
5802 }
5803 else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceSendRequest')) {
5804 var data_1 = args['data'];
5805 var normArgs_2 = { 'url': data_1['url'], 'method': data_1['requestMethod'] };
5806 return normalizeEvent(event, { 'name': 'sendRequest', 'args': normArgs_2 });
5807 }
5808 else if (this._isEvent(categories, name, ['blink.user_timing'], 'navigationStart')) {
5809 return normalizeEvent(event, { 'name': name });
5810 }
5811 return null; // nothing useful in this event
5812 };
5813 ChromeDriverExtension.prototype._parseCategories = function (categories) { return categories.split(','); };
5814 ChromeDriverExtension.prototype._isEvent = function (eventCategories, eventName, expectedCategories, expectedName) {
5815 if (expectedName === void 0) { expectedName = null; }
5816 var hasCategories = expectedCategories.reduce(function (value, cat) { return value && collection_1.ListWrapper.contains(eventCategories, cat); }, true);
5817 return lang_1.isBlank(expectedName) ? hasCategories :
5818 hasCategories && lang_1.StringWrapper.equals(eventName, expectedName);
5819 };
5820 ChromeDriverExtension.prototype.perfLogFeatures = function () {
5821 return new web_driver_extension_1.PerfLogFeatures({ render: true, gc: true, frameCapture: true, userTiming: true });
5822 };
5823 ChromeDriverExtension.prototype.supports = function (capabilities) {
5824 return this._majorChromeVersion != -1 &&
5825 lang_1.StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'chrome');
5826 };
5827 return ChromeDriverExtension;
5828}(web_driver_extension_1.WebDriverExtension));
5829exports.ChromeDriverExtension = ChromeDriverExtension;
5830function normalizeEvent(chromeEvent, data) {
5831 var ph = chromeEvent['ph'];
5832 if (lang_1.StringWrapper.equals(ph, 'S')) {
5833 ph = 'b';
5834 }
5835 else if (lang_1.StringWrapper.equals(ph, 'F')) {
5836 ph = 'e';
5837 }
5838 var result = { 'pid': chromeEvent['pid'], 'ph': ph, 'cat': 'timeline', 'ts': chromeEvent['ts'] / 1000 };
5839 if (chromeEvent['ph'] === 'X') {
5840 var dur = chromeEvent['dur'];
5841 if (lang_1.isBlank(dur)) {
5842 dur = chromeEvent['tdur'];
5843 }
5844 result['dur'] = lang_1.isBlank(dur) ? 0.0 : dur / 1000;
5845 }
5846 collection_1.StringMapWrapper.forEach(data, function (value, prop) { result[prop] = value; });
5847 return result;
5848}
5849var _PROVIDERS = [
5850 di_1.bind(ChromeDriverExtension)
5851 .toFactory(function (driver, userAgent) { return new ChromeDriverExtension(driver, userAgent); }, [web_driver_adapter_1.WebDriverAdapter, common_options_1.Options.USER_AGENT])
5852];
5853},{"../common_options":28,"../web_driver_adapter":44,"../web_driver_extension":45,"angular2/src/core/di":1,"angular2/src/facade/collection":19,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],47:[function(require,module,exports){
5854'use strict';"use strict";
5855var __extends = (this && this.__extends) || function (d, b) {
5856 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5857 function __() { this.constructor = d; }
5858 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5859};
5860var di_1 = require('angular2/src/core/di');
5861var lang_1 = require('angular2/src/facade/lang');
5862var web_driver_extension_1 = require('../web_driver_extension');
5863var web_driver_adapter_1 = require('../web_driver_adapter');
5864var FirefoxDriverExtension = (function (_super) {
5865 __extends(FirefoxDriverExtension, _super);
5866 function FirefoxDriverExtension(_driver) {
5867 _super.call(this);
5868 this._driver = _driver;
5869 this._profilerStarted = false;
5870 }
5871 Object.defineProperty(FirefoxDriverExtension, "BINDINGS", {
5872 get: function () { return _PROVIDERS; },
5873 enumerable: true,
5874 configurable: true
5875 });
5876 FirefoxDriverExtension.prototype.gc = function () { return this._driver.executeScript('window.forceGC()'); };
5877 FirefoxDriverExtension.prototype.timeBegin = function (name) {
5878 if (!this._profilerStarted) {
5879 this._profilerStarted = true;
5880 this._driver.executeScript('window.startProfiler();');
5881 }
5882 return this._driver.executeScript('window.markStart("' + name + '");');
5883 };
5884 FirefoxDriverExtension.prototype.timeEnd = function (name, restartName) {
5885 if (restartName === void 0) { restartName = null; }
5886 var script = 'window.markEnd("' + name + '");';
5887 if (lang_1.isPresent(restartName)) {
5888 script += 'window.markStart("' + restartName + '");';
5889 }
5890 return this._driver.executeScript(script);
5891 };
5892 FirefoxDriverExtension.prototype.readPerfLog = function () {
5893 return this._driver.executeAsyncScript('var cb = arguments[0]; window.getProfile(cb);');
5894 };
5895 FirefoxDriverExtension.prototype.perfLogFeatures = function () { return new web_driver_extension_1.PerfLogFeatures({ render: true, gc: true }); };
5896 FirefoxDriverExtension.prototype.supports = function (capabilities) {
5897 return lang_1.StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'firefox');
5898 };
5899 return FirefoxDriverExtension;
5900}(web_driver_extension_1.WebDriverExtension));
5901exports.FirefoxDriverExtension = FirefoxDriverExtension;
5902var _PROVIDERS = [
5903 di_1.bind(FirefoxDriverExtension)
5904 .toFactory(function (driver) { return new FirefoxDriverExtension(driver); }, [web_driver_adapter_1.WebDriverAdapter])
5905];
5906},{"../web_driver_adapter":44,"../web_driver_extension":45,"angular2/src/core/di":1,"angular2/src/facade/lang":22}],48:[function(require,module,exports){
5907'use strict';"use strict";
5908var __extends = (this && this.__extends) || function (d, b) {
5909 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5910 function __() { this.constructor = d; }
5911 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5912};
5913var di_1 = require('angular2/src/core/di');
5914var lang_1 = require('angular2/src/facade/lang');
5915var exceptions_1 = require('angular2/src/facade/exceptions');
5916var web_driver_extension_1 = require('../web_driver_extension');
5917var web_driver_adapter_1 = require('../web_driver_adapter');
5918var IOsDriverExtension = (function (_super) {
5919 __extends(IOsDriverExtension, _super);
5920 function IOsDriverExtension(_driver) {
5921 _super.call(this);
5922 this._driver = _driver;
5923 }
5924 Object.defineProperty(IOsDriverExtension, "BINDINGS", {
5925 // TODO(tbosch): use static values when our transpiler supports them
5926 get: function () { return _PROVIDERS; },
5927 enumerable: true,
5928 configurable: true
5929 });
5930 IOsDriverExtension.prototype.gc = function () { throw new exceptions_1.BaseException('Force GC is not supported on iOS'); };
5931 IOsDriverExtension.prototype.timeBegin = function (name) {
5932 return this._driver.executeScript("console.time('" + name + "');");
5933 };
5934 IOsDriverExtension.prototype.timeEnd = function (name, restartName) {
5935 if (restartName === void 0) { restartName = null; }
5936 var script = "console.timeEnd('" + name + "');";
5937 if (lang_1.isPresent(restartName)) {
5938 script += "console.time('" + restartName + "');";
5939 }
5940 return this._driver.executeScript(script);
5941 };
5942 // See https://github.com/WebKit/webkit/tree/master/Source/WebInspectorUI/Versions
5943 IOsDriverExtension.prototype.readPerfLog = function () {
5944 var _this = this;
5945 // TODO(tbosch): Bug in IOsDriver: Need to execute at least one command
5946 // so that the browser logs can be read out!
5947 return this._driver.executeScript('1+1')
5948 .then(function (_) { return _this._driver.logs('performance'); })
5949 .then(function (entries) {
5950 var records = [];
5951 entries.forEach(function (entry) {
5952 var message = lang_1.Json.parse(entry['message'])['message'];
5953 if (lang_1.StringWrapper.equals(message['method'], 'Timeline.eventRecorded')) {
5954 records.push(message['params']['record']);
5955 }
5956 });
5957 return _this._convertPerfRecordsToEvents(records);
5958 });
5959 };
5960 IOsDriverExtension.prototype._convertPerfRecordsToEvents = function (records, events) {
5961 var _this = this;
5962 if (events === void 0) { events = null; }
5963 if (lang_1.isBlank(events)) {
5964 events = [];
5965 }
5966 records.forEach(function (record) {
5967 var endEvent = null;
5968 var type = record['type'];
5969 var data = record['data'];
5970 var startTime = record['startTime'];
5971 var endTime = record['endTime'];
5972 if (lang_1.StringWrapper.equals(type, 'FunctionCall') &&
5973 (lang_1.isBlank(data) || !lang_1.StringWrapper.equals(data['scriptName'], 'InjectedScript'))) {
5974 events.push(createStartEvent('script', startTime));
5975 endEvent = createEndEvent('script', endTime);
5976 }
5977 else if (lang_1.StringWrapper.equals(type, 'Time')) {
5978 events.push(createMarkStartEvent(data['message'], startTime));
5979 }
5980 else if (lang_1.StringWrapper.equals(type, 'TimeEnd')) {
5981 events.push(createMarkEndEvent(data['message'], startTime));
5982 }
5983 else if (lang_1.StringWrapper.equals(type, 'RecalculateStyles') ||
5984 lang_1.StringWrapper.equals(type, 'Layout') ||
5985 lang_1.StringWrapper.equals(type, 'UpdateLayerTree') ||
5986 lang_1.StringWrapper.equals(type, 'Paint') || lang_1.StringWrapper.equals(type, 'Rasterize') ||
5987 lang_1.StringWrapper.equals(type, 'CompositeLayers')) {
5988 events.push(createStartEvent('render', startTime));
5989 endEvent = createEndEvent('render', endTime);
5990 }
5991 // Note: ios used to support GCEvent up until iOS 6 :-(
5992 if (lang_1.isPresent(record['children'])) {
5993 _this._convertPerfRecordsToEvents(record['children'], events);
5994 }
5995 if (lang_1.isPresent(endEvent)) {
5996 events.push(endEvent);
5997 }
5998 });
5999 return events;
6000 };
6001 IOsDriverExtension.prototype.perfLogFeatures = function () { return new web_driver_extension_1.PerfLogFeatures({ render: true }); };
6002 IOsDriverExtension.prototype.supports = function (capabilities) {
6003 return lang_1.StringWrapper.equals(capabilities['browserName'].toLowerCase(), 'safari');
6004 };
6005 return IOsDriverExtension;
6006}(web_driver_extension_1.WebDriverExtension));
6007exports.IOsDriverExtension = IOsDriverExtension;
6008function createEvent(ph, name, time, args) {
6009 if (args === void 0) { args = null; }
6010 var result = {
6011 'cat': 'timeline',
6012 'name': name,
6013 'ts': time,
6014 'ph': ph,
6015 // The ios protocol does not support the notions of multiple processes in
6016 // the perflog...
6017 'pid': 'pid0'
6018 };
6019 if (lang_1.isPresent(args)) {
6020 result['args'] = args;
6021 }
6022 return result;
6023}
6024function createStartEvent(name, time, args) {
6025 if (args === void 0) { args = null; }
6026 return createEvent('B', name, time, args);
6027}
6028function createEndEvent(name, time, args) {
6029 if (args === void 0) { args = null; }
6030 return createEvent('E', name, time, args);
6031}
6032function createMarkStartEvent(name, time) {
6033 return createEvent('b', name, time);
6034}
6035function createMarkEndEvent(name, time) {
6036 return createEvent('e', name, time);
6037}
6038var _PROVIDERS = [
6039 di_1.bind(IOsDriverExtension)
6040 .toFactory(function (driver) { return new IOsDriverExtension(driver); }, [web_driver_adapter_1.WebDriverAdapter])
6041];
6042},{"../web_driver_adapter":44,"../web_driver_extension":45,"angular2/src/core/di":1,"angular2/src/facade/exceptions":21,"angular2/src/facade/lang":22}],49:[function(require,module,exports){
6043'use strict';"use strict";
6044var __extends = (this && this.__extends) || function (d, b) {
6045 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6046 function __() { this.constructor = d; }
6047 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6048};
6049var async_1 = require('angular2/src/facade/async');
6050var di_1 = require('angular2/src/core/di');
6051var web_driver_adapter_1 = require('../web_driver_adapter');
6052var webdriver = require('selenium-webdriver');
6053/**
6054 * Adapter for the selenium-webdriver.
6055 */
6056var SeleniumWebDriverAdapter = (function (_super) {
6057 __extends(SeleniumWebDriverAdapter, _super);
6058 function SeleniumWebDriverAdapter(_driver) {
6059 _super.call(this);
6060 this._driver = _driver;
6061 }
6062 Object.defineProperty(SeleniumWebDriverAdapter, "PROTRACTOR_BINDINGS", {
6063 get: function () { return _PROTRACTOR_BINDINGS; },
6064 enumerable: true,
6065 configurable: true
6066 });
6067 SeleniumWebDriverAdapter.prototype._convertPromise = function (thenable) {
6068 var completer = async_1.PromiseWrapper.completer();
6069 thenable.then(
6070 // selenium-webdriver uses an own Node.js context,
6071 // so we need to convert data into objects of this context.
6072 // Previously needed for rtts_asserts.
6073 function (data) { return completer.resolve(convertToLocalProcess(data)); }, completer.reject);
6074 return completer.promise;
6075 };
6076 SeleniumWebDriverAdapter.prototype.waitFor = function (callback) {
6077 return this._convertPromise(this._driver.controlFlow().execute(callback));
6078 };
6079 SeleniumWebDriverAdapter.prototype.executeScript = function (script) {
6080 return this._convertPromise(this._driver.executeScript(script));
6081 };
6082 SeleniumWebDriverAdapter.prototype.executeAsyncScript = function (script) {
6083 return this._convertPromise(this._driver.executeAsyncScript(script));
6084 };
6085 SeleniumWebDriverAdapter.prototype.capabilities = function () {
6086 return this._convertPromise(this._driver.getCapabilities().then(function (capsObject) { return capsObject.serialize(); }));
6087 };
6088 SeleniumWebDriverAdapter.prototype.logs = function (type) {
6089 // Needed as selenium-webdriver does not forward
6090 // performance logs in the correct way via manage().logs
6091 return this._convertPromise(this._driver.schedule(new webdriver.Command(webdriver.CommandName.GET_LOG).setParameter('type', type), 'WebDriver.manage().logs().get(' + type + ')'));
6092 };
6093 return SeleniumWebDriverAdapter;
6094}(web_driver_adapter_1.WebDriverAdapter));
6095exports.SeleniumWebDriverAdapter = SeleniumWebDriverAdapter;
6096function convertToLocalProcess(data) {
6097 var serialized = JSON.stringify(data);
6098 if ('' + serialized === 'undefined') {
6099 return undefined;
6100 }
6101 return JSON.parse(serialized);
6102}
6103var _PROTRACTOR_BINDINGS = [
6104 di_1.bind(web_driver_adapter_1.WebDriverAdapter)
6105 .toFactory(function () { return new SeleniumWebDriverAdapter(global.browser); }, [])
6106];
6107},{"../web_driver_adapter":44,"angular2/src/core/di":1,"angular2/src/facade/async":17,"selenium-webdriver":undefined}],50:[function(require,module,exports){
6108"use strict";
6109var root_1 = require('./util/root');
6110var observable_1 = require('./symbol/observable');
6111var toSubscriber_1 = require('./util/toSubscriber');
6112/**
6113 * A representation of any set of values over any amount of time. This the most basic building block
6114 * of RxJS.
6115 *
6116 * @class Observable<T>
6117 */
6118var Observable = (function () {
6119 /**
6120 * @constructor
6121 * @param {Function} subscribe the function that is called when the Observable is
6122 * initially subscribed to. This function is given a Subscriber, to which new values
6123 * can be `next`ed, or an `error` method can be called to raise an error, or
6124 * `complete` can be called to notify of a successful completion.
6125 */
6126 function Observable(subscribe) {
6127 this._isScalar = false;
6128 if (subscribe) {
6129 this._subscribe = subscribe;
6130 }
6131 }
6132 /**
6133 * Creates a new Observable, with this Observable as the source, and the passed
6134 * operator defined as the new observable's operator.
6135 * @method lift
6136 * @param {Operator} operator the operator defining the operation to take on the observable
6137 * @return {Observable} a new observable with the Operator applied
6138 */
6139 Observable.prototype.lift = function (operator) {
6140 var observable = new Observable();
6141 observable.source = this;
6142 observable.operator = operator;
6143 return observable;
6144 };
6145 /**
6146 * Registers handlers for handling emitted values, error and completions from the observable, and
6147 * executes the observable's subscriber function, which will take action to set up the underlying data stream
6148 * @method subscribe
6149 * @param {PartialObserver|Function} observerOrNext (optional) either an observer defining all functions to be called,
6150 * or the first of three possible handlers, which is the handler for each value emitted from the observable.
6151 * @param {Function} error (optional) a handler for a terminal event resulting from an error. If no error handler is provided,
6152 * the error will be thrown as unhandled
6153 * @param {Function} complete (optional) a handler for a terminal event resulting from successful completion.
6154 * @return {ISubscription} a subscription reference to the registered handlers
6155 */
6156 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
6157 var operator = this.operator;
6158 var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
6159 sink.add(operator ? operator.call(sink, this) : this._subscribe(sink));
6160 if (sink.syncErrorThrowable) {
6161 sink.syncErrorThrowable = false;
6162 if (sink.syncErrorThrown) {
6163 throw sink.syncErrorValue;
6164 }
6165 }
6166 return sink;
6167 };
6168 /**
6169 * @method forEach
6170 * @param {Function} next a handler for each value emitted by the observable
6171 * @param {PromiseConstructor} [PromiseCtor] a constructor function used to instantiate the Promise
6172 * @return {Promise} a promise that either resolves on observable completion or
6173 * rejects with the handled error
6174 */
6175 Observable.prototype.forEach = function (next, PromiseCtor) {
6176 var _this = this;
6177 if (!PromiseCtor) {
6178 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
6179 PromiseCtor = root_1.root.Rx.config.Promise;
6180 }
6181 else if (root_1.root.Promise) {
6182 PromiseCtor = root_1.root.Promise;
6183 }
6184 }
6185 if (!PromiseCtor) {
6186 throw new Error('no Promise impl found');
6187 }
6188 return new PromiseCtor(function (resolve, reject) {
6189 var subscription = _this.subscribe(function (value) {
6190 if (subscription) {
6191 // if there is a subscription, then we can surmise
6192 // the next handling is asynchronous. Any errors thrown
6193 // need to be rejected explicitly and unsubscribe must be
6194 // called manually
6195 try {
6196 next(value);
6197 }
6198 catch (err) {
6199 reject(err);
6200 subscription.unsubscribe();
6201 }
6202 }
6203 else {
6204 // if there is NO subscription, then we're getting a nexted
6205 // value synchronously during subscription. We can just call it.
6206 // If it errors, Observable's `subscribe` imple will ensure the
6207 // unsubscription logic is called, then synchronously rethrow the error.
6208 // After that, Promise will trap the error and send it
6209 // down the rejection path.
6210 next(value);
6211 }
6212 }, reject, resolve);
6213 });
6214 };
6215 Observable.prototype._subscribe = function (subscriber) {
6216 return this.source.subscribe(subscriber);
6217 };
6218 /**
6219 * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
6220 * @method Symbol.observable
6221 * @return {Observable} this instance of the observable
6222 */
6223 Observable.prototype[observable_1.$$observable] = function () {
6224 return this;
6225 };
6226 // HACK: Since TypeScript inherits static properties too, we have to
6227 // fight against TypeScript here so Subject can have a different static create signature
6228 /**
6229 * Creates a new cold Observable by calling the Observable constructor
6230 * @static true
6231 * @owner Observable
6232 * @method create
6233 * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor
6234 * @return {Observable} a new cold observable
6235 */
6236 Observable.create = function (subscribe) {
6237 return new Observable(subscribe);
6238 };
6239 return Observable;
6240}());
6241exports.Observable = Observable;
6242
6243},{"./symbol/observable":58,"./util/root":66,"./util/toSubscriber":68}],51:[function(require,module,exports){
6244"use strict";
6245exports.empty = {
6246 isUnsubscribed: true,
6247 next: function (value) { },
6248 error: function (err) { throw err; },
6249 complete: function () { }
6250};
6251
6252},{}],52:[function(require,module,exports){
6253"use strict";
6254var __extends = (this && this.__extends) || function (d, b) {
6255 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6256 function __() { this.constructor = d; }
6257 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6258};
6259var Observable_1 = require('./Observable');
6260var Subscriber_1 = require('./Subscriber');
6261var Subscription_1 = require('./Subscription');
6262var SubjectSubscription_1 = require('./SubjectSubscription');
6263var rxSubscriber_1 = require('./symbol/rxSubscriber');
6264var throwError_1 = require('./util/throwError');
6265var ObjectUnsubscribedError_1 = require('./util/ObjectUnsubscribedError');
6266/**
6267 * @class Subject<T>
6268 */
6269var Subject = (function (_super) {
6270 __extends(Subject, _super);
6271 function Subject(destination, source) {
6272 _super.call(this);
6273 this.destination = destination;
6274 this.source = source;
6275 this.observers = [];
6276 this.isUnsubscribed = false;
6277 this.isStopped = false;
6278 this.hasErrored = false;
6279 this.dispatching = false;
6280 this.hasCompleted = false;
6281 this.source = source;
6282 }
6283 Subject.prototype.lift = function (operator) {
6284 var subject = new Subject(this.destination || this, this);
6285 subject.operator = operator;
6286 return subject;
6287 };
6288 Subject.prototype.add = function (subscription) {
6289 return Subscription_1.Subscription.prototype.add.call(this, subscription);
6290 };
6291 Subject.prototype.remove = function (subscription) {
6292 Subscription_1.Subscription.prototype.remove.call(this, subscription);
6293 };
6294 Subject.prototype.unsubscribe = function () {
6295 Subscription_1.Subscription.prototype.unsubscribe.call(this);
6296 };
6297 Subject.prototype._subscribe = function (subscriber) {
6298 if (this.source) {
6299 return this.source.subscribe(subscriber);
6300 }
6301 else {
6302 if (subscriber.isUnsubscribed) {
6303 return;
6304 }
6305 else if (this.hasErrored) {
6306 return subscriber.error(this.errorValue);
6307 }
6308 else if (this.hasCompleted) {
6309 return subscriber.complete();
6310 }
6311 this.throwIfUnsubscribed();
6312 var subscription = new SubjectSubscription_1.SubjectSubscription(this, subscriber);
6313 this.observers.push(subscriber);
6314 return subscription;
6315 }
6316 };
6317 Subject.prototype._unsubscribe = function () {
6318 this.source = null;
6319 this.isStopped = true;
6320 this.observers = null;
6321 this.destination = null;
6322 };
6323 Subject.prototype.next = function (value) {
6324 this.throwIfUnsubscribed();
6325 if (this.isStopped) {
6326 return;
6327 }
6328 this.dispatching = true;
6329 this._next(value);
6330 this.dispatching = false;
6331 if (this.hasErrored) {
6332 this._error(this.errorValue);
6333 }
6334 else if (this.hasCompleted) {
6335 this._complete();
6336 }
6337 };
6338 Subject.prototype.error = function (err) {
6339 this.throwIfUnsubscribed();
6340 if (this.isStopped) {
6341 return;
6342 }
6343 this.isStopped = true;
6344 this.hasErrored = true;
6345 this.errorValue = err;
6346 if (this.dispatching) {
6347 return;
6348 }
6349 this._error(err);
6350 };
6351 Subject.prototype.complete = function () {
6352 this.throwIfUnsubscribed();
6353 if (this.isStopped) {
6354 return;
6355 }
6356 this.isStopped = true;
6357 this.hasCompleted = true;
6358 if (this.dispatching) {
6359 return;
6360 }
6361 this._complete();
6362 };
6363 Subject.prototype.asObservable = function () {
6364 var observable = new SubjectObservable(this);
6365 return observable;
6366 };
6367 Subject.prototype._next = function (value) {
6368 if (this.destination) {
6369 this.destination.next(value);
6370 }
6371 else {
6372 this._finalNext(value);
6373 }
6374 };
6375 Subject.prototype._finalNext = function (value) {
6376 var index = -1;
6377 var observers = this.observers.slice(0);
6378 var len = observers.length;
6379 while (++index < len) {
6380 observers[index].next(value);
6381 }
6382 };
6383 Subject.prototype._error = function (err) {
6384 if (this.destination) {
6385 this.destination.error(err);
6386 }
6387 else {
6388 this._finalError(err);
6389 }
6390 };
6391 Subject.prototype._finalError = function (err) {
6392 var index = -1;
6393 var observers = this.observers;
6394 // optimization to block our SubjectSubscriptions from
6395 // splicing themselves out of the observers list one by one.
6396 this.observers = null;
6397 this.isUnsubscribed = true;
6398 if (observers) {
6399 var len = observers.length;
6400 while (++index < len) {
6401 observers[index].error(err);
6402 }
6403 }
6404 this.isUnsubscribed = false;
6405 this.unsubscribe();
6406 };
6407 Subject.prototype._complete = function () {
6408 if (this.destination) {
6409 this.destination.complete();
6410 }
6411 else {
6412 this._finalComplete();
6413 }
6414 };
6415 Subject.prototype._finalComplete = function () {
6416 var index = -1;
6417 var observers = this.observers;
6418 // optimization to block our SubjectSubscriptions from
6419 // splicing themselves out of the observers list one by one.
6420 this.observers = null;
6421 this.isUnsubscribed = true;
6422 if (observers) {
6423 var len = observers.length;
6424 while (++index < len) {
6425 observers[index].complete();
6426 }
6427 }
6428 this.isUnsubscribed = false;
6429 this.unsubscribe();
6430 };
6431 Subject.prototype.throwIfUnsubscribed = function () {
6432 if (this.isUnsubscribed) {
6433 throwError_1.throwError(new ObjectUnsubscribedError_1.ObjectUnsubscribedError());
6434 }
6435 };
6436 Subject.prototype[rxSubscriber_1.$$rxSubscriber] = function () {
6437 return new Subscriber_1.Subscriber(this);
6438 };
6439 Subject.create = function (destination, source) {
6440 return new Subject(destination, source);
6441 };
6442 return Subject;
6443}(Observable_1.Observable));
6444exports.Subject = Subject;
6445/**
6446 * We need this JSDoc comment for affecting ESDoc.
6447 * @ignore
6448 * @extends {Ignored}
6449 */
6450var SubjectObservable = (function (_super) {
6451 __extends(SubjectObservable, _super);
6452 function SubjectObservable(source) {
6453 _super.call(this);
6454 this.source = source;
6455 }
6456 return SubjectObservable;
6457}(Observable_1.Observable));
6458
6459},{"./Observable":50,"./SubjectSubscription":53,"./Subscriber":54,"./Subscription":55,"./symbol/rxSubscriber":59,"./util/ObjectUnsubscribedError":60,"./util/throwError":67}],53:[function(require,module,exports){
6460"use strict";
6461var __extends = (this && this.__extends) || function (d, b) {
6462 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6463 function __() { this.constructor = d; }
6464 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6465};
6466var Subscription_1 = require('./Subscription');
6467/**
6468 * We need this JSDoc comment for affecting ESDoc.
6469 * @ignore
6470 * @extends {Ignored}
6471 */
6472var SubjectSubscription = (function (_super) {
6473 __extends(SubjectSubscription, _super);
6474 function SubjectSubscription(subject, observer) {
6475 _super.call(this);
6476 this.subject = subject;
6477 this.observer = observer;
6478 this.isUnsubscribed = false;
6479 }
6480 SubjectSubscription.prototype.unsubscribe = function () {
6481 if (this.isUnsubscribed) {
6482 return;
6483 }
6484 this.isUnsubscribed = true;
6485 var subject = this.subject;
6486 var observers = subject.observers;
6487 this.subject = null;
6488 if (!observers || observers.length === 0 || subject.isUnsubscribed) {
6489 return;
6490 }
6491 var subscriberIndex = observers.indexOf(this.observer);
6492 if (subscriberIndex !== -1) {
6493 observers.splice(subscriberIndex, 1);
6494 }
6495 };
6496 return SubjectSubscription;
6497}(Subscription_1.Subscription));
6498exports.SubjectSubscription = SubjectSubscription;
6499
6500},{"./Subscription":55}],54:[function(require,module,exports){
6501"use strict";
6502var __extends = (this && this.__extends) || function (d, b) {
6503 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6504 function __() { this.constructor = d; }
6505 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6506};
6507var isFunction_1 = require('./util/isFunction');
6508var Subscription_1 = require('./Subscription');
6509var rxSubscriber_1 = require('./symbol/rxSubscriber');
6510var Observer_1 = require('./Observer');
6511/**
6512 * Implements the {@link Observer} interface and extends the
6513 * {@link Subscription} class. While the {@link Observer} is the public API for
6514 * consuming the values of an {@link Observable}, all Observers get converted to
6515 * a Subscriber, in order to provide Subscription-like capabilities such as
6516 * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
6517 * implementing operators, but it is rarely used as a public API.
6518 *
6519 * @class Subscriber<T>
6520 */
6521var Subscriber = (function (_super) {
6522 __extends(Subscriber, _super);
6523 /**
6524 * @param {Observer|function(value: T): void} [destinationOrNext] A partially
6525 * defined Observer or a `next` callback function.
6526 * @param {function(e: ?any): void} [error] The `error` callback of an
6527 * Observer.
6528 * @param {function(): void} [complete] The `complete` callback of an
6529 * Observer.
6530 */
6531 function Subscriber(destinationOrNext, error, complete) {
6532 _super.call(this);
6533 this.syncErrorValue = null;
6534 this.syncErrorThrown = false;
6535 this.syncErrorThrowable = false;
6536 this.isStopped = false;
6537 switch (arguments.length) {
6538 case 0:
6539 this.destination = Observer_1.empty;
6540 break;
6541 case 1:
6542 if (!destinationOrNext) {
6543 this.destination = Observer_1.empty;
6544 break;
6545 }
6546 if (typeof destinationOrNext === 'object') {
6547 if (destinationOrNext instanceof Subscriber) {
6548 this.destination = destinationOrNext;
6549 this.destination.add(this);
6550 }
6551 else {
6552 this.syncErrorThrowable = true;
6553 this.destination = new SafeSubscriber(this, destinationOrNext);
6554 }
6555 break;
6556 }
6557 default:
6558 this.syncErrorThrowable = true;
6559 this.destination = new SafeSubscriber(this, destinationOrNext, error, complete);
6560 break;
6561 }
6562 }
6563 /**
6564 * A static factory for a Subscriber, given a (potentially partial) definition
6565 * of an Observer.
6566 * @param {function(x: ?T): void} [next] The `next` callback of an Observer.
6567 * @param {function(e: ?any): void} [error] The `error` callback of an
6568 * Observer.
6569 * @param {function(): void} [complete] The `complete` callback of an
6570 * Observer.
6571 * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)
6572 * Observer represented by the given arguments.
6573 */
6574 Subscriber.create = function (next, error, complete) {
6575 var subscriber = new Subscriber(next, error, complete);
6576 subscriber.syncErrorThrowable = false;
6577 return subscriber;
6578 };
6579 /**
6580 * The {@link Observer} callback to receive notifications of type `next` from
6581 * the Observable, with a value. The Observable may call this method 0 or more
6582 * times.
6583 * @param {T} [value] The `next` value.
6584 * @return {void}
6585 */
6586 Subscriber.prototype.next = function (value) {
6587 if (!this.isStopped) {
6588 this._next(value);
6589 }
6590 };
6591 /**
6592 * The {@link Observer} callback to receive notifications of type `error` from
6593 * the Observable, with an attached {@link Error}. Notifies the Observer that
6594 * the Observable has experienced an error condition.
6595 * @param {any} [err] The `error` exception.
6596 * @return {void}
6597 */
6598 Subscriber.prototype.error = function (err) {
6599 if (!this.isStopped) {
6600 this.isStopped = true;
6601 this._error(err);
6602 }
6603 };
6604 /**
6605 * The {@link Observer} callback to receive a valueless notification of type
6606 * `complete` from the Observable. Notifies the Observer that the Observable
6607 * has finished sending push-based notifications.
6608 * @return {void}
6609 */
6610 Subscriber.prototype.complete = function () {
6611 if (!this.isStopped) {
6612 this.isStopped = true;
6613 this._complete();
6614 }
6615 };
6616 Subscriber.prototype.unsubscribe = function () {
6617 if (this.isUnsubscribed) {
6618 return;
6619 }
6620 this.isStopped = true;
6621 _super.prototype.unsubscribe.call(this);
6622 };
6623 Subscriber.prototype._next = function (value) {
6624 this.destination.next(value);
6625 };
6626 Subscriber.prototype._error = function (err) {
6627 this.destination.error(err);
6628 this.unsubscribe();
6629 };
6630 Subscriber.prototype._complete = function () {
6631 this.destination.complete();
6632 this.unsubscribe();
6633 };
6634 Subscriber.prototype[rxSubscriber_1.$$rxSubscriber] = function () {
6635 return this;
6636 };
6637 return Subscriber;
6638}(Subscription_1.Subscription));
6639exports.Subscriber = Subscriber;
6640/**
6641 * We need this JSDoc comment for affecting ESDoc.
6642 * @ignore
6643 * @extends {Ignored}
6644 */
6645var SafeSubscriber = (function (_super) {
6646 __extends(SafeSubscriber, _super);
6647 function SafeSubscriber(_parent, observerOrNext, error, complete) {
6648 _super.call(this);
6649 this._parent = _parent;
6650 var next;
6651 var context = this;
6652 if (isFunction_1.isFunction(observerOrNext)) {
6653 next = observerOrNext;
6654 }
6655 else if (observerOrNext) {
6656 context = observerOrNext;
6657 next = observerOrNext.next;
6658 error = observerOrNext.error;
6659 complete = observerOrNext.complete;
6660 if (isFunction_1.isFunction(context.unsubscribe)) {
6661 this.add(context.unsubscribe.bind(context));
6662 }
6663 context.unsubscribe = this.unsubscribe.bind(this);
6664 }
6665 this._context = context;
6666 this._next = next;
6667 this._error = error;
6668 this._complete = complete;
6669 }
6670 SafeSubscriber.prototype.next = function (value) {
6671 if (!this.isStopped && this._next) {
6672 var _parent = this._parent;
6673 if (!_parent.syncErrorThrowable) {
6674 this.__tryOrUnsub(this._next, value);
6675 }
6676 else if (this.__tryOrSetError(_parent, this._next, value)) {
6677 this.unsubscribe();
6678 }
6679 }
6680 };
6681 SafeSubscriber.prototype.error = function (err) {
6682 if (!this.isStopped) {
6683 var _parent = this._parent;
6684 if (this._error) {
6685 if (!_parent.syncErrorThrowable) {
6686 this.__tryOrUnsub(this._error, err);
6687 this.unsubscribe();
6688 }
6689 else {
6690 this.__tryOrSetError(_parent, this._error, err);
6691 this.unsubscribe();
6692 }
6693 }
6694 else if (!_parent.syncErrorThrowable) {
6695 this.unsubscribe();
6696 throw err;
6697 }
6698 else {
6699 _parent.syncErrorValue = err;
6700 _parent.syncErrorThrown = true;
6701 this.unsubscribe();
6702 }
6703 }
6704 };
6705 SafeSubscriber.prototype.complete = function () {
6706 if (!this.isStopped) {
6707 var _parent = this._parent;
6708 if (this._complete) {
6709 if (!_parent.syncErrorThrowable) {
6710 this.__tryOrUnsub(this._complete);
6711 this.unsubscribe();
6712 }
6713 else {
6714 this.__tryOrSetError(_parent, this._complete);
6715 this.unsubscribe();
6716 }
6717 }
6718 else {
6719 this.unsubscribe();
6720 }
6721 }
6722 };
6723 SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
6724 try {
6725 fn.call(this._context, value);
6726 }
6727 catch (err) {
6728 this.unsubscribe();
6729 throw err;
6730 }
6731 };
6732 SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
6733 try {
6734 fn.call(this._context, value);
6735 }
6736 catch (err) {
6737 parent.syncErrorValue = err;
6738 parent.syncErrorThrown = true;
6739 return true;
6740 }
6741 return false;
6742 };
6743 SafeSubscriber.prototype._unsubscribe = function () {
6744 var _parent = this._parent;
6745 this._context = null;
6746 this._parent = null;
6747 _parent.unsubscribe();
6748 };
6749 return SafeSubscriber;
6750}(Subscriber));
6751
6752},{"./Observer":51,"./Subscription":55,"./symbol/rxSubscriber":59,"./util/isFunction":64}],55:[function(require,module,exports){
6753"use strict";
6754var isArray_1 = require('./util/isArray');
6755var isObject_1 = require('./util/isObject');
6756var isFunction_1 = require('./util/isFunction');
6757var tryCatch_1 = require('./util/tryCatch');
6758var errorObject_1 = require('./util/errorObject');
6759var UnsubscriptionError_1 = require('./util/UnsubscriptionError');
6760/**
6761 * Represents a disposable resource, such as the execution of an Observable. A
6762 * Subscription has one important method, `unsubscribe`, that takes no argument
6763 * and just disposes the resource held by the subscription.
6764 *
6765 * Additionally, subscriptions may be grouped together through the `add()`
6766 * method, which will attach a child Subscription to the current Subscription.
6767 * When a Subscription is unsubscribed, all its children (and its grandchildren)
6768 * will be unsubscribed as well.
6769 *
6770 * @class Subscription
6771 */
6772var Subscription = (function () {
6773 /**
6774 * @param {function(): void} [unsubscribe] A function describing how to
6775 * perform the disposal of resources when the `unsubscribe` method is called.
6776 */
6777 function Subscription(unsubscribe) {
6778 /**
6779 * A flag to indicate whether this Subscription has already been unsubscribed.
6780 * @type {boolean}
6781 */
6782 this.isUnsubscribed = false;
6783 if (unsubscribe) {
6784 this._unsubscribe = unsubscribe;
6785 }
6786 }
6787 /**
6788 * Disposes the resources held by the subscription. May, for instance, cancel
6789 * an ongoing Observable execution or cancel any other type of work that
6790 * started when the Subscription was created.
6791 * @return {void}
6792 */
6793 Subscription.prototype.unsubscribe = function () {
6794 var hasErrors = false;
6795 var errors;
6796 if (this.isUnsubscribed) {
6797 return;
6798 }
6799 this.isUnsubscribed = true;
6800 var _a = this, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
6801 this._subscriptions = null;
6802 if (isFunction_1.isFunction(_unsubscribe)) {
6803 var trial = tryCatch_1.tryCatch(_unsubscribe).call(this);
6804 if (trial === errorObject_1.errorObject) {
6805 hasErrors = true;
6806 (errors = errors || []).push(errorObject_1.errorObject.e);
6807 }
6808 }
6809 if (isArray_1.isArray(_subscriptions)) {
6810 var index = -1;
6811 var len = _subscriptions.length;
6812 while (++index < len) {
6813 var sub = _subscriptions[index];
6814 if (isObject_1.isObject(sub)) {
6815 var trial = tryCatch_1.tryCatch(sub.unsubscribe).call(sub);
6816 if (trial === errorObject_1.errorObject) {
6817 hasErrors = true;
6818 errors = errors || [];
6819 var err = errorObject_1.errorObject.e;
6820 if (err instanceof UnsubscriptionError_1.UnsubscriptionError) {
6821 errors = errors.concat(err.errors);
6822 }
6823 else {
6824 errors.push(err);
6825 }
6826 }
6827 }
6828 }
6829 }
6830 if (hasErrors) {
6831 throw new UnsubscriptionError_1.UnsubscriptionError(errors);
6832 }
6833 };
6834 /**
6835 * Adds a tear down to be called during the unsubscribe() of this
6836 * Subscription.
6837 *
6838 * If the tear down being added is a subscription that is already
6839 * unsubscribed, is the same reference `add` is being called on, or is
6840 * `Subscription.EMPTY`, it will not be added.
6841 *
6842 * If this subscription is already in an `isUnsubscribed` state, the passed
6843 * tear down logic will be executed immediately.
6844 *
6845 * @param {TeardownLogic} teardown The additional logic to execute on
6846 * teardown.
6847 * @return {Subscription} Returns the Subscription used or created to be
6848 * added to the inner subscriptions list. This Subscription can be used with
6849 * `remove()` to remove the passed teardown logic from the inner subscriptions
6850 * list.
6851 */
6852 Subscription.prototype.add = function (teardown) {
6853 if (!teardown || (teardown === this) || (teardown === Subscription.EMPTY)) {
6854 return;
6855 }
6856 var sub = teardown;
6857 switch (typeof teardown) {
6858 case 'function':
6859 sub = new Subscription(teardown);
6860 case 'object':
6861 if (sub.isUnsubscribed || typeof sub.unsubscribe !== 'function') {
6862 break;
6863 }
6864 else if (this.isUnsubscribed) {
6865 sub.unsubscribe();
6866 }
6867 else {
6868 (this._subscriptions || (this._subscriptions = [])).push(sub);
6869 }
6870 break;
6871 default:
6872 throw new Error('Unrecognized teardown ' + teardown + ' added to Subscription.');
6873 }
6874 return sub;
6875 };
6876 /**
6877 * Removes a Subscription from the internal list of subscriptions that will
6878 * unsubscribe during the unsubscribe process of this Subscription.
6879 * @param {Subscription} subscription The subscription to remove.
6880 * @return {void}
6881 */
6882 Subscription.prototype.remove = function (subscription) {
6883 // HACK: This might be redundant because of the logic in `add()`
6884 if (subscription == null || (subscription === this) || (subscription === Subscription.EMPTY)) {
6885 return;
6886 }
6887 var subscriptions = this._subscriptions;
6888 if (subscriptions) {
6889 var subscriptionIndex = subscriptions.indexOf(subscription);
6890 if (subscriptionIndex !== -1) {
6891 subscriptions.splice(subscriptionIndex, 1);
6892 }
6893 }
6894 };
6895 Subscription.EMPTY = (function (empty) {
6896 empty.isUnsubscribed = true;
6897 return empty;
6898 }(new Subscription()));
6899 return Subscription;
6900}());
6901exports.Subscription = Subscription;
6902
6903},{"./util/UnsubscriptionError":61,"./util/errorObject":62,"./util/isArray":63,"./util/isFunction":64,"./util/isObject":65,"./util/tryCatch":69}],56:[function(require,module,exports){
6904"use strict";
6905var __extends = (this && this.__extends) || function (d, b) {
6906 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
6907 function __() { this.constructor = d; }
6908 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6909};
6910var root_1 = require('../util/root');
6911var Observable_1 = require('../Observable');
6912/**
6913 * We need this JSDoc comment for affecting ESDoc.
6914 * @extends {Ignored}
6915 * @hide true
6916 */
6917var PromiseObservable = (function (_super) {
6918 __extends(PromiseObservable, _super);
6919 function PromiseObservable(promise, scheduler) {
6920 if (scheduler === void 0) { scheduler = null; }
6921 _super.call(this);
6922 this.promise = promise;
6923 this.scheduler = scheduler;
6924 }
6925 /**
6926 * @param promise
6927 * @param scheduler
6928 * @return {PromiseObservable}
6929 * @static true
6930 * @name fromPromise
6931 * @owner Observable
6932 */
6933 PromiseObservable.create = function (promise, scheduler) {
6934 if (scheduler === void 0) { scheduler = null; }
6935 return new PromiseObservable(promise, scheduler);
6936 };
6937 PromiseObservable.prototype._subscribe = function (subscriber) {
6938 var _this = this;
6939 var promise = this.promise;
6940 var scheduler = this.scheduler;
6941 if (scheduler == null) {
6942 if (this._isScalar) {
6943 if (!subscriber.isUnsubscribed) {
6944 subscriber.next(this.value);
6945 subscriber.complete();
6946 }
6947 }
6948 else {
6949 promise.then(function (value) {
6950 _this.value = value;
6951 _this._isScalar = true;
6952 if (!subscriber.isUnsubscribed) {
6953 subscriber.next(value);
6954 subscriber.complete();
6955 }
6956 }, function (err) {
6957 if (!subscriber.isUnsubscribed) {
6958 subscriber.error(err);
6959 }
6960 })
6961 .then(null, function (err) {
6962 // escape the promise trap, throw unhandled errors
6963 root_1.root.setTimeout(function () { throw err; });
6964 });
6965 }
6966 }
6967 else {
6968 if (this._isScalar) {
6969 if (!subscriber.isUnsubscribed) {
6970 return scheduler.schedule(dispatchNext, 0, { value: this.value, subscriber: subscriber });
6971 }
6972 }
6973 else {
6974 promise.then(function (value) {
6975 _this.value = value;
6976 _this._isScalar = true;
6977 if (!subscriber.isUnsubscribed) {
6978 subscriber.add(scheduler.schedule(dispatchNext, 0, { value: value, subscriber: subscriber }));
6979 }
6980 }, function (err) {
6981 if (!subscriber.isUnsubscribed) {
6982 subscriber.add(scheduler.schedule(dispatchError, 0, { err: err, subscriber: subscriber }));
6983 }
6984 })
6985 .then(null, function (err) {
6986 // escape the promise trap, throw unhandled errors
6987 root_1.root.setTimeout(function () { throw err; });
6988 });
6989 }
6990 }
6991 };
6992 return PromiseObservable;
6993}(Observable_1.Observable));
6994exports.PromiseObservable = PromiseObservable;
6995function dispatchNext(arg) {
6996 var value = arg.value, subscriber = arg.subscriber;
6997 if (!subscriber.isUnsubscribed) {
6998 subscriber.next(value);
6999 subscriber.complete();
7000 }
7001}
7002function dispatchError(arg) {
7003 var err = arg.err, subscriber = arg.subscriber;
7004 if (!subscriber.isUnsubscribed) {
7005 subscriber.error(err);
7006 }
7007}
7008
7009},{"../Observable":50,"../util/root":66}],57:[function(require,module,exports){
7010"use strict";
7011var root_1 = require('../util/root');
7012/**
7013 * @param PromiseCtor
7014 * @return {Promise<T>}
7015 * @method toPromise
7016 * @owner Observable
7017 */
7018function toPromise(PromiseCtor) {
7019 var _this = this;
7020 if (!PromiseCtor) {
7021 if (root_1.root.Rx && root_1.root.Rx.config && root_1.root.Rx.config.Promise) {
7022 PromiseCtor = root_1.root.Rx.config.Promise;
7023 }
7024 else if (root_1.root.Promise) {
7025 PromiseCtor = root_1.root.Promise;
7026 }
7027 }
7028 if (!PromiseCtor) {
7029 throw new Error('no Promise impl found');
7030 }
7031 return new PromiseCtor(function (resolve, reject) {
7032 var value;
7033 _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
7034 });
7035}
7036exports.toPromise = toPromise;
7037
7038},{"../util/root":66}],58:[function(require,module,exports){
7039"use strict";
7040var root_1 = require('../util/root');
7041var Symbol = root_1.root.Symbol;
7042if (typeof Symbol === 'function') {
7043 if (Symbol.observable) {
7044 exports.$$observable = Symbol.observable;
7045 }
7046 else {
7047 if (typeof Symbol.for === 'function') {
7048 exports.$$observable = Symbol.for('observable');
7049 }
7050 else {
7051 exports.$$observable = Symbol('observable');
7052 }
7053 Symbol.observable = exports.$$observable;
7054 }
7055}
7056else {
7057 exports.$$observable = '@@observable';
7058}
7059
7060},{"../util/root":66}],59:[function(require,module,exports){
7061"use strict";
7062var root_1 = require('../util/root');
7063var Symbol = root_1.root.Symbol;
7064exports.$$rxSubscriber = (typeof Symbol === 'function' && typeof Symbol.for === 'function') ?
7065 Symbol.for('rxSubscriber') : '@@rxSubscriber';
7066
7067},{"../util/root":66}],60:[function(require,module,exports){
7068"use strict";
7069var __extends = (this && this.__extends) || function (d, b) {
7070 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7071 function __() { this.constructor = d; }
7072 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7073};
7074/**
7075 * An error thrown when an action is invalid because the object has been
7076 * unsubscribed.
7077 *
7078 * @see {@link Subject}
7079 * @see {@link BehaviorSubject}
7080 *
7081 * @class ObjectUnsubscribedError
7082 */
7083var ObjectUnsubscribedError = (function (_super) {
7084 __extends(ObjectUnsubscribedError, _super);
7085 function ObjectUnsubscribedError() {
7086 _super.call(this, 'object unsubscribed');
7087 this.name = 'ObjectUnsubscribedError';
7088 }
7089 return ObjectUnsubscribedError;
7090}(Error));
7091exports.ObjectUnsubscribedError = ObjectUnsubscribedError;
7092
7093},{}],61:[function(require,module,exports){
7094"use strict";
7095var __extends = (this && this.__extends) || function (d, b) {
7096 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
7097 function __() { this.constructor = d; }
7098 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7099};
7100/**
7101 * An error thrown when one or more errors have occurred during the
7102 * `unsubscribe` of a {@link Subscription}.
7103 */
7104var UnsubscriptionError = (function (_super) {
7105 __extends(UnsubscriptionError, _super);
7106 function UnsubscriptionError(errors) {
7107 _super.call(this);
7108 this.errors = errors;
7109 this.name = 'UnsubscriptionError';
7110 this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return ((i + 1) + ") " + err.toString()); }).join('\n') : '';
7111 }
7112 return UnsubscriptionError;
7113}(Error));
7114exports.UnsubscriptionError = UnsubscriptionError;
7115
7116},{}],62:[function(require,module,exports){
7117"use strict";
7118// typeof any so that it we don't have to cast when comparing a result to the error object
7119exports.errorObject = { e: {} };
7120
7121},{}],63:[function(require,module,exports){
7122"use strict";
7123exports.isArray = Array.isArray || (function (x) { return x && typeof x.length === 'number'; });
7124
7125},{}],64:[function(require,module,exports){
7126"use strict";
7127function isFunction(x) {
7128 return typeof x === 'function';
7129}
7130exports.isFunction = isFunction;
7131
7132},{}],65:[function(require,module,exports){
7133"use strict";
7134function isObject(x) {
7135 return x != null && typeof x === 'object';
7136}
7137exports.isObject = isObject;
7138
7139},{}],66:[function(require,module,exports){
7140"use strict";
7141var objectTypes = {
7142 'boolean': false,
7143 'function': true,
7144 'object': true,
7145 'number': false,
7146 'string': false,
7147 'undefined': false
7148};
7149exports.root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window);
7150/* tslint:disable:no-unused-variable */
7151var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
7152var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
7153var freeGlobal = objectTypes[typeof global] && global;
7154if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
7155 exports.root = freeGlobal;
7156}
7157
7158},{}],67:[function(require,module,exports){
7159"use strict";
7160function throwError(e) { throw e; }
7161exports.throwError = throwError;
7162
7163},{}],68:[function(require,module,exports){
7164"use strict";
7165var Subscriber_1 = require('../Subscriber');
7166var rxSubscriber_1 = require('../symbol/rxSubscriber');
7167function toSubscriber(nextOrObserver, error, complete) {
7168 if (nextOrObserver && typeof nextOrObserver === 'object') {
7169 if (nextOrObserver instanceof Subscriber_1.Subscriber) {
7170 return nextOrObserver;
7171 }
7172 else if (typeof nextOrObserver[rxSubscriber_1.$$rxSubscriber] === 'function') {
7173 return nextOrObserver[rxSubscriber_1.$$rxSubscriber]();
7174 }
7175 }
7176 return new Subscriber_1.Subscriber(nextOrObserver, error, complete);
7177}
7178exports.toSubscriber = toSubscriber;
7179
7180},{"../Subscriber":54,"../symbol/rxSubscriber":59}],69:[function(require,module,exports){
7181"use strict";
7182var errorObject_1 = require('./errorObject');
7183var tryCatchTarget;
7184function tryCatcher() {
7185 try {
7186 return tryCatchTarget.apply(this, arguments);
7187 }
7188 catch (e) {
7189 errorObject_1.errorObject.e = e;
7190 return errorObject_1.errorObject;
7191 }
7192}
7193function tryCatch(fn) {
7194 tryCatchTarget = fn;
7195 return tryCatcher;
7196}
7197exports.tryCatch = tryCatch;
7198;
7199
7200},{"./errorObject":62}]},{},[27]);
7201module.exports = global.__benchpressExports;