UNPKG

@angular/core

Version:

Angular - the core framework

1,328 lines (1,316 loc) 107 kB
/** * @license Angular v10.0.3 * (c) 2010-2020 Google LLC. https://angular.io/ * License: MIT */ import { getDebugNode, RendererFactory2, ɵstringify, ɵReflectionCapabilities, Directive, Component, Pipe, NgModule, ɵgetInjectableDef, ɵNG_COMP_DEF, ɵRender3NgModuleRef, ApplicationInitStatus, LOCALE_ID, ɵDEFAULT_LOCALE_ID, ɵsetLocaleId, ɵRender3ComponentFactory, ɵcompileComponent, ɵNG_DIR_DEF, ɵcompileDirective, ɵNG_PIPE_DEF, ɵcompilePipe, ɵNG_MOD_DEF, ɵtransitiveScopesFor, ɵpatchComponentDefWithScope, ɵNG_INJ_DEF, ɵcompileNgModuleDefs, NgZone, Compiler, COMPILER_OPTIONS, ɵNgModuleFactory, ModuleWithComponentFactories, InjectionToken, Injector, InjectFlags, ɵresetCompiledComponents, ɵflushModuleScopingQueueAsMuchAsPossible, Injectable, ɵclearOverrides, ɵoverrideComponentView, ɵINJECTOR_SCOPE, Optional, SkipSelf, ɵoverrideProvider, ɵivyEnabled } from '@angular/core'; import { __awaiter } from 'tslib'; import { ResourceLoader } from '@angular/compiler'; /** * @license * Copyright Google LLC 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 _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, (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 () { return new Promise((finishCallback, failCallback) => { runInTestZone(fn, this, finishCallback, failCallback); }); }; } function runInTestZone(fn, context, finishCallback, failCallback) { const currentZone = Zone.current; const 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'); } const 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'); } const 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. const proxyZone = Zone.current.getZoneWith('ProxyZoneSpec'); const previousDelegate = proxyZoneSpec.getDelegate(); proxyZone.parent.run(() => { const testZoneSpec = new AsyncTestZoneSpec(() => { // Need to restore the original zone. currentZone.run(() => { if (proxyZoneSpec.getDelegate() == testZoneSpec) { // Only reset the zone spec if it's sill this one. Otherwise, assume it's OK. proxyZoneSpec.setDelegate(previousDelegate); } finishCallback(); }); }, (error) => { // Need to restore the original zone. currentZone.run(() => { 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 LLC 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) { const _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'); }; } const 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 LLC 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 */ class ComponentFixture { constructor(componentRef, ngZone, _autoDetect) { 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(() => { this._onUnstableSubscription = ngZone.onUnstable.subscribe({ next: () => { this._isStable = false; } }); this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({ next: () => { 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: () => { 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(() => { if (!ngZone.hasPendingMacrotasks) { if (this._promise !== null) { this._resolve(true); this._resolve = null; this._promise = null; } } }); } } }); this._onErrorSubscription = ngZone.onError.subscribe({ next: (error) => { throw error; } }); }); } } _tick(checkNoChanges) { this.changeDetectorRef.detectChanges(); if (checkNoChanges) { this.checkNoChanges(); } } /** * Trigger a change detection cycle for the component. */ detectChanges(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(() => { 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. */ checkNoChanges() { this.changeDetectorRef.checkNoChanges(); } /** * Set whether the fixture should autodetect changes. * * Also runs detectChanges once so that any existing change is detected. */ autoDetectChanges(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. */ isStable() { 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. */ whenStable() { if (this.isStable()) { return Promise.resolve(false); } else if (this._promise !== null) { return this._promise; } else { this._promise = new Promise(res => { this._resolve = res; }); return this._promise; } } _getRenderer() { 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. */ whenRenderingDone() { const renderer = this._getRenderer(); if (renderer && renderer.whenRenderingDone) { return renderer.whenRenderingDone(); } return this.whenStable(); } /** * Trigger component destruction. */ destroy() { 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; } } } function scheduleMicroTask(fn) { Zone.current.scheduleMicroTask('scheduleMicrotask', fn); } /** * @license * Copyright Google LLC 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 */ const _Zone = typeof Zone !== 'undefined' ? Zone : null; const FakeAsyncTestZoneSpec = _Zone && _Zone['FakeAsyncTestZoneSpec']; const ProxyZoneSpec = _Zone && _Zone['ProxyZoneSpec']; let _fakeAsyncTestZoneSpec = null; /** * Clears out the shared fake async zone for a test. * To be called in a global `beforeEach`. * * @publicApi */ function resetFakeAsyncZoneFallback() { if (_fakeAsyncTestZoneSpec) { _fakeAsyncTestZoneSpec.unlockDatePatch(); } _fakeAsyncTestZoneSpec = null; // in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset. ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate(); } let _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 (...args) { const 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(); } let res; const lastProxyZoneSpec = proxyZoneSpec.getDelegate(); proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec); _fakeAsyncTestZoneSpec.lockDatePatch(); 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 = 0, tickOptions = { processNewMacroTasksSynchronously: true }) { _getFakeAsyncZoneSpec().tick(millis, null, tickOptions); } /** * 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() { const zoneSpec = _getFakeAsyncZoneSpec(); zoneSpec.pendingPeriodicTimers.length = 0; } /** * Flush any pending microtasks. * * @publicApi */ function flushMicrotasksFallback() { _getFakeAsyncZoneSpec().flushMicrotasks(); } /** * @license * Copyright Google LLC 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 _Zone$1 = typeof Zone !== 'undefined' ? Zone : null; const 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'} * * @param millis, the number of millisecond to advance the virtual timer * @param tickOptions, the options of tick with a flag called * processNewMacroTasksSynchronously, whether to invoke the new macroTasks, by default is * false, means the new macroTasks will be invoked * * For example, * * it ('test with nested setTimeout', fakeAsync(() => { * let nestedTimeoutInvoked = false; * function funcWithNestedTimeout() { * setTimeout(() => { * nestedTimeoutInvoked = true; * }); * }; * setTimeout(funcWithNestedTimeout); * tick(); * expect(nestedTimeoutInvoked).toBe(true); * })); * * in this case, we have a nested timeout (new macroTask), when we tick, both the * funcWithNestedTimeout and the nested timeout both will be invoked. * * it ('test with nested setTimeout', fakeAsync(() => { * let nestedTimeoutInvoked = false; * function funcWithNestedTimeout() { * setTimeout(() => { * nestedTimeoutInvoked = true; * }); * }; * setTimeout(funcWithNestedTimeout); * tick(0, {processNewMacroTasksSynchronously: false}); * expect(nestedTimeoutInvoked).toBe(false); * })); * * if we pass the tickOptions with processNewMacroTasksSynchronously to be false, the nested timeout * will not be invoked. * * * @publicApi */ function tick(millis = 0, tickOptions = { processNewMacroTasksSynchronously: true }) { if (fakeAsyncTestModule) { return fakeAsyncTestModule.tick(millis, tickOptions); } else { return tickFallback(millis, tickOptions); } } /** * 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 LLC 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. */ class AsyncTestCompleter { constructor() { this._promise = new Promise((res, rej) => { this._resolve = res; this._reject = rej; }); } done(value) { this._resolve(value); } fail(error, stackTrace) { this._reject(error); } get promise() { return this._promise; } } /** * @license * Copyright Google LLC 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. const componentResolved = []; // Cache so that we don't fetch the same resource more than once. const urlMap = new Map(); function cachedResourceResolve(url) { let promise = urlMap.get(url); if (!promise) { const resp = resourceResolver(url); urlMap.set(url, promise = resp.then(unwrapResponse)); } return promise; } componentResourceResolutionQueue.forEach((component, type) => { const promises = []; if (component.templateUrl) { promises.push(cachedResourceResolve(component.templateUrl).then((template) => { component.template = template; })); } const styleUrls = component.styleUrls; const styles = component.styles || (component.styles = []); const styleOffset = component.styles.length; styleUrls && styleUrls.forEach((styleUrl, index) => { styles.push(''); // pre-allocate array. promises.push(cachedResourceResolve(styleUrl).then((style) => { styles[styleOffset + index] = style; styleUrls.splice(styleUrls.indexOf(styleUrl), 1); if (styleUrls.length == 0) { component.styleUrls = undefined; } })); }); const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type)); componentResolved.push(fullyResolved); }); clearResolutionOfComponentResourcesQueue(); return Promise.all(componentResolved).then(() => undefined); } let componentResourceResolutionQueue = new Map(); // Track when existing ɵcmp for a Type is waiting on resources. const 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() { const old = componentResourceResolutionQueue; componentResourceResolutionQueue = new Map(); return old; } function restoreComponentResolutionQueue(queue) { componentDefPendingResolution.clear(); queue.forEach((_, type) => 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 LLC 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 */ let _nextReferenceId = 0; class MetadataOverrider { constructor() { this._references = new Map(); } /** * Creates a new instance for the given metadata class * based on an old instance and overrides. */ overrideMetadata(metadataClass, oldMetadata, override) { const props = {}; if (oldMetadata) { _valueProps(oldMetadata).forEach((prop) => 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); } } function removeMetadata(metadata, remove, references) { const removeObjects = new Set(); for (const prop in remove) { const removeValue = remove[prop]; if (Array.isArray(removeValue)) { removeValue.forEach((value) => { removeObjects.add(_propHashKey(prop, value, references)); }); } else { removeObjects.add(_propHashKey(prop, removeValue, references)); } } for (const prop in metadata) { const propValue = metadata[prop]; if (Array.isArray(propValue)) { metadata[prop] = propValue.filter((value) => !removeObjects.has(_propHashKey(prop, value, references))); } else { if (removeObjects.has(_propHashKey(prop, propValue, references))) { metadata[prop] = undefined; } } } } function addMetadata(metadata, add) { for (const prop in add) { const addValue = add[prop]; const propValue = metadata[prop]; if (propValue != null && Array.isArray(propValue)) { metadata[prop] = propValue.concat(addValue); } else { metadata[prop] = addValue; } } } function setMetadata(metadata, set) { for (const prop in set) { metadata[prop] = set[prop]; } } function _propHashKey(propName, propValue, references) { const replacer = (key, value) => { if (typeof value === 'function') { value = _serializeReference(value, references); } return value; }; return `${propName}:${JSON.stringify(propValue, replacer)}`; } function _serializeReference(ref, references) { let id = references.get(ref); if (!id) { id = `${ɵstringify(ref)}${_nextReferenceId++}`; references.set(ref, id); } return id; } function _valueProps(obj) { const props = []; // regular public props Object.keys(obj).forEach((prop) => { if (!prop.startsWith('_')) { props.push(prop); } }); // getters let proto = obj; while (proto = Object.getPrototypeOf(proto)) { Object.keys(proto).forEach((protoProp) => { const desc = Object.getOwnPropertyDescriptor(proto, protoProp); if (!protoProp.startsWith('_') && desc && 'get' in desc) { props.push(protoProp); } }); } return props; } /** * @license * Copyright Google LLC 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 reflection = new ɵReflectionCapabilities(); /** * Allows to override ivy metadata for tests (via the `TestBed`). */ class OverrideResolver { constructor() { this.overrides = new Map(); this.resolved = new Map(); } addOverride(type, override) { const overrides = this.overrides.get(type) || []; overrides.push(override); this.overrides.set(type, overrides); this.resolved.delete(type); } setOverrides(overrides) { this.overrides.clear(); overrides.forEach(([type, override]) => { this.addOverride(type, override); }); } getAnnotation(type) { const 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 (let i = annotations.length - 1; i >= 0; i--) { const annotation = annotations[i]; const isKnownType = annotation instanceof Directive || annotation instanceof Component || annotation instanceof Pipe || annotation instanceof NgModule; if (isKnownType) { return annotation instanceof this.type ? annotation : null; } } return null; } resolve(type) { let resolved = this.resolved.get(type) || null; if (!resolved) { resolved = this.getAnnotation(type); if (resolved) { const overrides = this.overrides.get(type); if (overrides) { const overrider = new MetadataOverrider(); overrides.forEach(override => { resolved = overrider.overrideMetadata(this.type, resolved, override); }); } } this.resolved.set(type, resolved); } return resolved; } } class DirectiveResolver extends OverrideResolver { get type() { return Directive; } } class ComponentResolver extends OverrideResolver { get type() { return Component; } } class PipeResolver extends OverrideResolver { get type() { return Pipe; } } class NgModuleResolver extends OverrideResolver { get type() { return NgModule; } } /** * @license * Copyright Google LLC 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; } class R3TestBedCompiler { constructor(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(); // Keep track of overridden modules, so that we can collect all affected ones in the module tree. this.overriddenModules = 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 = []; // Overrides for injectables with `{providedIn: SomeModule}` need to be tracked and added to that // module's provider list. this.providerOverridesByModule = new Map(); this.providerOverridesByToken = new Map(); this.moduleProvidersOverridden = new Set(); this.testModuleRef = null; class DynamicTestModule { } this.testModuleType = DynamicTestModule; } setCompilerProviders(providers) { this.compilerProviders = providers; this._injector = null; } configureTestingModule(moduleDef) { // Enqueue any compilation tasks for the directly declared component. if (moduleDef.declarations !== undefined) { this.queueTypeArray(moduleDef.declarations, TestingModuleOverride.DECLARATION); this.declarations.push(...moduleDef.declarations); } // Enqueue any compilation tasks for imported modules. if (moduleDef.imports !== undefined) { this.queueTypesFromModulesArray(moduleDef.imports); this.imports.push(...moduleDef.imports); } if (moduleDef.providers !== undefined) { this.providers.push(...moduleDef.providers); } if (moduleDef.schemas !== undefined) { this.schemas.push(...moduleDef.schemas); } } overrideModule(ngModule, override) { this.overriddenModules.add(ngModule); // Compile the module right away. this.resolvers.module.addOverride(ngModule, override); const metadata = this.resolvers.module.resolve(ngModule); if (metadata === null) { throw invalidTypeError(ngModule.name, 'NgModule'); } this.recompileNgModule(ngModule, metadata); // At this point, the module has a valid module def (ɵmod), 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]); } overrideComponent(component, override) { this.resolvers.component.addOverride(component, override); this.pendingComponents.add(component); } overrideDirective(directive, override) { this.resolvers.directive.addOverride(directive, override); this.pendingDirectives.add(directive); } overridePipe(pipe, override) { this.resolvers.pipe.addOverride(pipe, override); this.pendingPipes.add(pipe); } overrideProvider(token, provider) { let providerDef; if (provider.useFactory !== undefined) { providerDef = { provide: token, useFactory: provider.useFactory, deps: provider.deps || [], multi: provider.multi }; } else if (provider.useValue !== undefined) { providerDef = { provide: token, useValue: provider.useValue, multi: provider.multi }; } else { providerDef = { provide: token }; } const injectableDef = typeof token !== 'string' ? ɵgetInjectableDef(token) : null; const isRoot = injectableDef !== null && injectableDef.providedIn === 'root'; const 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); if (injectableDef !== null && injectableDef.providedIn !== null && typeof injectableDef.providedIn !== 'string') { const existingOverrides = this.providerOverridesByModule.get(injectableDef.providedIn); if (existingOverrides !== undefined) { existingOverrides.push(providerDef); } else { this.providerOverridesByModule.set(injectableDef.providedIn, [providerDef]); } } } overrideTemplateUsingTestingModule(type, template) { const def = type[ɵNG_COMP_DEF]; const hasStyleUrls = () => { const metadata = this.resolvers.component.resolve(type); return !!metadata.styleUrls && metadata.styleUrls.length > 0; }; const 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. const override = overrideStyleUrls ? { template, styles: [], styleUrls: [] } : { 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); } compileComponents() { return __awaiter(this, void 0, void 0, function* () { this.clearComponentResolutionQueue(); // Run compilers for all queued types. let needsAsyncResources = this.compileTypesSync(); // compileComponents() should not be async unless it needs to be. if (needsAsyncResources) { let resourceLoader; let resolver = (url) => { if (!resourceLoader) { resourceLoader = this.injector.get(ResourceLoader); } return Promise.resolve(resourceLoader.get(url)); }; yield resolveComponentResources(resolver); } }); } finalize() { // One last compile this.compileTypesSync(); // Create the testing module itself. this.compileTestModule(); this.applyTransitiveScopes(); this.applyProviderOverrides(); // Patch previously stored `styles` Component values (taken from ɵcmp), 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(); const parentInjector = this.platform.injector; this.testModuleRef = new ɵRender3NgModuleRef(this.testModuleType, parentInjector); // ApplicationInitStatus.runInitializers() is marked @internal to core. // Cast it to any before accessing it. this.testModuleRef.injector.get(ApplicationInitStatus).runInitializers(); // Set locale ID after running app initializers, since locale information might be updated while // running initializers. This is also consistent with the execution order while bootstrapping an // app (see `packages/core/src/application_ref.ts` file). const localeId = this.testModuleRef.injector.get(LOCALE_ID, ɵDEFAULT_LOCALE_ID); ɵsetLocaleId(localeId); return this.testModuleRef; } /** * @internal */ _compileNgModuleSync(moduleType) { this.queueTypesFromModulesArray([moduleType]); this.compileTypesSync(); this.applyProviderOverrides(); this.applyProviderOverridesToModule(moduleType); this.applyTransitiveScopes(); } /** * @internal */ _compileNgModuleAsync(moduleType) { return __awaiter(this, void 0, void 0, function* () { this.queueTypesFromModulesArray([moduleType]); yield this.compileComponents(); this.applyProviderOverrides(); this.applyProviderOverridesToModule(moduleType); this.applyTransitiveScopes(); }); } /** * @internal */ _getModuleResolver() { return this.resolvers.module; } /** * @internal */ _getComponentFactories(moduleType) { return maybeUnwrapFn(moduleType.ɵmod.declarations).reduce((factories, declaration) => { const componentDef = declaration.ɵcmp; componentDef && factories.push(new ɵRender3ComponentFactory(componentDef, this.testModuleRef)); return factories; }, []); } compileTypesSync() { // Compile all queued components, directives, pipes. let needsAsyncResources = false; this.pendingComponents.forEach(declaration => { needsAsyncResources = needsAsyncResources || isComponentDefPendingResolution(declaration); const metadata = this.resolvers.component.resolve(declaration); if (metadata === null) { throw invalidTypeError(declaration.name, 'Component'); } this.maybeStoreNgDef(ɵNG_COMP_DEF, declaration); ɵcompileComponent(declaration, metadata); }); this.pendingComponents.clear(); this.pendingDirectives.forEach(declaration => { const metadata = this.resolvers.directive.resolve(declaration); if (metadata === null) { throw invalidTypeError(declaration.name, 'Directive'); } this.maybeStoreNgDef(ɵNG_DIR_DEF, declaration); ɵcompileDirective(declaration, metadata); }); this.pendingDirectives.clear(); this.pendingPipes.forEach(declaration => { const metadata = this.resolvers.pipe.resolve(declaration); if (metadata === null) { throw invalidTypeError(declaration.name, 'Pipe'); } this.maybeStoreNgDef(ɵNG_PIPE_DEF, declaration); ɵcompilePipe(declaration, metadata); }); this.pendingPipes.clear(); return needsAsyncResources; } applyTransitiveScopes() { if (this.overriddenModules.size > 0) { // Module overrides (via `TestBed.overrideModule`) might affect scopes that were previously // calculated and stored in `transitiveCompileScopes`. If module overrides are present, // collect all affected modules and reset scopes to force their re-calculatation. const testingModuleDef = this.testModuleType[ɵNG_MOD_DEF]; const affectedModules = this.collectModulesAffectedByOverrides(testingModuleDef.imports); if (affectedModules.size > 0) { affectedModules.forEach(moduleType => { this.storeFieldOfDefOnType(moduleType, ɵNG_MOD_DEF, 'transitiveCompileScopes'); moduleType[ɵNG_MOD_DEF].transitiveCompileScopes = null; }); } } const moduleToScope = new Map(); const getScopeOfModule = (moduleType) => { if (!moduleToScope.has(moduleType)) { const isTestingModule = isTestingModuleOverride(moduleType); const realType = isTestingModule ? this.testModuleType : moduleType; moduleToScope.set(moduleType, ɵtransitiveScopesFor(realType)); } return moduleToScope.get(moduleType); }; this.componentToModuleScope.forEach((moduleType, componentType) => { const moduleScope = getScopeOfModule(moduleType); this.storeFieldOfDefOnType(componentType, ɵNG_COMP_DEF, 'directiveDefs'); this.storeFieldOfDefOnType(componentType, ɵNG_COMP_DEF, 'pipeDefs'); ɵpatchComponentDefWithScope(componentType.ɵcmp, moduleScope); }); this.componentToModuleScope.clear(); } applyProviderOverrides() { const maybeApplyOverrides = (field) => (type) => { const resolver = field === ɵNG_COMP_DEF ? this.resolvers.component : this.resolvers.directive; const metadata = resolver.resolve(type); if (this.hasProviderOverrides(metadata.providers)) { this.patchDefWithProviderOverrides(type, field); } }; this.seenComponents.forEach(maybeApplyOverrides(ɵNG_COMP_DEF)); this.seenDirectives.forEach(maybeApplyOverrides(ɵNG_DIR_DEF)); this.seenComponents.clear(); this.seenDirectives.clear(); } applyProviderOverridesToModule(moduleType) { if (this.moduleProvidersOverridden.has(moduleType)) { return; } this.moduleProvidersOverridden.add(moduleType); const injectorDef = moduleType[ɵNG_INJ_DEF]; if (this.providerOverridesByToken.size > 0) { const providers = [ ...injectorDef.providers, ...(this.providerOverridesByModule.get(moduleType) || []) ]; if (this.hasProviderOverrides(providers)) { this.maybeStoreNgDef(ɵNG_INJ_DEF, moduleType); this.storeFieldOfDefOnType(moduleType, ɵNG_INJ_DEF, 'providers'); injectorDef.providers = this.getOverriddenProviders(providers); }