tags or inline views, where the parent injector might live many views
// above the child injector.
while (viewOffset > 0) {
parentView = parentView[DECLARATION_VIEW];
viewOffset--;
}
return parentView;
}
/**
* Defines if the call to `inject` should include `viewProviders` in its resolution.
*
* This is set to true when we try to instantiate a component. This value is reset in
* `getNodeInjectable` to a value which matches the declaration location of the token about to be
* instantiated. This is done so that if we are injecting a token which was declared outside of
* `viewProviders` we don't accidentally pull `viewProviders` in.
*
* Example:
*
* ```
* @Injectable()
* class MyService {
* constructor(public value: String) {}
* }
*
* @Component({
* providers: [
* MyService,
* {provide: String, value: 'providers' }
* ]
* viewProviders: [
* {provide: String, value: 'viewProviders'}
* ]
* })
* class MyComponent {
* constructor(myService: MyService, value: String) {
* // We expect that Component can see into `viewProviders`.
* expect(value).toEqual('viewProviders');
* // `MyService` was not declared in `viewProviders` hence it can't see it.
* expect(myService.value).toEqual('providers');
* }
* }
*
* ```
*/
let includeViewProviders = true;
function setIncludeViewProviders(v) {
const oldValue = includeViewProviders;
includeViewProviders = v;
return oldValue;
}
/**
* The number of slots in each bloom filter (used by DI). The larger this number, the fewer
* directives that will share slots, and thus, the fewer false positives when checking for
* the existence of a directive.
*/
const BLOOM_SIZE = 256;
const BLOOM_MASK = BLOOM_SIZE - 1;
/**
* The number of bits that is represented by a single bloom bucket. JS bit operations are 32 bits,
* so each bucket represents 32 distinct tokens which accounts for log2(32) = 5 bits of a bloom hash
* number.
*/
const BLOOM_BUCKET_BITS = 5;
/** Counter used to generate unique IDs for directives. */
let nextNgElementId = 0;
/** Value used when something wasn't found by an injector. */
const NOT_FOUND = {};
/**
* Registers this directive as present in its node's injector by flipping the directive's
* corresponding bit in the injector's bloom filter.
*
* @param injectorIndex The index of the node injector where this token should be registered
* @param tView The TView for the injector's bloom filters
* @param type The directive token to register
*/
function bloomAdd(injectorIndex, tView, type) {
ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true');
let id;
if (typeof type === 'string') {
id = type.charCodeAt(0) || 0;
}
else if (type.hasOwnProperty(NG_ELEMENT_ID)) {
id = type[NG_ELEMENT_ID];
}
// Set a unique ID on the directive type, so if something tries to inject the directive,
// we can easily retrieve the ID and hash it into the bloom bit that should be checked.
if (id == null) {
id = type[NG_ELEMENT_ID] = nextNgElementId++;
}
// We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each),
// so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter.
const bloomHash = id & BLOOM_MASK;
// Create a mask that targets the specific bit associated with the directive.
// JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
// to bit positions 0 - 31 in a 32 bit integer.
const mask = 1 << bloomHash;
// Each bloom bucket in `tData` represents `BLOOM_BUCKET_BITS` number of bits of `bloomHash`.
// Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset that the mask
// should be written to.
tView.data[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)] |= mask;
}
/**
* Creates (or gets an existing) injector for a given element or container.
*
* @param tNode for which an injector should be retrieved / created.
* @param lView View where the node is stored
* @returns Node injector
*/
function getOrCreateNodeInjectorForNode(tNode, lView) {
const existingInjectorIndex = getInjectorIndex(tNode, lView);
if (existingInjectorIndex !== -1) {
return existingInjectorIndex;
}
const tView = lView[TVIEW];
if (tView.firstCreatePass) {
tNode.injectorIndex = lView.length;
insertBloom(tView.data, tNode); // foundation for node bloom
insertBloom(lView, null); // foundation for cumulative bloom
insertBloom(tView.blueprint, null);
}
const parentLoc = getParentInjectorLocation(tNode, lView);
const injectorIndex = tNode.injectorIndex;
// If a parent injector can't be found, its location is set to -1.
// In that case, we don't need to set up a cumulative bloom
if (hasParentInjector(parentLoc)) {
const parentIndex = getParentInjectorIndex(parentLoc);
const parentLView = getParentInjectorView(parentLoc, lView);
const parentData = parentLView[TVIEW].data;
// Creates a cumulative bloom filter that merges the parent's bloom filter
// and its own cumulative bloom (which contains tokens for all ancestors)
for (let i = 0; i < 8 /* NodeInjectorOffset.BLOOM_SIZE */; i++) {
lView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i];
}
}
lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */] = parentLoc;
return injectorIndex;
}
function insertBloom(arr, footer) {
arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer);
}
function getInjectorIndex(tNode, lView) {
if (tNode.injectorIndex === -1 ||
// If the injector index is the same as its parent's injector index, then the index has been
// copied down from the parent node. No injector has been created yet on this node.
(tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) ||
// After the first template pass, the injector index might exist but the parent values
// might not have been calculated yet for this instance
lView[tNode.injectorIndex + 8 /* NodeInjectorOffset.PARENT */] === null) {
return -1;
}
else {
ngDevMode && assertIndexInRange(lView, tNode.injectorIndex);
return tNode.injectorIndex;
}
}
/**
* Finds the index of the parent injector, with a view offset if applicable. Used to set the
* parent injector initially.
*
* @returns Returns a number that is the combination of the number of LViews that we have to go up
* to find the LView containing the parent inject AND the index of the injector within that LView.
*/
function getParentInjectorLocation(tNode, lView) {
if (tNode.parent && tNode.parent.injectorIndex !== -1) {
// If we have a parent `TNode` and there is an injector associated with it we are done, because
// the parent injector is within the current `LView`.
return tNode.parent.injectorIndex; // ViewOffset is 0
}
// When parent injector location is computed it may be outside of the current view. (ie it could
// be pointing to a declared parent location). This variable stores number of declaration parents
// we need to walk up in order to find the parent injector location.
let declarationViewOffset = 0;
let parentTNode = null;
let lViewCursor = lView;
// The parent injector is not in the current `LView`. We will have to walk the declared parent
// `LView` hierarchy and look for it. If we walk of the top, that means that there is no parent
// `NodeInjector`.
while (lViewCursor !== null) {
parentTNode = getTNodeFromLView(lViewCursor);
if (parentTNode === null) {
// If we have no parent, than we are done.
return NO_PARENT_INJECTOR;
}
ngDevMode && parentTNode && assertTNodeForLView(parentTNode, lViewCursor[DECLARATION_VIEW]);
// Every iteration of the loop requires that we go to the declared parent.
declarationViewOffset++;
lViewCursor = lViewCursor[DECLARATION_VIEW];
if (parentTNode.injectorIndex !== -1) {
// We found a NodeInjector which points to something.
return (parentTNode.injectorIndex |
(declarationViewOffset << 16 /* RelativeInjectorLocationFlags.ViewOffsetShift */));
}
}
return NO_PARENT_INJECTOR;
}
/**
* Makes a type or an injection token public to the DI system by adding it to an
* injector's bloom filter.
*
* @param di The node injector in which a directive will be added
* @param token The type or the injection token to be made public
*/
function diPublicInInjector(injectorIndex, tView, token) {
bloomAdd(injectorIndex, tView, token);
}
/**
* Inject static attribute value into directive constructor.
*
* This method is used with `factory` functions which are generated as part of
* `defineDirective` or `defineComponent`. The method retrieves the static value
* of an attribute. (Dynamic attributes are not supported since they are not resolved
* at the time of injection and can change over time.)
*
* # Example
* Given:
* ```
* @Component(...)
* class MyComponent {
* constructor(@Attribute('title') title: string) { ... }
* }
* ```
* When instantiated with
* ```
*
* ```
*
* Then factory method generated is:
* ```
* MyComponent.ɵcmp = defineComponent({
* factory: () => new MyComponent(injectAttribute('title'))
* ...
* })
* ```
*
* @publicApi
*/
function injectAttributeImpl(tNode, attrNameToInject) {
ngDevMode && assertTNodeType(tNode, 12 /* TNodeType.AnyContainer */ | 3 /* TNodeType.AnyRNode */);
ngDevMode && assertDefined(tNode, 'expecting tNode');
if (attrNameToInject === 'class') {
return tNode.classes;
}
if (attrNameToInject === 'style') {
return tNode.styles;
}
const attrs = tNode.attrs;
if (attrs) {
const attrsLength = attrs.length;
let i = 0;
while (i < attrsLength) {
const value = attrs[i];
// If we hit a `Bindings` or `Template` marker then we are done.
if (isNameOnlyAttributeMarker(value))
break;
// Skip namespaced attributes
if (value === 0 /* AttributeMarker.NamespaceURI */) {
// we skip the next two values
// as namespaced attributes looks like
// [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist',
// 'existValue', ...]
i = i + 2;
}
else if (typeof value === 'number') {
// Skip to the first value of the marked attribute.
i++;
while (i < attrsLength && typeof attrs[i] === 'string') {
i++;
}
}
else if (value === attrNameToInject) {
return attrs[i + 1];
}
else {
i = i + 2;
}
}
}
return null;
}
function notFoundValueOrThrow(notFoundValue, token, flags) {
if ((flags & InjectFlags.Optional) || notFoundValue !== undefined) {
return notFoundValue;
}
else {
throwProviderNotFoundError(token, 'NodeInjector');
}
}
/**
* Returns the value associated to the given token from the ModuleInjector or throws exception
*
* @param lView The `LView` that contains the `tNode`
* @param token The token to look for
* @param flags Injection flags
* @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
* @returns the value from the injector or throws an exception
*/
function lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue) {
if ((flags & InjectFlags.Optional) && notFoundValue === undefined) {
// This must be set or the NullInjector will throw for optional deps
notFoundValue = null;
}
if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) {
const moduleInjector = lView[INJECTOR$1];
// switch to `injectInjectorOnly` implementation for module injector, since module injector
// should not have access to Component/Directive DI scope (that may happen through
// `directiveInject` implementation)
const previousInjectImplementation = setInjectImplementation(undefined);
try {
if (moduleInjector) {
return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional);
}
else {
return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional);
}
}
finally {
setInjectImplementation(previousInjectImplementation);
}
}
return notFoundValueOrThrow(notFoundValue, token, flags);
}
/**
* Returns the value associated to the given token from the NodeInjectors => ModuleInjector.
*
* Look for the injector providing the token by walking up the node injector tree and then
* the module injector tree.
*
* This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom
* filter. `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`)
*
* @param tNode The Node where the search for the injector should start
* @param lView The `LView` that contains the `tNode`
* @param token The token to look for
* @param flags Injection flags
* @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
* @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
*/
function getOrCreateInjectable(tNode, lView, token, flags = InjectFlags.Default, notFoundValue) {
if (tNode !== null) {
// If the view or any of its ancestors have an embedded
// view injector, we have to look it up there first.
if (lView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */ &&
// The token must be present on the current node injector when the `Self`
// flag is set, so the lookup on embedded view injector(s) can be skipped.
!(flags & InjectFlags.Self)) {
const embeddedInjectorValue = lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, NOT_FOUND);
if (embeddedInjectorValue !== NOT_FOUND) {
return embeddedInjectorValue;
}
}
// Otherwise try the node injector.
const value = lookupTokenUsingNodeInjector(tNode, lView, token, flags, NOT_FOUND);
if (value !== NOT_FOUND) {
return value;
}
}
// Finally, fall back to the module injector.
return lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
}
/**
* Returns the value associated to the given token from the node injector.
*
* @param tNode The Node where the search for the injector should start
* @param lView The `LView` that contains the `tNode`
* @param token The token to look for
* @param flags Injection flags
* @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
* @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
*/
function lookupTokenUsingNodeInjector(tNode, lView, token, flags, notFoundValue) {
const bloomHash = bloomHashBitOrFactory(token);
// If the ID stored here is a function, this is a special object like ElementRef or TemplateRef
// so just call the factory function to create it.
if (typeof bloomHash === 'function') {
if (!enterDI(lView, tNode, flags)) {
// Failed to enter DI, try module injector instead. If a token is injected with the @Host
// flag, the module injector is not searched for that token in Ivy.
return (flags & InjectFlags.Host) ?
notFoundValueOrThrow(notFoundValue, token, flags) :
lookupTokenUsingModuleInjector(lView, token, flags, notFoundValue);
}
try {
let value;
if (ngDevMode) {
runInInjectorProfilerContext(new NodeInjector(getCurrentTNode(), getLView()), token, () => {
value = bloomHash(flags);
if (value != null) {
emitInstanceCreatedByInjectorEvent(value);
}
});
}
else {
value = bloomHash(flags);
}
if (value == null && !(flags & InjectFlags.Optional)) {
throwProviderNotFoundError(token);
}
else {
return value;
}
}
finally {
leaveDI();
}
}
else if (typeof bloomHash === 'number') {
// A reference to the previous injector TView that was found while climbing the element
// injector tree. This is used to know if viewProviders can be accessed on the current
// injector.
let previousTView = null;
let injectorIndex = getInjectorIndex(tNode, lView);
let parentLocation = NO_PARENT_INJECTOR;
let hostTElementNode = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null;
// If we should skip this injector, or if there is no injector on this node, start by
// searching the parent injector.
if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) {
parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) :
lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
if (parentLocation === NO_PARENT_INJECTOR || !shouldSearchParent(flags, false)) {
injectorIndex = -1;
}
else {
previousTView = lView[TVIEW];
injectorIndex = getParentInjectorIndex(parentLocation);
lView = getParentInjectorView(parentLocation, lView);
}
}
// Traverse up the injector tree until we find a potential match or until we know there
// *isn't* a match.
while (injectorIndex !== -1) {
ngDevMode && assertNodeInjector(lView, injectorIndex);
// Check the current injector. If it matches, see if it contains token.
const tView = lView[TVIEW];
ngDevMode &&
assertTNodeForLView(tView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */], lView);
if (bloomHasToken(bloomHash, injectorIndex, tView.data)) {
// At this point, we have an injector which *may* contain the token, so we step through
// the providers and directives associated with the injector's corresponding node to get
// the instance.
const instance = searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode);
if (instance !== NOT_FOUND) {
return instance;
}
}
parentLocation = lView[injectorIndex + 8 /* NodeInjectorOffset.PARENT */];
if (parentLocation !== NO_PARENT_INJECTOR &&
shouldSearchParent(flags, lView[TVIEW].data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */] === hostTElementNode) &&
bloomHasToken(bloomHash, injectorIndex, lView)) {
// The def wasn't found anywhere on this node, so it was a false positive.
// Traverse up the tree and continue searching.
previousTView = tView;
injectorIndex = getParentInjectorIndex(parentLocation);
lView = getParentInjectorView(parentLocation, lView);
}
else {
// If we should not search parent OR If the ancestor bloom filter value does not have the
// bit corresponding to the directive we can give up on traversing up to find the specific
// injector.
injectorIndex = -1;
}
}
}
return notFoundValue;
}
function searchTokensOnInjector(injectorIndex, lView, token, previousTView, flags, hostTElementNode) {
const currentTView = lView[TVIEW];
const tNode = currentTView.data[injectorIndex + 8 /* NodeInjectorOffset.TNODE */];
// First, we need to determine if view providers can be accessed by the starting element.
// There are two possibilities
const canAccessViewProviders = previousTView == null ?
// 1) This is the first invocation `previousTView == null` which means that we are at the
// `TNode` of where injector is starting to look. In such a case the only time we are allowed
// to look into the ViewProviders is if:
// - we are on a component
// - AND the injector set `includeViewProviders` to true (implying that the token can see
// ViewProviders because it is the Component or a Service which itself was declared in
// ViewProviders)
(isComponentHost(tNode) && includeViewProviders) :
// 2) `previousTView != null` which means that we are now walking across the parent nodes.
// In such a case we are only allowed to look into the ViewProviders if:
// - We just crossed from child View to Parent View `previousTView != currentTView`
// - AND the parent TNode is an Element.
// This means that we just came from the Component's View and therefore are allowed to see
// into the ViewProviders.
(previousTView != currentTView && ((tNode.type & 3 /* TNodeType.AnyRNode */) !== 0));
// This special case happens when there is a @host on the inject and when we are searching
// on the host element node.
const isHostSpecialCase = (flags & InjectFlags.Host) && hostTElementNode === tNode;
const injectableIdx = locateDirectiveOrProvider(tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase);
if (injectableIdx !== null) {
return getNodeInjectable(lView, currentTView, injectableIdx, tNode);
}
else {
return NOT_FOUND;
}
}
/**
* Searches for the given token among the node's directives and providers.
*
* @param tNode TNode on which directives are present.
* @param tView The tView we are currently processing
* @param token Provider token or type of a directive to look for.
* @param canAccessViewProviders Whether view providers should be considered.
* @param isHostSpecialCase Whether the host special case applies.
* @returns Index of a found directive or provider, or null when none found.
*/
function locateDirectiveOrProvider(tNode, tView, token, canAccessViewProviders, isHostSpecialCase) {
const nodeProviderIndexes = tNode.providerIndexes;
const tInjectables = tView.data;
const injectablesStart = nodeProviderIndexes & 1048575 /* TNodeProviderIndexes.ProvidersStartIndexMask */;
const directivesStart = tNode.directiveStart;
const directiveEnd = tNode.directiveEnd;
const cptViewProvidersCount = nodeProviderIndexes >> 20 /* TNodeProviderIndexes.CptViewProvidersCountShift */;
const startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount;
// When the host special case applies, only the viewProviders and the component are visible
const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd;
for (let i = startingIndex; i < endIndex; i++) {
const providerTokenOrDef = tInjectables[i];
if (i < directivesStart && token === providerTokenOrDef ||
i >= directivesStart && providerTokenOrDef.type === token) {
return i;
}
}
if (isHostSpecialCase) {
const dirDef = tInjectables[directivesStart];
if (dirDef && isComponentDef(dirDef) && dirDef.type === token) {
return directivesStart;
}
}
return null;
}
/**
* Retrieve or instantiate the injectable from the `LView` at particular `index`.
*
* This function checks to see if the value has already been instantiated and if so returns the
* cached `injectable`. Otherwise if it detects that the value is still a factory it
* instantiates the `injectable` and caches the value.
*/
function getNodeInjectable(lView, tView, index, tNode) {
let value = lView[index];
const tData = tView.data;
if (isFactory(value)) {
const factory = value;
if (factory.resolving) {
throwCyclicDependencyError(stringifyForError(tData[index]));
}
const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders);
factory.resolving = true;
let prevInjectContext;
if (ngDevMode) {
// tData indexes mirror the concrete instances in its corresponding LView.
// lView[index] here is either the injectable instace itself or a factory,
// therefore tData[index] is the constructor of that injectable or a
// definition object that contains the constructor in a `.type` field.
const token = tData[index].type || tData[index];
const injector = new NodeInjector(tNode, lView);
prevInjectContext = setInjectorProfilerContext({ injector, token });
}
const previousInjectImplementation = factory.injectImpl ? setInjectImplementation(factory.injectImpl) : null;
const success = enterDI(lView, tNode, InjectFlags.Default);
ngDevMode &&
assertEqual(success, true, 'Because flags do not contain \`SkipSelf\' we expect this to always succeed.');
try {
value = lView[index] = factory.factory(undefined, tData, lView, tNode);
ngDevMode && emitInstanceCreatedByInjectorEvent(value);
// This code path is hit for both directives and providers.
// For perf reasons, we want to avoid searching for hooks on providers.
// It does no harm to try (the hooks just won't exist), but the extra
// checks are unnecessary and this is a hot path. So we check to see
// if the index of the dependency is in the directive range for this
// tNode. If it's not, we know it's a provider and skip hook registration.
if (tView.firstCreatePass && index >= tNode.directiveStart) {
ngDevMode && assertDirectiveDef(tData[index]);
registerPreOrderHooks(index, tData[index], tView);
}
}
finally {
ngDevMode && setInjectorProfilerContext(prevInjectContext);
previousInjectImplementation !== null &&
setInjectImplementation(previousInjectImplementation);
setIncludeViewProviders(previousIncludeViewProviders);
factory.resolving = false;
leaveDI();
}
}
return value;
}
/**
* Returns the bit in an injector's bloom filter that should be used to determine whether or not
* the directive might be provided by the injector.
*
* When a directive is public, it is added to the bloom filter and given a unique ID that can be
* retrieved on the Type. When the directive isn't public or the token is not a directive `null`
* is returned as the node injector can not possibly provide that token.
*
* @param token the injection token
* @returns the matching bit to check in the bloom filter or `null` if the token is not known.
* When the returned value is negative then it represents special values such as `Injector`.
*/
function bloomHashBitOrFactory(token) {
ngDevMode && assertDefined(token, 'token must be defined');
if (typeof token === 'string') {
return token.charCodeAt(0) || 0;
}
const tokenId =
// First check with `hasOwnProperty` so we don't get an inherited ID.
token.hasOwnProperty(NG_ELEMENT_ID) ? token[NG_ELEMENT_ID] : undefined;
// Negative token IDs are used for special objects such as `Injector`
if (typeof tokenId === 'number') {
if (tokenId >= 0) {
return tokenId & BLOOM_MASK;
}
else {
ngDevMode &&
assertEqual(tokenId, -1 /* InjectorMarkers.Injector */, 'Expecting to get Special Injector Id');
return createNodeInjector;
}
}
else {
return tokenId;
}
}
function bloomHasToken(bloomHash, injectorIndex, injectorView) {
// Create a mask that targets the specific bit associated with the directive we're looking for.
// JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding
// to bit positions 0 - 31 in a 32 bit integer.
const mask = 1 << bloomHash;
// Each bloom bucket in `injectorView` represents `BLOOM_BUCKET_BITS` number of bits of
// `bloomHash`. Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset
// that should be used.
const value = injectorView[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)];
// If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on,
// this injector is a potential match.
return !!(value & mask);
}
/** Returns true if flags prevent parent injector from being searched for tokens */
function shouldSearchParent(flags, isFirstHostTNode) {
return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode);
}
function getNodeInjectorLView(nodeInjector) {
return nodeInjector._lView;
}
function getNodeInjectorTNode(nodeInjector) {
return nodeInjector._tNode;
}
class NodeInjector {
constructor(_tNode, _lView) {
this._tNode = _tNode;
this._lView = _lView;
}
get(token, notFoundValue, flags) {
return getOrCreateInjectable(this._tNode, this._lView, token, convertToBitFlags(flags), notFoundValue);
}
}
/** Creates a `NodeInjector` for the current node. */
function createNodeInjector() {
return new NodeInjector(getCurrentTNode(), getLView());
}
/**
* @codeGenApi
*/
function ɵɵgetInheritedFactory(type) {
return noSideEffects(() => {
const ownConstructor = type.prototype.constructor;
const ownFactory = ownConstructor[NG_FACTORY_DEF] || getFactoryOf(ownConstructor);
const objectPrototype = Object.prototype;
let parent = Object.getPrototypeOf(type.prototype).constructor;
// Go up the prototype until we hit `Object`.
while (parent && parent !== objectPrototype) {
const factory = parent[NG_FACTORY_DEF] || getFactoryOf(parent);
// If we hit something that has a factory and the factory isn't the same as the type,
// we've found the inherited factory. Note the check that the factory isn't the type's
// own factory is redundant in most cases, but if the user has custom decorators on the
// class, this lookup will start one level down in the prototype chain, causing us to
// find the own factory first and potentially triggering an infinite loop downstream.
if (factory && factory !== ownFactory) {
return factory;
}
parent = Object.getPrototypeOf(parent);
}
// There is no factory defined. Either this was improper usage of inheritance
// (no Angular decorator on the superclass) or there is no constructor at all
// in the inheritance chain. Since the two cases cannot be distinguished, the
// latter has to be assumed.
return (t) => new t();
});
}
function getFactoryOf(type) {
if (isForwardRef(type)) {
return () => {
const factory = getFactoryOf(resolveForwardRef(type));
return factory && factory();
};
}
return getFactoryDef(type);
}
/**
* Returns a value from the closest embedded or node injector.
*
* @param tNode The Node where the search for the injector should start
* @param lView The `LView` that contains the `tNode`
* @param token The token to look for
* @param flags Injection flags
* @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional`
* @returns the value from the injector, `null` when not found, or `notFoundValue` if provided
*/
function lookupTokenUsingEmbeddedInjector(tNode, lView, token, flags, notFoundValue) {
let currentTNode = tNode;
let currentLView = lView;
// When an LView with an embedded view injector is inserted, it'll likely be interlaced with
// nodes who may have injectors (e.g. node injector -> embedded view injector -> node injector).
// Since the bloom filters for the node injectors have already been constructed and we don't
// have a way of extracting the records from an injector, the only way to maintain the correct
// hierarchy when resolving the value is to walk it node-by-node while attempting to resolve
// the token at each level.
while (currentTNode !== null && currentLView !== null &&
(currentLView[FLAGS] & 2048 /* LViewFlags.HasEmbeddedViewInjector */) &&
!(currentLView[FLAGS] & 512 /* LViewFlags.IsRoot */)) {
ngDevMode && assertTNodeForLView(currentTNode, currentLView);
// Note that this lookup on the node injector is using the `Self` flag, because
// we don't want the node injector to look at any parent injectors since we
// may hit the embedded view injector first.
const nodeInjectorValue = lookupTokenUsingNodeInjector(currentTNode, currentLView, token, flags | InjectFlags.Self, NOT_FOUND);
if (nodeInjectorValue !== NOT_FOUND) {
return nodeInjectorValue;
}
// Has an explicit type due to a TS bug: https://github.com/microsoft/TypeScript/issues/33191
let parentTNode = currentTNode.parent;
// `TNode.parent` includes the parent within the current view only. If it doesn't exist,
// it means that we've hit the view boundary and we need to go up to the next view.
if (!parentTNode) {
// Before we go to the next LView, check if the token exists on the current embedded injector.
const embeddedViewInjector = currentLView[EMBEDDED_VIEW_INJECTOR];
if (embeddedViewInjector) {
const embeddedViewInjectorValue = embeddedViewInjector.get(token, NOT_FOUND, flags);
if (embeddedViewInjectorValue !== NOT_FOUND) {
return embeddedViewInjectorValue;
}
}
// Otherwise keep going up the tree.
parentTNode = getTNodeFromLView(currentLView);
currentLView = currentLView[DECLARATION_VIEW];
}
currentTNode = parentTNode;
}
return notFoundValue;
}
/** Gets the TNode associated with an LView inside of the declaration view. */
function getTNodeFromLView(lView) {
const tView = lView[TVIEW];
const tViewType = tView.type;
// The parent pointer differs based on `TView.type`.
if (tViewType === 2 /* TViewType.Embedded */) {
ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.');
return tView.declTNode;
}
else if (tViewType === 1 /* TViewType.Component */) {
// Components don't have `TView.declTNode` because each instance of component could be
// inserted in different location, hence `TView.declTNode` is meaningless.
return lView[T_HOST];
}
return null;
}
/**
* Facade for the attribute injection from DI.
*
* @codeGenApi
*/
function ɵɵinjectAttribute(attrNameToInject) {
return injectAttributeImpl(getCurrentTNode(), attrNameToInject);
}
/**
* Attribute decorator and metadata.
*
* @Annotation
* @publicApi
*/
const Attribute = makeParamDecorator('Attribute', (attributeName) => ({ attributeName, __NG_ELEMENT_ID__: () => ɵɵinjectAttribute(attributeName) }));
let _reflect = null;
function getReflect() {
return (_reflect = _reflect || new ReflectionCapabilities());
}
function reflectDependencies(type) {
return convertDependencies(getReflect().parameters(type));
}
function convertDependencies(deps) {
return deps.map(dep => reflectDependency(dep));
}
function reflectDependency(dep) {
const meta = {
token: null,
attribute: null,
host: false,
optional: false,
self: false,
skipSelf: false,
};
if (Array.isArray(dep) && dep.length > 0) {
for (let j = 0; j < dep.length; j++) {
const param = dep[j];
if (param === undefined) {
// param may be undefined if type of dep is not set by ngtsc
continue;
}
const proto = Object.getPrototypeOf(param);
if (param instanceof Optional || proto.ngMetadataName === 'Optional') {
meta.optional = true;
}
else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') {
meta.skipSelf = true;
}
else if (param instanceof Self || proto.ngMetadataName === 'Self') {
meta.self = true;
}
else if (param instanceof Host || 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 RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Attribute name must be defined.`);
}
meta.attribute = param.attributeName;
}
else {
meta.token = param;
}
}
}
else if (dep === undefined || (Array.isArray(dep) && dep.length === 0)) {
meta.token = null;
}
else {
meta.token = dep;
}
return meta;
}
/**
* Map of module-id to the corresponding NgModule.
*/
const modules = new Map();
/**
* Whether to check for duplicate NgModule registrations.
*
* This can be disabled for testing.
*/
let checkForDuplicateNgModules = true;
function assertSameOrNotExisting(id, type, incoming) {
if (type && type !== incoming && checkForDuplicateNgModules) {
throw new Error(`Duplicate module registered for ${id} - ${stringify(type)} vs ${stringify(type.name)}`);
}
}
/**
* Adds the given NgModule type to Angular's NgModule registry.
*
* This is generated as a side-effect of NgModule compilation. Note that the `id` is passed in
* explicitly and not read from the NgModule definition. This is for two reasons: it avoids a
* megamorphic read, and in JIT there's a chicken-and-egg problem where the NgModule may not be
* fully resolved when it's registered.
*
* @codeGenApi
*/
function registerNgModuleType(ngModuleType, id) {
const existing = modules.get(id) || null;
assertSameOrNotExisting(id, existing, ngModuleType);
modules.set(id, ngModuleType);
}
function clearModulesForTest() {
modules.clear();
}
function getRegisteredNgModuleType(id) {
return modules.get(id);
}
/**
* Control whether the NgModule registration system enforces that each NgModule type registered has
* a unique id.
*
* This is useful for testing as the NgModule registry cannot be properly reset between tests with
* Angular's current API.
*/
function setAllowDuplicateNgModuleIdsForTest(allowDuplicates) {
checkForDuplicateNgModules = !allowDuplicates;
}
/**
* 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 an additional level of type safety.
*
*
*
* **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the
* provider and the injection call. Creating a new instance of `InjectionToken` in different places,
* even with the same description, will be treated as different tokens by Angular's DI system,
* leading to a `NullInjectorError`.
*
*
*
*
*
* 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`](api/core/inject) function.
* As you can see in the Tree-shakable InjectionToken example below.
*
* 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` (note:
* this option is now deprecated). As mentioned above, `'root'` is the default value for
* `providedIn`.
*
* The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.
*
* @usageNotes
* ### Basic Examples
*
* ### Plain InjectionToken
*
* {@example core/di/ts/injector_spec.ts region='InjectionToken'}
*
* ### Tree-shakable InjectionToken
*
* {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
*
* @publicApi
*/
class InjectionToken {
/**
* @param _desc Description for the token,
* used only for debugging purposes,
* it should but does not need to be unique
* @param options Options for the token's usage, as described above
*/
constructor(_desc, options) {
this._desc = _desc;
/** @internal */
this.ngMetadataName = 'InjectionToken';
this.ɵprov = undefined;
if (typeof options == 'number') {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
assertLessThan(options, 0, 'Only negative numbers are supported here');
// This is a special hack to assign __NG_ELEMENT_ID__ to this instance.
// See `InjectorMarkers`
this.__NG_ELEMENT_ID__ = options;
}
else if (options !== undefined) {
this.ɵprov = ɵɵdefineInjectable({
token: this,
providedIn: options.providedIn || 'root',
factory: options.factory,
});
}
}
/**
* @internal
*/
get multi() {
return this;
}
toString() {
return `InjectionToken ${this._desc}`;
}
}
/**
* Most of the use of `document` in Angular is from within the DI system so it is possible to simply
* inject the `DOCUMENT` token and are done.
*
* Ivy is special because it does not rely upon the DI and must get hold of the document some other
* way.
*
* The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy.
* Wherever ivy needs the global document, it calls `getDocument()` instead.
*
* When running ivy outside of a browser environment, it is necessary to call `setDocument()` to
* tell ivy what the global `document` is.
*
* Angular does this for us in each of the standard platforms (`Browser` and `Server`)
* by calling `setDocument()` when providing the `DOCUMENT` token.
*/
let DOCUMENT = undefined;
/**
* Tell ivy what the `document` is for this platform.
*
* It is only necessary to call this if the current platform is not a browser.
*
* @param document The object representing the global `document` in this environment.
*/
function setDocument(document) {
DOCUMENT = document;
}
/**
* Access the object that represents the `document` for this platform.
*
* Ivy calls this whenever it needs to access the `document` object.
* For example to create the renderer or to do sanitization.
*/
function getDocument() {
if (DOCUMENT !== undefined) {
return DOCUMENT;
}
else if (typeof document !== 'undefined') {
return document;
}
throw new RuntimeError(210 /* RuntimeErrorCode.MISSING_DOCUMENT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
`The document object is not available in this context. Make sure the DOCUMENT injection token is provided.`);
// No "document" can be found. This should only happen if we are running ivy outside Angular and
// the current platform is not a browser. Since this is not a supported scenario at the moment
// this should not happen in Angular apps.
// Once we support running ivy outside of Angular we will need to publish `setDocument()` as a
// public API.
}
/**
* A [DI token](guide/glossary#di-token "DI token definition") representing a string ID, used
* primarily for prefixing application attributes and CSS styles when
* {@link ViewEncapsulation#Emulated} is being used.
*
* The token is needed in cases when multiple applications are bootstrapped on a page
* (for example, using `bootstrapApplication` calls). In this case, ensure that those applications
* have different `APP_ID` value setup. For example:
*
* ```
* bootstrapApplication(ComponentA, {
* providers: [
* { provide: APP_ID, useValue: 'app-a' },
* // ... other providers ...
* ]
* });
*
* bootstrapApplication(ComponentB, {
* providers: [
* { provide: APP_ID, useValue: 'app-b' },
* // ... other providers ...
* ]
* });
* ```
*
* By default, when there is only one application bootstrapped, you don't need to provide the
* `APP_ID` token (the `ng` will be used as an app ID).
*
* @publicApi
*/
const APP_ID = new InjectionToken('AppId', {
providedIn: 'root',
factory: () => DEFAULT_APP_ID,
});
/** Default value of the `APP_ID` token. */
const DEFAULT_APP_ID = 'ng';
/**
* A function that is executed when a platform is initialized.
* @publicApi
*/
const PLATFORM_INITIALIZER = new InjectionToken('Platform Initializer');
/**
* A token that indicates an opaque platform ID.
* @publicApi
*/
const PLATFORM_ID = new InjectionToken('Platform ID', {
providedIn: 'platform',
factory: () => 'unknown', // set a default platform name, when none set explicitly
});
/**
* A [DI token](guide/glossary#di-token "DI token definition") that indicates the root directory of
* the application
* @publicApi
* @deprecated
*/
const PACKAGE_ROOT_URL = new InjectionToken('Application Packages Root URL');
// We keep this token here, rather than the animations package, so that modules that only care
// about which animations module is loaded (e.g. the CDK) can retrieve it without having to
// include extra dependencies. See #44970 for more context.
/**
* A [DI token](guide/glossary#di-token "DI token definition") that indicates which animations
* module has been loaded.
* @publicApi
*/
const ANIMATION_MODULE_TYPE = new InjectionToken('AnimationModuleType');
// TODO(crisbeto): link to CSP guide here.
/**
* Token used to configure the [Content Security Policy](https://web.dev/strict-csp/) nonce that
* Angular will apply when inserting inline styles. If not provided, Angular will look up its value
* from the `ngCspNonce` attribute of the application root node.
*
* @publicApi
*/
const CSP_NONCE = new InjectionToken('CSP nonce', {
providedIn: 'root',
factory: () => {
// Ideally we wouldn't have to use `querySelector` here since we know that the nonce will be on
// the root node, but because the token value is used in renderers, it has to be available
// *very* early in the bootstrapping process. This should be a fairly shallow search, because
// the app won't have been added to the DOM yet. Some approaches that were considered:
// 1. Find the root node through `ApplicationRef.components[i].location` - normally this would
// be enough for our purposes, but the token is injected very early so the `components` array
// isn't populated yet.
// 2. Find the root `LView` through the current `LView` - renderers are a prerequisite to
// creating the `LView`. This means that no `LView` will have been entered when this factory is
// invoked for the root component.
// 3. Have the token factory return `() => string` which is invoked when a nonce is requested -
// the slightly later execution does allow us to get an `LView` reference, but the fact that
// it is a function means that it could be executed at *any* time (including immediately) which
// may lead to weird bugs.
// 4. Have the `ComponentFactory` read the attribute and provide it to the injector under the
// hood - has the same problem as #1 and #2 in that the renderer is used to query for the root
// node and the nonce value needs to be available when the renderer is created.
return getDocument().body?.querySelector('[ngCspNonce]')?.getAttribute('ngCspNonce') || null;
},
});
/**
* Internal token to collect all SSR-related features enabled for this application.
*
* Note: the token is in `core` to let other packages register features (the `core`
* package is imported in other packages).
*/
const ENABLED_SSR_FEATURES = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'ENABLED_SSR_FEATURES' : '', {
providedIn: 'root',
factory: () => new Set(),
});
/**
* A multi-provider token for initialization functions that will run upon construction of an
* environment injector.
*
* @publicApi
*/
const ENVIRONMENT_INITIALIZER = new InjectionToken('ENVIRONMENT_INITIALIZER');
/**
* 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
*/
const INJECTOR = new InjectionToken('INJECTOR',
// Disable tslint because this is const enum which gets inlined not top level prop access.
// tslint:disable-next-line: no-toplevel-property-access
-1 /* InjectorMarkers.Injector */);
const INJECTOR_DEF_TYPES = new InjectionToken('INJECTOR_DEF_TYPES');
class NullInjector {
get(token, notFoundValue = THROW_IF_NOT_FOUND) {
if (notFoundValue === THROW_IF_NOT_FOUND) {
const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
error.name = 'NullInjectorError';
throw error;
}
return notFoundValue;
}
}
/**
* Wrap an array of `Provider`s into `EnvironmentProviders`, preventing them from being accidentally
* referenced in `@Component` in a component injector.
*/
function makeEnvironmentProviders(providers) {
return {
ɵproviders: providers,
};
}
/**
* Collects providers from all NgModules and standalone components, including transitively imported
* ones.
*
* Providers extracted via `importProvidersFrom` are only usable in an application injector or
* another environment injector (such as a route injector). They should not be used in component
* providers.
*
* More information about standalone components can be found in [this
* guide](guide/standalone-components).
*
* @usageNotes
* The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call:
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* importProvidersFrom(NgModuleOne, NgModuleTwo)
* ]
* });
* ```
*
* You can also use the `importProvidersFrom` results in the `providers` field of a route, when a
* standalone component is used:
*
* ```typescript
* export const ROUTES: Route[] = [
* {
* path: 'foo',
* providers: [
* importProvidersFrom(NgModuleOne, NgModuleTwo)
* ],
* component: YourStandaloneComponent
* }
* ];
* ```
*
* @returns Collected providers from the specified list of types.
* @publicApi
*/
function importProvidersFrom(...sources) {
return {
ɵproviders: internalImportProvidersFrom(true, sources),
ɵfromNgModule: true,
};
}
function internalImportProvidersFrom(checkForStandaloneCmp, ...sources) {
const providersOut = [];
const dedup = new Set(); // already seen types
let injectorTypesWithProviders;
const collectProviders = (provider) => {
providersOut.push(provider);
};
deepForEach(sources, source => {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && checkForStandaloneCmp) {
const cmpDef = getComponentDef$1(source);
if (cmpDef?.standalone) {
throw new RuntimeError(800 /* RuntimeErrorCode.IMPORT_PROVIDERS_FROM_STANDALONE */, `Importing providers supports NgModule or ModuleWithProviders but got a standalone component "${stringifyForError(source)}"`);
}
}
// Narrow `source` to access the internal type analogue for `ModuleWithProviders`.
const internalSource = source;
if (walkProviderTree(internalSource, collectProviders, [], dedup)) {
injectorTypesWithProviders ||= [];
injectorTypesWithProviders.push(internalSource);
}
});
// Collect all providers from `ModuleWithProviders` types.
if (injectorTypesWithProviders !== undefined) {
processInjectorTypesWithProviders(injectorTypesWithProviders, collectProviders);
}
return providersOut;
}
/**
* Collects all providers from the list of `ModuleWithProviders` and appends them to the provided
* array.
*/
function processInjectorTypesWithProviders(typesWithProviders, visitor) {
for (let i = 0; i < typesWithProviders.length; i++) {
const { ngModule, providers } = typesWithProviders[i];
deepForEachProvider(providers, provider => {
ngDevMode && validateProvider(provider, providers || EMPTY_ARRAY, ngModule);
visitor(provider, ngModule);
});
}
}
/**
* The logic visits an `InjectorType`, an `InjectorTypeWithProviders`, or a standalone
* `ComponentType`, and all of its transitive providers and collects providers.
*
* If an `InjectorTypeWithProviders` that declares providers besides the type is specified,
* the function will return "true" to indicate that the providers of the type definition need
* to be processed. This allows us to process providers of injector types after all imports of
* an injector definition are processed. (following View Engine semantics: see FW-1349)
*/
function walkProviderTree(container, visitor, parents, dedup) {
container = resolveForwardRef(container);
if (!container)
return false;
// The actual type which had the definition. Usually `container`, but may be an unwrapped type
// from `InjectorTypeWithProviders`.
let defType = null;
let injDef = getInjectorDef(container);
const cmpDef = !injDef && getComponentDef$1(container);
if (!injDef && !cmpDef) {
// `container` is not an injector type or a component type. It might be:
// * An `InjectorTypeWithProviders` that wraps an injector type.
// * A standalone directive or pipe that got pulled in from a standalone component's
// dependencies.
// Try to unwrap it as an `InjectorTypeWithProviders` first.
const ngModule = container.ngModule;
injDef = getInjectorDef(ngModule);
if (injDef) {
defType = ngModule;
}
else {
// Not a component or injector type, so ignore it.
return false;
}
}
else if (cmpDef && !cmpDef.standalone) {
return false;
}
else {
defType = container;
}
// Check for circular dependencies.
if (ngDevMode && parents.indexOf(defType) !== -1) {
const defName = stringify(defType);
const path = parents.map(stringify);
throwCyclicDependencyError(defName, path);
}
// Check for multiple imports of the same module
const isDuplicate = dedup.has(defType);
if (cmpDef) {
if (isDuplicate) {
// This component definition has already been processed.
return false;
}
dedup.add(defType);
if (cmpDef.dependencies) {
const deps = typeof cmpDef.dependencies === 'function' ? cmpDef.dependencies() : cmpDef.dependencies;
for (const dep of deps) {
walkProviderTree(dep, visitor, parents, dedup);
}
}
}
else if (injDef) {
// First, include providers from any imports.
if (injDef.imports != null && !isDuplicate) {
// Before processing defType's imports, add it to the set of parents. This way, if it ends
// up deeply importing itself, this can be detected.
ngDevMode && parents.push(defType);
// Add it to the set of dedups. This way we can detect multiple imports of the same module
dedup.add(defType);
let importTypesWithProviders;
try {
deepForEach(injDef.imports, imported => {
if (walkProviderTree(imported, visitor, parents, dedup)) {
importTypesWithProviders ||= [];
// If the processed import is an injector type with providers, we store it in the
// list of import types with providers, so that we can process those afterwards.
importTypesWithProviders.push(imported);
}
});
}
finally {
// Remove it from the parents set when finished.
ngDevMode && parents.pop();
}
// Imports which are declared with providers (TypeWithProviders) need to be processed
// after all imported modules are processed. This is similar to how View Engine
// processes/merges module imports in the metadata resolver. See: FW-1349.
if (importTypesWithProviders !== undefined) {
processInjectorTypesWithProviders(importTypesWithProviders, visitor);
}
}
if (!isDuplicate) {
// Track the InjectorType and add a provider for it.
// It's important that this is done after the def's imports.
const factory = getFactoryDef(defType) || (() => new defType());
// Append extra providers to make more info available for consumers (to retrieve an injector
// type), as well as internally (to calculate an injection scope correctly and eagerly
// instantiate a `defType` when an injector is created).
// Provider to create `defType` using its factory.
visitor({ provide: defType, useFactory: factory, deps: EMPTY_ARRAY }, defType);
// Make this `defType` available to an internal logic that calculates injector scope.
visitor({ provide: INJECTOR_DEF_TYPES, useValue: defType, multi: true }, defType);
// Provider to eagerly instantiate `defType` via `INJECTOR_INITIALIZER`.
visitor({ provide: ENVIRONMENT_INITIALIZER, useValue: () => ɵɵinject(defType), multi: true }, defType);
}
// Next, include providers listed on the definition itself.
const defProviders = injDef.providers;
if (defProviders != null && !isDuplicate) {
const injectorType = container;
deepForEachProvider(defProviders, provider => {
ngDevMode && validateProvider(provider, defProviders, injectorType);
visitor(provider, injectorType);
});
}
}
else {
// Should not happen, but just in case.
return false;
}
return (defType !== container &&
container.providers !== undefined);
}
function validateProvider(provider, providers, containerType) {
if (isTypeProvider(provider) || isValueProvider(provider) || isFactoryProvider(provider) ||
isExistingProvider(provider)) {
return;
}
// Here we expect the provider to be a `useClass` provider (by elimination).
const classRef = resolveForwardRef(provider && (provider.useClass || provider.provide));
if (!classRef) {
throwInvalidProviderError(containerType, providers, provider);
}
}
function deepForEachProvider(providers, fn) {
for (let provider of providers) {
if (isEnvironmentProviders(provider)) {
provider = provider.ɵproviders;
}
if (Array.isArray(provider)) {
deepForEachProvider(provider, fn);
}
else {
fn(provider);
}
}
}
const USE_VALUE$1 = getClosureSafeProperty({ provide: String, useValue: getClosureSafeProperty });
function isValueProvider(value) {
return value !== null && typeof value == 'object' && USE_VALUE$1 in value;
}
function isExistingProvider(value) {
return !!(value && value.useExisting);
}
function isFactoryProvider(value) {
return !!(value && value.useFactory);
}
function isTypeProvider(value) {
return typeof value === 'function';
}
function isClassProvider(value) {
return !!value.useClass;
}
/**
* An internal token whose presence in an injector indicates that the injector should treat itself
* as a root scoped injector when processing requests for unknown tokens which may indicate
* they are provided in the root scope.
*/
const INJECTOR_SCOPE = new InjectionToken('Set Injector scope.');
/**
* Marker which indicates that a value has not yet been created from the factory function.
*/
const NOT_YET = {};
/**
* Marker which indicates that the factory function for a token is in the process of being called.
*
* If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
* injection of a dependency has recursively attempted to inject the original token, and there is
* a circular dependency among the providers.
*/
const CIRCULAR = {};
/**
* A lazily initialized NullInjector.
*/
let NULL_INJECTOR = undefined;
function getNullInjector() {
if (NULL_INJECTOR === undefined) {
NULL_INJECTOR = new NullInjector();
}
return NULL_INJECTOR;
}
/**
* An `Injector` that's part of the environment injector hierarchy, which exists outside of the
* component tree.
*/
class EnvironmentInjector {
}
class R3Injector extends EnvironmentInjector {
/**
* Flag indicating that this injector was previously destroyed.
*/
get destroyed() {
return this._destroyed;
}
constructor(providers, parent, source, scopes) {
super();
this.parent = parent;
this.source = source;
this.scopes = scopes;
/**
* Map of tokens to records which contain the instances of those tokens.
* - `null` value implies that we don't have the record. Used by tree-shakable injectors
* to prevent further searches.
*/
this.records = new Map();
/**
* Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
*/
this._ngOnDestroyHooks = new Set();
this._onDestroyHooks = [];
this._destroyed = false;
// Start off by creating Records for every provider.
forEachSingleProvider(providers, provider => this.processProvider(provider));
// Make sure the INJECTOR token provides this injector.
this.records.set(INJECTOR, makeRecord(undefined, this));
// And `EnvironmentInjector` if the current injector is supposed to be env-scoped.
if (scopes.has('environment')) {
this.records.set(EnvironmentInjector, makeRecord(undefined, this));
}
// Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
// any injectable scoped to APP_ROOT_SCOPE.
const record = this.records.get(INJECTOR_SCOPE);
if (record != null && typeof record.value === 'string') {
this.scopes.add(record.value);
}
this.injectorDefTypes =
new Set(this.get(INJECTOR_DEF_TYPES.multi, EMPTY_ARRAY, InjectFlags.Self));
}
/**
* Destroy the injector and release references to every instance or provider associated with it.
*
* Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
* hook was found.
*/
destroy() {
this.assertNotDestroyed();
// Set destroyed = true first, in case lifecycle hooks re-enter destroy().
this._destroyed = true;
try {
// Call all the lifecycle hooks.
for (const service of this._ngOnDestroyHooks) {
service.ngOnDestroy();
}
const onDestroyHooks = this._onDestroyHooks;
// Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister
// themselves from mutating the array during iteration.
this._onDestroyHooks = [];
for (const hook of onDestroyHooks) {
hook();
}
}
finally {
// Release all references.
this.records.clear();
this._ngOnDestroyHooks.clear();
this.injectorDefTypes.clear();
}
}
onDestroy(callback) {
this.assertNotDestroyed();
this._onDestroyHooks.push(callback);
return () => this.removeOnDestroy(callback);
}
runInContext(fn) {
this.assertNotDestroyed();
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
let prevInjectContext;
if (ngDevMode) {
prevInjectContext = setInjectorProfilerContext({ injector: this, token: null });
}
try {
return fn();
}
finally {
setCurrentInjector(previousInjector);
setInjectImplementation(previousInjectImplementation);
ngDevMode && setInjectorProfilerContext(prevInjectContext);
}
}
get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
this.assertNotDestroyed();
if (token.hasOwnProperty(NG_ENV_ID)) {
return token[NG_ENV_ID](this);
}
flags = convertToBitFlags(flags);
// Set the injection context.
let prevInjectContext;
if (ngDevMode) {
prevInjectContext = setInjectorProfilerContext({ injector: this, token: token });
}
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
try {
// Check for the SkipSelf flag.
if (!(flags & InjectFlags.SkipSelf)) {
// SkipSelf isn't set, check if the record belongs to this injector.
let record = this.records.get(token);
if (record === undefined) {
// No record, but maybe the token is scoped to this injector. Look for an injectable
// def with a scope matching this injector.
const def = couldBeInjectableType(token) && getInjectableDef(token);
if (def && this.injectableDefInScope(def)) {
// Found an injectable def and it's scoped to this injector. Pretend as if it was here
// all along.
record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
}
else {
record = null;
}
this.records.set(token, record);
}
// If a record was found, get the instance for it and return it.
if (record != null /* NOT null || undefined */) {
return this.hydrate(token, record);
}
}
// Select the next injector based on the Self flag - if self is set, the next injector is
// the NullInjector, otherwise it's the parent.
const nextInjector = !(flags & InjectFlags.Self) ? this.parent : getNullInjector();
// Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
// is undefined, the value is null, otherwise it's the notFoundValue.
notFoundValue = (flags & InjectFlags.Optional) && notFoundValue === THROW_IF_NOT_FOUND ?
null :
notFoundValue;
return nextInjector.get(token, notFoundValue);
}
catch (e) {
if (e.name === 'NullInjectorError') {
const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || [];
path.unshift(stringify(token));
if (previousInjector) {
// We still have a parent injector, keep throwing
throw e;
}
else {
// Format & throw the final error message when we don't have any previous injector
return catchInjectorError(e, token, 'R3InjectorError', this.source);
}
}
else {
throw e;
}
}
finally {
// Lastly, restore the previous injection context.
setInjectImplementation(previousInjectImplementation);
setCurrentInjector(previousInjector);
ngDevMode && setInjectorProfilerContext(prevInjectContext);
}
}
/** @internal */
resolveInjectorInitializers() {
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
let prevInjectContext;
if (ngDevMode) {
prevInjectContext = setInjectorProfilerContext({ injector: this, token: null });
}
try {
const initializers = this.get(ENVIRONMENT_INITIALIZER.multi, EMPTY_ARRAY, InjectFlags.Self);
if (ngDevMode && !Array.isArray(initializers)) {
throw new RuntimeError(-209 /* RuntimeErrorCode.INVALID_MULTI_PROVIDER */, 'Unexpected type of the `ENVIRONMENT_INITIALIZER` token value ' +
`(expected an array, but got ${typeof initializers}). ` +
'Please check that the `ENVIRONMENT_INITIALIZER` token is configured as a ' +
'`multi: true` provider.');
}
for (const initializer of initializers) {
initializer();
}
}
finally {
setCurrentInjector(previousInjector);
setInjectImplementation(previousInjectImplementation);
ngDevMode && setInjectorProfilerContext(prevInjectContext);
}
}
toString() {
const tokens = [];
const records = this.records;
for (const token of records.keys()) {
tokens.push(stringify(token));
}
return `R3Injector[${tokens.join(', ')}]`;
}
assertNotDestroyed() {
if (this._destroyed) {
throw new RuntimeError(205 /* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED */, ngDevMode && 'Injector has already been destroyed.');
}
}
/**
* Process a `SingleProvider` and add it.
*/
processProvider(provider) {
// Determine the token from the provider. Either it's its own token, or has a {provide: ...}
// property.
provider = resolveForwardRef(provider);
let token = isTypeProvider(provider) ? provider : resolveForwardRef(provider && provider.provide);
// Construct a `Record` for the provider.
const record = providerToRecord(provider);
if (ngDevMode) {
runInInjectorProfilerContext(this, token, () => {
// Emit InjectorProfilerEventType.Create if provider is a value provider because
// these are the only providers that do not go through the value hydration logic
// where this event would normally be emitted from.
if (isValueProvider(provider)) {
emitInstanceCreatedByInjectorEvent(provider.useValue);
}
emitProviderConfiguredEvent(provider);
});
}
if (!isTypeProvider(provider) && provider.multi === true) {
// If the provider indicates that it's a multi-provider, process it specially.
// First check whether it's been defined already.
let multiRecord = this.records.get(token);
if (multiRecord) {
// It has. Throw a nice error if
if (ngDevMode && multiRecord.multi === undefined) {
throwMixedMultiProviderError();
}
}
else {
multiRecord = makeRecord(undefined, NOT_YET, true);
multiRecord.factory = () => injectArgs(multiRecord.multi);
this.records.set(token, multiRecord);
}
token = provider;
multiRecord.multi.push(provider);
}
else {
const existing = this.records.get(token);
if (ngDevMode && existing && existing.multi !== undefined) {
throwMixedMultiProviderError();
}
}
this.records.set(token, record);
}
hydrate(token, record) {
if (ngDevMode && record.value === CIRCULAR) {
throwCyclicDependencyError(stringify(token));
}
else if (record.value === NOT_YET) {
record.value = CIRCULAR;
if (ngDevMode) {
runInInjectorProfilerContext(this, token, () => {
record.value = record.factory();
emitInstanceCreatedByInjectorEvent(record.value);
});
}
else {
record.value = record.factory();
}
}
if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
this._ngOnDestroyHooks.add(record.value);
}
return record.value;
}
injectableDefInScope(def) {
if (!def.providedIn) {
return false;
}
const providedIn = resolveForwardRef(def.providedIn);
if (typeof providedIn === 'string') {
return providedIn === 'any' || (this.scopes.has(providedIn));
}
else {
return this.injectorDefTypes.has(providedIn);
}
}
removeOnDestroy(callback) {
const destroyCBIdx = this._onDestroyHooks.indexOf(callback);
if (destroyCBIdx !== -1) {
this._onDestroyHooks.splice(destroyCBIdx, 1);
}
}
}
function injectableDefOrInjectorDefFactory(token) {
// Most tokens will have an injectable def directly on them, which specifies a factory directly.
const injectableDef = getInjectableDef(token);
const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
if (factory !== null) {
return factory;
}
// InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
// If it's missing that, it's an error.
if (token instanceof InjectionToken) {
throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Token ${stringify(token)} is missing a ɵprov definition.`);
}
// Undecorated types can sometimes be created if they have no constructor arguments.
if (token instanceof Function) {
return getUndecoratedInjectableFactory(token);
}
// There was no way to resolve a factory for this token.
throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && 'unreachable');
}
function getUndecoratedInjectableFactory(token) {
// If the token has parameters then it has dependencies that we cannot resolve implicitly.
const paramLength = token.length;
if (paramLength > 0) {
const args = newArray(paramLength, '?');
throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, ngDevMode && `Can't resolve all parameters for ${stringify(token)}: (${args.join(', ')}).`);
}
// The constructor function appears to have no parameters.
// This might be because it inherits from a super-class. In which case, use an injectable
// def from an ancestor if there is one.
// Otherwise this really is a simple class with no dependencies, so return a factory that
// just instantiates the zero-arg constructor.
const inheritedInjectableDef = getInheritedInjectableDef(token);
if (inheritedInjectableDef !== null) {
return () => inheritedInjectableDef.factory(token);
}
else {
return () => new token();
}
}
function providerToRecord(provider) {
if (isValueProvider(provider)) {
return makeRecord(undefined, provider.useValue);
}
else {
const factory = providerToFactory(provider);
return makeRecord(factory, NOT_YET);
}
}
/**
* Converts a `SingleProvider` into a factory function.
*
* @param provider provider to convert to factory
*/
function providerToFactory(provider, ngModuleType, providers) {
let factory = undefined;
if (ngDevMode && isEnvironmentProviders(provider)) {
throwInvalidProviderError(undefined, providers, provider);
}
if (isTypeProvider(provider)) {
const unwrappedProvider = resolveForwardRef(provider);
return getFactoryDef(unwrappedProvider) || injectableDefOrInjectorDefFactory(unwrappedProvider);
}
else {
if (isValueProvider(provider)) {
factory = () => resolveForwardRef(provider.useValue);
}
else if (isFactoryProvider(provider)) {
factory = () => provider.useFactory(...injectArgs(provider.deps || []));
}
else if (isExistingProvider(provider)) {
factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));
}
else {
const classRef = resolveForwardRef(provider &&
(provider.useClass || provider.provide));
if (ngDevMode && !classRef) {
throwInvalidProviderError(ngModuleType, providers, provider);
}
if (hasDeps(provider)) {
factory = () => new (classRef)(...injectArgs(provider.deps));
}
else {
return getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef);
}
}
}
return factory;
}
function makeRecord(factory, value, multi = false) {
return {
factory: factory,
value: value,
multi: multi ? [] : undefined,
};
}
function hasDeps(value) {
return !!value.deps;
}
function hasOnDestroy(value) {
return value !== null && typeof value === 'object' &&
typeof value.ngOnDestroy === 'function';
}
function couldBeInjectableType(value) {
return (typeof value === 'function') ||
(typeof value === 'object' && value instanceof InjectionToken);
}
function forEachSingleProvider(providers, fn) {
for (const provider of providers) {
if (Array.isArray(provider)) {
forEachSingleProvider(provider, fn);
}
else if (provider && isEnvironmentProviders(provider)) {
forEachSingleProvider(provider.ɵproviders, fn);
}
else {
fn(provider);
}
}
}
/**
* Runs the given function in the [context](guide/dependency-injection-context) of the given
* `Injector`.
*
* Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies
* from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in
* any asynchronous callbacks or after any `await` points.
*
* @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn`
* is executing
* @param fn the closure to be run in the context of `injector`
* @returns the return value of the function, if any
* @publicApi
*/
function runInInjectionContext(injector, fn) {
if (injector instanceof R3Injector) {
injector.assertNotDestroyed();
}
let prevInjectorProfilerContext;
if (ngDevMode) {
prevInjectorProfilerContext = setInjectorProfilerContext({ injector, token: null });
}
const prevInjector = setCurrentInjector(injector);
const previousInjectImplementation = setInjectImplementation(undefined);
try {
return fn();
}
finally {
setCurrentInjector(prevInjector);
ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext);
setInjectImplementation(previousInjectImplementation);
}
}
/**
* Asserts that the current stack frame is within an [injection
* context](guide/dependency-injection-context) and has access to `inject`.
*
* @param debugFn a reference to the function making the assertion (used for the error message).
*
* @publicApi
*/
function assertInInjectionContext(debugFn) {
// Taking a `Function` instead of a string name here prevents the unminified name of the function
// from being retained in the bundle regardless of minification.
if (!getInjectImplementation() && !getCurrentInjector()) {
throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode &&
(debugFn.name +
'() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`'));
}
}
/**
* 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.
*/
const angularCoreDiEnv = {
'ɵɵdefineInjectable': ɵɵdefineInjectable,
'ɵɵdefineInjector': ɵɵdefineInjector,
'ɵɵinject': ɵɵinject,
'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
'resolveForwardRef': resolveForwardRef,
};
/**
* Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting
* injectable def (`ɵprov`) onto the injectable type.
*/
function compileInjectable(type, meta) {
let ngInjectableDef = null;
let ngFactoryDef = null;
// if NG_PROV_DEF is already defined on this class then don't overwrite it
if (!type.hasOwnProperty(NG_PROV_DEF)) {
Object.defineProperty(type, NG_PROV_DEF, {
get: () => {
if (ngInjectableDef === null) {
const compiler = getCompilerFacade({ usage: 0 /* JitCompilerUsage.Decorator */, kind: 'injectable', type });
ngInjectableDef = compiler.compileInjectable(angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, meta));
}
return ngInjectableDef;
},
});
}
// if NG_FACTORY_DEF is already defined on this class then don't overwrite it
if (!type.hasOwnProperty(NG_FACTORY_DEF)) {
Object.defineProperty(type, NG_FACTORY_DEF, {
get: () => {
if (ngFactoryDef === null) {
const compiler = getCompilerFacade({ usage: 0 /* JitCompilerUsage.Decorator */, kind: 'injectable', type });
ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, {
name: type.name,
type,
typeArgumentCount: 0,
deps: reflectDependencies(type),
target: compiler.FactoryTarget.Injectable
});
}
return ngFactoryDef;
},
// Leave this configurable so that the factories from directives or pipes can take precedence.
configurable: true
});
}
}
const USE_VALUE = getClosureSafeProperty({ provide: String, useValue: getClosureSafeProperty });
function isUseClassProvider(meta) {
return meta.useClass !== undefined;
}
function isUseValueProvider(meta) {
return USE_VALUE in meta;
}
function isUseFactoryProvider(meta) {
return meta.useFactory !== undefined;
}
function isUseExistingProvider(meta) {
return meta.useExisting !== undefined;
}
function getInjectableMetadata(type, srcMeta) {
// Allow the compilation of a class with a `@Injectable()` decorator without parameters
const meta = srcMeta || { providedIn: null };
const compilerMeta = {
name: type.name,
type: type,
typeArgumentCount: 0,
providedIn: meta.providedIn,
};
if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) {
compilerMeta.deps = convertDependencies(meta.deps);
}
// Check to see if the user explicitly provided a `useXxxx` property.
if (isUseClassProvider(meta)) {
compilerMeta.useClass = meta.useClass;
}
else if (isUseValueProvider(meta)) {
compilerMeta.useValue = meta.useValue;
}
else if (isUseFactoryProvider(meta)) {
compilerMeta.useFactory = meta.useFactory;
}
else if (isUseExistingProvider(meta)) {
compilerMeta.useExisting = meta.useExisting;
}
return compilerMeta;
}
/**
* Injectable decorator and metadata.
*
* @Annotation
* @publicApi
*/
const Injectable = makeDecorator('Injectable', undefined, undefined, undefined, (type, meta) => compileInjectable(type, meta));
/**
* Create a new `Injector` which is configured using a `defType` of `InjectorType`s.
*/
function createInjector(defType, parent = null, additionalProviders = null, name) {
const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
injector.resolveInjectorInitializers();
return injector;
}
/**
* Creates a new injector without eagerly resolving its injector types. Can be used in places
* where resolving the injector types immediately can lead to an infinite loop. The injector types
* should be resolved at a later point by calling `_resolveInjectorDefTypes`.
*/
function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name, scopes = new Set()) {
const providers = [
additionalProviders || EMPTY_ARRAY,
importProvidersFrom(defType),
];
name = name || (typeof defType === 'object' ? undefined : stringify(defType));
return new R3Injector(providers, parent || getNullInjector(), name || null, scopes);
}
/**
* Concrete injectors implement this interface. Injectors are configured
* with [providers](guide/glossary#provider) that associate
* dependencies of various types with [injection tokens](guide/glossary#di-token).
*
* @see ["DI Providers"](guide/dependency-injection-providers).
* @see {@link StaticProvider}
*
* @usageNotes
*
* The following example creates a service injector instance.
*
* {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
*
* ### Usage example
*
* {@example core/di/ts/injector_spec.ts region='Injector'}
*
* `Injector` returns itself when given `Injector` as a token:
*
* {@example core/di/ts/injector_spec.ts region='injectInjector'}
*
* @publicApi
*/
class Injector {
static { this.THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND; }
static { this.NULL = ( /* @__PURE__ */new NullInjector()); }
static create(options, parent) {
if (Array.isArray(options)) {
return createInjector({ name: '' }, parent, options, '');
}
else {
const name = options.name ?? '';
return createInjector({ name }, options.parent, options.providers, name);
}
}
/** @nocollapse */
static { this.ɵprov = ɵɵdefineInjectable({
token: Injector,
providedIn: 'any',
factory: () => ɵɵinject(INJECTOR),
}); }
/**
* @internal
* @nocollapse
*/
static { this.__NG_ELEMENT_ID__ = -1 /* InjectorMarkers.Injector */; }
}
/**
* @module
* @description
* The `di` module provides dependency injection container services.
*/
/**
* This file should not be necessary because node resolution should just default to `./di/index`!
*
* However it does not seem to work and it breaks:
* - //packages/animations/browser/test:test_web_chromium-local
* - //packages/compiler-cli/test:extract_i18n
* - //packages/compiler-cli/test:ngc
* - //packages/compiler-cli/test:perform_watch
* - //packages/compiler-cli/test/diagnostics:check_types
* - //packages/compiler-cli/test/transformers:test
* - //packages/compiler/test:test
* - //tools/public_api_guard:core_api
*
* Remove this file once the above is solved or wait until `ngc` is deleted and then it should be
* safe to delete this file.
*/
/**
*
* @codeGenApi
*/
function ɵɵresolveWindow(element) {
return element.ownerDocument.defaultView;
}
/**
*
* @codeGenApi
*/
function ɵɵresolveDocument(element) {
return element.ownerDocument;
}
/**
*
* @codeGenApi
*/
function ɵɵresolveBody(element) {
return element.ownerDocument.body;
}
/**
* The special delimiter we use to separate property names, prefixes, and suffixes
* in property binding metadata. See storeBindingMetadata().
*
* We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
* because it is a very uncommon character that is unlikely to be part of a user's
* property names or interpolation strings. If it is in fact used in a property
* binding, DebugElement.properties will not return the correct value for that
* binding. However, there should be no runtime effect for real applications.
*
* This character is typically rendered as a question mark inside of a diamond.
* See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
*
*/
const INTERPOLATION_DELIMITER = `�`;
/**
* Unwrap a value which might be behind a closure (for forward declaration reasons).
*/
function maybeUnwrapFn$1(value) {
if (value instanceof Function) {
return value();
}
else {
return value;
}
}
/**
* Detects whether the code is invoked in a browser.
* Later on, this check should be replaced with a tree-shakable
* flag (e.g. `!isServer`).
*/
function isPlatformBrowser(injector) {
return (injector ?? inject$1(Injector)).get(PLATFORM_ID) === 'browser';
}
/**
* Defines a schema that allows an NgModule to contain the following:
* - Non-Angular elements named with dash case (`-`).
* - Element properties named with dash case (`-`).
* Dash case is the naming convention for custom elements.
*
* @publicApi
*/
const CUSTOM_ELEMENTS_SCHEMA = {
name: 'custom-elements'
};
/**
* Defines a schema that allows any property on any element.
*
* This schema allows you to ignore the errors related to any unknown elements or properties in a
* template. The usage of this schema is generally discouraged because it prevents useful validation
* and may hide real errors in your template. Consider using the `CUSTOM_ELEMENTS_SCHEMA` instead.
*
* @publicApi
*/
const NO_ERRORS_SCHEMA = {
name: 'no-errors-schema'
};
let shouldThrowErrorOnUnknownElement = false;
/**
* Sets a strict mode for JIT-compiled components to throw an error on unknown elements,
* instead of just logging the error.
* (for AOT-compiled ones this check happens at build time).
*/
function ɵsetUnknownElementStrictMode(shouldThrow) {
shouldThrowErrorOnUnknownElement = shouldThrow;
}
/**
* Gets the current value of the strict mode.
*/
function ɵgetUnknownElementStrictMode() {
return shouldThrowErrorOnUnknownElement;
}
let shouldThrowErrorOnUnknownProperty = false;
/**
* Sets a strict mode for JIT-compiled components to throw an error on unknown properties,
* instead of just logging the error.
* (for AOT-compiled ones this check happens at build time).
*/
function ɵsetUnknownPropertyStrictMode(shouldThrow) {
shouldThrowErrorOnUnknownProperty = shouldThrow;
}
/**
* Gets the current value of the strict mode.
*/
function ɵgetUnknownPropertyStrictMode() {
return shouldThrowErrorOnUnknownProperty;
}
/**
* Validates that the element is known at runtime and produces
* an error if it's not the case.
* This check is relevant for JIT-compiled components (for AOT-compiled
* ones this check happens at build time).
*
* The element is considered known if either:
* - it's a known HTML element
* - it's a known custom element
* - the element matches any directive
* - the element is allowed by one of the schemas
*
* @param element Element to validate
* @param lView An `LView` that represents a current component that is being rendered
* @param tagName Name of the tag to check
* @param schemas Array of schemas
* @param hasDirectives Boolean indicating that the element matches any directive
*/
function validateElementIsKnown(element, lView, tagName, schemas, hasDirectives) {
// If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
// mode where this check happens at compile time. In JIT mode, `schemas` is always present and
// defined as an array (as an empty array in case `schemas` field is not defined) and we should
// execute the check below.
if (schemas === null)
return;
// If the element matches any directive, it's considered as valid.
if (!hasDirectives && tagName !== null) {
// The element is unknown if it's an instance of HTMLUnknownElement, or it isn't registered
// as a custom element. Note that unknown elements with a dash in their name won't be instances
// of HTMLUnknownElement in browsers that support web components.
const isUnknown =
// Note that we can't check for `typeof HTMLUnknownElement === 'function'` because
// Domino doesn't expose HTMLUnknownElement globally.
(typeof HTMLUnknownElement !== 'undefined' && HTMLUnknownElement &&
element instanceof HTMLUnknownElement) ||
(typeof customElements !== 'undefined' && tagName.indexOf('-') > -1 &&
!customElements.get(tagName));
if (isUnknown && !matchingSchemas(schemas, tagName)) {
const isHostStandalone = isHostComponentStandalone(lView);
const templateLocation = getTemplateLocationDetails(lView);
const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
let message = `'${tagName}' is not a known element${templateLocation}:\n`;
message += `1. If '${tagName}' is an Angular component, then verify that it is ${isHostStandalone ? 'included in the \'@Component.imports\' of this component' :
'a part of an @NgModule where this component is declared'}.\n`;
if (tagName && tagName.indexOf('-') > -1) {
message +=
`2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.`;
}
else {
message +=
`2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`;
}
if (shouldThrowErrorOnUnknownElement) {
throw new RuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message);
}
else {
console.error(formatRuntimeError(304 /* RuntimeErrorCode.UNKNOWN_ELEMENT */, message));
}
}
}
}
/**
* Validates that the property of the element is known at runtime and returns
* false if it's not the case.
* This check is relevant for JIT-compiled components (for AOT-compiled
* ones this check happens at build time).
*
* The property is considered known if either:
* - it's a known property of the element
* - the element is allowed by one of the schemas
* - the property is used for animations
*
* @param element Element to validate
* @param propName Name of the property to check
* @param tagName Name of the tag hosting the property
* @param schemas Array of schemas
*/
function isPropertyValid(element, propName, tagName, schemas) {
// If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
// mode where this check happens at compile time. In JIT mode, `schemas` is always present and
// defined as an array (as an empty array in case `schemas` field is not defined) and we should
// execute the check below.
if (schemas === null)
return true;
// The property is considered valid if the element matches the schema, it exists on the element,
// or it is synthetic.
if (matchingSchemas(schemas, tagName) || propName in element || isAnimationProp(propName)) {
return true;
}
// Note: `typeof Node` returns 'function' in most browsers, but is undefined with domino.
return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
}
/**
* Logs or throws an error that a property is not supported on an element.
*
* @param propName Name of the invalid property
* @param tagName Name of the tag hosting the property
* @param nodeType Type of the node hosting the property
* @param lView An `LView` that represents a current component
*/
function handleUnknownPropertyError(propName, tagName, nodeType, lView) {
// Special-case a situation when a structural directive is applied to
// an `` element, for example: ``.
// In this case the compiler generates the `ɵɵtemplate` instruction with
// the `null` as the tagName. The directive matching logic at runtime relies
// on this effect (see `isInlineTemplate`), thus using the 'ng-template' as
// a default value of the `tNode.value` is not feasible at this moment.
if (!tagName && nodeType === 4 /* TNodeType.Container */) {
tagName = 'ng-template';
}
const isHostStandalone = isHostComponentStandalone(lView);
const templateLocation = getTemplateLocationDetails(lView);
let message = `Can't bind to '${propName}' since it isn't a known property of '${tagName}'${templateLocation}.`;
const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
const importLocation = isHostStandalone ?
'included in the \'@Component.imports\' of this component' :
'a part of an @NgModule where this component is declared';
if (KNOWN_CONTROL_FLOW_DIRECTIVES.has(propName)) {
// Most likely this is a control flow directive (such as `*ngIf`) used in
// a template, but the directive or the `CommonModule` is not imported.
const correspondingImport = KNOWN_CONTROL_FLOW_DIRECTIVES.get(propName);
message += `\nIf the '${propName}' is an Angular control flow directive, ` +
`please make sure that either the '${correspondingImport}' directive or the 'CommonModule' is ${importLocation}.`;
}
else {
// May be an Angular component, which is not imported/declared?
message += `\n1. If '${tagName}' is an Angular component and it has the ` +
`'${propName}' input, then verify that it is ${importLocation}.`;
// May be a Web Component?
if (tagName && tagName.indexOf('-') > -1) {
message += `\n2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' ` +
`to the ${schemas} of this component to suppress this message.`;
message += `\n3. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
`the ${schemas} of this component.`;
}
else {
// If it's expected, the error can be suppressed by the `NO_ERRORS_SCHEMA` schema.
message += `\n2. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
`the ${schemas} of this component.`;
}
}
reportUnknownPropertyError(message);
}
function reportUnknownPropertyError(message) {
if (shouldThrowErrorOnUnknownProperty) {
throw new RuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message);
}
else {
console.error(formatRuntimeError(303 /* RuntimeErrorCode.UNKNOWN_BINDING */, message));
}
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode and also it relies on the constructor function being available.
*
* Gets a reference to the host component def (where a current component is declared).
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
function getDeclarationComponentDef(lView) {
!ngDevMode && throwError('Must never be called in production mode');
const declarationLView = lView[DECLARATION_COMPONENT_VIEW];
const context = declarationLView[CONTEXT];
// Unable to obtain a context.
if (!context)
return null;
return context.constructor ? getComponentDef$1(context.constructor) : null;
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode.
*
* Checks if the current component is declared inside of a standalone component template.
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
function isHostComponentStandalone(lView) {
!ngDevMode && throwError('Must never be called in production mode');
const componentDef = getDeclarationComponentDef(lView);
// Treat host component as non-standalone if we can't obtain the def.
return !!componentDef?.standalone;
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode.
*
* Constructs a string describing the location of the host component template. The function is used
* in dev mode to produce error messages.
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
function getTemplateLocationDetails(lView) {
!ngDevMode && throwError('Must never be called in production mode');
const hostComponentDef = getDeclarationComponentDef(lView);
const componentClassName = hostComponentDef?.type?.name;
return componentClassName ? ` (used in the '${componentClassName}' component template)` : '';
}
/**
* The set of known control flow directives and their corresponding imports.
* We use this set to produce a more precises error message with a note
* that the `CommonModule` should also be included.
*/
const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([
['ngIf', 'NgIf'], ['ngFor', 'NgFor'], ['ngSwitchCase', 'NgSwitchCase'],
['ngSwitchDefault', 'NgSwitchDefault']
]);
/**
* Returns true if the tag name is allowed by specified schemas.
* @param schemas Array of schemas
* @param tagName Name of the tag
*/
function matchingSchemas(schemas, tagName) {
if (schemas !== null) {
for (let i = 0; i < schemas.length; i++) {
const schema = schemas[i];
if (schema === NO_ERRORS_SCHEMA ||
schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1) {
return true;
}
}
}
return false;
}
/**
* The name of an attribute that can be added to the hydration boundary node
* (component host node) to disable hydration for the content within that boundary.
*/
const SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration';
/**
* Helper function to check if a given TNode has the 'ngSkipHydration' attribute.
*/
function hasSkipHydrationAttrOnTNode(tNode) {
const SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = SKIP_HYDRATION_ATTR_NAME.toLowerCase();
const attrs = tNode.mergedAttrs;
if (attrs === null)
return false;
// only ever look at the attribute name and skip the values
for (let i = 0; i < attrs.length; i += 2) {
const value = attrs[i];
// This is a marker, which means that the static attributes section is over,
// so we can exit early.
if (typeof value === 'number')
return false;
if (typeof value === 'string' && value.toLowerCase() === SKIP_HYDRATION_ATTR_NAME_LOWER_CASE) {
return true;
}
}
return false;
}
/**
* Helper function to check if a given RElement has the 'ngSkipHydration' attribute.
*/
function hasSkipHydrationAttrOnRElement(rNode) {
return rNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME);
}
/**
* Checks whether a TNode has a flag to indicate that it's a part of
* a skip hydration block.
*/
function hasInSkipHydrationBlockFlag(tNode) {
return (tNode.flags & 128 /* TNodeFlags.inSkipHydrationBlock */) === 128 /* TNodeFlags.inSkipHydrationBlock */;
}
/**
* Helper function that determines if a given node is within a skip hydration block
* by navigating up the TNode tree to see if any parent nodes have skip hydration
* attribute.
*
* TODO(akushnir): this function should contain the logic of `hasInSkipHydrationBlockFlag`,
* there is no need to traverse parent nodes when we have a TNode flag (which would also
* make this lookup O(1)).
*/
function isInSkipHydrationBlock(tNode) {
let currentTNode = tNode.parent;
while (currentTNode) {
if (hasSkipHydrationAttrOnTNode(currentTNode)) {
return true;
}
currentTNode = currentTNode.parent;
}
return false;
}
/**
* Flags for renderer-specific style modifiers.
* @publicApi
*/
var RendererStyleFlags2;
(function (RendererStyleFlags2) {
// TODO(misko): This needs to be refactored into a separate file so that it can be imported from
// `node_manipulation.ts` Currently doing the import cause resolution order to change and fails
// the tests. The work around is to have hard coded value in `node_manipulation.ts` for now.
/**
* Marks a style as important.
*/
RendererStyleFlags2[RendererStyleFlags2["Important"] = 1] = "Important";
/**
* Marks a style as using dash case naming (this-is-dash-case).
*/
RendererStyleFlags2[RendererStyleFlags2["DashCase"] = 2] = "DashCase";
})(RendererStyleFlags2 || (RendererStyleFlags2 = {}));
/**
* Disallowed strings in the comment.
*
* see: https://html.spec.whatwg.org/multipage/syntax.html#comments
*/
const COMMENT_DISALLOWED = /^>|^->||--!>|)/g;
const COMMENT_DELIMITER_ESCAPED = '\u200B$1\u200B';
/**
* Escape the content of comment strings so that it can be safely inserted into a comment node.
*
* The issue is that HTML does not specify any way to escape comment end text inside the comment.
* Consider: `" or
* "--!>" at the end. -->`. Above the `"-->"` is meant to be text not an end to the comment. This
* can be created programmatically through DOM APIs. (`` or `--!>`) the
* text it will render normally but it will not cause the HTML parser to close/open the comment.
*
* @param value text to make safe for comment node by escaping the comment open/close character
* sequence.
*/
function escapeCommentText(value) {
return value.replace(COMMENT_DISALLOWED, (text) => text.replace(COMMENT_DELIMITER, COMMENT_DELIMITER_ESCAPED));
}
// Keeps track of the currently-active LViews.
const TRACKED_LVIEWS = new Map();
// Used for generating unique IDs for LViews.
let uniqueIdCounter = 0;
/** Gets a unique ID that can be assigned to an LView. */
function getUniqueLViewId() {
return uniqueIdCounter++;
}
/** Starts tracking an LView. */
function registerLView(lView) {
ngDevMode && assertNumber(lView[ID], 'LView must have an ID in order to be registered');
TRACKED_LVIEWS.set(lView[ID], lView);
}
/** Gets an LView by its unique ID. */
function getLViewById(id) {
ngDevMode && assertNumber(id, 'ID used for LView lookup must be a number');
return TRACKED_LVIEWS.get(id) || null;
}
/** Stops tracking an LView. */
function unregisterLView(lView) {
ngDevMode && assertNumber(lView[ID], 'Cannot stop tracking an LView that does not have an ID');
TRACKED_LVIEWS.delete(lView[ID]);
}
/**
* The internal view context which is specific to a given DOM element, directive or
* component instance. Each value in here (besides the LView and element node details)
* can be present, null or undefined. If undefined then it implies the value has not been
* looked up yet, otherwise, if null, then a lookup was executed and nothing was found.
*
* Each value will get filled when the respective value is examined within the getContext
* function. The component, element and each directive instance will share the same instance
* of the context.
*/
class LContext {
/** Component's parent view data. */
get lView() {
return getLViewById(this.lViewId);
}
constructor(
/**
* ID of the component's parent view data.
*/
lViewId,
/**
* The index instance of the node.
*/
nodeIndex,
/**
* The instance of the DOM node that is attached to the lNode.
*/
native) {
this.lViewId = lViewId;
this.nodeIndex = nodeIndex;
this.native = native;
}
}
/**
* Returns the matching `LContext` data for a given DOM node, directive or component instance.
*
* This function will examine the provided DOM element, component, or directive instance\'s
* monkey-patched property to derive the `LContext` data. Once called then the monkey-patched
* value will be that of the newly created `LContext`.
*
* If the monkey-patched value is the `LView` instance then the context value for that
* target will be created and the monkey-patch reference will be updated. Therefore when this
* function is called it may mutate the provided element\'s, component\'s or any of the associated
* directive\'s monkey-patch values.
*
* If the monkey-patch value is not detected then the code will walk up the DOM until an element
* is found which contains a monkey-patch reference. When that occurs then the provided element
* will be updated with a new context (which is then returned). If the monkey-patch value is not
* detected for a component/directive instance then it will throw an error (all components and
* directives should be automatically monkey-patched by ivy).
*
* @param target Component, Directive or DOM Node.
*/
function getLContext(target) {
let mpValue = readPatchedData(target);
if (mpValue) {
// only when it's an array is it considered an LView instance
// ... otherwise it's an already constructed LContext instance
if (isLView(mpValue)) {
const lView = mpValue;
let nodeIndex;
let component = undefined;
let directives = undefined;
if (isComponentInstance(target)) {
nodeIndex = findViaComponent(lView, target);
if (nodeIndex == -1) {
throw new Error('The provided component was not found in the application');
}
component = target;
}
else if (isDirectiveInstance(target)) {
nodeIndex = findViaDirective(lView, target);
if (nodeIndex == -1) {
throw new Error('The provided directive was not found in the application');
}
directives = getDirectivesAtNodeIndex(nodeIndex, lView);
}
else {
nodeIndex = findViaNativeElement(lView, target);
if (nodeIndex == -1) {
return null;
}
}
// the goal is not to fill the entire context full of data because the lookups
// are expensive. Instead, only the target data (the element, component, container, ICU
// expression or directive details) are filled into the context. If called multiple times
// with different target values then the missing target data will be filled in.
const native = unwrapRNode(lView[nodeIndex]);
const existingCtx = readPatchedData(native);
const context = (existingCtx && !Array.isArray(existingCtx)) ?
existingCtx :
createLContext(lView, nodeIndex, native);
// only when the component has been discovered then update the monkey-patch
if (component && context.component === undefined) {
context.component = component;
attachPatchData(context.component, context);
}
// only when the directives have been discovered then update the monkey-patch
if (directives && context.directives === undefined) {
context.directives = directives;
for (let i = 0; i < directives.length; i++) {
attachPatchData(directives[i], context);
}
}
attachPatchData(context.native, context);
mpValue = context;
}
}
else {
const rElement = target;
ngDevMode && assertDomNode(rElement);
// if the context is not found then we need to traverse upwards up the DOM
// to find the nearest element that has already been monkey patched with data
let parent = rElement;
while (parent = parent.parentNode) {
const parentContext = readPatchedData(parent);
if (parentContext) {
const lView = Array.isArray(parentContext) ? parentContext : parentContext.lView;
// the edge of the app was also reached here through another means
// (maybe because the DOM was changed manually).
if (!lView) {
return null;
}
const index = findViaNativeElement(lView, rElement);
if (index >= 0) {
const native = unwrapRNode(lView[index]);
const context = createLContext(lView, index, native);
attachPatchData(native, context);
mpValue = context;
break;
}
}
}
}
return mpValue || null;
}
/**
* Creates an empty instance of a `LContext` context
*/
function createLContext(lView, nodeIndex, native) {
return new LContext(lView[ID], nodeIndex, native);
}
/**
* Takes a component instance and returns the view for that component.
*
* @param componentInstance
* @returns The component's view
*/
function getComponentViewByInstance(componentInstance) {
let patchedData = readPatchedData(componentInstance);
let lView;
if (isLView(patchedData)) {
const contextLView = patchedData;
const nodeIndex = findViaComponent(contextLView, componentInstance);
lView = getComponentLViewByIndex(nodeIndex, contextLView);
const context = createLContext(contextLView, nodeIndex, lView[HOST]);
context.component = componentInstance;
attachPatchData(componentInstance, context);
attachPatchData(context.native, context);
}
else {
const context = patchedData;
const contextLView = context.lView;
ngDevMode && assertLView(contextLView);
lView = getComponentLViewByIndex(context.nodeIndex, contextLView);
}
return lView;
}
/**
* This property will be monkey-patched on elements, components and directives.
*/
const MONKEY_PATCH_KEY_NAME = '__ngContext__';
/**
* Assigns the given data to the given target (which could be a component,
* directive or DOM node instance) using monkey-patching.
*/
function attachPatchData(target, data) {
ngDevMode && assertDefined(target, 'Target expected');
// Only attach the ID of the view in order to avoid memory leaks (see #41047). We only do this
// for `LView`, because we have control over when an `LView` is created and destroyed, whereas
// we can't know when to remove an `LContext`.
if (isLView(data)) {
target[MONKEY_PATCH_KEY_NAME] = data[ID];
registerLView(data);
}
else {
target[MONKEY_PATCH_KEY_NAME] = data;
}
}
/**
* Returns the monkey-patch value data present on the target (which could be
* a component, directive or a DOM node).
*/
function readPatchedData(target) {
ngDevMode && assertDefined(target, 'Target expected');
const data = target[MONKEY_PATCH_KEY_NAME];
return (typeof data === 'number') ? getLViewById(data) : data || null;
}
function readPatchedLView(target) {
const value = readPatchedData(target);
if (value) {
return (isLView(value) ? value : value.lView);
}
return null;
}
function isComponentInstance(instance) {
return instance && instance.constructor && instance.constructor.ɵcmp;
}
function isDirectiveInstance(instance) {
return instance && instance.constructor && instance.constructor.ɵdir;
}
/**
* Locates the element within the given LView and returns the matching index
*/
function findViaNativeElement(lView, target) {
const tView = lView[TVIEW];
for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) {
if (unwrapRNode(lView[i]) === target) {
return i;
}
}
return -1;
}
/**
* Locates the next tNode (child, sibling or parent).
*/
function traverseNextElement(tNode) {
if (tNode.child) {
return tNode.child;
}
else if (tNode.next) {
return tNode.next;
}
else {
// Let's take the following template: text
// After checking the text node, we need to find the next parent that has a "next" TNode,
// in this case the parent `div`, so that we can find the component.
while (tNode.parent && !tNode.parent.next) {
tNode = tNode.parent;
}
return tNode.parent && tNode.parent.next;
}
}
/**
* Locates the component within the given LView and returns the matching index
*/
function findViaComponent(lView, componentInstance) {
const componentIndices = lView[TVIEW].components;
if (componentIndices) {
for (let i = 0; i < componentIndices.length; i++) {
const elementComponentIndex = componentIndices[i];
const componentView = getComponentLViewByIndex(elementComponentIndex, lView);
if (componentView[CONTEXT] === componentInstance) {
return elementComponentIndex;
}
}
}
else {
const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView);
const rootComponent = rootComponentView[CONTEXT];
if (rootComponent === componentInstance) {
// we are dealing with the root element here therefore we know that the
// element is the very first element after the HEADER data in the lView
return HEADER_OFFSET;
}
}
return -1;
}
/**
* Locates the directive within the given LView and returns the matching index
*/
function findViaDirective(lView, directiveInstance) {
// if a directive is monkey patched then it will (by default)
// have a reference to the LView of the current view. The
// element bound to the directive being search lives somewhere
// in the view data. We loop through the nodes and check their
// list of directives for the instance.
let tNode = lView[TVIEW].firstChild;
while (tNode) {
const directiveIndexStart = tNode.directiveStart;
const directiveIndexEnd = tNode.directiveEnd;
for (let i = directiveIndexStart; i < directiveIndexEnd; i++) {
if (lView[i] === directiveInstance) {
return tNode.index;
}
}
tNode = traverseNextElement(tNode);
}
return -1;
}
/**
* Returns a list of directives applied to a node at a specific index. The list includes
* directives matched by selector and any host directives, but it excludes components.
* Use `getComponentAtNodeIndex` to find the component applied to a node.
*
* @param nodeIndex The node index
* @param lView The target view data
*/
function getDirectivesAtNodeIndex(nodeIndex, lView) {
const tNode = lView[TVIEW].data[nodeIndex];
if (tNode.directiveStart === 0)
return EMPTY_ARRAY;
const results = [];
for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) {
const directiveInstance = lView[i];
if (!isComponentInstance(directiveInstance)) {
results.push(directiveInstance);
}
}
return results;
}
function getComponentAtNodeIndex(nodeIndex, lView) {
const tNode = lView[TVIEW].data[nodeIndex];
const { directiveStart, componentOffset } = tNode;
return componentOffset > -1 ? lView[directiveStart + componentOffset] : null;
}
/**
* Returns a map of local references (local reference name => element or directive instance) that
* exist on a given element.
*/
function discoverLocalRefs(lView, nodeIndex) {
const tNode = lView[TVIEW].data[nodeIndex];
if (tNode && tNode.localNames) {
const result = {};
let localIndex = tNode.index + 1;
for (let i = 0; i < tNode.localNames.length; i += 2) {
result[tNode.localNames[i]] = lView[localIndex];
localIndex++;
}
return result;
}
return null;
}
let _icuContainerIterate;
/**
* Iterator which provides ability to visit all of the `TIcuContainerNode` root `RNode`s.
*/
function icuContainerIterate(tIcuContainerNode, lView) {
return _icuContainerIterate(tIcuContainerNode, lView);
}
/**
* Ensures that `IcuContainerVisitor`'s implementation is present.
*
* This function is invoked when i18n instruction comes across an ICU. The purpose is to allow the
* bundler to tree shake ICU logic and only load it if ICU instruction is executed.
*/
function ensureIcuContainerVisitorLoaded(loader) {
if (_icuContainerIterate === undefined) {
// Do not inline this function. We want to keep `ensureIcuContainerVisitorLoaded` light, so it
// can be inlined into call-site.
_icuContainerIterate = loader();
}
}
/**
* Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
* that LContainer, which is an LView
* @param lView the lView whose parent to get
*/
function getLViewParent(lView) {
ngDevMode && assertLView(lView);
const parent = lView[PARENT];
return isLContainer(parent) ? parent[PARENT] : parent;
}
/**
* Retrieve the root view from any component or `LView` by walking the parent `LView` until
* reaching the root `LView`.
*
* @param componentOrLView any component or `LView`
*/
function getRootView(componentOrLView) {
ngDevMode && assertDefined(componentOrLView, 'component');
let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView);
while (lView && !(lView[FLAGS] & 512 /* LViewFlags.IsRoot */)) {
lView = getLViewParent(lView);
}
ngDevMode && assertLView(lView);
return lView;
}
/**
* Returns the context information associated with the application where the target is situated. It
* does this by walking the parent views until it gets to the root view, then getting the context
* off of that.
*
* @param viewOrComponent the `LView` or component to get the root context for.
*/
function getRootContext(viewOrComponent) {
const rootView = getRootView(viewOrComponent);
ngDevMode &&
assertDefined(rootView[CONTEXT], 'Root view has no context. Perhaps it is disconnected?');
return rootView[CONTEXT];
}
/**
* Gets the first `LContainer` in the LView or `null` if none exists.
*/
function getFirstLContainer(lView) {
return getNearestLContainer(lView[CHILD_HEAD]);
}
/**
* Gets the next `LContainer` that is a sibling of the given container.
*/
function getNextLContainer(container) {
return getNearestLContainer(container[NEXT]);
}
function getNearestLContainer(viewOrContainer) {
while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
viewOrContainer = viewOrContainer[NEXT];
}
return viewOrContainer;
}
/**
* NOTE: for performance reasons, the possible actions are inlined within the function instead of
* being passed as an argument.
*/
function applyToElementOrContainer(action, renderer, parent, lNodeToHandle, beforeNode) {
// If this slot was allocated for a text node dynamically created by i18n, the text node itself
// won't be created until i18nApply() in the update block, so this node should be skipped.
// For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor"
// in `i18n_spec.ts`.
if (lNodeToHandle != null) {
let lContainer;
let isComponent = false;
// We are expecting an RNode, but in the case of a component or LContainer the `RNode` is
// wrapped in an array which needs to be unwrapped. We need to know if it is a component and if
// it has LContainer so that we can process all of those cases appropriately.
if (isLContainer(lNodeToHandle)) {
lContainer = lNodeToHandle;
}
else if (isLView(lNodeToHandle)) {
isComponent = true;
ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView');
lNodeToHandle = lNodeToHandle[HOST];
}
const rNode = unwrapRNode(lNodeToHandle);
if (action === 0 /* WalkTNodeTreeAction.Create */ && parent !== null) {
if (beforeNode == null) {
nativeAppendChild(renderer, parent, rNode);
}
else {
nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
}
}
else if (action === 1 /* WalkTNodeTreeAction.Insert */ && parent !== null) {
nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true);
}
else if (action === 2 /* WalkTNodeTreeAction.Detach */) {
nativeRemoveNode(renderer, rNode, isComponent);
}
else if (action === 3 /* WalkTNodeTreeAction.Destroy */) {
ngDevMode && ngDevMode.rendererDestroyNode++;
renderer.destroyNode(rNode);
}
if (lContainer != null) {
applyContainer(renderer, action, lContainer, parent, beforeNode);
}
}
}
function createTextNode(renderer, value) {
ngDevMode && ngDevMode.rendererCreateTextNode++;
ngDevMode && ngDevMode.rendererSetText++;
return renderer.createText(value);
}
function updateTextNode(renderer, rNode, value) {
ngDevMode && ngDevMode.rendererSetText++;
renderer.setValue(rNode, value);
}
function createCommentNode(renderer, value) {
ngDevMode && ngDevMode.rendererCreateComment++;
return renderer.createComment(escapeCommentText(value));
}
/**
* Creates a native element from a tag name, using a renderer.
* @param renderer A renderer to use
* @param name the tag name
* @param namespace Optional namespace for element.
* @returns the element created
*/
function createElementNode(renderer, name, namespace) {
ngDevMode && ngDevMode.rendererCreateElement++;
return renderer.createElement(name, namespace);
}
/**
* Removes all DOM elements associated with a view.
*
* Because some root nodes of the view may be containers, we sometimes need
* to propagate deeply into the nested containers to remove all elements in the
* views beneath it.
*
* @param tView The `TView' of the `LView` from which elements should be added or removed
* @param lView The view from which elements should be added or removed
*/
function removeViewFromDOM(tView, lView) {
const renderer = lView[RENDERER];
applyView(tView, lView, renderer, 2 /* WalkTNodeTreeAction.Detach */, null, null);
lView[HOST] = null;
lView[T_HOST] = null;
}
/**
* Adds all DOM elements associated with a view.
*
* Because some root nodes of the view may be containers, we sometimes need
* to propagate deeply into the nested containers to add all elements in the
* views beneath it.
*
* @param tView The `TView' of the `LView` from which elements should be added or removed
* @param parentTNode The `TNode` where the `LView` should be attached to.
* @param renderer Current renderer to use for DOM manipulations.
* @param lView The view from which elements should be added or removed
* @param parentNativeNode The parent `RElement` where it should be inserted into.
* @param beforeNode The node before which elements should be added, if insert mode
*/
function addViewToDOM(tView, parentTNode, renderer, lView, parentNativeNode, beforeNode) {
lView[HOST] = parentNativeNode;
lView[T_HOST] = parentTNode;
applyView(tView, lView, renderer, 1 /* WalkTNodeTreeAction.Insert */, parentNativeNode, beforeNode);
}
/**
* Detach a `LView` from the DOM by detaching its nodes.
*
* @param tView The `TView' of the `LView` to be detached
* @param lView the `LView` to be detached.
*/
function detachViewFromDOM(tView, lView) {
applyView(tView, lView, lView[RENDERER], 2 /* WalkTNodeTreeAction.Detach */, null, null);
}
/**
* Traverses down and up the tree of views and containers to remove listeners and
* call onDestroy callbacks.
*
* Notes:
* - Because it's used for onDestroy calls, it needs to be bottom-up.
* - Must process containers instead of their views to avoid splicing
* when views are destroyed and re-added.
* - Using a while loop because it's faster than recursion
* - Destroy only called on movement to sibling or movement to parent (laterally or up)
*
* @param rootView The view to destroy
*/
function destroyViewTree(rootView) {
// If the view has no children, we can clean it up and return early.
let lViewOrLContainer = rootView[CHILD_HEAD];
if (!lViewOrLContainer) {
return cleanUpView(rootView[TVIEW], rootView);
}
while (lViewOrLContainer) {
let next = null;
if (isLView(lViewOrLContainer)) {
// If LView, traverse down to child.
next = lViewOrLContainer[CHILD_HEAD];
}
else {
ngDevMode && assertLContainer(lViewOrLContainer);
// If container, traverse down to its first LView.
const firstView = lViewOrLContainer[CONTAINER_HEADER_OFFSET];
if (firstView)
next = firstView;
}
if (!next) {
// Only clean up view when moving to the side or up, as destroy hooks
// should be called in order from the bottom up.
while (lViewOrLContainer && !lViewOrLContainer[NEXT] && lViewOrLContainer !== rootView) {
if (isLView(lViewOrLContainer)) {
cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
}
lViewOrLContainer = lViewOrLContainer[PARENT];
}
if (lViewOrLContainer === null)
lViewOrLContainer = rootView;
if (isLView(lViewOrLContainer)) {
cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer);
}
next = lViewOrLContainer && lViewOrLContainer[NEXT];
}
lViewOrLContainer = next;
}
}
/**
* Inserts a view into a container.
*
* This adds the view to the container's array of active views in the correct
* position. It also adds the view's elements to the DOM if the container isn't a
* root node of another view (in that case, the view's elements will be added when
* the container's parent view is added later).
*
* @param tView The `TView' of the `LView` to insert
* @param lView The view to insert
* @param lContainer The container into which the view should be inserted
* @param index Which index in the container to insert the child view into
*/
function insertView(tView, lView, lContainer, index) {
ngDevMode && assertLView(lView);
ngDevMode && assertLContainer(lContainer);
const indexInContainer = CONTAINER_HEADER_OFFSET + index;
const containerLength = lContainer.length;
if (index > 0) {
// This is a new view, we need to add it to the children.
lContainer[indexInContainer - 1][NEXT] = lView;
}
if (index < containerLength - CONTAINER_HEADER_OFFSET) {
lView[NEXT] = lContainer[indexInContainer];
addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView);
}
else {
lContainer.push(lView);
lView[NEXT] = null;
}
lView[PARENT] = lContainer;
// track views where declaration and insertion points are different
const declarationLContainer = lView[DECLARATION_LCONTAINER];
if (declarationLContainer !== null && lContainer !== declarationLContainer) {
trackMovedView(declarationLContainer, lView);
}
// notify query that a new view has been added
const lQueries = lView[QUERIES];
if (lQueries !== null) {
lQueries.insertView(tView);
}
// Sets the attached flag
lView[FLAGS] |= 128 /* LViewFlags.Attached */;
}
/**
* Track views created from the declaration container (TemplateRef) and inserted into a
* different LContainer.
*/
function trackMovedView(declarationContainer, lView) {
ngDevMode && assertDefined(lView, 'LView required');
ngDevMode && assertLContainer(declarationContainer);
const movedViews = declarationContainer[MOVED_VIEWS];
const insertedLContainer = lView[PARENT];
ngDevMode && assertLContainer(insertedLContainer);
const insertedComponentLView = insertedLContainer[PARENT][DECLARATION_COMPONENT_VIEW];
ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView');
const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW];
ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView');
if (declaredComponentLView !== insertedComponentLView) {
// At this point the declaration-component is not same as insertion-component; this means that
// this is a transplanted view. Mark the declared lView as having transplanted views so that
// those views can participate in CD.
declarationContainer[HAS_TRANSPLANTED_VIEWS] = true;
}
if (movedViews === null) {
declarationContainer[MOVED_VIEWS] = [lView];
}
else {
movedViews.push(lView);
}
}
function detachMovedView(declarationContainer, lView) {
ngDevMode && assertLContainer(declarationContainer);
ngDevMode &&
assertDefined(declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection');
const movedViews = declarationContainer[MOVED_VIEWS];
const declarationViewIndex = movedViews.indexOf(lView);
const insertionLContainer = lView[PARENT];
ngDevMode && assertLContainer(insertionLContainer);
// If the view was marked for refresh but then detached before it was checked (where the flag
// would be cleared and the counter decremented), we need to update the status here.
clearViewRefreshFlag(lView);
movedViews.splice(declarationViewIndex, 1);
}
/**
* Detaches a view from a container.
*
* This method removes the view from the container's array of active views. It also
* removes the view's elements from the DOM.
*
* @param lContainer The container from which to detach a view
* @param removeIndex The index of the view to detach
* @returns Detached LView instance.
*/
function detachView(lContainer, removeIndex) {
if (lContainer.length <= CONTAINER_HEADER_OFFSET)
return;
const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
const viewToDetach = lContainer[indexInContainer];
if (viewToDetach) {
const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
if (declarationLContainer !== null && declarationLContainer !== lContainer) {
detachMovedView(declarationLContainer, viewToDetach);
}
if (removeIndex > 0) {
lContainer[indexInContainer - 1][NEXT] = viewToDetach[NEXT];
}
const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
removeViewFromDOM(viewToDetach[TVIEW], viewToDetach);
// notify query that a view has been removed
const lQueries = removedLView[QUERIES];
if (lQueries !== null) {
lQueries.detachView(removedLView[TVIEW]);
}
viewToDetach[PARENT] = null;
viewToDetach[NEXT] = null;
// Unsets the attached flag
viewToDetach[FLAGS] &= ~128 /* LViewFlags.Attached */;
}
return viewToDetach;
}
/**
* A standalone function which destroys an LView,
* conducting clean up (e.g. removing listeners, calling onDestroys).
*
* @param tView The `TView' of the `LView` to be destroyed
* @param lView The view to be destroyed.
*/
function destroyLView(tView, lView) {
if (!(lView[FLAGS] & 256 /* LViewFlags.Destroyed */)) {
const renderer = lView[RENDERER];
lView[REACTIVE_TEMPLATE_CONSUMER] && consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]);
lView[REACTIVE_HOST_BINDING_CONSUMER] && consumerDestroy(lView[REACTIVE_HOST_BINDING_CONSUMER]);
if (renderer.destroyNode) {
applyView(tView, lView, renderer, 3 /* WalkTNodeTreeAction.Destroy */, null, null);
}
destroyViewTree(lView);
}
}
/**
* Calls onDestroys hooks for all directives and pipes in a given view and then removes all
* listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks
* can be propagated to @Output listeners.
*
* @param tView `TView` for the `LView` to clean up.
* @param lView The LView to clean up
*/
function cleanUpView(tView, lView) {
if (!(lView[FLAGS] & 256 /* LViewFlags.Destroyed */)) {
// Usually the Attached flag is removed when the view is detached from its parent, however
// if it's a root view, the flag won't be unset hence why we're also removing on destroy.
lView[FLAGS] &= ~128 /* LViewFlags.Attached */;
// Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook
// runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If
// We don't flag the view as destroyed before the hooks, this could lead to an infinite loop.
// This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is
// really more of an "afterDestroy" hook if you think about it.
lView[FLAGS] |= 256 /* LViewFlags.Destroyed */;
executeOnDestroys(tView, lView);
processCleanups(tView, lView);
// For component views only, the local renderer is destroyed at clean up time.
if (lView[TVIEW].type === 1 /* TViewType.Component */) {
ngDevMode && ngDevMode.rendererDestroy++;
lView[RENDERER].destroy();
}
const declarationContainer = lView[DECLARATION_LCONTAINER];
// we are dealing with an embedded view that is still inserted into a container
if (declarationContainer !== null && isLContainer(lView[PARENT])) {
// and this is a projected view
if (declarationContainer !== lView[PARENT]) {
detachMovedView(declarationContainer, lView);
}
// For embedded views still attached to a container: remove query result from this view.
const lQueries = lView[QUERIES];
if (lQueries !== null) {
lQueries.detachView(tView);
}
}
// Unregister the view once everything else has been cleaned up.
unregisterLView(lView);
}
}
/** Removes listeners and unsubscribes from output subscriptions */
function processCleanups(tView, lView) {
const tCleanup = tView.cleanup;
const lCleanup = lView[CLEANUP];
if (tCleanup !== null) {
for (let i = 0; i < tCleanup.length - 1; i += 2) {
if (typeof tCleanup[i] === 'string') {
// This is a native DOM listener. It will occupy 4 entries in the TCleanup array (hence i +=
// 2 at the end of this block).
const targetIdx = tCleanup[i + 3];
ngDevMode && assertNumber(targetIdx, 'cleanup target must be a number');
if (targetIdx >= 0) {
// unregister
lCleanup[targetIdx]();
}
else {
// Subscription
lCleanup[-targetIdx].unsubscribe();
}
i += 2;
}
else {
// This is a cleanup function that is grouped with the index of its context
const context = lCleanup[tCleanup[i + 1]];
tCleanup[i].call(context);
}
}
}
if (lCleanup !== null) {
lView[CLEANUP] = null;
}
const destroyHooks = lView[ON_DESTROY_HOOKS];
if (destroyHooks !== null) {
// Reset the ON_DESTROY_HOOKS array before iterating over it to prevent hooks that unregister
// themselves from mutating the array during iteration.
lView[ON_DESTROY_HOOKS] = null;
for (let i = 0; i < destroyHooks.length; i++) {
const destroyHooksFn = destroyHooks[i];
ngDevMode && assertFunction(destroyHooksFn, 'Expecting destroy hook to be a function.');
destroyHooksFn();
}
}
}
/** Calls onDestroy hooks for this view */
function executeOnDestroys(tView, lView) {
let destroyHooks;
if (tView != null && (destroyHooks = tView.destroyHooks) != null) {
for (let i = 0; i < destroyHooks.length; i += 2) {
const context = lView[destroyHooks[i]];
// Only call the destroy hook if the context has been requested.
if (!(context instanceof NodeInjectorFactory)) {
const toCall = destroyHooks[i + 1];
if (Array.isArray(toCall)) {
for (let j = 0; j < toCall.length; j += 2) {
const callContext = context[toCall[j]];
const hook = toCall[j + 1];
profiler(4 /* ProfilerEvent.LifecycleHookStart */, callContext, hook);
try {
hook.call(callContext);
}
finally {
profiler(5 /* ProfilerEvent.LifecycleHookEnd */, callContext, hook);
}
}
}
else {
profiler(4 /* ProfilerEvent.LifecycleHookStart */, context, toCall);
try {
toCall.call(context);
}
finally {
profiler(5 /* ProfilerEvent.LifecycleHookEnd */, context, toCall);
}
}
}
}
}
}
/**
* Returns a native element if a node can be inserted into the given parent.
*
* There are two reasons why we may not be able to insert a element immediately.
* - Projection: When creating a child content element of a component, we have to skip the
* insertion because the content of a component will be projected.
* `delayed due to projection`
* - Parent container is disconnected: This can happen when we are inserting a view into
* parent container, which itself is disconnected. For example the parent container is part
* of a View which has not be inserted or is made for projection but has not been inserted
* into destination.
*
* @param tView: Current `TView`.
* @param tNode: `TNode` for which we wish to retrieve render parent.
* @param lView: Current `LView`.
*/
function getParentRElement(tView, tNode, lView) {
return getClosestRElement(tView, tNode.parent, lView);
}
/**
* Get closest `RElement` or `null` if it can't be found.
*
* If `TNode` is `TNodeType.Element` => return `RElement` at `LView[tNode.index]` location.
* If `TNode` is `TNodeType.ElementContainer|IcuContain` => return the parent (recursively).
* If `TNode` is `null` then return host `RElement`:
* - return `null` if projection
* - return `null` if parent container is disconnected (we have no parent.)
*
* @param tView: Current `TView`.
* @param tNode: `TNode` for which we wish to retrieve `RElement` (or `null` if host element is
* needed).
* @param lView: Current `LView`.
* @returns `null` if the `RElement` can't be determined at this time (no parent / projection)
*/
function getClosestRElement(tView, tNode, lView) {
let parentTNode = tNode;
// Skip over element and ICU containers as those are represented by a comment node and
// can't be used as a render parent.
while (parentTNode !== null &&
(parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */))) {
tNode = parentTNode;
parentTNode = tNode.parent;
}
// If the parent tNode is null, then we are inserting across views: either into an embedded view
// or a component view.
if (parentTNode === null) {
// We are inserting a root element of the component view into the component host element and
// it should always be eager.
return lView[HOST];
}
else {
ngDevMode && assertTNodeType(parentTNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
const { componentOffset } = parentTNode;
if (componentOffset > -1) {
ngDevMode && assertTNodeForLView(parentTNode, lView);
const { encapsulation } = tView.data[parentTNode.directiveStart + componentOffset];
// We've got a parent which is an element in the current view. We just need to verify if the
// parent element is not a component. Component's content nodes are not inserted immediately
// because they will be projected, and so doing insert at this point would be wasteful.
// Since the projection would then move it to its final destination. Note that we can't
// make this assumption when using the Shadow DOM, because the native projection placeholders
// ( or ) have to be in place as elements are being inserted.
if (encapsulation === ViewEncapsulation.None ||
encapsulation === ViewEncapsulation.Emulated) {
return null;
}
}
return getNativeByTNode(parentTNode, lView);
}
}
/**
* Inserts a native node before another native node for a given parent.
* This is a utility function that can be used when native nodes were determined.
*/
function nativeInsertBefore(renderer, parent, child, beforeNode, isMove) {
ngDevMode && ngDevMode.rendererInsertBefore++;
renderer.insertBefore(parent, child, beforeNode, isMove);
}
function nativeAppendChild(renderer, parent, child) {
ngDevMode && ngDevMode.rendererAppendChild++;
ngDevMode && assertDefined(parent, 'parent node must be defined');
renderer.appendChild(parent, child);
}
function nativeAppendOrInsertBefore(renderer, parent, child, beforeNode, isMove) {
if (beforeNode !== null) {
nativeInsertBefore(renderer, parent, child, beforeNode, isMove);
}
else {
nativeAppendChild(renderer, parent, child);
}
}
/** Removes a node from the DOM given its native parent. */
function nativeRemoveChild(renderer, parent, child, isHostElement) {
renderer.removeChild(parent, child, isHostElement);
}
/** Checks if an element is a `` node. */
function isTemplateNode(node) {
return node.tagName === 'TEMPLATE' && node.content !== undefined;
}
/**
* Returns a native parent of a given native node.
*/
function nativeParentNode(renderer, node) {
return renderer.parentNode(node);
}
/**
* Returns a native sibling of a given native node.
*/
function nativeNextSibling(renderer, node) {
return renderer.nextSibling(node);
}
/**
* Find a node in front of which `currentTNode` should be inserted.
*
* This method determines the `RNode` in front of which we should insert the `currentRNode`. This
* takes `TNode.insertBeforeIndex` into account if i18n code has been invoked.
*
* @param parentTNode parent `TNode`
* @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
* @param lView current `LView`
*/
function getInsertInFrontOfRNode(parentTNode, currentTNode, lView) {
return _getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView);
}
/**
* Find a node in front of which `currentTNode` should be inserted. (Does not take i18n into
* account)
*
* This method determines the `RNode` in front of which we should insert the `currentRNode`. This
* does not take `TNode.insertBeforeIndex` into account.
*
* @param parentTNode parent `TNode`
* @param currentTNode current `TNode` (The node which we would like to insert into the DOM)
* @param lView current `LView`
*/
function getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView) {
if (parentTNode.type & (8 /* TNodeType.ElementContainer */ | 32 /* TNodeType.Icu */)) {
return getNativeByTNode(parentTNode, lView);
}
return null;
}
/**
* Tree shakable boundary for `getInsertInFrontOfRNodeWithI18n` function.
*
* This function will only be set if i18n code runs.
*/
let _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithNoI18n;
/**
* Tree shakable boundary for `processI18nInsertBefore` function.
*
* This function will only be set if i18n code runs.
*/
let _processI18nInsertBefore;
function setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore) {
_getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithI18n;
_processI18nInsertBefore = processI18nInsertBefore;
}
/**
* Appends the `child` native node (or a collection of nodes) to the `parent`.
*
* @param tView The `TView' to be appended
* @param lView The current LView
* @param childRNode The native child (or children) that should be appended
* @param childTNode The TNode of the child element
*/
function appendChild(tView, lView, childRNode, childTNode) {
const parentRNode = getParentRElement(tView, childTNode, lView);
const renderer = lView[RENDERER];
const parentTNode = childTNode.parent || lView[T_HOST];
const anchorNode = getInsertInFrontOfRNode(parentTNode, childTNode, lView);
if (parentRNode != null) {
if (Array.isArray(childRNode)) {
for (let i = 0; i < childRNode.length; i++) {
nativeAppendOrInsertBefore(renderer, parentRNode, childRNode[i], anchorNode, false);
}
}
else {
nativeAppendOrInsertBefore(renderer, parentRNode, childRNode, anchorNode, false);
}
}
_processI18nInsertBefore !== undefined &&
_processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRNode);
}
/**
* Returns the first native node for a given LView, starting from the provided TNode.
*
* Native nodes are returned in the order in which those appear in the native tree (DOM).
*/
function getFirstNativeNode(lView, tNode) {
if (tNode !== null) {
ngDevMode &&
assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 32 /* TNodeType.Icu */ | 16 /* TNodeType.Projection */);
const tNodeType = tNode.type;
if (tNodeType & 3 /* TNodeType.AnyRNode */) {
return getNativeByTNode(tNode, lView);
}
else if (tNodeType & 4 /* TNodeType.Container */) {
return getBeforeNodeForView(-1, lView[tNode.index]);
}
else if (tNodeType & 8 /* TNodeType.ElementContainer */) {
const elIcuContainerChild = tNode.child;
if (elIcuContainerChild !== null) {
return getFirstNativeNode(lView, elIcuContainerChild);
}
else {
const rNodeOrLContainer = lView[tNode.index];
if (isLContainer(rNodeOrLContainer)) {
return getBeforeNodeForView(-1, rNodeOrLContainer);
}
else {
return unwrapRNode(rNodeOrLContainer);
}
}
}
else if (tNodeType & 32 /* TNodeType.Icu */) {
let nextRNode = icuContainerIterate(tNode, lView);
let rNode = nextRNode();
// If the ICU container has no nodes, than we use the ICU anchor as the node.
return rNode || unwrapRNode(lView[tNode.index]);
}
else {
const projectionNodes = getProjectionNodes(lView, tNode);
if (projectionNodes !== null) {
if (Array.isArray(projectionNodes)) {
return projectionNodes[0];
}
const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]);
ngDevMode && assertParentView(parentView);
return getFirstNativeNode(parentView, projectionNodes);
}
else {
return getFirstNativeNode(lView, tNode.next);
}
}
}
return null;
}
function getProjectionNodes(lView, tNode) {
if (tNode !== null) {
const componentView = lView[DECLARATION_COMPONENT_VIEW];
const componentHost = componentView[T_HOST];
const slotIdx = tNode.projection;
ngDevMode && assertProjectionSlots(lView);
return componentHost.projection[slotIdx];
}
return null;
}
function getBeforeNodeForView(viewIndexInContainer, lContainer) {
const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1;
if (nextViewIndex < lContainer.length) {
const lView = lContainer[nextViewIndex];
const firstTNodeOfView = lView[TVIEW].firstChild;
if (firstTNodeOfView !== null) {
return getFirstNativeNode(lView, firstTNodeOfView);
}
}
return lContainer[NATIVE];
}
/**
* Removes a native node itself using a given renderer. To remove the node we are looking up its
* parent from the native tree as not all platforms / browsers support the equivalent of
* node.remove().
*
* @param renderer A renderer to be used
* @param rNode The native node that should be removed
* @param isHostElement A flag indicating if a node to be removed is a host of a component.
*/
function nativeRemoveNode(renderer, rNode, isHostElement) {
ngDevMode && ngDevMode.rendererRemoveNode++;
const nativeParent = nativeParentNode(renderer, rNode);
if (nativeParent) {
nativeRemoveChild(renderer, nativeParent, rNode, isHostElement);
}
}
/**
* Clears the contents of a given RElement.
*
* @param rElement the native RElement to be cleared
*/
function clearElementContents(rElement) {
rElement.textContent = '';
}
/**
* Performs the operation of `action` on the node. Typically this involves inserting or removing
* nodes on the LView or projection boundary.
*/
function applyNodes(renderer, action, tNode, lView, parentRElement, beforeNode, isProjection) {
while (tNode != null) {
ngDevMode && assertTNodeForLView(tNode, lView);
ngDevMode &&
assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 12 /* TNodeType.AnyContainer */ | 16 /* TNodeType.Projection */ | 32 /* TNodeType.Icu */);
const rawSlotValue = lView[tNode.index];
const tNodeType = tNode.type;
if (isProjection) {
if (action === 0 /* WalkTNodeTreeAction.Create */) {
rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView);
tNode.flags |= 2 /* TNodeFlags.isProjected */;
}
}
if ((tNode.flags & 32 /* TNodeFlags.isDetached */) !== 32 /* TNodeFlags.isDetached */) {
if (tNodeType & 8 /* TNodeType.ElementContainer */) {
applyNodes(renderer, action, tNode.child, lView, parentRElement, beforeNode, false);
applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
}
else if (tNodeType & 32 /* TNodeType.Icu */) {
const nextRNode = icuContainerIterate(tNode, lView);
let rNode;
while (rNode = nextRNode()) {
applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
}
applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
}
else if (tNodeType & 16 /* TNodeType.Projection */) {
applyProjectionRecursive(renderer, action, lView, tNode, parentRElement, beforeNode);
}
else {
ngDevMode && assertTNodeType(tNode, 3 /* TNodeType.AnyRNode */ | 4 /* TNodeType.Container */);
applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode);
}
}
tNode = isProjection ? tNode.projectionNext : tNode.next;
}
}
function applyView(tView, lView, renderer, action, parentRElement, beforeNode) {
applyNodes(renderer, action, tView.firstChild, lView, parentRElement, beforeNode, false);
}
/**
* `applyProjection` performs operation on the projection.
*
* Inserting a projection requires us to locate the projected nodes from the parent component. The
* complication is that those nodes themselves could be re-projected from their parent component.
*
* @param tView The `TView` of `LView` which needs to be inserted, detached, destroyed
* @param lView The `LView` which needs to be inserted, detached, destroyed.
* @param tProjectionNode node to project
*/
function applyProjection(tView, lView, tProjectionNode) {
const renderer = lView[RENDERER];
const parentRNode = getParentRElement(tView, tProjectionNode, lView);
const parentTNode = tProjectionNode.parent || lView[T_HOST];
let beforeNode = getInsertInFrontOfRNode(parentTNode, tProjectionNode, lView);
applyProjectionRecursive(renderer, 0 /* WalkTNodeTreeAction.Create */, lView, tProjectionNode, parentRNode, beforeNode);
}
/**
* `applyProjectionRecursive` performs operation on the projection specified by `action` (insert,
* detach, destroy)
*
* Inserting a projection requires us to locate the projected nodes from the parent component. The
* complication is that those nodes themselves could be re-projected from their parent component.
*
* @param renderer Render to use
* @param action action to perform (insert, detach, destroy)
* @param lView The LView which needs to be inserted, detached, destroyed.
* @param tProjectionNode node to project
* @param parentRElement parent DOM element for insertion/removal.
* @param beforeNode Before which node the insertions should happen.
*/
function applyProjectionRecursive(renderer, action, lView, tProjectionNode, parentRElement, beforeNode) {
const componentLView = lView[DECLARATION_COMPONENT_VIEW];
const componentNode = componentLView[T_HOST];
ngDevMode &&
assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index');
const nodeToProjectOrRNodes = componentNode.projection[tProjectionNode.projection];
if (Array.isArray(nodeToProjectOrRNodes)) {
// This should not exist, it is a bit of a hack. When we bootstrap a top level node and we
// need to support passing projectable nodes, so we cheat and put them in the TNode
// of the Host TView. (Yes we put instance info at the T Level). We can get away with it
// because we know that that TView is not shared and therefore it will not be a problem.
// This should be refactored and cleaned up.
for (let i = 0; i < nodeToProjectOrRNodes.length; i++) {
const rNode = nodeToProjectOrRNodes[i];
applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode);
}
}
else {
let nodeToProject = nodeToProjectOrRNodes;
const projectedComponentLView = componentLView[PARENT];
// If a parent is located within a skip hydration block,
// annotate an actual node that is being projected with the same flag too.
if (hasInSkipHydrationBlockFlag(tProjectionNode)) {
nodeToProject.flags |= 128 /* TNodeFlags.inSkipHydrationBlock */;
}
applyNodes(renderer, action, nodeToProject, projectedComponentLView, parentRElement, beforeNode, true);
}
}
/**
* `applyContainer` performs an operation on the container and its views as specified by
* `action` (insert, detach, destroy)
*
* Inserting a Container is complicated by the fact that the container may have Views which
* themselves have containers or projections.
*
* @param renderer Renderer to use
* @param action action to perform (insert, detach, destroy)
* @param lContainer The LContainer which needs to be inserted, detached, destroyed.
* @param parentRElement parent DOM element for insertion/removal.
* @param beforeNode Before which node the insertions should happen.
*/
function applyContainer(renderer, action, lContainer, parentRElement, beforeNode) {
ngDevMode && assertLContainer(lContainer);
const anchor = lContainer[NATIVE]; // LContainer has its own before node.
const native = unwrapRNode(lContainer);
// An LContainer can be created dynamically on any node by injecting ViewContainerRef.
// Asking for a ViewContainerRef on an element will result in a creation of a separate anchor
// node (comment in the DOM) that will be different from the LContainer's host node. In this
// particular case we need to execute action on 2 nodes:
// - container's host node (this is done in the executeActionOnElementOrContainer)
// - container's host node (this is done here)
if (anchor !== native) {
// This is very strange to me (Misko). I would expect that the native is same as anchor. I
// don't see a reason why they should be different, but they are.
//
// If they are we need to process the second anchor as well.
applyToElementOrContainer(action, renderer, parentRElement, anchor, beforeNode);
}
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
const lView = lContainer[i];
applyView(lView[TVIEW], lView, renderer, action, parentRElement, anchor);
}
}
/**
* Writes class/style to element.
*
* @param renderer Renderer to use.
* @param isClassBased `true` if it should be written to `class` (`false` to write to `style`)
* @param rNode The Node to write to.
* @param prop Property to write to. This would be the class/style name.
* @param value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add
* otherwise).
*/
function applyStyling(renderer, isClassBased, rNode, prop, value) {
if (isClassBased) {
// We actually want JS true/false here because any truthy value should add the class
if (!value) {
ngDevMode && ngDevMode.rendererRemoveClass++;
renderer.removeClass(rNode, prop);
}
else {
ngDevMode && ngDevMode.rendererAddClass++;
renderer.addClass(rNode, prop);
}
}
else {
let flags = prop.indexOf('-') === -1 ? undefined : RendererStyleFlags2.DashCase;
if (value == null /** || value === undefined */) {
ngDevMode && ngDevMode.rendererRemoveStyle++;
renderer.removeStyle(rNode, prop, flags);
}
else {
// A value is important if it ends with `!important`. The style
// parser strips any semicolons at the end of the value.
const isImportant = typeof value === 'string' ? value.endsWith('!important') : false;
if (isImportant) {
// !important has to be stripped from the value for it to be valid.
value = value.slice(0, -10);
flags |= RendererStyleFlags2.Important;
}
ngDevMode && ngDevMode.rendererSetStyle++;
renderer.setStyle(rNode, prop, value, flags);
}
}
}
/**
* Write `cssText` to `RElement`.
*
* This function does direct write without any reconciliation. Used for writing initial values, so
* that static styling values do not pull in the style parser.
*
* @param renderer Renderer to use
* @param element The element which needs to be updated.
* @param newValue The new class list to write.
*/
function writeDirectStyle(renderer, element, newValue) {
ngDevMode && assertString(newValue, '\'newValue\' should be a string');
renderer.setAttribute(element, 'style', newValue);
ngDevMode && ngDevMode.rendererSetStyle++;
}
/**
* Write `className` to `RElement`.
*
* This function does direct write without any reconciliation. Used for writing initial values, so
* that static styling values do not pull in the style parser.
*
* @param renderer Renderer to use
* @param element The element which needs to be updated.
* @param newValue The new class list to write.
*/
function writeDirectClass(renderer, element, newValue) {
ngDevMode && assertString(newValue, '\'newValue\' should be a string');
if (newValue === '') {
// There are tests in `google3` which expect `element.getAttribute('class')` to be `null`.
renderer.removeAttribute(element, 'class');
}
else {
renderer.setAttribute(element, 'class', newValue);
}
ngDevMode && ngDevMode.rendererSetClassName++;
}
/** Sets up the static DOM attributes on an `RNode`. */
function setupStaticAttributes(renderer, element, tNode) {
const { mergedAttrs, classes, styles } = tNode;
if (mergedAttrs !== null) {
setUpAttributes(renderer, element, mergedAttrs);
}
if (classes !== null) {
writeDirectClass(renderer, element, classes);
}
if (styles !== null) {
writeDirectStyle(renderer, element, styles);
}
}
/**
* @fileoverview
* A module to facilitate use of a Trusted Types policy internally within
* Angular. It lazily constructs the Trusted Types policy, providing helper
* utilities for promoting strings to Trusted Types. When Trusted Types are not
* available, strings are used as a fallback.
* @security All use of this module is security-sensitive and should go through
* security review.
*/
/**
* The Trusted Types policy, or null if Trusted Types are not
* enabled/supported, or undefined if the policy has not been created yet.
*/
let policy$1;
/**
* Returns the Trusted Types policy, or null if Trusted Types are not
* enabled/supported. The first call to this function will create the policy.
*/
function getPolicy$1() {
if (policy$1 === undefined) {
policy$1 = null;
if (_global.trustedTypes) {
try {
policy$1 = _global.trustedTypes.createPolicy('angular', {
createHTML: (s) => s,
createScript: (s) => s,
createScriptURL: (s) => s,
});
}
catch {
// trustedTypes.createPolicy throws if called with a name that is
// already registered, even in report-only mode. Until the API changes,
// catch the error not to break the applications functionally. In such
// cases, the code will fall back to using strings.
}
}
}
return policy$1;
}
/**
* Unsafely promote a string to a TrustedHTML, falling back to strings when
* Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that the
* provided string will never cause an XSS vulnerability if used in a context
* that will be interpreted as HTML by a browser, e.g. when assigning to
* element.innerHTML.
*/
function trustedHTMLFromString(html) {
return getPolicy$1()?.createHTML(html) || html;
}
/**
* Unsafely promote a string to a TrustedScript, falling back to strings when
* Trusted Types are not available.
* @security In particular, it must be assured that the provided string will
* never cause an XSS vulnerability if used in a context that will be
* interpreted and executed as a script by a browser, e.g. when calling eval.
*/
function trustedScriptFromString(script) {
return getPolicy$1()?.createScript(script) || script;
}
/**
* Unsafely promote a string to a TrustedScriptURL, falling back to strings
* when Trusted Types are not available.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that the
* provided string will never cause an XSS vulnerability if used in a context
* that will cause a browser to load and execute a resource, e.g. when
* assigning to script.src.
*/
function trustedScriptURLFromString(url) {
return getPolicy$1()?.createScriptURL(url) || url;
}
/**
* Unsafely call the Function constructor with the given string arguments. It
* is only available in development mode, and should be stripped out of
* production code.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that it
* is only called from development code, as use in production code can lead to
* XSS vulnerabilities.
*/
function newTrustedFunctionForDev(...args) {
if (typeof ngDevMode === 'undefined') {
throw new Error('newTrustedFunctionForDev should never be called in production');
}
if (!_global.trustedTypes) {
// In environments that don't support Trusted Types, fall back to the most
// straightforward implementation:
return new Function(...args);
}
// Chrome currently does not support passing TrustedScript to the Function
// constructor. The following implements the workaround proposed on the page
// below, where the Chromium bug is also referenced:
// https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor
const fnArgs = args.slice(0, -1).join(',');
const fnBody = args[args.length - 1];
const body = `(function anonymous(${fnArgs}
) { ${fnBody}
})`;
// Using eval directly confuses the compiler and prevents this module from
// being stripped out of JS binaries even if not used. The global['eval']
// indirection fixes that.
const fn = _global['eval'](trustedScriptFromString(body));
if (fn.bind === undefined) {
// Workaround for a browser bug that only exists in Chrome 83, where passing
// a TrustedScript to eval just returns the TrustedScript back without
// evaluating it. In that case, fall back to the most straightforward
// implementation:
return new Function(...args);
}
// To completely mimic the behavior of calling "new Function", two more
// things need to happen:
// 1. Stringifying the resulting function should return its source code
fn.toString = () => body;
// 2. When calling the resulting function, `this` should refer to `global`
return fn.bind(_global);
// When Trusted Types support in Function constructors is widely available,
// the implementation of this function can be simplified to:
// return new Function(...args.map(a => trustedScriptFromString(a)));
}
/**
* Validation function invoked at runtime for each binding that might potentially
* represent a security-sensitive attribute of an