@angular/core
Version:
Angular - the core framework
1,283 lines (1,271 loc) • 113 kB
JavaScript
/**
* @license Angular v8.2.9
* (c) 2010-2019 Google LLC. https://angular.io/
* License: MIT
*/
import { getDebugNode, RendererFactory2, InjectionToken, ɵstringify, ɵReflectionCapabilities, Directive, Component, Pipe, NgModule, ɵgetInjectableDef, ɵNG_COMPONENT_DEF, ɵRender3NgModuleRef, LOCALE_ID, ɵDEFAULT_LOCALE_ID, ɵsetLocaleId, ApplicationInitStatus, ɵRender3ComponentFactory, ɵcompileComponent, ɵNG_DIRECTIVE_DEF, ɵcompileDirective, ɵNG_PIPE_DEF, ɵcompilePipe, ɵtransitiveScopesFor, ɵpatchComponentDefWithScope, ɵNG_INJECTOR_DEF, ɵNG_MODULE_DEF, ɵcompileNgModuleDefs, NgZone, Compiler, COMPILER_OPTIONS, ɵNgModuleFactory, ModuleWithComponentFactories, Injector, InjectFlags, ɵresetCompiledComponents, ɵflushModuleScopingQueueAsMuchAsPossible, Injectable, ɵclearOverrides, ɵoverrideComponentView, ɵAPP_ROOT, Optional, SkipSelf, ɵoverrideProvider, ɵivyEnabled } from '@angular/core';
import { __read, __extends, __spread, __awaiter, __generator, __values, __decorate } from 'tslib';
import { ResourceLoader } from '@angular/compiler';
/**
* @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 _global = (typeof window === 'undefined' ? global : window);
/**
* Wraps a test function in an asynchronous test zone. The test will automatically
* complete when all asynchronous calls within this zone are done. Can be used
* to wrap an {@link inject} call.
*
* Example:
*
* ```
* it('...', async(inject([AClass], (object) => {
* object.doSomething.then(() => {
* expect(...);
* })
* });
* ```
*
*
*/
function asyncFallback(fn) {
// If we're running using the Jasmine test framework, adapt to call the 'done'
// function when asynchronous activity is finished.
if (_global.jasmine) {
// Not using an arrow function to preserve context passed from call site
return function (done) {
if (!done) {
// if we run beforeEach in @angular/core/testing/testing_internal then we get no done
// fake it here and assume sync.
done = function () { };
done.fail = function (e) { throw e; };
}
runInTestZone(fn, this, done, function (err) {
if (typeof err === 'string') {
return done.fail(new Error(err));
}
else {
done.fail(err);
}
});
};
}
// Otherwise, return a promise which will resolve when asynchronous activity
// is finished. This will be correctly consumed by the Mocha framework with
// it('...', async(myFn)); or can be used in a custom framework.
// Not using an arrow function to preserve context passed from call site
return function () {
var _this = this;
return new Promise(function (finishCallback, failCallback) {
runInTestZone(fn, _this, finishCallback, failCallback);
});
};
}
function runInTestZone(fn, context, finishCallback, failCallback) {
var currentZone = Zone.current;
var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
if (AsyncTestZoneSpec === undefined) {
throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/dist/async-test.js');
}
var ProxyZoneSpec = Zone['ProxyZoneSpec'];
if (ProxyZoneSpec === undefined) {
throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/dist/proxy.js');
}
var proxyZoneSpec = ProxyZoneSpec.get();
ProxyZoneSpec.assertPresent();
// We need to create the AsyncTestZoneSpec outside the ProxyZone.
// If we do it in ProxyZone then we will get to infinite recursion.
var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
var previousDelegate = proxyZoneSpec.getDelegate();
proxyZone.parent.run(function () {
var testZoneSpec = new AsyncTestZoneSpec(function () {
// Need to restore the original zone.
currentZone.run(function () {
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
finishCallback();
});
}, function (error) {
// Need to restore the original zone.
currentZone.run(function () {
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
failCallback(error);
});
}, 'test');
proxyZoneSpec.setDelegate(testZoneSpec);
});
return Zone.current.runGuarded(fn, context);
}
/**
* @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
*/
/**
* Wraps a test function in an asynchronous test zone. The test will automatically
* complete when all asynchronous calls within this zone are done. Can be used
* to wrap an {@link inject} call.
*
* Example:
*
* ```
* it('...', async(inject([AClass], (object) => {
* object.doSomething.then(() => {
* expect(...);
* })
* });
* ```
*
* @publicApi
*/
function async(fn) {
var _Zone = typeof Zone !== 'undefined' ? Zone : null;
if (!_Zone) {
return function () {
return Promise.reject('Zone is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/dist/zone.js');
};
}
var asyncTest = _Zone && _Zone[_Zone.__symbol__('asyncTest')];
if (typeof asyncTest === 'function') {
return asyncTest(fn);
}
// not using new version of zone.js
// TODO @JiaLiPassion, remove this after all library updated to
// newest version of zone.js(0.8.25)
return asyncFallback(fn);
}
/**
* @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
*/
/**
* Fixture for debugging and testing a component.
*
* @publicApi
*/
var ComponentFixture = /** @class */ (function () {
function ComponentFixture(componentRef, ngZone, _autoDetect) {
var _this = this;
this.componentRef = componentRef;
this.ngZone = ngZone;
this._autoDetect = _autoDetect;
this._isStable = true;
this._isDestroyed = false;
this._resolve = null;
this._promise = null;
this._onUnstableSubscription = null;
this._onStableSubscription = null;
this._onMicrotaskEmptySubscription = null;
this._onErrorSubscription = null;
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
this.ngZone = ngZone;
if (ngZone) {
// Create subscriptions outside the NgZone so that the callbacks run oustide
// of NgZone.
ngZone.runOutsideAngular(function () {
_this._onUnstableSubscription =
ngZone.onUnstable.subscribe({ next: function () { _this._isStable = false; } });
_this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
next: function () {
if (_this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run.
_this.detectChanges(true);
}
}
});
_this._onStableSubscription = ngZone.onStable.subscribe({
next: function () {
_this._isStable = true;
// Check whether there is a pending whenStable() completer to resolve.
if (_this._promise !== null) {
// If so check whether there are no pending macrotasks before resolving.
// Do this check in the next tick so that ngZone gets a chance to update the state of
// pending macrotasks.
scheduleMicroTask(function () {
if (!ngZone.hasPendingMacrotasks) {
if (_this._promise !== null) {
_this._resolve(true);
_this._resolve = null;
_this._promise = null;
}
}
});
}
}
});
_this._onErrorSubscription =
ngZone.onError.subscribe({ next: function (error) { throw error; } });
});
}
}
ComponentFixture.prototype._tick = function (checkNoChanges) {
this.changeDetectorRef.detectChanges();
if (checkNoChanges) {
this.checkNoChanges();
}
};
/**
* Trigger a change detection cycle for the component.
*/
ComponentFixture.prototype.detectChanges = function (checkNoChanges) {
var _this = this;
if (checkNoChanges === void 0) { checkNoChanges = true; }
if (this.ngZone != null) {
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this.ngZone.run(function () { _this._tick(checkNoChanges); });
}
else {
// Running without zone. Just do the change detection.
this._tick(checkNoChanges);
}
};
/**
* Do a change detection run to make sure there were no changes.
*/
ComponentFixture.prototype.checkNoChanges = function () { this.changeDetectorRef.checkNoChanges(); };
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*/
ComponentFixture.prototype.autoDetectChanges = function (autoDetect) {
if (autoDetect === void 0) { autoDetect = true; }
if (this.ngZone == null) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
}
this._autoDetect = autoDetect;
this.detectChanges();
};
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
ComponentFixture.prototype.isStable = function () { return this._isStable && !this.ngZone.hasPendingMacrotasks; };
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
ComponentFixture.prototype.whenStable = function () {
var _this = this;
if (this.isStable()) {
return Promise.resolve(false);
}
else if (this._promise !== null) {
return this._promise;
}
else {
this._promise = new Promise(function (res) { _this._resolve = res; });
return this._promise;
}
};
ComponentFixture.prototype._getRenderer = function () {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(RendererFactory2, null);
}
return this._renderer;
};
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
ComponentFixture.prototype.whenRenderingDone = function () {
var renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
};
/**
* Trigger component destruction.
*/
ComponentFixture.prototype.destroy = function () {
if (!this._isDestroyed) {
this.componentRef.destroy();
if (this._onUnstableSubscription != null) {
this._onUnstableSubscription.unsubscribe();
this._onUnstableSubscription = null;
}
if (this._onStableSubscription != null) {
this._onStableSubscription.unsubscribe();
this._onStableSubscription = null;
}
if (this._onMicrotaskEmptySubscription != null) {
this._onMicrotaskEmptySubscription.unsubscribe();
this._onMicrotaskEmptySubscription = null;
}
if (this._onErrorSubscription != null) {
this._onErrorSubscription.unsubscribe();
this._onErrorSubscription = null;
}
this._isDestroyed = true;
}
};
return ComponentFixture;
}());
function scheduleMicroTask(fn) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
/**
* @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
*/
/**
* fakeAsync has been moved to zone.js
* this file is for fallback in case old version of zone.js is used
*/
var _Zone = typeof Zone !== 'undefined' ? Zone : null;
var FakeAsyncTestZoneSpec = _Zone && _Zone['FakeAsyncTestZoneSpec'];
var ProxyZoneSpec = _Zone && _Zone['ProxyZoneSpec'];
var _fakeAsyncTestZoneSpec = null;
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @publicApi
*/
function resetFakeAsyncZoneFallback() {
_fakeAsyncTestZoneSpec = null;
// in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
}
var _inFakeAsyncCall = false;
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* Can be used to wrap inject() calls.
*
* @usageNotes
* ### Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* @param fn
* @returns The function wrapped to be executed in the fakeAsync zone
*
* @publicApi
*/
function fakeAsyncFallback(fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var proxyZoneSpec = ProxyZoneSpec.assertPresent();
if (_inFakeAsyncCall) {
throw new Error('fakeAsync() calls can not be nested');
}
_inFakeAsyncCall = true;
try {
if (!_fakeAsyncTestZoneSpec) {
if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
throw new Error('fakeAsync() calls can not be nested');
}
_fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
}
var res = void 0;
var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
try {
res = fn.apply(this, args);
flushMicrotasksFallback();
}
finally {
proxyZoneSpec.setDelegate(lastProxyZoneSpec);
}
if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
throw new Error(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length + " " +
"periodic timer(s) still in the queue.");
}
if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
throw new Error(_fakeAsyncTestZoneSpec.pendingTimers.length + " timer(s) still in the queue.");
}
return res;
}
finally {
_inFakeAsyncCall = false;
resetFakeAsyncZoneFallback();
}
};
}
function _getFakeAsyncZoneSpec() {
if (_fakeAsyncTestZoneSpec == null) {
throw new Error('The code should be running in the fakeAsync zone to call this function');
}
return _fakeAsyncTestZoneSpec;
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* @usageNotes
* ### Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* @publicApi
*/
function tickFallback(millis) {
if (millis === void 0) { millis = 0; }
_getFakeAsyncZoneSpec().tick(millis);
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
* draining the macrotask queue until it is empty. The returned value is the milliseconds
* of time that would have been elapsed.
*
* @param maxTurns
* @returns The simulated time elapsed, in millis.
*
* @publicApi
*/
function flushFallback(maxTurns) {
return _getFakeAsyncZoneSpec().flush(maxTurns);
}
/**
* Discard all remaining periodic tasks.
*
* @publicApi
*/
function discardPeriodicTasksFallback() {
var zoneSpec = _getFakeAsyncZoneSpec();
zoneSpec.pendingPeriodicTimers.length = 0;
}
/**
* Flush any pending microtasks.
*
* @publicApi
*/
function flushMicrotasksFallback() {
_getFakeAsyncZoneSpec().flushMicrotasks();
}
/**
* @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 _Zone$1 = typeof Zone !== 'undefined' ? Zone : null;
var fakeAsyncTestModule = _Zone$1 && _Zone$1[_Zone$1.__symbol__('fakeAsyncTest')];
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @publicApi
*/
function resetFakeAsyncZone() {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.resetFakeAsyncZone();
}
else {
return resetFakeAsyncZoneFallback();
}
}
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* Can be used to wrap inject() calls.
*
* @usageNotes
* ### Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* @param fn
* @returns The function wrapped to be executed in the fakeAsync zone
*
* @publicApi
*/
function fakeAsync(fn) {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.fakeAsync(fn);
}
else {
return fakeAsyncFallback(fn);
}
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* @usageNotes
* ### Example
*
* {@example core/testing/ts/fake_async.ts region='basic'}
*
* @publicApi
*/
function tick(millis) {
if (millis === void 0) { millis = 0; }
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.tick(millis);
}
else {
return tickFallback(millis);
}
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
* draining the macrotask queue until it is empty. The returned value is the milliseconds
* of time that would have been elapsed.
*
* @param maxTurns
* @returns The simulated time elapsed, in millis.
*
* @publicApi
*/
function flush(maxTurns) {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.flush(maxTurns);
}
else {
return flushFallback(maxTurns);
}
}
/**
* Discard all remaining periodic tasks.
*
* @publicApi
*/
function discardPeriodicTasks() {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.discardPeriodicTasks();
}
else {
discardPeriodicTasksFallback();
}
}
/**
* Flush any pending microtasks.
*
* @publicApi
*/
function flushMicrotasks() {
if (fakeAsyncTestModule) {
return fakeAsyncTestModule.flushMicrotasks();
}
else {
return flushMicrotasksFallback();
}
}
/**
* @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
*/
/**
* Injectable completer that allows signaling completion of an asynchronous test. Used internally.
*/
var AsyncTestCompleter = /** @class */ (function () {
function AsyncTestCompleter() {
var _this = this;
this._promise = new Promise(function (res, rej) {
_this._resolve = res;
_this._reject = rej;
});
}
AsyncTestCompleter.prototype.done = function (value) { this._resolve(value); };
AsyncTestCompleter.prototype.fail = function (error, stackTrace) { this._reject(error); };
Object.defineProperty(AsyncTestCompleter.prototype, "promise", {
get: function () { return this._promise; },
enumerable: true,
configurable: true
});
return AsyncTestCompleter;
}());
/**
* @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
*/
/**
* An abstract class for inserting the root test component element in a platform independent way.
*
* @publicApi
*/
var TestComponentRenderer = /** @class */ (function () {
function TestComponentRenderer() {
}
TestComponentRenderer.prototype.insertRootElement = function (rootElementId) { };
return TestComponentRenderer;
}());
/**
* @publicApi
*/
var ComponentFixtureAutoDetect = new InjectionToken('ComponentFixtureAutoDetect');
/**
* @publicApi
*/
var ComponentFixtureNoNgZone = new InjectionToken('ComponentFixtureNoNgZone');
/**
* @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
*/
/**
* Used to resolve resource URLs on `@Component` when used with JIT compilation.
*
* Example:
* ```
* @Component({
* selector: 'my-comp',
* templateUrl: 'my-comp.html', // This requires asynchronous resolution
* })
* class MyComponent{
* }
*
* // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
* // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously.
*
* // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into
* // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
*
* // Use browser's `fetch()` function as the default resource resolution strategy.
* resolveComponentResources(fetch).then(() => {
* // After resolution all URLs have been converted into `template` strings.
* renderComponent(MyComponent);
* });
*
* ```
*
* NOTE: In AOT the resolution happens during compilation, and so there should be no need
* to call this method outside JIT mode.
*
* @param resourceResolver a function which is responsible for returning a `Promise` to the
* contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
*/
function resolveComponentResources(resourceResolver) {
// Store all promises which are fetching the resources.
var componentResolved = [];
// Cache so that we don't fetch the same resource more than once.
var urlMap = new Map();
function cachedResourceResolve(url) {
var promise = urlMap.get(url);
if (!promise) {
var resp = resourceResolver(url);
urlMap.set(url, promise = resp.then(unwrapResponse));
}
return promise;
}
componentResourceResolutionQueue.forEach(function (component, type) {
var promises = [];
if (component.templateUrl) {
promises.push(cachedResourceResolve(component.templateUrl).then(function (template) {
component.template = template;
}));
}
var styleUrls = component.styleUrls;
var styles = component.styles || (component.styles = []);
var styleOffset = component.styles.length;
styleUrls && styleUrls.forEach(function (styleUrl, index) {
styles.push(''); // pre-allocate array.
promises.push(cachedResourceResolve(styleUrl).then(function (style) {
styles[styleOffset + index] = style;
styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
if (styleUrls.length == 0) {
component.styleUrls = undefined;
}
}));
});
var fullyResolved = Promise.all(promises).then(function () { return componentDefResolved(type); });
componentResolved.push(fullyResolved);
});
clearResolutionOfComponentResourcesQueue();
return Promise.all(componentResolved).then(function () { return undefined; });
}
var componentResourceResolutionQueue = new Map();
// Track when existing ngComponentDef for a Type is waiting on resources.
var componentDefPendingResolution = new Set();
function maybeQueueResolutionOfComponentResources(type, metadata) {
if (componentNeedsResolution(metadata)) {
componentResourceResolutionQueue.set(type, metadata);
componentDefPendingResolution.add(type);
}
}
function isComponentDefPendingResolution(type) {
return componentDefPendingResolution.has(type);
}
function componentNeedsResolution(component) {
return !!((component.templateUrl && !component.hasOwnProperty('template')) ||
component.styleUrls && component.styleUrls.length);
}
function clearResolutionOfComponentResourcesQueue() {
var old = componentResourceResolutionQueue;
componentResourceResolutionQueue = new Map();
return old;
}
function restoreComponentResolutionQueue(queue) {
componentDefPendingResolution.clear();
queue.forEach(function (_, type) { return componentDefPendingResolution.add(type); });
componentResourceResolutionQueue = queue;
}
function isComponentResourceResolutionQueueEmpty() {
return componentResourceResolutionQueue.size === 0;
}
function unwrapResponse(response) {
return typeof response == 'string' ? response : response.text();
}
function componentDefResolved(type) {
componentDefPendingResolution.delete(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
*/
var _nextReferenceId = 0;
var MetadataOverrider = /** @class */ (function () {
function MetadataOverrider() {
this._references = new Map();
}
/**
* Creates a new instance for the given metadata class
* based on an old instance and overrides.
*/
MetadataOverrider.prototype.overrideMetadata = function (metadataClass, oldMetadata, override) {
var props = {};
if (oldMetadata) {
_valueProps(oldMetadata).forEach(function (prop) { return props[prop] = oldMetadata[prop]; });
}
if (override.set) {
if (override.remove || override.add) {
throw new Error("Cannot set and add/remove " + ɵstringify(metadataClass) + " at the same time!");
}
setMetadata(props, override.set);
}
if (override.remove) {
removeMetadata(props, override.remove, this._references);
}
if (override.add) {
addMetadata(props, override.add);
}
return new metadataClass(props);
};
return MetadataOverrider;
}());
function removeMetadata(metadata, remove, references) {
var removeObjects = new Set();
var _loop_1 = function (prop) {
var removeValue = remove[prop];
if (removeValue instanceof Array) {
removeValue.forEach(function (value) { removeObjects.add(_propHashKey(prop, value, references)); });
}
else {
removeObjects.add(_propHashKey(prop, removeValue, references));
}
};
for (var prop in remove) {
_loop_1(prop);
}
var _loop_2 = function (prop) {
var propValue = metadata[prop];
if (propValue instanceof Array) {
metadata[prop] = propValue.filter(function (value) { return !removeObjects.has(_propHashKey(prop, value, references)); });
}
else {
if (removeObjects.has(_propHashKey(prop, propValue, references))) {
metadata[prop] = undefined;
}
}
};
for (var prop in metadata) {
_loop_2(prop);
}
}
function addMetadata(metadata, add) {
for (var prop in add) {
var addValue = add[prop];
var propValue = metadata[prop];
if (propValue != null && propValue instanceof Array) {
metadata[prop] = propValue.concat(addValue);
}
else {
metadata[prop] = addValue;
}
}
}
function setMetadata(metadata, set) {
for (var prop in set) {
metadata[prop] = set[prop];
}
}
function _propHashKey(propName, propValue, references) {
var replacer = function (key, value) {
if (typeof value === 'function') {
value = _serializeReference(value, references);
}
return value;
};
return propName + ":" + JSON.stringify(propValue, replacer);
}
function _serializeReference(ref, references) {
var id = references.get(ref);
if (!id) {
id = "" + ɵstringify(ref) + _nextReferenceId++;
references.set(ref, id);
}
return id;
}
function _valueProps(obj) {
var props = [];
// regular public props
Object.keys(obj).forEach(function (prop) {
if (!prop.startsWith('_')) {
props.push(prop);
}
});
// getters
var proto = obj;
while (proto = Object.getPrototypeOf(proto)) {
Object.keys(proto).forEach(function (protoProp) {
var desc = Object.getOwnPropertyDescriptor(proto, protoProp);
if (!protoProp.startsWith('_') && desc && 'get' in desc) {
props.push(protoProp);
}
});
}
return props;
}
/**
* @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 reflection = new ɵReflectionCapabilities();
/**
* Allows to override ivy metadata for tests (via the `TestBed`).
*/
var OverrideResolver = /** @class */ (function () {
function OverrideResolver() {
this.overrides = new Map();
this.resolved = new Map();
}
OverrideResolver.prototype.addOverride = function (type, override) {
var overrides = this.overrides.get(type) || [];
overrides.push(override);
this.overrides.set(type, overrides);
this.resolved.delete(type);
};
OverrideResolver.prototype.setOverrides = function (overrides) {
var _this = this;
this.overrides.clear();
overrides.forEach(function (_a) {
var _b = __read(_a, 2), type = _b[0], override = _b[1];
_this.addOverride(type, override);
});
};
OverrideResolver.prototype.getAnnotation = function (type) {
var annotations = reflection.annotations(type);
// Try to find the nearest known Type annotation and make sure that this annotation is an
// instance of the type we are looking for, so we can use it for resolution. Note: there might
// be multiple known annotations found due to the fact that Components can extend Directives (so
// both Directive and Component annotations would be present), so we always check if the known
// annotation has the right type.
for (var i = annotations.length - 1; i >= 0; i--) {
var annotation = annotations[i];
var isKnownType = annotation instanceof Directive || annotation instanceof Component ||
annotation instanceof Pipe || annotation instanceof NgModule;
if (isKnownType) {
return annotation instanceof this.type ? annotation : null;
}
}
return null;
};
OverrideResolver.prototype.resolve = function (type) {
var _this = this;
var resolved = this.resolved.get(type) || null;
if (!resolved) {
resolved = this.getAnnotation(type);
if (resolved) {
var overrides = this.overrides.get(type);
if (overrides) {
var overrider_1 = new MetadataOverrider();
overrides.forEach(function (override) {
resolved = overrider_1.overrideMetadata(_this.type, resolved, override);
});
}
}
this.resolved.set(type, resolved);
}
return resolved;
};
return OverrideResolver;
}());
var DirectiveResolver = /** @class */ (function (_super) {
__extends(DirectiveResolver, _super);
function DirectiveResolver() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(DirectiveResolver.prototype, "type", {
get: function () { return Directive; },
enumerable: true,
configurable: true
});
return DirectiveResolver;
}(OverrideResolver));
var ComponentResolver = /** @class */ (function (_super) {
__extends(ComponentResolver, _super);
function ComponentResolver() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(ComponentResolver.prototype, "type", {
get: function () { return Component; },
enumerable: true,
configurable: true
});
return ComponentResolver;
}(OverrideResolver));
var PipeResolver = /** @class */ (function (_super) {
__extends(PipeResolver, _super);
function PipeResolver() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(PipeResolver.prototype, "type", {
get: function () { return Pipe; },
enumerable: true,
configurable: true
});
return PipeResolver;
}(OverrideResolver));
var NgModuleResolver = /** @class */ (function (_super) {
__extends(NgModuleResolver, _super);
function NgModuleResolver() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(NgModuleResolver.prototype, "type", {
get: function () { return NgModule; },
enumerable: true,
configurable: true
});
return NgModuleResolver;
}(OverrideResolver));
/**
* @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 TestingModuleOverride;
(function (TestingModuleOverride) {
TestingModuleOverride[TestingModuleOverride["DECLARATION"] = 0] = "DECLARATION";
TestingModuleOverride[TestingModuleOverride["OVERRIDE_TEMPLATE"] = 1] = "OVERRIDE_TEMPLATE";
})(TestingModuleOverride || (TestingModuleOverride = {}));
function isTestingModuleOverride(value) {
return value === TestingModuleOverride.DECLARATION ||
value === TestingModuleOverride.OVERRIDE_TEMPLATE;
}
var R3TestBedCompiler = /** @class */ (function () {
function R3TestBedCompiler(platform, additionalModuleTypes) {
this.platform = platform;
this.additionalModuleTypes = additionalModuleTypes;
this.originalComponentResolutionQueue = null;
// Testing module configuration
this.declarations = [];
this.imports = [];
this.providers = [];
this.schemas = [];
// Queues of components/directives/pipes that should be recompiled.
this.pendingComponents = new Set();
this.pendingDirectives = new Set();
this.pendingPipes = new Set();
// Keep track of all components and directives, so we can patch Providers onto defs later.
this.seenComponents = new Set();
this.seenDirectives = new Set();
// Store resolved styles for Components that have template overrides present and `styleUrls`
// defined at the same time.
this.existingComponentStyles = new Map();
this.resolvers = initResolvers();
this.componentToModuleScope = new Map();
// Map that keeps initial version of component/directive/pipe defs in case
// we compile a Type again, thus overriding respective static fields. This is
// required to make sure we restore defs to their initial states between test runs
// TODO: we should support the case with multiple defs on a type
this.initialNgDefs = new Map();
// Array that keeps cleanup operations for initial versions of component/directive/pipe/module
// defs in case TestBed makes changes to the originals.
this.defCleanupOps = [];
this._injector = null;
this.compilerProviders = null;
this.providerOverrides = [];
this.rootProviderOverrides = [];
this.providerOverridesByToken = new Map();
this.moduleProvidersOverridden = new Set();
this.testModuleRef = null;
var DynamicTestModule = /** @class */ (function () {
function DynamicTestModule() {
}
return DynamicTestModule;
}());
this.testModuleType = DynamicTestModule;
}
R3TestBedCompiler.prototype.setCompilerProviders = function (providers) {
this.compilerProviders = providers;
this._injector = null;
};
R3TestBedCompiler.prototype.configureTestingModule = function (moduleDef) {
var _a, _b, _c, _d;
// Enqueue any compilation tasks for the directly declared component.
if (moduleDef.declarations !== undefined) {
this.queueTypeArray(moduleDef.declarations, TestingModuleOverride.DECLARATION);
(_a = this.declarations).push.apply(_a, __spread(moduleDef.declarations));
}
// Enqueue any compilation tasks for imported modules.
if (moduleDef.imports !== undefined) {
this.queueTypesFromModulesArray(moduleDef.imports);
(_b = this.imports).push.apply(_b, __spread(moduleDef.imports));
}
if (moduleDef.providers !== undefined) {
(_c = this.providers).push.apply(_c, __spread(moduleDef.providers));
}
if (moduleDef.schemas !== undefined) {
(_d = this.schemas).push.apply(_d, __spread(moduleDef.schemas));
}
};
R3TestBedCompiler.prototype.overrideModule = function (ngModule, override) {
// Compile the module right away.
this.resolvers.module.addOverride(ngModule, override);
var metadata = this.resolvers.module.resolve(ngModule);
if (metadata === null) {
throw new Error(ngModule.name + " is not an @NgModule or is missing metadata");
}
this.recompileNgModule(ngModule);
// At this point, the module has a valid .ngModuleDef, but the override may have introduced
// new declarations or imported modules. Ingest any possible new types and add them to the
// current queue.
this.queueTypesFromModulesArray([ngModule]);
};
R3TestBedCompiler.prototype.overrideComponent = function (component, override) {
this.resolvers.component.addOverride(component, override);
this.pendingComponents.add(component);
};
R3TestBedCompiler.prototype.overrideDirective = function (directive, override) {
this.resolvers.directive.addOverride(directive, override);
this.pendingDirectives.add(directive);
};
R3TestBedCompiler.prototype.overridePipe = function (pipe, override) {
this.resolvers.pipe.addOverride(pipe, override);
this.pendingPipes.add(pipe);
};
R3TestBedCompiler.prototype.overrideProvider = function (token, provider) {
var providerDef = provider.useFactory ?
{
provide: token,
useFactory: provider.useFactory,
deps: provider.deps || [],
multi: provider.multi,
} :
{ provide: token, useValue: provider.useValue, multi: provider.multi };
var injectableDef;
var isRoot = (typeof token !== 'string' && (injectableDef = ɵgetInjectableDef(token)) &&
injectableDef.providedIn === 'root');
var overridesBucket = isRoot ? this.rootProviderOverrides : this.providerOverrides;
overridesBucket.push(providerDef);
// Keep overrides grouped by token as well for fast lookups using token
this.providerOverridesByToken.set(token, providerDef);
};
R3TestBedCompiler.prototype.overrideTemplateUsingTestingModule = function (type, template) {
var _this = this;
var def = type[ɵNG_COMPONENT_DEF];
var hasStyleUrls = function () {
var metadata = _this.resolvers.component.resolve(type);
return !!metadata.styleUrls && metadata.styleUrls.length > 0;
};
var overrideStyleUrls = !!def && !isComponentDefPendingResolution(type) && hasStyleUrls();
// In Ivy, compiling a component does not require knowing the module providing the
// component's scope, so overrideTemplateUsingTestingModule can be implemented purely via
// overrideComponent. Important: overriding template requires full Component re-compilation,
// which may fail in case styleUrls are also present (thus Component is considered as required
// resolution). In order to avoid this, we preemptively set styleUrls to an empty array,
// preserve current styles available on Component def and restore styles back once compilation
// is complete.
var override = overrideStyleUrls ? { template: template, styles: [], styleUrls: [] } : { template: template };
this.overrideComponent(type, { set: override });
if (overrideStyleUrls && def.styles && def.styles.length > 0) {
this.existingComponentStyles.set(type, def.styles);
}
// Set the component's scope to be the testing module.
this.componentToModuleScope.set(type, TestingModuleOverride.OVERRIDE_TEMPLATE);
};
R3TestBedCompiler.prototype.compileComponents = function () {
return __awaiter(this, void 0, void 0, function () {
var needsAsyncResources, resourceLoader_1, resolver;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.clearComponentResolutionQueue();
needsAsyncResources = this.compileTypesSync();
if (!needsAsyncResources) return [3 /*break*/, 2];
resolver = function (url) {
if (!resourceLoader_1) {
resourceLoader_1 = _this.injector.get(ResourceLoader);
}
return Promise.resolve(resourceLoader_1.get(url));
};
return [4 /*yield*/, resolveComponentResources(resolver)];
case 1:
_a.sent();
_a.label = 2;
case 2: return [2 /*return*/];
}
});
});
};
R3TestBedCompiler.prototype.finalize = function () {
// One last compile
this.compileTypesSync();
// Create the testing module itself.
this.compileTestModule();
this.applyTransitiveScopes();
this.applyProviderOverrides();
// Patch previously stored `styles` Component values (taken from ngComponentDef), in case these
// Components have `styleUrls` fields defined and template override was requested.
this.patchComponentsWithExistingStyles();
// Clear the componentToModuleScope map, so that future compilations don't reset the scope of
// every component.
this.componentToModuleScope.clear();
var parentInjector = this.platform.injector;
this.testModuleRef = new ɵRender3NgModuleRef(this.testModuleType, parentInjector);
// Set the locale ID, it can be overridden for the tests
var localeId = this.testModuleRef.injector.get(LOCALE_ID, ɵDEFAULT_LOCALE_ID);
ɵsetLocaleId(localeId);
// ApplicationInitStatus.runInitializers() is marked @internal to core.
// Cast it to any before accessing it.
this.testModuleRef.injector.get(ApplicationInitStatus).runInitializers();
return this.testModuleRef;
};
/**
* @internal
*/
R3TestBedCompiler.prototype._compileNgModuleSync = function (moduleType) {
this.queueTypesFromModulesArray([moduleType]);
this.compileTypesSync();
this.applyProviderOverrides();
this.applyProviderOverridesToModule(moduleType);
this.applyTransitiveScopes();
};
/**
* @internal
*/
R3TestBedCompiler.prototype._compileNgModuleAsync = function (moduleType) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.queueTypesFromModulesArray([moduleType]);
return [4 /*yield*/, this.compileComponents()];
case 1:
_a.sent();
this.applyProviderOverrides();
this.applyProviderOverridesToModule(moduleType);
this.applyTransitiveScopes();
return [2 /*return*/];
}
});
});
};
/**
* @internal
*/
R3TestBedCompiler.prototype._getModuleResolver = function () { return this.resolvers.module; };
/**
* @internal
*/
R3TestBedCompiler.prototype._getComponentFactories = function (moduleType) {
var _this = this;
return maybeUnwrapFn(moduleType.ngModuleDef.declarations).reduce(function (factories, declaration) {
var componentDef = declaration.ngComponentDef;
componentDef && factories.push(new ɵRender3ComponentFactory(componentDef, _this.testModuleRef));
return factories;
}, []);
};
R3TestBedCompiler.prototype.compileTypesSync = function () {
var _this = this;
// Compile all queued components, directives, pipes.
var needsAsyncResources = false;
this.pendingComponents.forEach(function (declaration) {
needsAsyncResources = needsAsyncResources || isComponentDefPendingResolution(declaration);
var metadata = _this.resolvers.component.resolve(declaration);
_this.maybeStoreNgDef(ɵNG_COMPONENT_DEF, declaration);
ɵcompileComponent(declaration, metadata);
});
this.pendingComponents.clear();
this.pendingDirectives.forEach(function (declaration) {
var metadata = _this.resolvers.directive.resolve(declaration);
_this.maybeStoreNgDef(ɵNG_DIRECTIVE_DEF, declaration);
ɵcompileDirective(declaration, metadata);
});
this.pendingDirectives.clear();
this.pendingPipes.forEach(function (declaration) {
var metadata = _this.resolvers.pipe.resolve(declaration);
_this.maybeStoreNgDef(ɵNG_PIPE_DEF, declaration);
ɵcompilePipe(declaration, metadata);
});
this.pendingPipes.clear();
return needsAsyncResources;
};
R3TestBedCompiler.prototype.applyTransitiveScopes = function () {
var _this = this;
var moduleToScope = new Map();
var getScopeOfModule = function (moduleType) {
if (!moduleToScope.has(moduleType)) {
var realType = isTestingModuleOverride(moduleType) ? _this.testModuleType : moduleType;
moduleToScope.set(moduleType, ɵtransitiveScopesFor(realType));
}
return moduleToScope.get(moduleType);
};
this.componentToModuleScope.forEach(function (moduleType, componentType) {
var moduleScope = getScopeOfModule(moduleType);
_this.storeFieldOfDefOnType(componentType, ɵNG_COMPONENT_DEF, 'directiveDefs');
_this.storeFieldOfDefOnType(componentType, ɵNG_COMPONENT_DEF, 'pip