static-injector 5.0.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/import/change_detection/scheduling/zoneless_scheduling.d.ts +37 -0
  2. package/import/change_detection/scheduling/zoneless_scheduling_impl.d.ts +16 -0
  3. package/import/core_reactivity_export_internal.d.ts +17 -0
  4. package/import/di/contextual.d.ts +36 -0
  5. package/{typings → import}/di/create_injector.d.ts +1 -1
  6. package/{typings → import}/di/forward_ref.d.ts +2 -2
  7. package/import/di/index.d.ts +3 -0
  8. package/{typings → import}/di/initializer_token.d.ts +8 -1
  9. package/{typings → import}/di/inject_switch.d.ts +2 -2
  10. package/{typings → import}/di/injectable.d.ts +4 -4
  11. package/{typings → import}/di/injection_token.d.ts +3 -4
  12. package/{typings → import}/di/injector.d.ts +4 -4
  13. package/{typings → import}/di/injector_compatibility.d.ts +1 -1
  14. package/{typings → import}/di/injector_marker.d.ts +1 -1
  15. package/{typings → import}/di/injector_token.d.ts +1 -1
  16. package/{typings → import}/di/interface/defs.d.ts +1 -1
  17. package/{typings → import}/di/interface/injector.d.ts +1 -1
  18. package/{typings → import}/di/interface/provider.d.ts +16 -18
  19. package/{typings → import}/di/internal_tokens.d.ts +1 -1
  20. package/{typings → import}/di/metadata.d.ts +9 -13
  21. package/{typings → import}/di/null_injector.d.ts +1 -1
  22. package/{typings → import}/di/provider_collection.d.ts +32 -4
  23. package/{typings → import}/di/provider_token.d.ts +1 -1
  24. package/{typings → import}/di/r3_injector.d.ts +2 -2
  25. package/{typings → import}/di/scope.d.ts +1 -1
  26. package/{typings → import}/di.d.ts +1 -1
  27. package/import/error_handler.d.ts +45 -0
  28. package/{typings → import}/errors.d.ts +13 -7
  29. package/import/index.d.ts +37 -0
  30. package/{typings → import}/interface/lifecycle_hooks.d.ts +2 -2
  31. package/{typings → import}/interface/type.d.ts +4 -9
  32. package/import/linker/destroy_ref.d.ts +44 -0
  33. package/import/pending_tasks.d.ts +78 -0
  34. package/{typings → import}/render3/definition_factory.d.ts +1 -1
  35. package/{typings → import}/render3/errors_di.d.ts +1 -1
  36. package/{typings → import}/render3/fields.d.ts +1 -1
  37. package/{typings → import}/render3/instructions/di.d.ts +1 -1
  38. package/import/render3/reactivity/api.d.ts +27 -0
  39. package/import/render3/reactivity/asserts.d.ts +16 -0
  40. package/import/render3/reactivity/computed.d.ts +25 -0
  41. package/import/render3/reactivity/effect.d.ts +121 -0
  42. package/import/render3/reactivity/linked_signal.d.ts +33 -0
  43. package/import/render3/reactivity/microtask_effect.d.ts +21 -0
  44. package/import/render3/reactivity/patch.d.ts +11 -0
  45. package/import/render3/reactivity/root_effect_scheduler.d.ts +54 -0
  46. package/import/render3/reactivity/signal.d.ts +61 -0
  47. package/import/render3/reactivity/untracked.d.ts +12 -0
  48. package/import/resource/api.d.ts +219 -0
  49. package/{es2022/di/injectable.js → import/resource/index.d.ts} +3 -2
  50. package/import/resource/resource.d.ts +89 -0
  51. package/import/util/callback_scheduler.d.ts +35 -0
  52. package/{typings → import}/util/closure.d.ts +1 -1
  53. package/{typings → import}/util/decorators.d.ts +3 -3
  54. package/{typings → import}/util/empty.d.ts +1 -1
  55. package/{es2022/di/provider_token.js → import/util/noop.d.ts} +2 -2
  56. package/{typings → import}/util/property.d.ts +1 -1
  57. package/{typings → import}/util/stringify.d.ts +1 -1
  58. package/index.js +2349 -0
  59. package/index.js.map +7 -0
  60. package/index.mjs +2258 -0
  61. package/index.mjs.map +7 -0
  62. package/package.json +19 -10
  63. package/primitives/signals/index.d.ts +15 -0
  64. package/primitives/signals/src/computed.d.ts +55 -0
  65. package/primitives/signals/src/equality.d.ts +15 -0
  66. package/primitives/signals/src/errors.d.ts +10 -0
  67. package/primitives/signals/src/graph.d.ts +182 -0
  68. package/primitives/signals/src/linked_signal.d.ts +72 -0
  69. package/primitives/signals/src/signal.d.ts +29 -0
  70. package/primitives/signals/src/watch.d.ts +43 -0
  71. package/{es2022/di/injector_marker.js → primitives/signals/src/weak_ref.d.ts} +2 -2
  72. package/readme.md +18 -14
  73. package/commonjs/index.js +0 -1576
  74. package/es2022/di/create_injector.js +0 -32
  75. package/es2022/di/forward_ref.js +0 -80
  76. package/es2022/di/index.js +0 -1
  77. package/es2022/di/initializer_token.js +0 -15
  78. package/es2022/di/inject_switch.js +0 -51
  79. package/es2022/di/injection_token.js +0 -93
  80. package/es2022/di/injector.js +0 -60
  81. package/es2022/di/injector_compatibility.js +0 -265
  82. package/es2022/di/injector_token.js +0 -20
  83. package/es2022/di/interface/defs.js +0 -110
  84. package/es2022/di/interface/injector.js +0 -26
  85. package/es2022/di/interface/provider.js +0 -10
  86. package/es2022/di/internal_tokens.js +0 -9
  87. package/es2022/di/metadata.js +0 -49
  88. package/es2022/di/null_injector.js +0 -19
  89. package/es2022/di/provider_collection.js +0 -104
  90. package/es2022/di/r3_injector.js +0 -449
  91. package/es2022/di/scope.js +0 -14
  92. package/es2022/di.js +0 -24
  93. package/es2022/errors.js +0 -44
  94. package/es2022/index.js +0 -11
  95. package/es2022/interface/lifecycle_hooks.js +0 -8
  96. package/es2022/interface/type.js +0 -21
  97. package/es2022/render3/definition_factory.js +0 -10
  98. package/es2022/render3/errors_di.js +0 -13
  99. package/es2022/render3/fields.js +0 -22
  100. package/es2022/render3/instructions/di.js +0 -23
  101. package/es2022/render3/util/stringify_utils.js +0 -38
  102. package/es2022/util/closure.js +0 -19
  103. package/es2022/util/decorators.js +0 -31
  104. package/es2022/util/empty.js +0 -18
  105. package/es2022/util/property.js +0 -15
  106. package/es2022/util/stringify.js +0 -45
  107. package/fesm2022/index.js +0 -1539
  108. package/typings/di/index.d.ts +0 -1
  109. package/typings/index.d.ts +0 -11
  110. package/typings/render3/util/stringify_utils.d.ts +0 -21
package/fesm2022/index.js DELETED
@@ -1,1539 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright Google LLC All Rights Reserved.
4
- *
5
- * Use of this source code is governed by an MIT-style license that can be
6
- * found in the LICENSE file at https://angular.io/license
7
- */
8
- /**
9
- * Convince closure compiler that the wrapped function has no side-effects.
10
- *
11
- * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to
12
- * allow us to execute a function but have closure compiler mark the call as no-side-effects.
13
- * It is important that the return value for the `noSideEffects` function be assigned
14
- * to something which is retained otherwise the call to `noSideEffects` will be removed by closure
15
- * compiler.
16
- */
17
- function noSideEffects(fn) {
18
- return { toString: fn }.toString();
19
- }
20
-
21
- /**
22
- * @license
23
- * Copyright Google LLC All Rights Reserved.
24
- *
25
- * Use of this source code is governed by an MIT-style license that can be
26
- * found in the LICENSE file at https://angular.io/license
27
- */
28
- function makeMetadataCtor(props) {
29
- return function ctor(...args) {
30
- if (props) {
31
- const values = props(...args);
32
- for (const propName in values) {
33
- this[propName] = values[propName];
34
- }
35
- }
36
- };
37
- }
38
- function makeParamDecorator(name, props, parentClass) {
39
- return noSideEffects(() => {
40
- const metaCtor = makeMetadataCtor(props);
41
- function ParamDecoratorFactory(...args) {
42
- metaCtor.apply(this, args);
43
- return this;
44
- }
45
- return ParamDecoratorFactory;
46
- });
47
- }
48
-
49
- /**
50
- * @license
51
- * Copyright Google LLC All Rights Reserved.
52
- *
53
- * Use of this source code is governed by an MIT-style license that can be
54
- * found in the LICENSE file at https://angular.io/license
55
- */
56
- /**
57
- * Class that represents a runtime error.
58
- * Formats and outputs the error message in a consistent way.
59
- *
60
- * Example:
61
- * ```
62
- * throw new RuntimeError(
63
- * RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED,
64
- * ngDevMode && 'Injector has already been destroyed.');
65
- * ```
66
- *
67
- * Note: the `message` argument contains a descriptive error message as a string in development
68
- * mode (when the `ngDevMode` is defined). In production mode (after tree-shaking pass), the
69
- * `message` argument becomes `false`, thus we account for it in the typings and the runtime
70
- * logic.
71
- */
72
- class RuntimeError extends Error {
73
- code;
74
- constructor(code, message) {
75
- super(formatRuntimeError(code, message));
76
- this.code = code;
77
- }
78
- }
79
- /**
80
- * Called to format a runtime error.
81
- * See additional info on the `message` argument type in the `RuntimeError` class description.
82
- */
83
- function formatRuntimeError(code, message) {
84
- // Error code might be a negative number, which is a special marker that instructs the logic to
85
- // generate a link to the error details page on angular.io.
86
- // We also prepend `0` to non-compile-time errors.
87
- const fullCode = `NG0${Math.abs(code)}`;
88
- let errorMessage = `${fullCode}${message ? ': ' + message : ''}`;
89
- return errorMessage;
90
- }
91
-
92
- /**
93
- * @license
94
- * Copyright Google LLC All Rights Reserved.
95
- *
96
- * Use of this source code is governed by an MIT-style license that can be
97
- * found in the LICENSE file at https://angular.io/license
98
- */
99
- function stringify(token) {
100
- if (typeof token === 'string') {
101
- return token;
102
- }
103
- if (Array.isArray(token)) {
104
- return '[' + token.map(stringify).join(', ') + ']';
105
- }
106
- if (token == null) {
107
- return '' + token;
108
- }
109
- if (token.overriddenName) {
110
- return `${token.overriddenName}`;
111
- }
112
- if (token.name) {
113
- return `${token.name}`;
114
- }
115
- const res = token.toString();
116
- if (res == null) {
117
- return '' + res;
118
- }
119
- const newLineIndex = res.indexOf('\n');
120
- return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
121
- }
122
-
123
- /**
124
- * @license
125
- * Copyright Google LLC All Rights Reserved.
126
- *
127
- * Use of this source code is governed by an MIT-style license that can be
128
- * found in the LICENSE file at https://angular.io/license
129
- */
130
- function getClosureSafeProperty(objWithPropertyToExtract) {
131
- for (let key in objWithPropertyToExtract) {
132
- if (objWithPropertyToExtract[key] === getClosureSafeProperty) {
133
- return key;
134
- }
135
- }
136
- throw Error('Could not find renamed property on target object.');
137
- }
138
-
139
- /**
140
- * @license
141
- * Copyright Google LLC All Rights Reserved.
142
- *
143
- * Use of this source code is governed by an MIT-style license that can be
144
- * found in the LICENSE file at https://angular.io/license
145
- */
146
- const __forward_ref__ = getClosureSafeProperty({
147
- __forward_ref__: getClosureSafeProperty,
148
- });
149
- /**
150
- * Allows to refer to references which are not yet defined.
151
- *
152
- * For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
153
- * DI is declared, but not yet defined. It is also used when the `token` which we use when creating
154
- * a query is not yet defined.
155
- *
156
- * `forwardRef` is also used to break circularities in standalone components imports.
157
- *
158
- * @usageNotes
159
- * ### Circular dependency example
160
- * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
161
- *
162
- * ### Circular standalone reference import example
163
- * ```ts
164
- * @Component({
165
- * standalone: true,
166
- * imports: [ChildComponent],
167
- * selector: 'app-parent',
168
- * template: `<app-child [hideParent]="hideParent"></app-child>`,
169
- * })
170
- * export class ParentComponent {
171
- * @Input() hideParent: boolean;
172
- * }
173
- *
174
- *
175
- * @Component({
176
- * standalone: true,
177
- * imports: [CommonModule, forwardRef(() => ParentComponent)],
178
- * selector: 'app-child',
179
- * template: `<app-parent *ngIf="!hideParent"></app-parent>`,
180
- * })
181
- * export class ChildComponent {
182
- * @Input() hideParent: boolean;
183
- * }
184
- * ```
185
- *
186
- * @publicApi
187
- */
188
- function forwardRef(forwardRefFn) {
189
- forwardRefFn.__forward_ref__ = forwardRef;
190
- forwardRefFn.toString = function () {
191
- return stringify(this());
192
- };
193
- return forwardRefFn;
194
- }
195
- /**
196
- * Lazily retrieves the reference value from a forwardRef.
197
- *
198
- * Acts as the identity function when given a non-forward-ref value.
199
- *
200
- * @usageNotes
201
- * ### Example
202
- *
203
- * {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
204
- *
205
- * @see {@link forwardRef}
206
- * @publicApi
207
- */
208
- function resolveForwardRef(type) {
209
- return isForwardRef(type) ? type() : type;
210
- }
211
- /** Checks whether a function is wrapped by a `forwardRef`. */
212
- function isForwardRef(fn) {
213
- return (typeof fn === 'function' &&
214
- fn.hasOwnProperty(__forward_ref__) &&
215
- fn.__forward_ref__ === forwardRef);
216
- }
217
-
218
- /**
219
- * @license
220
- * Copyright Google LLC All Rights Reserved.
221
- *
222
- * Use of this source code is governed by an MIT-style license that can be
223
- * found in the LICENSE file at https://angular.io/license
224
- */
225
- /** Throws an error when a token is not found in DI. */
226
- function throwProviderNotFoundError(token, injectorName) {
227
- const errorMessage = null;
228
- throw new RuntimeError(-201 /* RuntimeErrorCode.PROVIDER_NOT_FOUND */, errorMessage);
229
- }
230
-
231
- /**
232
- * @license
233
- * Copyright Google LLC All Rights Reserved.
234
- *
235
- * Use of this source code is governed by an MIT-style license that can be
236
- * found in the LICENSE file at https://angular.io/license
237
- */
238
- /**
239
- * Construct an injectable definition which defines how a token will be constructed by the DI
240
- * system, and in which injectors (if any) it will be available.
241
- *
242
- * This should be assigned to a static `ɵprov` field on a type, which will then be an
243
- * `InjectableType`.
244
- *
245
- * Options:
246
- * * `providedIn` determines which injectors will include the injectable, by either associating it
247
- * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be
248
- * provided in the `'root'` injector, which will be the application-level injector in most apps.
249
- * * `factory` gives the zero argument function which will create an instance of the injectable.
250
- * The factory can call [`inject`](api/core/inject) to access the `Injector` and request injection
251
- * of dependencies.
252
- *
253
- * @codeGenApi
254
- * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm.
255
- */
256
- function ɵɵdefineInjectable(opts) {
257
- return {
258
- token: opts.token,
259
- providedIn: opts.providedIn || null,
260
- factory: opts.factory,
261
- value: undefined,
262
- };
263
- }
264
- /**
265
- * Construct an `InjectorDef` which configures an injector.
266
- *
267
- * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an
268
- * `InjectorType`.
269
- *
270
- * Options:
271
- *
272
- * * `providers`: an optional array of providers to add to the injector. Each provider must
273
- * either have a factory or point to a type which has a `ɵprov` static property (the
274
- * type must be an `InjectableType`).
275
- * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s
276
- * whose providers will also be added to the injector. Locally provided types will override
277
- * providers from imports.
278
- *
279
- * @codeGenApi
280
- */
281
- function ɵɵdefineInjector(options) {
282
- return { providers: options.providers || [], imports: options.imports || [] };
283
- }
284
- /**
285
- * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading
286
- * inherited value.
287
- *
288
- * @param type A type which may have its own (non-inherited) `ɵprov`.
289
- */
290
- function getInjectableDef(type) {
291
- return (getOwnDefinition(type, NG_PROV_DEF) || {
292
- token: type,
293
- factory: () => new type(),
294
- ...type.injectOptions,
295
- });
296
- }
297
- function isInjectable(type) {
298
- return getInjectableDef(type) !== null;
299
- }
300
- /**
301
- * Return definition only if it is defined directly on `type` and is not inherited from a base
302
- * class of `type`.
303
- */
304
- function getOwnDefinition(type, field) {
305
- return type.hasOwnProperty(field) ? type[field] : null;
306
- }
307
- /**
308
- * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors.
309
- *
310
- * @param type A type which may have `ɵprov`, via inheritance.
311
- *
312
- * @deprecated Will be removed in a future version of Angular, where an error will occur in the
313
- * scenario if we find the `ɵprov` on an ancestor only.
314
- */
315
- function getInheritedInjectableDef(type) {
316
- const def = type && (type[NG_PROV_DEF] || null);
317
- if (def) {
318
- return def;
319
- }
320
- else {
321
- return null;
322
- }
323
- }
324
- /**
325
- * Read the injector def type in a way which is immune to accidentally reading inherited value.
326
- *
327
- * @param type type which may have an injector def (`ɵinj`)
328
- */
329
- function getInjectorDef(type) {
330
- return type && (type.hasOwnProperty(NG_INJ_DEF) || false)
331
- ? type[NG_INJ_DEF]
332
- : null;
333
- }
334
- const NG_PROV_DEF = getClosureSafeProperty({
335
- ɵprov: getClosureSafeProperty,
336
- });
337
- const NG_INJ_DEF = getClosureSafeProperty({
338
- ɵinj: getClosureSafeProperty,
339
- });
340
-
341
- /**
342
- * @license
343
- * Copyright Google LLC All Rights Reserved.
344
- *
345
- * Use of this source code is governed by an MIT-style license that can be
346
- * found in the LICENSE file at https://angular.io/license
347
- */
348
- /**
349
- * Injection flags for DI.
350
- *
351
- * @publicApi
352
- * @deprecated use an options object for [`inject`](api/core/inject) instead.
353
- */
354
- var InjectFlags;
355
- (function (InjectFlags) {
356
- // TODO(alxhub): make this 'const' (and remove `InternalInjectFlags` enum) when ngc no longer
357
- // writes exports of it into ngfactory files.
358
- /** Check self and check parent injector if needed */
359
- InjectFlags[InjectFlags["Default"] = 0] = "Default";
360
- /** Don't ascend to ancestors of the node requesting injection. */
361
- InjectFlags[InjectFlags["Self"] = 2] = "Self";
362
- /** Skip the node that is requesting injection. */
363
- InjectFlags[InjectFlags["SkipSelf"] = 4] = "SkipSelf";
364
- /** Inject `defaultValue` instead if token not found. */
365
- InjectFlags[InjectFlags["Optional"] = 8] = "Optional";
366
- })(InjectFlags || (InjectFlags = {}));
367
-
368
- /**
369
- * @license
370
- * Copyright Google LLC All Rights Reserved.
371
- *
372
- * Use of this source code is governed by an MIT-style license that can be
373
- * found in the LICENSE file at https://angular.io/license
374
- */
375
- /**
376
- * Current implementation of inject.
377
- *
378
- * By default, it is `injectInjectorOnly`, which makes it `Injector`-only aware. It can be changed
379
- * to `directiveInject`, which brings in the `NodeInjector` system of ivy. It is designed this
380
- * way for two reasons:
381
- * 1. `Injector` should not depend on ivy logic.
382
- * 2. To maintain tree shake-ability we don't want to bring in unnecessary code.
383
- */
384
- let _injectImplementation;
385
- function getInjectImplementation() {
386
- return _injectImplementation;
387
- }
388
- /**
389
- * Sets the current inject implementation.
390
- */
391
- function setInjectImplementation(impl) {
392
- const previous = _injectImplementation;
393
- _injectImplementation = impl;
394
- return previous;
395
- }
396
- /**
397
- * Injects `root` tokens in limp mode.
398
- *
399
- * If no injector exists, we can still inject tree-shakable providers which have `providedIn` set to
400
- * `"root"`. This is known as the limp mode injection. In such case the value is stored in the
401
- * injectable definition.
402
- */
403
- function injectRootLimpMode(token, notFoundValue, flags) {
404
- const injectableDef = getInjectableDef(token);
405
- if (injectableDef && injectableDef.providedIn == 'root') {
406
- return injectableDef.value === undefined
407
- ? (injectableDef.value = injectableDef.factory())
408
- : injectableDef.value;
409
- }
410
- if (flags & InjectFlags.Optional)
411
- return null;
412
- throwProviderNotFoundError();
413
- }
414
-
415
- /**
416
- * @license
417
- * Copyright Google LLC All Rights Reserved.
418
- *
419
- * Use of this source code is governed by an MIT-style license that can be
420
- * found in the LICENSE file at https://angular.io/license
421
- */
422
- const _THROW_IF_NOT_FOUND = {};
423
- const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND;
424
- /*
425
- * Name of a property (that we patch onto DI decorator), which is used as an annotation of which
426
- * InjectFlag this decorator represents. This allows to avoid direct references to the DI decorators
427
- * in the code, thus making them tree-shakable.
428
- */
429
- const DI_DECORATOR_FLAG = '__NG_DI_FLAG__';
430
- const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath';
431
- const NG_TOKEN_PATH = 'ngTokenPath';
432
- const NEW_LINE = /\n/gm;
433
- const NO_NEW_LINE = 'ɵ';
434
- const SOURCE = '__source';
435
- /**
436
- * Current injector value used by `inject`.
437
- * - `undefined`: it is an error to call `inject`
438
- * - `null`: `inject` can be called but there is no injector (limp-mode).
439
- * - Injector instance: Use the injector for resolution.
440
- */
441
- let _currentInjector = undefined;
442
- function getCurrentInjector() {
443
- return _currentInjector;
444
- }
445
- function setCurrentInjector(injector) {
446
- const former = _currentInjector;
447
- _currentInjector = injector;
448
- return former;
449
- }
450
- function injectInjectorOnly(token, flags = InjectFlags.Default) {
451
- if (_currentInjector === undefined) {
452
- throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, null);
453
- }
454
- else if (_currentInjector === null) {
455
- return injectRootLimpMode(token, undefined, flags);
456
- }
457
- else {
458
- const value = _currentInjector.get(token, flags & InjectFlags.Optional ? null : undefined, flags);
459
- return value;
460
- }
461
- }
462
- function ɵɵinject(token, flags = InjectFlags.Default) {
463
- return (getInjectImplementation() || injectInjectorOnly)(resolveForwardRef(token), flags);
464
- }
465
- /**
466
- * Throws an error indicating that a factory function could not be generated by the compiler for a
467
- * particular class.
468
- *
469
- * The name of the class is not mentioned here, but will be in the generated factory function name
470
- * and thus in the stack trace.
471
- *
472
- * @codeGenApi
473
- */
474
- function ɵɵinvalidFactoryDep(index) {
475
- throw new RuntimeError(202 /* RuntimeErrorCode.INVALID_FACTORY_DEPENDENCY */, null);
476
- }
477
- /**
478
- * @param token A token that represents a static attribute on the host node that should be injected.
479
- * @returns Value of the attribute if it exists.
480
- * @throws If called outside of a supported context or the attribute does not exist.
481
- *
482
- * @publicApi
483
- */
484
- /**
485
- * @param token A token that represents a static attribute on the host node that should be injected.
486
- * @returns Value of the attribute if it exists, otherwise `null`.
487
- * @throws If called outside of a supported context.
488
- *
489
- * @publicApi
490
- */
491
- /**
492
- * @param token A token that represents a static attribute on the host node that should be injected.
493
- * @returns Value of the attribute if it exists.
494
- * @throws If called outside of a supported context or the attribute does not exist.
495
- *
496
- * @publicApi
497
- */
498
- /**
499
- * Injects a token from the currently active injector.
500
- * `inject` is only supported in an [injection context](/guide/dependency-injection-context). It can
501
- * be used during:
502
- * - Construction (via the `constructor`) of a class being instantiated by the DI system, such
503
- * as an `@Injectable` or `@Component`.
504
- * - In the initializer for fields of such classes.
505
- * - In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`.
506
- * - In the `factory` function specified for an `InjectionToken`.
507
- * - In a stackframe of a function call in a DI context
508
- *
509
- * @param token A token that represents a dependency that should be injected.
510
- * @param flags Optional flags that control how injection is executed.
511
- * The flags correspond to injection strategies that can be specified with
512
- * parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`.
513
- * @returns the injected value if operation is successful, `null` otherwise.
514
- * @throws if called outside of a supported context.
515
- *
516
- * @usageNotes
517
- * In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a
518
- * field initializer:
519
- *
520
- * ```typescript
521
- * @Injectable({providedIn: 'root'})
522
- * export class Car {
523
- * radio: Radio|undefined;
524
- * // OK: field initializer
525
- * spareTyre = inject(Tyre);
526
- *
527
- * constructor() {
528
- * // OK: constructor body
529
- * this.radio = inject(Radio);
530
- * }
531
- * }
532
- * ```
533
- *
534
- * It is also legal to call `inject` from a provider's factory:
535
- *
536
- * ```typescript
537
- * providers: [
538
- * {provide: Car, useFactory: () => {
539
- * // OK: a class factory
540
- * const engine = inject(Engine);
541
- * return new Car(engine);
542
- * }}
543
- * ]
544
- * ```
545
- *
546
- * Calls to the `inject()` function outside of the class creation context will result in error. Most
547
- * notably, calls to `inject()` are disallowed after a class instance was created, in methods
548
- * (including lifecycle hooks):
549
- *
550
- * ```typescript
551
- * @Component({ ... })
552
- * export class CarComponent {
553
- * ngOnInit() {
554
- * // ERROR: too late, the component instance was already created
555
- * const engine = inject(Engine);
556
- * engine.start();
557
- * }
558
- * }
559
- * ```
560
- *
561
- * @publicApi
562
- */
563
- function inject(token, flags = InjectFlags.Default) {
564
- // The `as any` here _shouldn't_ be necessary, but without it JSCompiler
565
- // throws a disambiguation error due to the multiple signatures.
566
- return ɵɵinject(token, convertToBitFlags(flags));
567
- }
568
- // Converts object-based DI flags (`InjectOptions`) to bit flags (`InjectFlags`).
569
- function convertToBitFlags(flags) {
570
- if (typeof flags === 'undefined' || typeof flags === 'number') {
571
- return flags;
572
- }
573
- // While TypeScript doesn't accept it without a cast, bitwise OR with false-y values in
574
- // JavaScript is a no-op. We can use that for a very codesize-efficient conversion from
575
- // `InjectOptions` to `InjectFlags`.
576
- return (0 /* InternalInjectFlags.Default */ | // comment to force a line break in the formatter
577
- (flags.optional && 8 /* InternalInjectFlags.Optional */) |
578
- 0 |
579
- (flags.self && 2 /* InternalInjectFlags.Self */) |
580
- (flags.skipSelf &&
581
- 4 /* InternalInjectFlags.SkipSelf */));
582
- }
583
- function injectArgs(types) {
584
- const args = [];
585
- for (let i = 0; i < types.length; i++) {
586
- const arg = resolveForwardRef(types[i]);
587
- if (Array.isArray(arg)) {
588
- if (arg.length === 0) {
589
- throw new RuntimeError(900 /* RuntimeErrorCode.INVALID_DIFFER_INPUT */, null);
590
- }
591
- let type = undefined;
592
- let flags = InjectFlags.Default;
593
- for (let j = 0; j < arg.length; j++) {
594
- const meta = arg[j];
595
- const flag = getInjectFlag(meta);
596
- if (typeof flag === 'number') {
597
- // Special case when we handle @Inject decorator.
598
- if (flag === -1 /* DecoratorFlags.Inject */) {
599
- type = meta.token;
600
- }
601
- else {
602
- flags |= flag;
603
- }
604
- }
605
- else {
606
- type = meta;
607
- }
608
- }
609
- args.push(ɵɵinject(type, flags));
610
- }
611
- else {
612
- args.push(ɵɵinject(arg));
613
- }
614
- }
615
- return args;
616
- }
617
- /**
618
- * Attaches a given InjectFlag to a given decorator using monkey-patching.
619
- * Since DI decorators can be used in providers `deps` array (when provider is configured using
620
- * `useFactory`) without initialization (e.g. `Host`) and as an instance (e.g. `new Host()`), we
621
- * attach the flag to make it available both as a static property and as a field on decorator
622
- * instance.
623
- *
624
- * @param decorator Provided DI decorator.
625
- * @param flag InjectFlag that should be applied.
626
- */
627
- function attachInjectFlag(decorator, flag) {
628
- decorator[DI_DECORATOR_FLAG] = flag;
629
- decorator.prototype[DI_DECORATOR_FLAG] = flag;
630
- return decorator;
631
- }
632
- /**
633
- * Reads monkey-patched property that contains InjectFlag attached to a decorator.
634
- *
635
- * @param token Token that may contain monkey-patched DI flags property.
636
- */
637
- function getInjectFlag(token) {
638
- return token[DI_DECORATOR_FLAG];
639
- }
640
- function catchInjectorError(e, token, injectorErrorName, source) {
641
- const tokenPath = e[NG_TEMP_TOKEN_PATH];
642
- if (token[SOURCE]) {
643
- tokenPath.unshift(token[SOURCE]);
644
- }
645
- e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source);
646
- e[NG_TOKEN_PATH] = tokenPath;
647
- e[NG_TEMP_TOKEN_PATH] = null;
648
- throw e;
649
- }
650
- function formatError(text, obj, injectorErrorName, source = null) {
651
- text =
652
- text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE
653
- ? text.slice(2)
654
- : text;
655
- let context = stringify(obj);
656
- if (Array.isArray(obj)) {
657
- context = obj.map(stringify).join(' -> ');
658
- }
659
- else if (typeof obj === 'object') {
660
- let parts = [];
661
- for (let key in obj) {
662
- if (obj.hasOwnProperty(key)) {
663
- let value = obj[key];
664
- parts.push(key +
665
- ':' +
666
- (typeof value === 'string'
667
- ? JSON.stringify(value)
668
- : stringify(value)));
669
- }
670
- }
671
- context = `{${parts.join(', ')}}`;
672
- }
673
- return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace(NEW_LINE, '\n ')}`;
674
- }
675
-
676
- /**
677
- * @license
678
- * Copyright Google LLC All Rights Reserved.
679
- *
680
- * Use of this source code is governed by an MIT-style license that can be
681
- * found in the LICENSE file at https://angular.io/license
682
- */
683
- /**
684
- * Inject decorator and metadata.
685
- *
686
- * @Annotation
687
- * @publicApi
688
- */
689
- const Inject = attachInjectFlag(
690
- // Disable tslint because `DecoratorFlags` is a const enum which gets inlined.
691
- // tslint:disable-next-line: no-toplevel-property-access
692
- makeParamDecorator('Inject', (token) => ({ token })), -1 /* DecoratorFlags.Inject */);
693
- /**
694
- * Optional decorator and metadata.
695
- *
696
- * @Annotation
697
- * @publicApi
698
- */
699
- const Optional =
700
- // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
701
- // tslint:disable-next-line: no-toplevel-property-access
702
- attachInjectFlag(makeParamDecorator(), 8 /* InternalInjectFlags.Optional */);
703
- /**
704
- * Self decorator and metadata.
705
- *
706
- * @Annotation
707
- * @publicApi
708
- */
709
- const Self =
710
- // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
711
- // tslint:disable-next-line: no-toplevel-property-access
712
- attachInjectFlag(makeParamDecorator(), 2 /* InternalInjectFlags.Self */);
713
- /**
714
- * `SkipSelf` decorator and metadata.
715
- *
716
- * @Annotation
717
- * @publicApi
718
- */
719
- const SkipSelf =
720
- // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined.
721
- // tslint:disable-next-line: no-toplevel-property-access
722
- attachInjectFlag(makeParamDecorator(), 4 /* InternalInjectFlags.SkipSelf */);
723
-
724
- /**
725
- * @license
726
- * Copyright Google LLC All Rights Reserved.
727
- *
728
- * Use of this source code is governed by an MIT-style license that can be
729
- * found in the LICENSE file at https://angular.io/license
730
- */
731
- function getFactoryDef(type, throwNotFound) {
732
- return () => new type();
733
- }
734
-
735
- /**
736
- * @license
737
- * Copyright Google LLC All Rights Reserved.
738
- *
739
- * Use of this source code is governed by an MIT-style license that can be
740
- * found in the LICENSE file at https://angular.io/license
741
- */
742
- getClosureSafeProperty({
743
- ɵfac: getClosureSafeProperty,
744
- });
745
- /**
746
- * The `NG_ENV_ID` field on a DI token indicates special processing in the `EnvironmentInjector`:
747
- * getting such tokens from the `EnvironmentInjector` will bypass the standard DI resolution
748
- * strategy and instead will return implementation produced by the `NG_ENV_ID` factory function.
749
- *
750
- * This particular retrieval of DI tokens is mostly done to eliminate circular dependencies and
751
- * improve tree-shaking.
752
- */
753
- const NG_ENV_ID = getClosureSafeProperty({
754
- __NG_ENV_ID__: getClosureSafeProperty,
755
- });
756
-
757
- /**
758
- * @license
759
- * Copyright Google LLC All Rights Reserved.
760
- *
761
- * Use of this source code is governed by an MIT-style license that can be
762
- * found in the LICENSE file at https://angular.io/license
763
- */
764
- /**
765
- * This file contains reuseable "empty" symbols that can be used as default return values
766
- * in different parts of the rendering code. Because the same symbols are returned, this
767
- * allows for identity checks against these values to be consistently used by the framework
768
- * code.
769
- */
770
- const EMPTY_ARRAY = [];
771
-
772
- /**
773
- * @license
774
- * Copyright Google LLC All Rights Reserved.
775
- *
776
- * Use of this source code is governed by an MIT-style license that can be
777
- * found in the LICENSE file at https://angular.io/license
778
- */
779
- /**
780
- * Creates a token that can be used in a DI Provider.
781
- *
782
- * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a
783
- * runtime representation) such as when injecting an interface, callable type, array or
784
- * parameterized type.
785
- *
786
- * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by
787
- * the `Injector`. This provides an additional level of type safety.
788
- *
789
- * <div class="alert is-helpful">
790
- *
791
- * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the
792
- * provider and the injection call. Creating a new instance of `InjectionToken` in different places,
793
- * even with the same description, will be treated as different tokens by Angular's DI system,
794
- * leading to a `NullInjectorError`.
795
- *
796
- * </div>
797
- *
798
- * <code-example format="typescript" language="typescript" path="injection-token/src/main.ts"
799
- * region="InjectionToken"></code-example>
800
- *
801
- * When creating an `InjectionToken`, you can optionally specify a factory function which returns
802
- * (possibly by creating) a default value of the parameterized type `T`. This sets up the
803
- * `InjectionToken` using this factory as a provider as if it was defined explicitly in the
804
- * application's root injector. If the factory function, which takes zero arguments, needs to inject
805
- * dependencies, it can do so using the [`inject`](api/core/inject) function.
806
- * As you can see in the Tree-shakable InjectionToken example below.
807
- *
808
- * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which
809
- * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note:
810
- * this option is now deprecated). As mentioned above, `'root'` is the default value for
811
- * `providedIn`.
812
- *
813
- * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated.
814
- *
815
- * @usageNotes
816
- * ### Basic Examples
817
- *
818
- * ### Plain InjectionToken
819
- *
820
- * {@example core/di/ts/injector_spec.ts region='InjectionToken'}
821
- *
822
- * ### Tree-shakable InjectionToken
823
- *
824
- * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'}
825
- *
826
- * @publicApi
827
- */
828
- class InjectionToken {
829
- _desc;
830
- /** @internal */
831
- ngMetadataName = 'InjectionToken';
832
- ɵprov;
833
- /**
834
- * @param _desc Description for the token,
835
- * used only for debugging purposes,
836
- * it should but does not need to be unique
837
- * @param options Options for the token's usage, as described above
838
- */
839
- constructor(_desc, options) {
840
- this._desc = _desc;
841
- this.ɵprov = undefined;
842
- if (typeof options == 'number') ;
843
- else if (options !== undefined) {
844
- this.ɵprov = ɵɵdefineInjectable({
845
- token: this,
846
- providedIn: options.providedIn || 'root',
847
- factory: options.factory,
848
- });
849
- }
850
- }
851
- /**
852
- * @internal
853
- */
854
- get multi() {
855
- return this;
856
- }
857
- toString() {
858
- return `InjectionToken ${this._desc}`;
859
- }
860
- }
861
-
862
- /**
863
- * @license
864
- * Copyright Google LLC All Rights Reserved.
865
- *
866
- * Use of this source code is governed by an MIT-style license that can be
867
- * found in the LICENSE file at https://angular.io/license
868
- */
869
- /**
870
- * A multi-provider token for initialization functions that will run upon construction of an
871
- * environment injector.
872
- *
873
- * @publicApi
874
- */
875
- const ENVIRONMENT_INITIALIZER = new InjectionToken('');
876
-
877
- /**
878
- * @license
879
- * Copyright Google LLC All Rights Reserved.
880
- *
881
- * Use of this source code is governed by an MIT-style license that can be
882
- * found in the LICENSE file at https://angular.io/license
883
- */
884
- /**
885
- * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors.
886
- *
887
- * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a
888
- * project.
889
- *
890
- * @publicApi
891
- */
892
- const INJECTOR = new InjectionToken('',
893
- // Disable tslint because this is const enum which gets inlined not top level prop access.
894
- // tslint:disable-next-line: no-toplevel-property-access
895
- -1 /* InjectorMarkers.Injector */);
896
-
897
- /**
898
- * @license
899
- * Copyright Google LLC All Rights Reserved.
900
- *
901
- * Use of this source code is governed by an MIT-style license that can be
902
- * found in the LICENSE file at https://angular.io/license
903
- */
904
- function isEnvironmentProviders(value) {
905
- return value && !!value.ɵproviders;
906
- }
907
-
908
- /**
909
- * @license
910
- * Copyright Google LLC All Rights Reserved.
911
- *
912
- * Use of this source code is governed by an MIT-style license that can be
913
- * found in the LICENSE file at https://angular.io/license
914
- */
915
- const INJECTOR_DEF_TYPES = new InjectionToken('');
916
-
917
- /**
918
- * @license
919
- * Copyright Google LLC All Rights Reserved.
920
- *
921
- * Use of this source code is governed by an MIT-style license that can be
922
- * found in the LICENSE file at https://angular.io/license
923
- */
924
- class NullInjector {
925
- get(token, notFoundValue = THROW_IF_NOT_FOUND) {
926
- if (notFoundValue === THROW_IF_NOT_FOUND) {
927
- const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`);
928
- error.name = 'NullInjectorError';
929
- throw error;
930
- }
931
- return notFoundValue;
932
- }
933
- }
934
-
935
- /**
936
- * @license
937
- * Copyright Google LLC All Rights Reserved.
938
- *
939
- * Use of this source code is governed by an MIT-style license that can be
940
- * found in the LICENSE file at https://angular.io/license
941
- */
942
- /**
943
- * Collects providers from all NgModules and standalone components, including transitively imported
944
- * ones.
945
- *
946
- * Providers extracted via `importProvidersFrom` are only usable in an application injector or
947
- * another environment injector (such as a route injector). They should not be used in component
948
- * providers.
949
- *
950
- * More information about standalone components can be found in [this
951
- * guide](guide/standalone-components).
952
- *
953
- * @usageNotes
954
- * The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call:
955
- *
956
- * ```typescript
957
- * await bootstrapApplication(RootComponent, {
958
- * providers: [
959
- * importProvidersFrom(NgModuleOne, NgModuleTwo)
960
- * ]
961
- * });
962
- * ```
963
- *
964
- * You can also use the `importProvidersFrom` results in the `providers` field of a route, when a
965
- * standalone component is used:
966
- *
967
- * ```typescript
968
- * export const ROUTES: Route[] = [
969
- * {
970
- * path: 'foo',
971
- * providers: [
972
- * importProvidersFrom(NgModuleOne, NgModuleTwo)
973
- * ],
974
- * component: YourStandaloneComponent
975
- * }
976
- * ];
977
- * ```
978
- *
979
- * @returns Collected providers from the specified list of types.
980
- * @publicApi
981
- */
982
- function importProvidersFrom(...sources) {
983
- return {
984
- ɵproviders: internalImportProvidersFrom(true, sources),
985
- ɵfromNgModule: true,
986
- };
987
- }
988
- function internalImportProvidersFrom(checkForStandaloneCmp, ...sources) {
989
- const providersOut = [];
990
- return providersOut;
991
- }
992
- const USE_VALUE = getClosureSafeProperty({
993
- provide: String,
994
- useValue: getClosureSafeProperty,
995
- });
996
- function isValueProvider(value) {
997
- return value !== null && typeof value == 'object' && USE_VALUE in value;
998
- }
999
- function isExistingProvider(value) {
1000
- return !!(value && value.useExisting);
1001
- }
1002
- function isFactoryProvider(value) {
1003
- return !!(value && value.useFactory);
1004
- }
1005
- function isTypeProvider(value) {
1006
- return typeof value === 'function';
1007
- }
1008
-
1009
- /**
1010
- * @license
1011
- * Copyright Google LLC All Rights Reserved.
1012
- *
1013
- * Use of this source code is governed by an MIT-style license that can be
1014
- * found in the LICENSE file at https://angular.io/license
1015
- */
1016
- /**
1017
- * An internal token whose presence in an injector indicates that the injector should treat itself
1018
- * as a root scoped injector when processing requests for unknown tokens which may indicate
1019
- * they are provided in the root scope.
1020
- */
1021
- const INJECTOR_SCOPE = new InjectionToken('');
1022
-
1023
- /**
1024
- * @license
1025
- * Copyright Google LLC All Rights Reserved.
1026
- *
1027
- * Use of this source code is governed by an MIT-style license that can be
1028
- * found in the LICENSE file at https://angular.io/license
1029
- */
1030
- /**
1031
- * Marker which indicates that a value has not yet been created from the factory function.
1032
- */
1033
- const NOT_YET = {};
1034
- /**
1035
- * Marker which indicates that the factory function for a token is in the process of being called.
1036
- *
1037
- * If the injector is asked to inject a token with its value set to CIRCULAR, that indicates
1038
- * injection of a dependency has recursively attempted to inject the original token, and there is
1039
- * a circular dependency among the providers.
1040
- */
1041
- const CIRCULAR = {};
1042
- /**
1043
- * A lazily initialized NullInjector.
1044
- */
1045
- let NULL_INJECTOR = undefined;
1046
- function getNullInjector() {
1047
- if (NULL_INJECTOR === undefined) {
1048
- NULL_INJECTOR = new NullInjector();
1049
- }
1050
- return NULL_INJECTOR;
1051
- }
1052
- /**
1053
- * An `Injector` that's part of the environment injector hierarchy, which exists outside of the
1054
- * component tree.
1055
- */
1056
- class EnvironmentInjector {
1057
- }
1058
- class R3Injector extends EnvironmentInjector {
1059
- parent;
1060
- source;
1061
- scopes;
1062
- /**
1063
- * Map of tokens to records which contain the instances of those tokens.
1064
- * - `null` value implies that we don't have the record. Used by tree-shakable injectors
1065
- * to prevent further searches.
1066
- */
1067
- records = new Map();
1068
- /**
1069
- * Set of values instantiated by this injector which contain `ngOnDestroy` lifecycle hooks.
1070
- */
1071
- _ngOnDestroyHooks = new Set();
1072
- _onDestroyHooks = [];
1073
- /**
1074
- * Flag indicating that this injector was previously destroyed.
1075
- */
1076
- get destroyed() {
1077
- return this._destroyed;
1078
- }
1079
- _destroyed = false;
1080
- injectorDefTypes;
1081
- constructor(providers, parent, source, scopes) {
1082
- super();
1083
- this.parent = parent;
1084
- this.source = source;
1085
- this.scopes = scopes;
1086
- // Start off by creating Records for every provider.
1087
- forEachSingleProvider(providers, (provider) => this.processProvider(provider));
1088
- // Make sure the INJECTOR token provides this injector.
1089
- this.records.set(INJECTOR, makeRecord(undefined, this));
1090
- // And `EnvironmentInjector` if the current injector is supposed to be env-scoped.
1091
- if (scopes.has('environment')) {
1092
- this.records.set(EnvironmentInjector, makeRecord(undefined, this));
1093
- }
1094
- // Detect whether this injector has the APP_ROOT_SCOPE token and thus should provide
1095
- // any injectable scoped to APP_ROOT_SCOPE.
1096
- const record = this.records.get(INJECTOR_SCOPE);
1097
- if (record != null && typeof record.value === 'string') {
1098
- this.scopes.add(record.value);
1099
- }
1100
- this.injectorDefTypes = new Set(this.get(INJECTOR_DEF_TYPES, EMPTY_ARRAY, InjectFlags.Self));
1101
- }
1102
- /**
1103
- * Destroy the injector and release references to every instance or provider associated with it.
1104
- *
1105
- * Also calls the `OnDestroy` lifecycle hooks of every instance that was created for which a
1106
- * hook was found.
1107
- */
1108
- destroy() {
1109
- this.assertNotDestroyed();
1110
- // Set destroyed = true first, in case lifecycle hooks re-enter destroy().
1111
- this._destroyed = true;
1112
- try {
1113
- // Call all the lifecycle hooks.
1114
- for (const service of this._ngOnDestroyHooks) {
1115
- service.ngOnDestroy();
1116
- }
1117
- const onDestroyHooks = this._onDestroyHooks;
1118
- // Reset the _onDestroyHooks array before iterating over it to prevent hooks that unregister
1119
- // themselves from mutating the array during iteration.
1120
- this._onDestroyHooks = [];
1121
- for (const hook of onDestroyHooks) {
1122
- hook();
1123
- }
1124
- }
1125
- finally {
1126
- // Release all references.
1127
- this.records.clear();
1128
- this._ngOnDestroyHooks.clear();
1129
- this.injectorDefTypes.clear();
1130
- }
1131
- }
1132
- onDestroy(callback) {
1133
- this.assertNotDestroyed();
1134
- this._onDestroyHooks.push(callback);
1135
- return () => this.removeOnDestroy(callback);
1136
- }
1137
- runInContext(fn) {
1138
- this.assertNotDestroyed();
1139
- const previousInjector = setCurrentInjector(this);
1140
- const previousInjectImplementation = setInjectImplementation(undefined);
1141
- try {
1142
- return fn();
1143
- }
1144
- finally {
1145
- setCurrentInjector(previousInjector);
1146
- setInjectImplementation(previousInjectImplementation);
1147
- }
1148
- }
1149
- get(token, notFoundValue = THROW_IF_NOT_FOUND, flags = InjectFlags.Default) {
1150
- this.assertNotDestroyed();
1151
- if (token.hasOwnProperty(NG_ENV_ID)) {
1152
- return token[NG_ENV_ID](this);
1153
- }
1154
- flags = convertToBitFlags(flags);
1155
- const previousInjector = setCurrentInjector(this);
1156
- const previousInjectImplementation = setInjectImplementation(undefined);
1157
- try {
1158
- // Check for the SkipSelf flag.
1159
- if (!(flags & InjectFlags.SkipSelf)) {
1160
- // SkipSelf isn't set, check if the record belongs to this injector.
1161
- let record = this.records.get(token);
1162
- if (record === undefined) {
1163
- // No record, but maybe the token is scoped to this injector. Look for an injectable
1164
- // def with a scope matching this injector.
1165
- const def = couldBeInjectableType(token) && getInjectableDef(token);
1166
- if (def && this.injectableDefInScope(def)) {
1167
- // Found an injectable def and it's scoped to this injector. Pretend as if it was here
1168
- // all along.
1169
- if (false) ;
1170
- record = makeRecord(injectableDefOrInjectorDefFactory(token), NOT_YET);
1171
- }
1172
- else {
1173
- record = null;
1174
- }
1175
- this.records.set(token, record);
1176
- }
1177
- // If a record was found, get the instance for it and return it.
1178
- if (record != null /* NOT null || undefined */) {
1179
- return this.hydrate(token, record);
1180
- }
1181
- }
1182
- // Select the next injector based on the Self flag - if self is set, the next injector is
1183
- // the NullInjector, otherwise it's the parent.
1184
- const nextInjector = !(flags & InjectFlags.Self)
1185
- ? this.parent
1186
- : getNullInjector();
1187
- // Set the notFoundValue based on the Optional flag - if optional is set and notFoundValue
1188
- // is undefined, the value is null, otherwise it's the notFoundValue.
1189
- notFoundValue =
1190
- flags & InjectFlags.Optional && notFoundValue === THROW_IF_NOT_FOUND
1191
- ? null
1192
- : notFoundValue;
1193
- return nextInjector.get(token, notFoundValue);
1194
- }
1195
- catch (e) {
1196
- if (e.name === 'NullInjectorError') {
1197
- const path = (e[NG_TEMP_TOKEN_PATH] =
1198
- e[NG_TEMP_TOKEN_PATH] || []);
1199
- path.unshift(stringify(token));
1200
- if (previousInjector) {
1201
- // We still have a parent injector, keep throwing
1202
- throw e;
1203
- }
1204
- else {
1205
- // Format & throw the final error message when we don't have any previous injector
1206
- return catchInjectorError(e, token, 'R3InjectorError', this.source);
1207
- }
1208
- }
1209
- else {
1210
- throw e;
1211
- }
1212
- }
1213
- finally {
1214
- // Lastly, restore the previous injection context.
1215
- setInjectImplementation(previousInjectImplementation);
1216
- setCurrentInjector(previousInjector);
1217
- }
1218
- }
1219
- /** @internal */
1220
- resolveInjectorInitializers() {
1221
- const previousInjector = setCurrentInjector(this);
1222
- const previousInjectImplementation = setInjectImplementation(undefined);
1223
- try {
1224
- const initializers = this.get(ENVIRONMENT_INITIALIZER, EMPTY_ARRAY, InjectFlags.Self);
1225
- if (false) ;
1226
- for (const initializer of initializers) {
1227
- initializer();
1228
- }
1229
- }
1230
- finally {
1231
- setCurrentInjector(previousInjector);
1232
- setInjectImplementation(previousInjectImplementation);
1233
- }
1234
- }
1235
- toString() {
1236
- const tokens = [];
1237
- const records = this.records;
1238
- for (const token of records.keys()) {
1239
- tokens.push(stringify(token));
1240
- }
1241
- return `R3Injector[${tokens.join(', ')}]`;
1242
- }
1243
- assertNotDestroyed() {
1244
- if (this._destroyed) {
1245
- throw new RuntimeError(205 /* RuntimeErrorCode.INJECTOR_ALREADY_DESTROYED */, null);
1246
- }
1247
- }
1248
- /**
1249
- * Process a `SingleProvider` and add it.
1250
- */
1251
- processProvider(provider) {
1252
- // Determine the token from the provider. Either it's its own token, or has a {provide: ...}
1253
- // property.
1254
- provider = resolveForwardRef(provider);
1255
- let token = isTypeProvider(provider)
1256
- ? provider
1257
- : resolveForwardRef(provider && provider.provide);
1258
- // Construct a `Record` for the provider.
1259
- const record = providerToRecord(provider);
1260
- if (!isTypeProvider(provider) && provider.multi === true) {
1261
- // If the provider indicates that it's a multi-provider, process it specially.
1262
- // First check whether it's been defined already.
1263
- let multiRecord = this.records.get(token);
1264
- if (multiRecord) ;
1265
- else {
1266
- multiRecord = makeRecord(undefined, NOT_YET, true);
1267
- multiRecord.factory = () => injectArgs(multiRecord.multi);
1268
- this.records.set(token, multiRecord);
1269
- }
1270
- token = provider;
1271
- multiRecord.multi.push(provider);
1272
- }
1273
- this.records.set(token, record);
1274
- }
1275
- hydrate(token, record) {
1276
- try {
1277
- if (false) ;
1278
- else if (record.value === NOT_YET) {
1279
- record.value = CIRCULAR;
1280
- if (false) ;
1281
- else {
1282
- record.value = record.factory();
1283
- }
1284
- }
1285
- if (typeof record.value === 'object' &&
1286
- record.value &&
1287
- hasOnDestroy(record.value)) {
1288
- this._ngOnDestroyHooks.add(record.value);
1289
- }
1290
- return record.value;
1291
- }
1292
- finally {
1293
- }
1294
- }
1295
- injectableDefInScope(def) {
1296
- if (!def.providedIn) {
1297
- return false;
1298
- }
1299
- const providedIn = resolveForwardRef(def.providedIn);
1300
- if (typeof providedIn === 'string') {
1301
- return providedIn === 'any' || this.scopes.has(providedIn);
1302
- }
1303
- else {
1304
- return this.injectorDefTypes.has(providedIn);
1305
- }
1306
- }
1307
- removeOnDestroy(callback) {
1308
- const destroyCBIdx = this._onDestroyHooks.indexOf(callback);
1309
- if (destroyCBIdx !== -1) {
1310
- this._onDestroyHooks.splice(destroyCBIdx, 1);
1311
- }
1312
- }
1313
- }
1314
- function injectableDefOrInjectorDefFactory(token) {
1315
- // Most tokens will have an injectable def directly on them, which specifies a factory directly.
1316
- const injectableDef = getInjectableDef(token);
1317
- const factory = injectableDef !== null ? injectableDef.factory : getFactoryDef(token);
1318
- if (factory !== null) {
1319
- return factory;
1320
- }
1321
- // InjectionTokens should have an injectable def (ɵprov) and thus should be handled above.
1322
- // If it's missing that, it's an error.
1323
- if (token instanceof InjectionToken) {
1324
- throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, null);
1325
- }
1326
- // Undecorated types can sometimes be created if they have no constructor arguments.
1327
- if (token instanceof Function) {
1328
- return getUndecoratedInjectableFactory(token);
1329
- }
1330
- // There was no way to resolve a factory for this token.
1331
- throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, null);
1332
- }
1333
- function getUndecoratedInjectableFactory(token) {
1334
- // If the token has parameters then it has dependencies that we cannot resolve implicitly.
1335
- const paramLength = token.length;
1336
- if (paramLength > 0) {
1337
- throw new RuntimeError(204 /* RuntimeErrorCode.INVALID_INJECTION_TOKEN */, null);
1338
- }
1339
- // The constructor function appears to have no parameters.
1340
- // This might be because it inherits from a super-class. In which case, use an injectable
1341
- // def from an ancestor if there is one.
1342
- // Otherwise this really is a simple class with no dependencies, so return a factory that
1343
- // just instantiates the zero-arg constructor.
1344
- const inheritedInjectableDef = getInheritedInjectableDef(token);
1345
- if (inheritedInjectableDef !== null) {
1346
- return () => inheritedInjectableDef.factory(token);
1347
- }
1348
- else {
1349
- return () => new token();
1350
- }
1351
- }
1352
- function providerToRecord(provider) {
1353
- if (isValueProvider(provider)) {
1354
- return makeRecord(undefined, provider.useValue);
1355
- }
1356
- else {
1357
- const factory = providerToFactory(provider);
1358
- return makeRecord(factory, NOT_YET);
1359
- }
1360
- }
1361
- /**
1362
- * Converts a `SingleProvider` into a factory function.
1363
- *
1364
- * @param provider provider to convert to factory
1365
- */
1366
- function providerToFactory(provider, ngModuleType, providers) {
1367
- let factory = undefined;
1368
- if (isTypeProvider(provider)) {
1369
- const unwrappedProvider = resolveForwardRef(provider);
1370
- return (getFactoryDef(unwrappedProvider) ||
1371
- injectableDefOrInjectorDefFactory(unwrappedProvider));
1372
- }
1373
- else {
1374
- if (isValueProvider(provider)) {
1375
- factory = () => resolveForwardRef(provider.useValue);
1376
- }
1377
- else if (isFactoryProvider(provider)) {
1378
- factory = () => provider.useFactory(...injectArgs(provider.deps || []));
1379
- }
1380
- else if (isExistingProvider(provider)) {
1381
- factory = () => ɵɵinject(resolveForwardRef(provider.useExisting));
1382
- }
1383
- else {
1384
- const classRef = resolveForwardRef(provider &&
1385
- (provider.useClass ||
1386
- provider.provide));
1387
- if (hasDeps(provider)) {
1388
- factory = () => new classRef(...injectArgs(provider.deps));
1389
- }
1390
- else {
1391
- return (getFactoryDef(classRef) || injectableDefOrInjectorDefFactory(classRef));
1392
- }
1393
- }
1394
- }
1395
- return factory;
1396
- }
1397
- function makeRecord(factory, value, multi = false) {
1398
- return {
1399
- factory: factory,
1400
- value: value,
1401
- multi: multi ? [] : undefined,
1402
- };
1403
- }
1404
- function hasDeps(value) {
1405
- return !!value.deps;
1406
- }
1407
- function hasOnDestroy(value) {
1408
- return (value !== null &&
1409
- typeof value === 'object' &&
1410
- typeof value.ngOnDestroy === 'function');
1411
- }
1412
- function couldBeInjectableType(value) {
1413
- return (typeof value === 'function' ||
1414
- (typeof value === 'object' && value instanceof InjectionToken));
1415
- }
1416
- function forEachSingleProvider(providers, fn) {
1417
- for (const provider of providers) {
1418
- if (Array.isArray(provider)) {
1419
- forEachSingleProvider(provider, fn);
1420
- }
1421
- else if (provider && isEnvironmentProviders(provider)) {
1422
- forEachSingleProvider(provider.ɵproviders, fn);
1423
- }
1424
- else {
1425
- fn(provider);
1426
- }
1427
- }
1428
- }
1429
-
1430
- /**
1431
- * @license
1432
- * Copyright Google LLC All Rights Reserved.
1433
- *
1434
- * Use of this source code is governed by an MIT-style license that can be
1435
- * found in the LICENSE file at https://angular.io/license
1436
- */
1437
- /**
1438
- * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s.
1439
- */
1440
- function createInjector(defType, parent = null, additionalProviders = null, name) {
1441
- const injector = createInjectorWithoutInjectorInstances(defType, parent, additionalProviders, name);
1442
- injector.resolveInjectorInitializers();
1443
- return injector;
1444
- }
1445
- /**
1446
- * Creates a new injector without eagerly resolving its injector types. Can be used in places
1447
- * where resolving the injector types immediately can lead to an infinite loop. The injector types
1448
- * should be resolved at a later point by calling `_resolveInjectorDefTypes`.
1449
- */
1450
- function createInjectorWithoutInjectorInstances(defType, parent = null, additionalProviders = null, name, scopes = new Set()) {
1451
- const providers = [
1452
- additionalProviders || EMPTY_ARRAY,
1453
- importProvidersFrom(defType),
1454
- ];
1455
- name = name || (typeof defType === 'object' ? undefined : stringify(defType));
1456
- return new R3Injector(providers, parent || getNullInjector(), name || null, scopes);
1457
- }
1458
-
1459
- /**
1460
- * @license
1461
- * Copyright Google LLC All Rights Reserved.
1462
- *
1463
- * Use of this source code is governed by an MIT-style license that can be
1464
- * found in the LICENSE file at https://angular.io/license
1465
- */
1466
- /**
1467
- * Concrete injectors implement this interface. Injectors are configured
1468
- * with [providers](guide/dependency-injection-providers) that associate
1469
- * dependencies of various types with [injection tokens](guide/dependency-injection-providers).
1470
- *
1471
- * @see [DI Providers](guide/dependency-injection-providers).
1472
- * @see {@link StaticProvider}
1473
- *
1474
- * @usageNotes
1475
- *
1476
- * The following example creates a service injector instance.
1477
- *
1478
- * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'}
1479
- *
1480
- * ### Usage example
1481
- *
1482
- * {@example core/di/ts/injector_spec.ts region='Injector'}
1483
- *
1484
- * `Injector` returns itself when given `Injector` as a token:
1485
- *
1486
- * {@example core/di/ts/injector_spec.ts region='injectInjector'}
1487
- *
1488
- * @publicApi
1489
- */
1490
- class Injector {
1491
- static THROW_IF_NOT_FOUND = THROW_IF_NOT_FOUND;
1492
- static NULL = new NullInjector();
1493
- static create(options, parent) {
1494
- if (Array.isArray(options)) {
1495
- return createInjector({ name: '' }, parent, options, '');
1496
- }
1497
- else {
1498
- const name = options.name ?? '';
1499
- return createInjector({ name }, options.parent, options.providers, name);
1500
- }
1501
- }
1502
- /** @nocollapse */
1503
- static ɵprov = /** @pureOrBreakMyCode */ ɵɵdefineInjectable({
1504
- token: Injector,
1505
- providedIn: 'any',
1506
- factory: () => ɵɵinject(INJECTOR),
1507
- });
1508
- /**
1509
- * @internal
1510
- * @nocollapse
1511
- */
1512
- static __NG_ELEMENT_ID__ = -1 /* InjectorMarkers.Injector */;
1513
- }
1514
-
1515
- /**
1516
- * @license
1517
- * Copyright Google LLC All Rights Reserved.
1518
- *
1519
- * Use of this source code is governed by an MIT-style license that can be
1520
- * found in the LICENSE file at https://angular.io/license
1521
- */
1522
- /**
1523
- * Throws an error indicating that a factory function could not be generated by the compiler for a
1524
- * particular class.
1525
- *
1526
- * This instruction allows the actual error message to be optimized away when ngDevMode is turned
1527
- * off, saving bytes of generated code while still providing a good experience in dev mode.
1528
- *
1529
- * The name of the class is not mentioned here, but will be in the generated factory function name
1530
- * and thus in the stack trace.
1531
- *
1532
- * @codeGenApi
1533
- */
1534
- function ɵɵinvalidFactory() {
1535
- const msg = 'invalid';
1536
- throw new Error(msg);
1537
- }
1538
-
1539
- export { EnvironmentInjector, INJECTOR_SCOPE, Inject, InjectFlags, InjectionToken, Injector, NG_INJ_DEF, NG_PROV_DEF, NG_TEMP_TOKEN_PATH, NullInjector, Optional, R3Injector, SOURCE, Self, SkipSelf, THROW_IF_NOT_FOUND, attachInjectFlag, catchInjectorError, convertToBitFlags, formatError, getCurrentInjector, getInheritedInjectableDef, getInjectFlag, getInjectableDef, getInjectorDef, getNullInjector, inject, injectArgs, injectInjectorOnly, isInjectable, providerToFactory, setCurrentInjector, ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵinject, ɵɵinvalidFactory, ɵɵinvalidFactoryDep };