forked from angular/angular
/
r3_injector.ts
535 lines (481 loc) · 19.8 KB
/
r3_injector.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import '../util/ng_dev_mode';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {OnDestroy} from '../interface/lifecycle_hooks';
import {Type} from '../interface/type';
import {getComponentDef} from '../render3/definition';
import {FactoryFn, getFactoryDef} from '../render3/definition_factory';
import {throwCyclicDependencyError, throwInvalidProviderError, throwMixedMultiProviderError} from '../render3/errors_di';
import {newArray} from '../util/array_utils';
import {EMPTY_ARRAY} from '../util/empty';
import {stringify} from '../util/stringify';
import {resolveForwardRef} from './forward_ref';
import {ENVIRONMENT_INITIALIZER} from './initializer_token';
import {setInjectImplementation} from './inject_switch';
import {InjectionToken} from './injection_token';
import {Injector} from './injector';
import {catchInjectorError, convertToBitFlags, injectArgs, NG_TEMP_TOKEN_PATH, setCurrentInjector, THROW_IF_NOT_FOUND, ɵɵinject} from './injector_compatibility';
import {INJECTOR} from './injector_token';
import {getInheritedInjectableDef, getInjectableDef, InjectorType, ɵɵInjectableDeclaration} from './interface/defs';
import {InjectFlags, InjectOptions} from './interface/injector';
import {ClassProvider, ConstructorProvider, ImportedNgModuleProviders, Provider, StaticClassProvider} from './interface/provider';
import {INJECTOR_DEF_TYPES} from './internal_tokens';
import {NullInjector} from './null_injector';
import {isExistingProvider, isFactoryProvider, isTypeProvider, isValueProvider, SingleProvider} from './provider_collection';
import {ProviderToken} from './provider_token';
import {INJECTOR_SCOPE, InjectorScope} from './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: Injector|undefined = undefined;
export function getNullInjector(): Injector {
if (NULL_INJECTOR === undefined) {
NULL_INJECTOR = new NullInjector();
}
return NULL_INJECTOR;
}
/**
* An entry in the injector which tracks information about the given token, including a possible
* current value.
*/
interface Record<T> {
factory: (() => T)|undefined;
value: T|{};
multi: any[]|undefined;
}
/**
* An `Injector` that's part of the environment injector hierarchy, which exists outside of the
* component tree.
*
* @developerPreview
*/
export abstract class EnvironmentInjector implements Injector {
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue: undefined, options: InjectOptions&{
optional?: false;
}): T;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue: null|undefined, options: InjectOptions): T
|null;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, options?: InjectOptions): T;
/**
* Retrieves an instance from the injector based on the provided token.
* @returns The instance from the injector if defined, otherwise the `notFoundValue`.
* @throws When the `notFoundValue` is `undefined` or `Injector.THROW_IF_NOT_FOUND`.
* @deprecated use object-based flags (`InjectOptions`) instead.
*/
abstract get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags): T;
/**
* @deprecated from v4.0.0 use ProviderToken<T>
* @suppress {duplicate}
*/
abstract get(token: any, notFoundValue?: any): any;
/**
* Runs the given function in the context of this `EnvironmentInjector`.
*
* Within the function's stack frame, `inject` can be used to inject dependencies from this
* injector. Note that `inject` is only usable synchronously, and cannot be used in any
* asynchronous callbacks or after any `await` points.
*
* @param fn the closure to be run in the context of this injector
* @returns the return value of the function, if any
*/
abstract runInContext<ReturnT>(fn: () => ReturnT): ReturnT;
abstract destroy(): void;
/**
* @internal
*/
abstract onDestroy(callback: () => void): void;
}
export class R3Injector extends EnvironmentInjector {
/**
* 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.
*/
private records = new Map<ProviderToken<any>, Record<any>|null>();
/**
* Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
*/
private _ngOnDestroyHooks = new Set<OnDestroy>();
private _onDestroyHooks: Array<() => void> = [];
/**
* Flag indicating that this injector was previously destroyed.
*/
get destroyed(): boolean {
return this._destroyed;
}
private _destroyed = false;
private injectorDefTypes: Set<Type<unknown>>;
constructor(
providers: Array<Provider|ImportedNgModuleProviders>, readonly parent: Injector,
readonly source: string|null, readonly scopes: Set<InjectorScope>) {
super();
// 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) as Record<InjectorScope|null>;
if (record != null && typeof record.value === 'string') {
this.scopes.add(record.value as InjectorScope);
}
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.
*/
override destroy(): void {
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();
}
for (const hook of this._onDestroyHooks) {
hook();
}
} finally {
// Release all references.
this.records.clear();
this._ngOnDestroyHooks.clear();
this.injectorDefTypes.clear();
this._onDestroyHooks.length = 0;
}
}
override onDestroy(callback: () => void): void {
this._onDestroyHooks.push(callback);
}
override runInContext<ReturnT>(fn: () => ReturnT): ReturnT {
this.assertNotDestroyed();
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
try {
return fn();
} finally {
setCurrentInjector(previousInjector);
setInjectImplementation(previousInjectImplementation);
}
}
override get<T>(
token: ProviderToken<T>, notFoundValue: any = THROW_IF_NOT_FOUND,
flags: InjectFlags|InjectOptions = InjectFlags.Default): T {
this.assertNotDestroyed();
flags = convertToBitFlags(flags) as InjectFlags;
// Set the injection context.
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: Record<T>|undefined|null = 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: any) {
if (e.name === 'NullInjectorError') {
const path: any[] = 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);
}
}
/** @internal */
resolveInjectorInitializers() {
const previousInjector = setCurrentInjector(this);
const previousInjectImplementation = setInjectImplementation(undefined);
try {
const initializers = this.get(ENVIRONMENT_INITIALIZER.multi, EMPTY_ARRAY, InjectFlags.Self);
if (ngDevMode && !Array.isArray(initializers)) {
throw new RuntimeError(
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);
}
}
override toString() {
const tokens: string[] = [];
const records = this.records;
for (const token of records.keys()) {
tokens.push(stringify(token));
}
return `R3Injector[${tokens.join(', ')}]`;
}
private assertNotDestroyed(): void {
if (this._destroyed) {
throw new RuntimeError(
RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,
ngDevMode && 'Injector has already been destroyed.');
}
}
/**
* Process a `SingleProvider` and add it.
*/
private processProvider(provider: SingleProvider): void {
// Determine the token from the provider. Either it's its own token, or has a {provide: ...}
// property.
provider = resolveForwardRef(provider);
let token: any =
isTypeProvider(provider) ? provider : resolveForwardRef(provider && provider.provide);
// Construct a `Record` for the provider.
const record = providerToRecord(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);
}
private hydrate<T>(token: ProviderToken<T>, record: Record<T>): T {
if (ngDevMode && record.value === CIRCULAR) {
throwCyclicDependencyError(stringify(token));
} else if (record.value === NOT_YET) {
record.value = CIRCULAR;
record.value = record.factory!();
}
if (typeof record.value === 'object' && record.value && hasOnDestroy(record.value)) {
this._ngOnDestroyHooks.add(record.value);
}
return record.value as T;
}
private injectableDefInScope(def: ɵɵInjectableDeclaration<any>): boolean {
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);
}
}
}
function injectableDefOrInjectorDefFactory(token: ProviderToken<any>): FactoryFn<any> {
// 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(
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(RuntimeErrorCode.INVALID_INJECTION_TOKEN, ngDevMode && 'unreachable');
}
function getUndecoratedInjectableFactory(token: Function) {
// If the token has parameters then it has dependencies that we cannot resolve implicitly.
const paramLength = token.length;
if (paramLength > 0) {
const args: string[] = newArray(paramLength, '?');
throw new RuntimeError(
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 as Type<any>);
} else {
return () => new (token as Type<any>)();
}
}
function providerToRecord(provider: SingleProvider): Record<any> {
if (isValueProvider(provider)) {
return makeRecord(undefined, provider.useValue);
} else {
const factory: (() => any)|undefined = providerToFactory(provider);
return makeRecord(factory, NOT_YET);
}
}
/**
* Converts a `SingleProvider` into a factory function.
*
* @param provider provider to convert to factory
*/
export function providerToFactory(
provider: SingleProvider, ngModuleType?: InjectorType<any>, providers?: any[]): () => any {
let factory: (() => any)|undefined = undefined;
if (ngDevMode && isImportedNgModuleProviders(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 as StaticClassProvider | ClassProvider).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<T>(
factory: (() => T)|undefined, value: T|{}, multi: boolean = false): Record<T> {
return {
factory: factory,
value: value,
multi: multi ? [] : undefined,
};
}
function hasDeps(value: ClassProvider|ConstructorProvider|
StaticClassProvider): value is ClassProvider&{deps: any[]} {
return !!(value as any).deps;
}
function hasOnDestroy(value: any): value is OnDestroy {
return value !== null && typeof value === 'object' &&
typeof (value as OnDestroy).ngOnDestroy === 'function';
}
function couldBeInjectableType(value: any): value is ProviderToken<any> {
return (typeof value === 'function') ||
(typeof value === 'object' && value instanceof InjectionToken);
}
function isImportedNgModuleProviders(provider: Provider|ImportedNgModuleProviders):
provider is ImportedNgModuleProviders {
return !!(provider as ImportedNgModuleProviders).ɵproviders;
}
function forEachSingleProvider(
providers: Array<Provider|ImportedNgModuleProviders>,
fn: (provider: SingleProvider) => void): void {
for (const provider of providers) {
if (Array.isArray(provider)) {
forEachSingleProvider(provider, fn);
} else if (isImportedNgModuleProviders(provider)) {
forEachSingleProvider(provider.ɵproviders, fn);
} else {
fn(provider);
}
}
}