@angular/core
Version:
Angular - the core framework
1,386 lines (1,367 loc) • 1.44 MB
JavaScript
/**
* @license Angular v8.1.3
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
import { Subject, Subscription, Observable, merge as merge$1 } from 'rxjs';
import { share } from 'rxjs/operators';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ANNOTATIONS = '__annotations__';
const PARAMETERS = '__parameters__';
const PROP_METADATA = '__prop__metadata__';
/**
* @suppress {globalThis}
*/
function makeDecorator(name, props, parentClass, additionalProcessing, typeFn) {
const metaCtor = makeMetadataCtor(props);
function DecoratorFactory(...args) {
if (this instanceof DecoratorFactory) {
metaCtor.call(this, ...args);
return this;
}
const annotationInstance = new DecoratorFactory(...args);
return function TypeDecorator(cls) {
if (typeFn)
typeFn(cls, ...args);
// Use of Object.defineProperty is important since it creates non-enumerable property which
// prevents the property is copied during subclassing.
const annotations = cls.hasOwnProperty(ANNOTATIONS) ?
cls[ANNOTATIONS] :
Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS];
annotations.push(annotationInstance);
if (additionalProcessing)
additionalProcessing(cls);
return cls;
};
}
if (parentClass) {
DecoratorFactory.prototype = Object.create(parentClass.prototype);
}
DecoratorFactory.prototype.ngMetadataName = name;
DecoratorFactory.annotationCls = DecoratorFactory;
return DecoratorFactory;
}
function makeMetadataCtor(props) {
return function ctor(...args) {
if (props) {
const values = props(...args);
for (const propName in values) {
this[propName] = values[propName];
}
}
};
}
function makeParamDecorator(name, props, parentClass) {
const metaCtor = makeMetadataCtor(props);
function ParamDecoratorFactory(...args) {
if (this instanceof ParamDecoratorFactory) {
metaCtor.apply(this, args);
return this;
}
const annotationInstance = new ParamDecoratorFactory(...args);
ParamDecorator.annotation = annotationInstance;
return ParamDecorator;
function ParamDecorator(cls, unusedKey, index) {
// Use of Object.defineProperty is important since it creates non-enumerable property which
// prevents the property is copied during subclassing.
const parameters = cls.hasOwnProperty(PARAMETERS) ?
cls[PARAMETERS] :
Object.defineProperty(cls, PARAMETERS, { value: [] })[PARAMETERS];
// there might be gaps if some in between parameters do not have annotations.
// we pad with nulls.
while (parameters.length <= index) {
parameters.push(null);
}
(parameters[index] = parameters[index] || []).push(annotationInstance);
return cls;
}
}
if (parentClass) {
ParamDecoratorFactory.prototype = Object.create(parentClass.prototype);
}
ParamDecoratorFactory.prototype.ngMetadataName = name;
ParamDecoratorFactory.annotationCls = ParamDecoratorFactory;
return ParamDecoratorFactory;
}
function makePropDecorator(name, props, parentClass, additionalProcessing) {
const metaCtor = makeMetadataCtor(props);
function PropDecoratorFactory(...args) {
if (this instanceof PropDecoratorFactory) {
metaCtor.apply(this, args);
return this;
}
const decoratorInstance = new PropDecoratorFactory(...args);
function PropDecorator(target, name) {
const constructor = target.constructor;
// Use of Object.defineProperty is important since it creates non-enumerable property which
// prevents the property is copied during subclassing.
const meta = constructor.hasOwnProperty(PROP_METADATA) ?
constructor[PROP_METADATA] :
Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA];
meta[name] = meta.hasOwnProperty(name) && meta[name] || [];
meta[name].unshift(decoratorInstance);
if (additionalProcessing)
additionalProcessing(target, name, ...args);
}
return PropDecorator;
}
if (parentClass) {
PropDecoratorFactory.prototype = Object.create(parentClass.prototype);
}
PropDecoratorFactory.prototype.ngMetadataName = name;
PropDecoratorFactory.annotationCls = PropDecoratorFactory;
return PropDecoratorFactory;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// WARNING: interface has both a type and a value, skipping emit
const ɵ0 = /**
* @param {?} token
* @return {?}
*/
(token) => ({ token });
/**
* Inject decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Inject = makeParamDecorator('Inject', (ɵ0));
// WARNING: interface has both a type and a value, skipping emit
/**
* Optional decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Optional = makeParamDecorator('Optional');
// WARNING: interface has both a type and a value, skipping emit
/**
* Self decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Self = makeParamDecorator('Self');
// WARNING: interface has both a type and a value, skipping emit
/**
* SkipSelf decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const SkipSelf = makeParamDecorator('SkipSelf');
// WARNING: interface has both a type and a value, skipping emit
/**
* Host decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Host = makeParamDecorator('Host');
// WARNING: interface has both a type and a value, skipping emit
const ɵ1 = /**
* @param {?=} attributeName
* @return {?}
*/
(attributeName) => ({ attributeName });
/**
* Attribute decorator and metadata.
*
* \@Annotation
* \@publicApi
* @type {?}
*/
const Attribute = makeParamDecorator('Attribute', (ɵ1));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Injection flags for DI.
*
* @publicApi
*/
var InjectFlags;
(function (InjectFlags) {
// TODO(alxhub): make this 'const' when ngc no longer writes exports of it into ngfactory files.
/** Check self and check parent injector if needed */
InjectFlags[InjectFlags["Default"] = 0] = "Default";
/**
* Specifies that an injector should retrieve a dependency from any injector until reaching the
* host element of the current component. (Only used with Element Injector)
*/
InjectFlags[InjectFlags["Host"] = 1] = "Host";
/** Don't ascend to ancestors of the node requesting injection. */
InjectFlags[InjectFlags["Self"] = 2] = "Self";
/** Skip the node that is requesting injection. */
InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
/** Inject `defaultValue` instead if token not found. */
InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
})(InjectFlags || (InjectFlags = {}));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function getClosureSafeProperty(objWithPropertyToExtract) {
for (let key in objWithPropertyToExtract) {
if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
return key;
}
}
throw Error('Could not find renamed property on target object.');
}
/**
* Sets properties on a target object from a source object, but only if
* the property doesn't already exist on the target object.
* @param target The target to set properties on
* @param source The source of the property keys and values to set
*/
function fillProperties(target, source) {
for (const key in source) {
if (source.hasOwnProperty(key) && !target.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Construct an `InjectableDef` which defines how a token will be constructed by the DI system, and
* in which injectors (if any) it will be available.
*
* This should be assigned to a static `ngInjectableDef` field on a type, which will then be an
* `InjectableType`.
*
* Options:
* * `providedIn` determines which injectors will include the injectable, by either associating it
* with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
* provided in the `'root'` injector, which will be the application-level injector in most apps.
* * `factory` gives the zero argument function which will create an instance of the injectable.
* The factory can call `inject` to access the `Injector` and request injection of dependencies.
*
* @codeGenApi
*/
function ɵɵdefineInjectable(opts) {
return {
token: opts.token, providedIn: opts.providedIn || null, factory: opts.factory,
value: undefined,
};
}
/**
* @deprecated in v8, delete after v10. This API should be used only be generated code, and that
* code should now use ɵɵdefineInjectable instead.
* @publicApi
*/
const defineInjectable = ɵɵdefineInjectable;
/**
* Construct an `InjectorDef` which configures an injector.
*
* This should be assigned to a static `ngInjectorDef` field on a type, which will then be an
* `InjectorType`.
*
* Options:
*
* * `factory`: an `InjectorType` is an instantiable type, so a zero argument `factory` function to
* create the type must be provided. If that factory function needs to inject arguments, it can
* use the `inject` function.
* * `providers`: an optional array of providers to add to the injector. Each provider must
* either have a factory or point to a type which has an `ngInjectableDef` static property (the
* type must be an `InjectableType`).
* * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
* whose providers will also be added to the injector. Locally provided types will override
* providers from imports.
*
* @publicApi
*/
function ɵɵdefineInjector(options) {
return {
factory: options.factory, providers: options.providers || [], imports: options.imports || [],
};
}
/**
* Read the `ngInjectableDef` for `type` in a way which is immune to accidentally reading inherited
* value.
*
* @param type A type which may have its own (non-inherited) `ngInjectableDef`.
*/
function getInjectableDef(type) {
const def = type[NG_INJECTABLE_DEF];
// The definition read above may come from a base class. `hasOwnProperty` is not sufficient to
// distinguish this case, as in older browsers (e.g. IE10) static property inheritance is
// implemented by copying the properties.
//
// Instead, the ngInjectableDef's token is compared to the type, and if they don't match then the
// property was not defined directly on the type itself, and was likely inherited. The definition
// is only returned if the type matches the def.token.
return def && def.token === type ? def : null;
}
/**
* Read the `ngInjectableDef` for `type` or read the `ngInjectableDef` from one of its ancestors.
*
* @param type A type which may have `ngInjectableDef`, via inheritance.
*
* @deprecated Will be removed in v10, where an error will occur in the scenario if we find the
* `ngInjectableDef` on an ancestor only.
*/
function getInheritedInjectableDef(type) {
if (type && type[NG_INJECTABLE_DEF]) {
// TODO(FW-1307): Re-add ngDevMode when closure can handle it
// ngDevMode &&
console.warn(`DEPRECATED: DI is instantiating a token "${type.name}" that inherits its @Injectable decorator but does not provide one itself.\n` +
`This will become an error in v10. Please add @Injectable() to the "${type.name}" class.`);
return type[NG_INJECTABLE_DEF];
}
else {
return null;
}
}
/**
* Read the `ngInjectorDef` type in a way which is immune to accidentally reading inherited value.
*
* @param type type which may have `ngInjectorDef`
*/
function getInjectorDef(type) {
return type && type.hasOwnProperty(NG_INJECTOR_DEF) ? type[NG_INJECTOR_DEF] : null;
}
const NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty });
const NG_INJECTOR_DEF = getClosureSafeProperty({ ngInjectorDef: getClosureSafeProperty });
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function stringify(token) {
if (typeof token === 'string') {
return token;
}
if (token instanceof Array) {
return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
if (res == null) {
return '' + res;
}
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty });
/**
* Allows to refer to references which are not yet defined.
*
* For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
* DI is declared, but not yet defined. It is also used when the `token` which we use when creating
* a query is not yet defined.
*
* \@usageNotes
* ### Example
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
* \@publicApi
* @param {?} forwardRefFn
* @return {?}
*/
function forwardRef(forwardRefFn) {
((/** @type {?} */ (forwardRefFn))).__forward_ref__ = forwardRef;
((/** @type {?} */ (forwardRefFn))).toString = (/**
* @return {?}
*/
function () { return stringify(this()); });
return ((/** @type {?} */ ((/** @type {?} */ (forwardRefFn)))));
}
/**
* Lazily retrieves the reference value from a forwardRef.
*
* Acts as the identity function when given a non-forward-ref value.
*
* \@usageNotes
* ### Example
*
* {\@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
*
* @see `forwardRef`
* \@publicApi
* @template T
* @param {?} type
* @return {?}
*/
function resolveForwardRef(type) {
/** @type {?} */
const fn = type;
if (typeof fn === 'function' && fn.hasOwnProperty(__forward_ref__) &&
fn.__forward_ref__ === forwardRef) {
return fn();
}
else {
return type;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const __globalThis = typeof globalThis !== 'undefined' && globalThis;
const __window = typeof window !== 'undefined' && window;
const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
self instanceof WorkerGlobalScope && self;
const __global = typeof global !== 'undefined' && global;
// Always use __globalThis if available, which is the spec-defined global variable across all
// environments, then fallback to __global first, because in Node tests both __global and
// __window may be defined and _global should be __global in that case.
const _global = __globalThis || __global || __window || __self;
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var R3ResolvedDependencyType;
(function (R3ResolvedDependencyType) {
R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
})(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function getCompilerFacade() {
const globalNg = _global['ng'];
if (!globalNg || !globalNg.ɵcompilerFacade) {
throw new Error(`Angular JIT compilation failed: '@angular/compiler' not loaded!\n` +
` - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.\n` +
` - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?\n` +
` - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.`);
}
return globalNg.ɵcompilerFacade;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Creates a token that can be used in a DI Provider.
*
* Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
* runtime representation) such as when injecting an interface, callable type, array or
* parameterized type.
*
* `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
* the `Injector`. This provides additional level of type safety.
*
* ```
* interface MyInterface {...}
* var myInterface = injector.get(new InjectionToken<MyInterface>('SomeToken'));
* // myInterface is inferred to be MyInterface.
* ```
*
* When creating an `InjectionToken`, you can optionally specify a factory function which returns
* (possibly by creating) a default value of the parameterized type `T`. This sets up the
* `InjectionToken` using this factory as a provider as if it was defined explicitly in the
* application's root injector. If the factory function, which takes zero arguments, needs to inject
* dependencies, it can do so using the `inject` function. See below for an example.
*
* Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
* overrides the above behavior and marks the token as belonging to a particular `\@NgModule`. As
* mentioned above, `'root'` is the default value for `providedIn`.
*
* \@usageNotes
* ### Basic Example
*
* ### Plain InjectionToken
*
* {\@example core/di/ts/injector_spec.ts region='InjectionToken'}
*
* ### Tree-shakable InjectionToken
*
* {\@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
*
*
* \@publicApi
* @template T
*/
class InjectionToken {
/**
* @param {?} _desc
* @param {?=} options
*/
constructor(_desc, options) {
this._desc = _desc;
/**
* \@internal
*/
this.ngMetadataName = 'InjectionToken';
/** @nocollapse */ this.ngInjectableDef = undefined;
if (typeof options == 'number') {
// This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
// __NG_ELEMENT_ID__ is Used by Ivy to determine bloom filter id.
// We are using it to assign `-1` which is used to identify `Injector`.
((/** @type {?} */ (this))).__NG_ELEMENT_ID__ = options;
}
else if (options !== undefined) {
/** @nocollapse */ this.ngInjectableDef = ɵɵdefineInjectable({
token: this,
providedIn: options.providedIn || 'root',
factory: options.factory,
});
}
}
/**
* @return {?}
*/
toString() { return `InjectionToken ${this._desc}`; }
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
*
* Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
* project.
*
* \@publicApi
* @type {?}
*/
const INJECTOR = new InjectionToken('INJECTOR', (/** @type {?} */ (-1)));
/** @type {?} */
const _THROW_IF_NOT_FOUND = new Object();
/** @type {?} */
const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
/** @type {?} */
const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
/** @type {?} */
const NG_TOKEN_PATH = 'ngTokenPath';
/** @type {?} */
const NEW_LINE = /\n/gm;
/** @type {?} */
const NO_NEW_LINE = 'ɵ';
/** @type {?} */
const SOURCE = '__source';
const ɵ0$1 = getClosureSafeProperty;
/** @type {?} */
const USE_VALUE = getClosureSafeProperty({ provide: String, useValue: ɵ0$1 });
/**
* Current injector value used by `inject`.
* - `undefined`: it is an error to call `inject`
* - `null`: `inject` can be called but there is no injector (limp-mode).
* - Injector instance: Use the injector for resolution.
* @type {?}
*/
let _currentInjector = undefined;
/**
* @param {?} injector
* @return {?}
*/
function setCurrentInjector(injector) {
/** @type {?} */
const former = _currentInjector;
_currentInjector = injector;
return former;
}
/**
* Current implementation of inject.
*
* By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
* to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
* way for two reasons:
* 1. `Injector` should not depend on ivy logic.
* 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
* @type {?}
*/
let _injectImplementation;
/**
* Sets the current inject implementation.
* @param {?} impl
* @return {?}
*/
function setInjectImplementation(impl) {
/** @type {?} */
const previous = _injectImplementation;
_injectImplementation = impl;
return previous;
}
/**
* @template T
* @param {?} token
* @param {?=} flags
* @return {?}
*/
function injectInjectorOnly(token, flags = InjectFlags.Default) {
if (_currentInjector === undefined) {
throw new Error(`inject() must be called from an injection context`);
}
else if (_currentInjector === null) {
return injectRootLimpMode(token, undefined, flags);
}
else {
return _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
}
}
/**
* @template T
* @param {?} token
* @param {?=} flags
* @return {?}
*/
function ɵɵinject(token, flags = InjectFlags.Default) {
return (_injectImplementation || injectInjectorOnly)(token, flags);
}
/**
* Injects a token from the currently active injector.
*
* Must be used in the context of a factory function such as one defined for an
* `InjectionToken`. Throws an error if not called from such a context.
*
* Within such a factory function, using this function to request injection of a dependency
* is faster and more type-safe than providing an additional array of dependencies
* (as has been common with `useFactory` providers).
*
* \@param token The injection token for the dependency to be injected.
* \@param flags Optional flags that control how injection is executed.
* The flags correspond to injection strategies that can be specified with
* parameter decorators `\@Host`, `\@Self`, `\@SkipSef`, and `\@Optional`.
* \@return True if injection is successful, null otherwise.
*
* \@usageNotes
*
* ### Example
*
* {\@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
*
* \@publicApi
* @type {?}
*/
const inject = ɵɵinject;
/**
* Injects `root` tokens in limp mode.
*
* If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
* `"root"`. This is known as the limp mode injection. In such case the value is stored in the
* `InjectableDef`.
* @template T
* @param {?} token
* @param {?} notFoundValue
* @param {?} flags
* @return {?}
*/
function injectRootLimpMode(token, notFoundValue, flags) {
/** @type {?} */
const injectableDef = getInjectableDef(token);
if (injectableDef && injectableDef.providedIn == 'root') {
return injectableDef.value === undefined ? injectableDef.value = injectableDef.factory() :
injectableDef.value;
}
if (flags & InjectFlags.Optional)
return null;
if (notFoundValue !== undefined)
return notFoundValue;
throw new Error(`Injector: NOT_FOUND [${stringify(token)}]`);
}
/**
* @param {?} types
* @return {?}
*/
function injectArgs(types) {
/** @type {?} */
const args = [];
for (let i = 0; i < types.length; i++) {
/** @type {?} */
const arg = resolveForwardRef(types[i]);
if (Array.isArray(arg)) {
if (arg.length === 0) {
throw new Error('Arguments array must have arguments.');
}
/** @type {?} */
let type = undefined;
/** @type {?} */
let flags = InjectFlags.Default;
for (let j = 0; j < arg.length; j++) {
/** @type {?} */
const meta = arg[j];
if (meta instanceof Optional || meta.ngMetadataName === 'Optional' || meta === Optional) {
flags |= InjectFlags.Optional;
}
else if (meta instanceof SkipSelf || meta.ngMetadataName === 'SkipSelf' || meta === SkipSelf) {
flags |= InjectFlags.SkipSelf;
}
else if (meta instanceof Self || meta.ngMetadataName === 'Self' || meta === Self) {
flags |= InjectFlags.Self;
}
else if (meta instanceof Inject || meta === Inject) {
type = meta.token;
}
else {
type = meta;
}
}
args.push(ɵɵinject((/** @type {?} */ (type)), flags));
}
else {
args.push(ɵɵinject(arg));
}
}
return args;
}
class NullInjector {
/**
* @param {?} token
* @param {?=} notFoundValue
* @return {?}
*/
get(token, notFoundValue = THROW_IF_NOT_FOUND) {
if (notFoundValue === THROW_IF_NOT_FOUND) {
// Intentionally left behind: With dev tools open the debugger will stop here. There is no
// reason why correctly written application should cause this exception.
// TODO(misko): uncomment the next line once `ngDevMode` works with closure.
// if(ngDevMode) debugger;
/** @type {?} */
const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
error.name = 'NullInjectorError';
throw error;
}
return notFoundValue;
}
}
/**
* @param {?} e
* @param {?} token
* @param {?} injectorErrorName
* @param {?} source
* @return {?}
*/
function catchInjectorError(e, token, injectorErrorName, source) {
/** @type {?} */
const tokenPath = e[NG_TEMP_TOKEN_PATH];
if (token[SOURCE]) {
tokenPath.unshift(token[SOURCE]);
}
e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
e[NG_TOKEN_PATH] = tokenPath;
e[NG_TEMP_TOKEN_PATH] = null;
throw e;
}
/**
* @param {?} text
* @param {?} obj
* @param {?} injectorErrorName
* @param {?=} source
* @return {?}
*/
function formatError(text, obj, injectorErrorName, source = null) {
text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text;
/** @type {?} */
let context = stringify(obj);
if (obj instanceof Array) {
context = obj.map(stringify).join(' -> ');
}
else if (typeof obj === 'object') {
/** @type {?} */
let parts = (/** @type {?} */ ([]));
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
/** @type {?} */
let value = obj[key];
parts.push(key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)));
}
}
context = `{${parts.join(', ')}}`;
}
return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* A mapping of the \@angular/core API surface used in generated expressions to the actual symbols.
*
* This should be kept up to date with the public exports of \@angular/core.
* @type {?}
*/
const angularCoreDiEnv = {
'ɵɵdefineInjectable': ɵɵdefineInjectable,
'ɵɵdefineInjector': ɵɵdefineInjector,
'ɵɵinject': ɵɵinject,
'ɵɵgetFactoryOf': getFactoryOf,
};
/**
* @template T
* @param {?} type
* @return {?}
*/
function getFactoryOf(type) {
/** @type {?} */
const typeAny = (/** @type {?} */ (type));
/** @type {?} */
const def = getInjectableDef(typeAny) || getInjectorDef(typeAny);
if (!def || def.factory === undefined) {
return null;
}
return def.factory;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @description
*
* Represents a type that a Component or other object is instances of.
*
* An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by
* the `MyCustomComponent` constructor function.
*
* @publicApi
*/
const Type = Function;
function isType(v) {
return typeof v === 'function';
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Attention: These regex has to hold even if the code is minified!
*/
const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/;
const INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
const INHERITED_CLASS_WITH_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
const INHERITED_CLASS_WITH_DELEGATE_CTOR = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{\s+super\(\.\.\.arguments\)/;
/**
* Determine whether a stringified type is a class which delegates its constructor
* to its parent.
*
* This is not trivial since compiled code can actually contain a constructor function
* even if the original source code did not. For instance, when the child class contains
* an initialized instance property.
*/
function isDelegateCtor(typeStr) {
return DELEGATE_CTOR.test(typeStr) || INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
(INHERITED_CLASS.test(typeStr) && !INHERITED_CLASS_WITH_CTOR.test(typeStr));
}
class ReflectionCapabilities {
constructor(reflect) { this._reflect = reflect || _global['Reflect']; }
isReflectionEnabled() { return true; }
factory(t) { return (...args) => new t(...args); }
/** @internal */
_zipTypesAndAnnotations(paramTypes, paramAnnotations) {
let result;
if (typeof paramTypes === 'undefined') {
result = new Array(paramAnnotations.length);
}
else {
result = new Array(paramTypes.length);
}
for (let i = 0; i < result.length; i++) {
// TS outputs Object for parameters without types, while Traceur omits
// the annotations. For now we preserve the Traceur behavior to aid
// migration, but this can be revisited.
if (typeof paramTypes === 'undefined') {
result[i] = [];
}
else if (paramTypes[i] && paramTypes[i] != Object) {
result[i] = [paramTypes[i]];
}
else {
result[i] = [];
}
if (paramAnnotations && paramAnnotations[i] != null) {
result[i] = result[i].concat(paramAnnotations[i]);
}
}
return result;
}
_ownParameters(type, parentCtor) {
const typeStr = type.toString();
// If we have no decorators, we only have function.length as metadata.
// In that case, to detect whether a child class declared an own constructor or not,
// we need to look inside of that constructor to check whether it is
// just calling the parent.
// This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
// that sets 'design:paramtypes' to []
// if a class inherits from another class but has no ctor declared itself.
if (isDelegateCtor(typeStr)) {
return null;
}
// Prefer the direct API.
if (type.parameters && type.parameters !== parentCtor.parameters) {
return type.parameters;
}
// API of tsickle for lowering decorators to properties on the class.
const tsickleCtorParams = type.ctorParameters;
if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
// Newer tsickle uses a function closure
// Retain the non-function case for compatibility with older tsickle
const ctorParameters = typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
const paramTypes = ctorParameters.map((ctorParam) => ctorParam && ctorParam.type);
const paramAnnotations = ctorParameters.map((ctorParam) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators));
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// API for metadata created by invoking the decorators.
const paramAnnotations = type.hasOwnProperty(PARAMETERS) && type[PARAMETERS];
const paramTypes = this._reflect && this._reflect.getOwnMetadata &&
this._reflect.getOwnMetadata('design:paramtypes', type);
if (paramTypes || paramAnnotations) {
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// If a class has no decorators, at least create metadata
// based on function.length.
// Note: We know that this is a real constructor as we checked
// the content of the constructor above.
return new Array(type.length).fill(undefined);
}
parameters(type) {
// Note: only report metadata if we have at least one class decorator
// to stay in sync with the static reflector.
if (!isType(type)) {
return [];
}
const parentCtor = getParentCtor(type);
let parameters = this._ownParameters(type, parentCtor);
if (!parameters && parentCtor !== Object) {
parameters = this.parameters(parentCtor);
}
return parameters || [];
}
_ownAnnotations(typeOrFunc, parentCtor) {
// Prefer the direct API.
if (typeOrFunc.annotations && typeOrFunc.annotations !== parentCtor.annotations) {
let annotations = typeOrFunc.annotations;
if (typeof annotations === 'function' && annotations.annotations) {
annotations = annotations.annotations;
}
return annotations;
}
// API of tsickle for lowering decorators to properties on the class.
if (typeOrFunc.decorators && typeOrFunc.decorators !== parentCtor.decorators) {
return convertTsickleDecoratorIntoMetadata(typeOrFunc.decorators);
}
// API for metadata created by invoking the decorators.
if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
return typeOrFunc[ANNOTATIONS];
}
return null;
}
annotations(typeOrFunc) {
if (!isType(typeOrFunc)) {
return [];
}
const parentCtor = getParentCtor(typeOrFunc);
const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
return parentAnnotations.concat(ownAnnotations);
}
_ownPropMetadata(typeOrFunc, parentCtor) {
// Prefer the direct API.
if (typeOrFunc.propMetadata &&
typeOrFunc.propMetadata !== parentCtor.propMetadata) {
let propMetadata = typeOrFunc.propMetadata;
if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
propMetadata = propMetadata.propMetadata;
}
return propMetadata;
}
// API of tsickle for lowering decorators to properties on the class.
if (typeOrFunc.propDecorators &&
typeOrFunc.propDecorators !== parentCtor.propDecorators) {
const propDecorators = typeOrFunc.propDecorators;
const propMetadata = {};
Object.keys(propDecorators).forEach(prop => {
propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
});
return propMetadata;
}
// API for metadata created by invoking the decorators.
if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
return typeOrFunc[PROP_METADATA];
}
return null;
}
propMetadata(typeOrFunc) {
if (!isType(typeOrFunc)) {
return {};
}
const parentCtor = getParentCtor(typeOrFunc);
const propMetadata = {};
if (parentCtor !== Object) {
const parentPropMetadata = this.propMetadata(parentCtor);
Object.keys(parentPropMetadata).forEach((propName) => {
propMetadata[propName] = parentPropMetadata[propName];
});
}
const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
if (ownPropMetadata) {
Object.keys(ownPropMetadata).forEach((propName) => {
const decorators = [];
if (propMetadata.hasOwnProperty(propName)) {
decorators.push(...propMetadata[propName]);
}
decorators.push(...ownPropMetadata[propName]);
propMetadata[propName] = decorators;
});
}
return propMetadata;
}
ownPropMetadata(typeOrFunc) {
if (!isType(typeOrFunc)) {
return {};
}
return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
}
hasLifecycleHook(type, lcProperty) {
return type instanceof Type && lcProperty in type.prototype;
}
guards(type) { return {}; }
getter(name) { return new Function('o', 'return o.' + name + ';'); }
setter(name) {
return new Function('o', 'v', 'return o.' + name + ' = v;');
}
method(name) {
const functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined');
return o.${name}.apply(o, args);`;
return new Function('o', 'args', functionBody);
}
// There is not a concept of import uri in Js, but this is useful in developing Dart applications.
importUri(type) {
// StaticSymbol
if (typeof type === 'object' && type['filePath']) {
return type['filePath'];
}
// Runtime type
return `./${stringify(type)}`;
}
resourceUri(type) { return `./${stringify(type)}`; }
resolveIdentifier(name, moduleUrl, members, runtime) {
return runtime;
}
resolveEnum(enumIdentifier, name) { return enumIdentifier[name]; }
}
function convertTsickleDecoratorIntoMetadata(decoratorInvocations) {
if (!decoratorInvocations) {
return [];
}
return decoratorInvocations.map(decoratorInvocation => {
const decoratorType = decoratorInvocation.type;
const annotationCls = decoratorType.annotationCls;
const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
return new annotationCls(...annotationArgs);
});
}
function getParentCtor(ctor) {
const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
const parentCtor = parentProto ? parentProto.constructor : null;
// Note: We always use `Object` as the null value
// to simplify checking later on.
return parentCtor || Object;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
let _reflect = null;
/**
* @return {?}
*/
function getReflect() {
return (_reflect = _reflect || new ReflectionCapabilities());
}
/**
* @param {?} type
* @return {?}
*/
function reflectDependencies(type) {
return convertDependencies(getReflect().parameters(type));
}
/**
* @param {?} deps
* @return {?}
*/
function convertDependencies(deps) {
/** @type {?} */
const compiler = getCompilerFacade();
return deps.map((/**
* @param {?} dep
* @return {?}
*/
dep => reflectDependency(compiler, dep)));
}
/**
* @param {?} compiler
* @param {?} dep
* @return {?}
*/
function reflectDependency(compiler, dep) {
/** @type {?} */
const meta = {
token: null,
host: false,
optional: false,
resolved: compiler.R3ResolvedDependencyType.Token,
self: false,
skipSelf: false,
};
/**
* @param {?} token
* @return {?}
*/
function setTokenAndResolvedType(token) {
meta.resolved = compiler.R3ResolvedDependencyType.Token;
meta.token = token;
}
if (Array.isArray(dep)) {
if (dep.length === 0) {
throw new Error('Dependency array must have arguments.');
}
for (let j = 0; j < dep.length; j++) {
/** @type {?} */
const param = dep[j];
if (param === undefined) {
// param may be undefined if type of dep is not set by ngtsc
continue;
}
else if (param instanceof Optional || param.__proto__.ngMetadataName === 'Optional') {
meta.optional = true;
}
else if (param instanceof SkipSelf || param.__proto__.ngMetadataName === 'SkipSelf') {
meta.skipSelf = true;
}
else if (param instanceof Self || param.__proto__.ngMetadataName === 'Self') {
meta.self = true;
}
else if (param instanceof Host || param.__proto__.ngMetadataName === 'Host') {
meta.host = true;
}
else if (param instanceof Inject) {
meta.token = param.token;
}
else if (param instanceof Attribute) {
if (param.attributeName === undefined) {
throw new Error(`Attribute name must be defined.`);
}
meta.token = param.attributeName;
meta.resolved = compiler.R3ResolvedDependencyType.Attribute;
}
else {
setTokenAndResolvedType(param);
}
}
}
else {
setTokenAndResolvedType(dep);
}
return meta;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
* `ngInjectableDef` onto the injectable type.
* @param {?} type
* @param {?=} srcMeta
* @return {?}
*/
function compileInjectable(type, srcMeta) {
/** @type {?} */
let def = null;
// if NG_INJECTABLE_DEF is already defined on this class then don't overwrite it
if (type.hasOwnProperty(NG_INJECTABLE_DEF))
return;
Object.defineProperty(type, NG_INJECTABLE_DEF, {
get: (/**
* @return {?}
*/
() => {
if (def === null) {
// Allow the compilation of a class with a `@Injectable()` decorator without parameters
/** @type {?} */
const meta = srcMeta || { providedIn: null };
/** @type {?} */
const hasAProvider = isUseClassProvider(meta) || isUseFactoryProvider(meta) ||
isUseValueProvider(meta) || isUseExistingProvider(meta);
/** @type {?} */
const compilerMeta = {
name: type.name,
type: type,
typeArgumentCount: 0,
providedIn: meta.providedIn,
ctorDeps: reflectDependencies(type),
userDeps: undefined,
};
if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
compilerMeta.userDeps = convertDependencies(meta.deps);
}
if (!hasAProvider) {
// In the case the user specifies a type provider, treat it as {provide: X, useClass: X}.
// The deps will have been reflected above, causing the factory to create the class by
// calling
// its constructor with injected deps.
compilerMeta.useClass = type;
}
else if (isUseClassProvider(meta)) {
// The user explicitly specified useClass, and may or may not have provided deps.
compilerMeta.useClass = meta.useClass;
}
else if (isUseValueProvider(meta)) {
// The user explicitly specified useValue.
compilerMeta.useValue = meta.useValue;
}
else if (isUseFactoryProvider(meta)) {
// The user explicitly specified useFactory.
compilerMeta.useFactory = meta.useFactory;
}
else if (isUseExistingProvider(meta)) {
// The user explicitly specified useExisting.
compilerMeta.useExisting = meta.useExisting;
}
else {
// Can't happen - either hasAProvider will be false, or one of the providers will be set.
throw new Error(`Unreachable state.`);
}
def = getCompilerFacade().compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ngInjectableDef.js`, compilerMeta);
}
return def;
}),
});
}
const ɵ0$2 = getClosureSafeProperty;
/** @type {?} */
const USE_VALUE$1 = getClosureSafeProperty({ provide: String, useValue: ɵ0$2 });
/**
* @param {?} meta
* @return {?}
*/
function isUseClassProvider(meta) {
return ((/** @type {?} */ (meta))).useClass !== undefined;
}
/**
* @param {?} meta
* @return {?}
*/
function isUseValueProvider(meta) {
return USE_VALUE$1 in meta;
}
/**
* @param {?} meta
* @return {?}
*/
function isUseFactoryProvider(meta) {
return ((/** @type {?} */ (meta))).useFactory !== undefined;
}
/**
* @param {?} meta
* @return {?}
*/
function isUseExistingProvider(meta) {
return ((/** @type {?} */ (meta))).useExisting !== undefined;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
const ɵ0$3 = getClosureSafeProperty;
/** @type {?} */
const USE_VALUE$2 = getClosureSafeProperty({ provide: String, useValue: ɵ0$3 });
/** @type {?} */
const EMPTY_ARRAY = [];
/**
* @param {?} type
* @param {?=} provider
* @return {?}
*/
function convertInjectableProviderToFactory(type, provider) {
if (!provider) {
/** @type {?} */
const reflectionCapabilities = new ReflectionCapabilities();
/** @type {?} */
const deps = reflectionCapabilities.parameters(type);
// TODO - convert to flags.
return (/**
* @return {?}
*/
() => new type(...injectArgs((/** @type {?} */ (deps)))));
}
if (USE_VALUE$2 in provider) {
/** @type {?} */
const valueProvider = ((/** @type {?} */ (provider)));
return (/**
* @return {?}
*/
() => valueProvider.useValue);
}
else if (((/** @type {?} */ (provider))).useExisting) {
/** @type {?} */
const existingProvider = ((/** @type {?} */ (provider)));
return (/**
* @return {?}
*/
() => ɵɵinject(existingProvider.useExisting));
}
else if (((/** @type {?} */ (provider))).useFactory) {
/** @type {?} */
const factoryProvider = ((/** @type {?} */ (provider)));
return (/**
* @return {?}
*/
() => factoryProvider.useFactory(...injectArgs(factoryProvider.deps || EMPTY_ARRAY)));
}
else if (((/** @type {?} */ (provider))).useClass) {
/** @type {?} */
const classProvider = ((/** @type {?} */ (provider)));
/*