@microsoft/fast-element 2.0.0-beta.2 → 2.0.0-beta.5

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 (54) hide show
  1. package/CHANGELOG.json +147 -0
  2. package/CHANGELOG.md +42 -1
  3. package/dist/dts/components/fast-definitions.d.ts +9 -8
  4. package/dist/dts/components/fast-element.d.ts +12 -24
  5. package/dist/dts/context.d.ts +1 -1
  6. package/dist/dts/di/di.d.ts +858 -0
  7. package/dist/dts/hooks.d.ts +2 -2
  8. package/dist/dts/interfaces.d.ts +40 -7
  9. package/dist/dts/observation/observable.d.ts +19 -13
  10. package/dist/dts/styles/element-styles.d.ts +6 -0
  11. package/dist/dts/templating/binding-signal.d.ts +10 -27
  12. package/dist/dts/templating/binding-two-way.d.ts +16 -41
  13. package/dist/dts/templating/binding.d.ts +79 -118
  14. package/dist/dts/templating/html-directive.d.ts +31 -3
  15. package/dist/dts/templating/render.d.ts +277 -0
  16. package/dist/dts/templating/repeat.d.ts +12 -16
  17. package/dist/dts/templating/template.d.ts +3 -3
  18. package/dist/dts/templating/when.d.ts +3 -3
  19. package/dist/dts/testing/exports.d.ts +2 -0
  20. package/dist/dts/testing/fixture.d.ts +90 -0
  21. package/dist/dts/testing/timeout.d.ts +7 -0
  22. package/dist/esm/components/fast-definitions.js +25 -27
  23. package/dist/esm/components/fast-element.js +20 -11
  24. package/dist/esm/context.js +5 -1
  25. package/dist/esm/debug.js +36 -4
  26. package/dist/esm/di/di.js +1351 -0
  27. package/dist/esm/observation/arrays.js +303 -2
  28. package/dist/esm/observation/observable.js +11 -6
  29. package/dist/esm/platform.js +1 -1
  30. package/dist/esm/styles/element-styles.js +14 -0
  31. package/dist/esm/templating/binding-signal.js +56 -61
  32. package/dist/esm/templating/binding-two-way.js +56 -34
  33. package/dist/esm/templating/binding.js +137 -156
  34. package/dist/esm/templating/compiler.js +30 -7
  35. package/dist/esm/templating/html-directive.js +16 -2
  36. package/dist/esm/templating/render.js +392 -0
  37. package/dist/esm/templating/repeat.js +57 -40
  38. package/dist/esm/templating/template.js +8 -5
  39. package/dist/esm/templating/view.js +3 -1
  40. package/dist/esm/templating/when.js +5 -4
  41. package/dist/esm/testing/exports.js +2 -0
  42. package/dist/esm/testing/fixture.js +88 -0
  43. package/dist/esm/testing/timeout.js +24 -0
  44. package/dist/fast-element.api.json +2828 -2758
  45. package/dist/fast-element.d.ts +218 -230
  46. package/dist/fast-element.debug.js +656 -257
  47. package/dist/fast-element.debug.min.js +1 -1
  48. package/dist/fast-element.js +620 -253
  49. package/dist/fast-element.min.js +1 -1
  50. package/dist/fast-element.untrimmed.d.ts +226 -235
  51. package/docs/api-report.md +88 -91
  52. package/package.json +15 -6
  53. package/dist/dts/observation/splice-strategies.d.ts +0 -13
  54. package/dist/esm/observation/splice-strategies.js +0 -400
@@ -0,0 +1,1351 @@
1
+ /**
2
+ * Big thanks to https://github.com/fkleuver and the https://github.com/aurelia/aurelia project
3
+ * for the bulk of this code and many of the associated tests.
4
+ */
5
+ import { Context } from "../context.js";
6
+ import "../interfaces.js";
7
+ import { Metadata } from "../metadata.js";
8
+ import { emptyArray, FAST } from "../platform.js";
9
+ /**
10
+ * A utility class used that constructs and registers resolvers for a dependency
11
+ * injection container. Supports a standard set of object lifetimes.
12
+ * @public
13
+ */
14
+ export class ResolverBuilder {
15
+ /**
16
+ *
17
+ * @param container - The container to create resolvers for.
18
+ * @param key - The key to register resolvers under.
19
+ */
20
+ constructor(container, key) {
21
+ this.container = container;
22
+ this.key = key;
23
+ }
24
+ /**
25
+ * Creates a resolver for an existing object instance.
26
+ * @param value - The instance to resolve.
27
+ * @returns The resolver.
28
+ */
29
+ instance(value) {
30
+ return this.registerResolver(0 /* ResolverStrategy.instance */, value);
31
+ }
32
+ /**
33
+ * Creates a resolver that enforces a singleton lifetime.
34
+ * @param value - The type to create and cache the singleton for.
35
+ * @returns The resolver.
36
+ */
37
+ singleton(value) {
38
+ return this.registerResolver(1 /* ResolverStrategy.singleton */, value);
39
+ }
40
+ /**
41
+ * Creates a resolver that creates a new instance for every dependency request.
42
+ * @param value - The type to create instances of.
43
+ * @returns - The resolver.
44
+ */
45
+ transient(value) {
46
+ return this.registerResolver(2 /* ResolverStrategy.transient */, value);
47
+ }
48
+ /**
49
+ * Creates a resolver that invokes a callback function for every dependency resolution
50
+ * request, allowing custom logic to return the dependency.
51
+ * @param value - The callback to call during resolution.
52
+ * @returns The resolver.
53
+ */
54
+ callback(value) {
55
+ return this.registerResolver(3 /* ResolverStrategy.callback */, value);
56
+ }
57
+ /**
58
+ * Creates a resolver that invokes a callback function the first time that a dependency
59
+ * resolution is requested. The returned value is then cached and provided for all
60
+ * subsequent requests.
61
+ * @param value - The callback to call during the first resolution.
62
+ * @returns The resolver.
63
+ */
64
+ cachedCallback(value) {
65
+ return this.registerResolver(3 /* ResolverStrategy.callback */, cacheCallbackResult(value));
66
+ }
67
+ /**
68
+ * Aliases the current key to a different key.
69
+ * @param destinationKey - The key to point the alias to.
70
+ * @returns The resolver.
71
+ */
72
+ aliasTo(destinationKey) {
73
+ return this.registerResolver(5 /* ResolverStrategy.alias */, destinationKey);
74
+ }
75
+ registerResolver(strategy, state) {
76
+ const { container, key } = this;
77
+ /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
78
+ this.container = this.key = (void 0);
79
+ return container.registerResolver(key, new ResolverImpl(key, strategy, state));
80
+ }
81
+ }
82
+ function cloneArrayWithPossibleProps(source) {
83
+ const clone = source.slice();
84
+ const keys = Object.keys(source);
85
+ const len = keys.length;
86
+ let key;
87
+ for (let i = 0; i < len; ++i) {
88
+ key = keys[i];
89
+ if (!isArrayIndex(key)) {
90
+ clone[key] = source[key];
91
+ }
92
+ }
93
+ return clone;
94
+ }
95
+ /**
96
+ * A set of default resolvers useful in configuring a container.
97
+ * @public
98
+ */
99
+ export const DefaultResolver = Object.freeze({
100
+ /**
101
+ * Disables auto-registration and throws for all un-registered dependencies.
102
+ * @param key - The key to create the resolver for.
103
+ */
104
+ none(key) {
105
+ throw FAST.error(1512 /* Message.noDefaultResolver */, { key });
106
+ },
107
+ /**
108
+ * Provides default singleton resolution behavior during auto-registration.
109
+ * @param key - The key to create the resolver for.
110
+ * @returns The resolver.
111
+ */
112
+ singleton(key) {
113
+ return new ResolverImpl(key, 1 /* ResolverStrategy.singleton */, key);
114
+ },
115
+ /**
116
+ * Provides default transient resolution behavior during auto-registration.
117
+ * @param key - The key to create the resolver for.
118
+ * @returns The resolver.
119
+ */
120
+ transient(key) {
121
+ return new ResolverImpl(key, 2 /* ResolverStrategy.transient */, key);
122
+ },
123
+ });
124
+ /**
125
+ * Configuration for a dependency injection container.
126
+ * @public
127
+ */
128
+ export const ContainerConfiguration = Object.freeze({
129
+ /**
130
+ * The default configuration used when creating a DOM-disconnected container.
131
+ * @remarks
132
+ * The default creates a root container, with no parent container. It does not handle
133
+ * owner requests and it uses singleton resolution behavior for auto-registration.
134
+ */
135
+ default: Object.freeze({
136
+ parentLocator: () => null,
137
+ responsibleForOwnerRequests: false,
138
+ defaultResolver: DefaultResolver.singleton,
139
+ }),
140
+ });
141
+ function createContext(nameConfigOrCallback, configuror) {
142
+ const configure = typeof nameConfigOrCallback === "function" ? nameConfigOrCallback : configuror;
143
+ const friendlyName = typeof nameConfigOrCallback === "string"
144
+ ? nameConfigOrCallback
145
+ : nameConfigOrCallback && "friendlyName" in nameConfigOrCallback
146
+ ? nameConfigOrCallback.friendlyName || defaultFriendlyName
147
+ : defaultFriendlyName;
148
+ const respectConnection = typeof nameConfigOrCallback === "string"
149
+ ? false
150
+ : nameConfigOrCallback && "respectConnection" in nameConfigOrCallback
151
+ ? nameConfigOrCallback.respectConnection || false
152
+ : false;
153
+ const Interface = function (target, property, index) {
154
+ if (target == null || new.target !== undefined) {
155
+ throw FAST.error(1501 /* Message.noRegistrationForContext */, { name: Interface.name });
156
+ }
157
+ if (property) {
158
+ DI.defineProperty(target, property, Interface, respectConnection);
159
+ }
160
+ else {
161
+ const annotationParamtypes = Metadata.getOrCreateAnnotationParamTypes(target);
162
+ annotationParamtypes[index] = Interface;
163
+ }
164
+ };
165
+ Interface.$isInterface = true;
166
+ Reflect.defineProperty(Interface, "name", {
167
+ value: friendlyName !== null && friendlyName !== void 0 ? friendlyName : defaultFriendlyName,
168
+ });
169
+ if (configure != null) {
170
+ Interface.register = function (container, key) {
171
+ return configure(new ResolverBuilder(container, key !== null && key !== void 0 ? key : Interface));
172
+ };
173
+ }
174
+ Interface.toString = function toString() {
175
+ return `DIContext<${Interface.name}>`;
176
+ };
177
+ return Interface;
178
+ }
179
+ const dependencyLookup = new Map();
180
+ let rootDOMContainer = null;
181
+ let nonRootDOMContainerCount = 0;
182
+ /**
183
+ * The gateway to dependency injection APIs.
184
+ * @public
185
+ */
186
+ export const DI = Object.freeze({
187
+ /**
188
+ * Installs dependency injection as the default strategy for handling
189
+ * all calls to Context.request.
190
+ * @param fallback - Creates a container if one cannot be found.
191
+ */
192
+ installAsContextRequestStrategy(fallback) {
193
+ Context.setDefaultRequestStrategy((target, context, callback) => {
194
+ const container = DI.findResponsibleContainer(target, fallback);
195
+ callback(container.get(context));
196
+ });
197
+ },
198
+ /**
199
+ * Creates a new dependency injection container.
200
+ * @param config - The configuration for the container.
201
+ * @returns A newly created dependency injection container.
202
+ */
203
+ createContainer(config) {
204
+ return new ContainerImpl(null, Object.assign({}, ContainerConfiguration.default, config));
205
+ },
206
+ /**
207
+ * Finds the dependency injection container responsible for providing dependencies
208
+ * to the specified node.
209
+ * @param target - The node to find the responsible container for.
210
+ * @param fallback - Creates a container if one cannot be found.
211
+ * @returns The container responsible for providing dependencies to the node.
212
+ * @remarks
213
+ * This will be the same as the parent container if the specified node
214
+ * does not itself host a container configured with responsibleForOwnerRequests.
215
+ */
216
+ findResponsibleContainer(target, fallback) {
217
+ const owned = target.$$container$$;
218
+ if (owned && owned.responsibleForOwnerRequests) {
219
+ return owned;
220
+ }
221
+ return DI.findParentContainer(target, fallback);
222
+ },
223
+ /**
224
+ * Find the dependency injection container up the DOM tree from this node.
225
+ * @param target - The node to find the parent container for.
226
+ * @param fallback - Creates a container if one cannot be found.
227
+ * @returns The parent container of this node.
228
+ * @remarks
229
+ * This will be the same as the responsible container if the specified node
230
+ * does not itself host a container configured with responsibleForOwnerRequests.
231
+ */
232
+ findParentContainer(target, fallback) {
233
+ // NOTE: If there are no node-specific containers in existence other
234
+ // than the root, then we can bypass raising events and instead just grab
235
+ // the reference to the root container because we know it's the parent
236
+ // for this node.
237
+ if (nonRootDOMContainerCount < 1) {
238
+ return fallback ? fallback() : DI.getOrCreateDOMContainer();
239
+ }
240
+ // NOTE: If even one node-specific container has been created then we can
241
+ // no longer assume that the parent container for the target is the root
242
+ // and we must dispatch a context event in order to find the parent
243
+ // container in the DOM.
244
+ let container;
245
+ Context.dispatch(target, DOMContainer, value => (container = value));
246
+ // NOTE: If there are node-specific containers but there doesn't happen to
247
+ // be one that is a parent to the target node, then we still need to fall
248
+ // back to the root container.
249
+ return container !== null && container !== void 0 ? container : (fallback ? fallback() : DI.getOrCreateDOMContainer());
250
+ },
251
+ /**
252
+ * Returns a dependency injection container if one is explicitly owned by the specified
253
+ * node. If one is not owned, then a new container is created and assigned to the node.
254
+ * @param target - The node to find or create the container for.
255
+ * @param config - The configuration for the container if one needs to be created.
256
+ * @returns The located or created container.
257
+ * @remarks
258
+ * This API does not search for a responsible or parent container. It looks only for a container
259
+ * directly defined on the specified node and creates one at that location if one does not
260
+ * already exist.
261
+ */
262
+ getOrCreateDOMContainer(target, config) {
263
+ if (!target) {
264
+ return (rootDOMContainer ||
265
+ (rootDOMContainer = new ContainerImpl(typeof window !== "undefined" ? window : null, Object.assign({}, ContainerConfiguration.default, config, {
266
+ parentLocator: () => null,
267
+ }))));
268
+ }
269
+ let container = target.$$container$$;
270
+ if (container === void 0) {
271
+ // NOTE: Creating a node-specific container de-optimizes container resolution.
272
+ nonRootDOMContainerCount++;
273
+ container = new ContainerImpl(target, Object.assign({}, ContainerConfiguration.default, config, {
274
+ parentLocator: DI.findParentContainer,
275
+ }));
276
+ }
277
+ return container;
278
+ },
279
+ /**
280
+ * Gets the dependency keys representing what is needed to instantiate the specified type.
281
+ * @param Type - The type to get the dependencies for.
282
+ * @returns An array of dependency keys.
283
+ */
284
+ getDependencies(Type) {
285
+ // Note: Every detail of this getDependencies method is pretty deliberate at the moment, and probably not yet 100% tested from every possible angle,
286
+ // so be careful with making changes here as it can have a huge impact on complex end user apps.
287
+ // Preferably, only make changes to the dependency resolution process via a RFC.
288
+ let dependencies = dependencyLookup.get(Type);
289
+ if (dependencies === void 0) {
290
+ // Type.length is the number of constructor parameters. If this is 0, it could mean the class has an empty constructor
291
+ // but it could also mean the class has no constructor at all (in which case it inherits the constructor from the prototype).
292
+ // Non-zero constructor length + no paramtypes means emitDecoratorMetadata is off, or the class has no decorator.
293
+ // We're not doing anything with the above right now, but it's good to keep in mind for any future issues.
294
+ const inject = Type.inject;
295
+ if (inject === void 0) {
296
+ // design:paramtypes is set by tsc when emitDecoratorMetadata is enabled.
297
+ const designParamtypes = Metadata.getDesignParamTypes(Type);
298
+ // di:paramtypes is set by the parameter decorator from DI.createInterface or by @inject
299
+ const annotationParamtypes = Metadata.getAnnotationParamTypes(Type);
300
+ if (designParamtypes === emptyArray) {
301
+ if (annotationParamtypes === emptyArray) {
302
+ // Only go up the prototype if neither static inject nor any of the paramtypes is defined, as
303
+ // there is no sound way to merge a type's deps with its prototype's deps
304
+ const Proto = Object.getPrototypeOf(Type);
305
+ if (typeof Proto === "function" && Proto !== Function.prototype) {
306
+ dependencies = cloneArrayWithPossibleProps(DI.getDependencies(Proto));
307
+ }
308
+ else {
309
+ dependencies = [];
310
+ }
311
+ }
312
+ else {
313
+ // No design:paramtypes so just use the di:paramtypes
314
+ dependencies = cloneArrayWithPossibleProps(annotationParamtypes);
315
+ }
316
+ }
317
+ else if (annotationParamtypes === emptyArray) {
318
+ // No di:paramtypes so just use the design:paramtypes
319
+ dependencies = cloneArrayWithPossibleProps(designParamtypes);
320
+ }
321
+ else {
322
+ // We've got both, so merge them (in case of conflict on same index, di:paramtypes take precedence)
323
+ dependencies = cloneArrayWithPossibleProps(designParamtypes);
324
+ let len = annotationParamtypes.length;
325
+ let auAnnotationParamtype;
326
+ for (let i = 0; i < len; ++i) {
327
+ auAnnotationParamtype = annotationParamtypes[i];
328
+ if (auAnnotationParamtype !== void 0) {
329
+ dependencies[i] = auAnnotationParamtype;
330
+ }
331
+ }
332
+ const keys = Object.keys(annotationParamtypes);
333
+ len = keys.length;
334
+ let key;
335
+ for (let i = 0; i < len; ++i) {
336
+ key = keys[i];
337
+ if (!isArrayIndex(key)) {
338
+ dependencies[key] = annotationParamtypes[key];
339
+ }
340
+ }
341
+ }
342
+ }
343
+ else {
344
+ // Ignore paramtypes if we have static inject
345
+ dependencies = cloneArrayWithPossibleProps(inject);
346
+ }
347
+ dependencyLookup.set(Type, dependencies);
348
+ }
349
+ return dependencies;
350
+ },
351
+ /**
352
+ * Defines a property on a web component class. The value of this property will
353
+ * be resolved from the dependency injection container responsible for the element
354
+ * instance, based on where it is connected in the DOM.
355
+ * @param target - The target to define the property on.
356
+ * @param propertyName - The name of the property to define.
357
+ * @param key - The dependency injection key.
358
+ * @param respectConnection - Indicates whether or not to update the property value if the
359
+ * hosting component is disconnected and then re-connected at a different location in the DOM.
360
+ * @remarks
361
+ * The respectConnection option is only applicable to elements that descend from FASTElement.
362
+ */
363
+ defineProperty(target, propertyName, key, respectConnection = false) {
364
+ const diPropertyKey = `$di_${propertyName}`;
365
+ Reflect.defineProperty(target, propertyName, {
366
+ get: function () {
367
+ let value = this[diPropertyKey];
368
+ if (value === void 0) {
369
+ const container = this instanceof Node
370
+ ? DI.findResponsibleContainer(this)
371
+ : DI.getOrCreateDOMContainer();
372
+ value = container.get(key);
373
+ this[diPropertyKey] = value;
374
+ if (respectConnection) {
375
+ const notifier = this.$fastController;
376
+ if (!notifier) {
377
+ throw FAST.error(1514 /* Message.connectUpdateRequiresController */);
378
+ }
379
+ const handleChange = () => {
380
+ const newContainer = DI.findResponsibleContainer(this);
381
+ const newValue = newContainer.get(key);
382
+ const oldValue = this[diPropertyKey];
383
+ if (newValue !== oldValue) {
384
+ this[diPropertyKey] = value;
385
+ notifier.notify(propertyName);
386
+ }
387
+ };
388
+ notifier.subscribe({ handleChange }, "isConnected");
389
+ }
390
+ }
391
+ return value;
392
+ },
393
+ });
394
+ },
395
+ /**
396
+ * Creates a dependency injection key.
397
+ * @param nameConfigOrCallback - A friendly name for the key or a lambda that configures a
398
+ * default resolution for the dependency.
399
+ * @param configuror - If a friendly name was provided for the first parameter, then an optional
400
+ * lambda that configures a default resolution for the dependency can be provided second.
401
+ * @returns The created key.
402
+ * @remarks
403
+ * The created key can be used as a property decorator or constructor parameter decorator,
404
+ * in addition to its standard use in an inject array or through direct container APIs.
405
+ */
406
+ createContext,
407
+ /**
408
+ * @deprecated
409
+ * Use DI.createContext instead.
410
+ */
411
+ createInterface: createContext,
412
+ /**
413
+ * A decorator that specifies what to inject into its target.
414
+ * @param dependencies - The dependencies to inject.
415
+ * @returns The decorator to be applied to the target class.
416
+ * @remarks
417
+ * The decorator can be used to decorate a class, listing all of the classes dependencies.
418
+ * Or it can be used to decorate a constructor parameter, indicating what to inject for that
419
+ * parameter.
420
+ * Or it can be used for a web component property, indicating what that property should resolve to.
421
+ */
422
+ inject(...dependencies) {
423
+ return function (target, key, descriptor) {
424
+ if (typeof descriptor === "number") {
425
+ // It's a parameter decorator.
426
+ const annotationParamtypes = Metadata.getOrCreateAnnotationParamTypes(target);
427
+ const dep = dependencies[0];
428
+ if (dep !== void 0) {
429
+ annotationParamtypes[descriptor] = dep;
430
+ }
431
+ }
432
+ else if (key) {
433
+ DI.defineProperty(target, key, dependencies[0]);
434
+ }
435
+ else {
436
+ const annotationParamtypes = descriptor
437
+ ? Metadata.getOrCreateAnnotationParamTypes(descriptor.value)
438
+ : Metadata.getOrCreateAnnotationParamTypes(target);
439
+ let dep;
440
+ for (let i = 0; i < dependencies.length; ++i) {
441
+ dep = dependencies[i];
442
+ if (dep !== void 0) {
443
+ annotationParamtypes[i] = dep;
444
+ }
445
+ }
446
+ }
447
+ };
448
+ },
449
+ /**
450
+ * Registers the `target` class as a transient dependency; each time the dependency is resolved
451
+ * a new instance will be created.
452
+ *
453
+ * @param target - The class / constructor function to register as transient.
454
+ * @returns The same class, with a static `register` method that takes a container and returns the appropriate resolver.
455
+ *
456
+ * @example
457
+ * On an existing class
458
+ * ```ts
459
+ * class Foo { }
460
+ * DI.transient(Foo);
461
+ * ```
462
+ *
463
+ * @example
464
+ * Inline declaration
465
+ *
466
+ * ```ts
467
+ * const Foo = DI.transient(class { });
468
+ * // Foo is now strongly typed with register
469
+ * Foo.register(container);
470
+ * ```
471
+ *
472
+ * @public
473
+ */
474
+ transient(target) {
475
+ target.register = function register(container) {
476
+ const registration = Registration.transient(target, target);
477
+ return registration.register(container);
478
+ };
479
+ target.registerInRequestor = false;
480
+ return target;
481
+ },
482
+ /**
483
+ * Registers the `target` class as a singleton dependency; the class will only be created once. Each
484
+ * consecutive time the dependency is resolved, the same instance will be returned.
485
+ *
486
+ * @param target - The class / constructor function to register as a singleton.
487
+ * @returns The same class, with a static `register` method that takes a container and returns the appropriate resolver.
488
+ * @example
489
+ * On an existing class
490
+ * ```ts
491
+ * class Foo { }
492
+ * DI.singleton(Foo);
493
+ * ```
494
+ *
495
+ * @example
496
+ * Inline declaration
497
+ * ```ts
498
+ * const Foo = DI.singleton(class { });
499
+ * // Foo is now strongly typed with register
500
+ * Foo.register(container);
501
+ * ```
502
+ *
503
+ * @public
504
+ */
505
+ singleton(target, options = defaultSingletonOptions) {
506
+ target.register = function register(container) {
507
+ const registration = Registration.singleton(target, target);
508
+ return registration.register(container);
509
+ };
510
+ target.registerInRequestor = options.scoped;
511
+ return target;
512
+ },
513
+ });
514
+ /**
515
+ * The key that resolves the dependency injection Container itself.
516
+ * @public
517
+ */
518
+ export const Container = DI.createContext("Container");
519
+ /**
520
+ * The key that resolves a DOMContainer itself.
521
+ * @public
522
+ */
523
+ export const DOMContainer = Container;
524
+ /**
525
+ * The key that resolves the ServiceLocator itself.
526
+ * @public
527
+ */
528
+ export const ServiceLocator = Container;
529
+ function createResolver(getter) {
530
+ return function (key) {
531
+ const resolver = function (target, property, descriptor) {
532
+ DI.inject(resolver)(target, property, descriptor);
533
+ };
534
+ resolver.$isResolver = true;
535
+ resolver.resolve = function (handler, requestor) {
536
+ return getter(key, handler, requestor);
537
+ };
538
+ return resolver;
539
+ };
540
+ }
541
+ /**
542
+ * A decorator that specifies what to inject into its target.
543
+ * @param dependencies - The dependencies to inject.
544
+ * @returns The decorator to be applied to the target class.
545
+ * @remarks
546
+ * The decorator can be used to decorate a class, listing all of the classes dependencies.
547
+ * Or it can be used to decorate a constructor paramter, indicating what to inject for that
548
+ * parameter.
549
+ * Or it can be used for a web component property, indicating what that property should resolve to.
550
+ *
551
+ * @public
552
+ */
553
+ export const inject = DI.inject;
554
+ function transientDecorator(target) {
555
+ return DI.transient(target);
556
+ }
557
+ export function transient(target) {
558
+ return target == null ? transientDecorator : transientDecorator(target);
559
+ }
560
+ const defaultSingletonOptions = { scoped: false };
561
+ function singletonDecorator(target) {
562
+ return DI.singleton(target);
563
+ }
564
+ /**
565
+ * @public
566
+ */
567
+ export function singleton(targetOrOptions) {
568
+ if (typeof targetOrOptions === "function") {
569
+ return DI.singleton(targetOrOptions);
570
+ }
571
+ return function ($target) {
572
+ return DI.singleton($target, targetOrOptions);
573
+ };
574
+ }
575
+ function createAllResolver(getter) {
576
+ return function (key, searchAncestors) {
577
+ searchAncestors = !!searchAncestors;
578
+ const resolver = function (target, property, descriptor) {
579
+ DI.inject(resolver)(target, property, descriptor);
580
+ };
581
+ resolver.$isResolver = true;
582
+ resolver.resolve = function (handler, requestor) {
583
+ /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
584
+ return getter(key, handler, requestor, searchAncestors);
585
+ };
586
+ return resolver;
587
+ };
588
+ }
589
+ /**
590
+ * A decorator and DI resolver that will resolve an array of all dependencies
591
+ * registered with the specified key.
592
+ * @param key - The key to resolve all dependencies for.
593
+ * @param searchAncestors - [optional] Indicates whether to search ancestor containers.
594
+ * @public
595
+ */
596
+ export const all = createAllResolver((key, handler, requestor, searchAncestors) => requestor.getAll(key, searchAncestors));
597
+ /**
598
+ * A decorator that lazily injects a dependency depending on whether the `Key` is present at the time of function call.
599
+ *
600
+ * @example
601
+ * You need to make your argument a function that returns the type, for example
602
+ * ```ts
603
+ * class Foo {
604
+ * constructor( @lazy('random') public random: () => number )
605
+ * }
606
+ * const foo = container.get(Foo); // instanceof Foo
607
+ * foo.random(); // throws
608
+ * ```
609
+ * would throw an exception because you haven't registered `'random'` before calling the method.
610
+ * @example
611
+ * This, would give you a new 'Math.random()' number each time.
612
+ * ```ts
613
+ * class Foo {
614
+ * constructor( @lazy('random') public random: () => random )
615
+ * }
616
+ * container.register(Registration.callback('random', Math.random ));
617
+ * container.get(Foo).random(); // some random number
618
+ * container.get(Foo).random(); // another random number
619
+ * ```
620
+ *
621
+ * `@lazy` does not manage the lifecycle of the underlying key. If you want a singleton, you have to register as a
622
+ * `singleton`, `transient` would also behave as you would expect, providing you a new instance each time.
623
+ *
624
+ * @param key - The key to lazily resolve.
625
+ * see {@link DI.createContext} on interactions with interfaces
626
+ *
627
+ * @public
628
+ */
629
+ export const lazy = createResolver((key, handler, requestor) => {
630
+ return () => requestor.get(key);
631
+ });
632
+ /**
633
+ * A decorator that allows you to optionally inject a dependency depending on whether the [[`Key`]] is present, for example:
634
+ * @example
635
+ * ```ts
636
+ * class Foo {
637
+ * constructor( @inject('mystring') public str: string = 'somestring' )
638
+ * }
639
+ * container.get(Foo); // throws
640
+ * ```
641
+ * would fail
642
+ *
643
+ * @example
644
+ * ```ts
645
+ * class Foo {
646
+ * constructor( @optional('mystring') public str: string = 'somestring' )
647
+ * }
648
+ * container.get(Foo).str // somestring
649
+ * ```
650
+ * if you use it without a default it will inject `undefined`, so remember to mark your input type as
651
+ * possibly `undefined`!
652
+ *
653
+ * @param key - The key to optionally resolve.
654
+ * see {@link DI.createContext} on interactions with interfaces
655
+ *
656
+ * @public
657
+ */
658
+ export const optional = createResolver((key, handler, requestor) => {
659
+ if (requestor.has(key, true)) {
660
+ return requestor.get(key);
661
+ }
662
+ else {
663
+ return undefined;
664
+ }
665
+ });
666
+ /**
667
+ * A decorator that tells the container not to try to inject a dependency.
668
+ *
669
+ * @public
670
+ */
671
+ export function ignore(target, property, descriptor) {
672
+ DI.inject(ignore)(target, property, descriptor);
673
+ }
674
+ // Hack: casting below used to prevent TS from generate a namespace which can't be commented
675
+ // and results in documentation validation errors.
676
+ ignore.$isResolver = true;
677
+ ignore.resolve = () => undefined;
678
+ /**
679
+ * A decorator that indicates that a new instance should be injected scoped to the
680
+ * container that requested the instance.
681
+ * @param key - The dependency key for the new instance.
682
+ * @remarks
683
+ * This creates a resolver with an instance strategy pointing to the new instance, effectively
684
+ * making this a singleton, scoped to the container or DOM's subtree.
685
+ *
686
+ * @public
687
+ */
688
+ export const newInstanceForScope = createResolver((key, handler, requestor) => {
689
+ const instance = createNewInstance(key, handler);
690
+ const resolver = new ResolverImpl(key, 0 /* ResolverStrategy.instance */, instance);
691
+ requestor.registerResolver(key, resolver);
692
+ return instance;
693
+ });
694
+ /**
695
+ * A decorator that indicates that a new instance should be injected.
696
+ * @param key - The dependency key for the new instance.
697
+ * @remarks
698
+ * The instance is not internally cached with a resolver as newInstanceForScope does.
699
+ *
700
+ * @public
701
+ */
702
+ export const newInstanceOf = createResolver((key, handler, _requestor) => createNewInstance(key, handler));
703
+ function createNewInstance(key, handler) {
704
+ /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
705
+ return handler.getFactory(key).construct(handler);
706
+ }
707
+ /** @internal */
708
+ export class ResolverImpl {
709
+ constructor(key, strategy, state) {
710
+ this.key = key;
711
+ this.strategy = strategy;
712
+ this.state = state;
713
+ this.resolving = false;
714
+ }
715
+ get $isResolver() {
716
+ return true;
717
+ }
718
+ register(container) {
719
+ return container.registerResolver(this.key, this);
720
+ }
721
+ resolve(handler, requestor) {
722
+ switch (this.strategy) {
723
+ case 0 /* ResolverStrategy.instance */:
724
+ return this.state;
725
+ case 1 /* ResolverStrategy.singleton */: {
726
+ if (this.resolving) {
727
+ throw FAST.error(1513 /* Message.cyclicDependency */, { name: this.state.name });
728
+ }
729
+ this.resolving = true;
730
+ this.state = handler
731
+ .getFactory(this.state)
732
+ .construct(requestor);
733
+ this.strategy = 0 /* ResolverStrategy.instance */;
734
+ this.resolving = false;
735
+ return this.state;
736
+ }
737
+ case 2 /* ResolverStrategy.transient */: {
738
+ // Always create transients from the requesting container
739
+ const factory = handler.getFactory(this.state);
740
+ if (factory === null) {
741
+ throw FAST.error(1502 /* Message.noFactoryForResolver */, { key: this.key });
742
+ }
743
+ return factory.construct(requestor);
744
+ }
745
+ case 3 /* ResolverStrategy.callback */:
746
+ return this.state(handler, requestor, this);
747
+ case 4 /* ResolverStrategy.array */:
748
+ return this.state[0].resolve(handler, requestor);
749
+ case 5 /* ResolverStrategy.alias */:
750
+ return requestor.get(this.state);
751
+ default:
752
+ throw FAST.error(1503 /* Message.invalidResolverStrategy */, {
753
+ strategy: this.strategy,
754
+ });
755
+ }
756
+ }
757
+ getFactory(container) {
758
+ var _a, _b, _c;
759
+ switch (this.strategy) {
760
+ case 1 /* ResolverStrategy.singleton */:
761
+ case 2 /* ResolverStrategy.transient */:
762
+ return container.getFactory(this.state);
763
+ case 5 /* ResolverStrategy.alias */:
764
+ return (_c = (_b = (_a = container.getResolver(this.state)) === null || _a === void 0 ? void 0 : _a.getFactory) === null || _b === void 0 ? void 0 : _b.call(_a, container)) !== null && _c !== void 0 ? _c : null;
765
+ default:
766
+ return null;
767
+ }
768
+ }
769
+ }
770
+ function containerGetKey(d) {
771
+ return this.get(d);
772
+ }
773
+ function transformInstance(inst, transform) {
774
+ return transform(inst);
775
+ }
776
+ /** @internal */
777
+ export class FactoryImpl {
778
+ constructor(Type, dependencies) {
779
+ this.Type = Type;
780
+ this.dependencies = dependencies;
781
+ this.transformers = null;
782
+ }
783
+ construct(container, dynamicDependencies) {
784
+ let instance;
785
+ if (dynamicDependencies === void 0) {
786
+ instance = new this.Type(...this.dependencies.map(containerGetKey, container));
787
+ }
788
+ else {
789
+ instance = new this.Type(...this.dependencies.map(containerGetKey, container), ...dynamicDependencies);
790
+ }
791
+ if (this.transformers == null) {
792
+ return instance;
793
+ }
794
+ return this.transformers.reduce(transformInstance, instance);
795
+ }
796
+ registerTransformer(transformer) {
797
+ (this.transformers || (this.transformers = [])).push(transformer);
798
+ }
799
+ }
800
+ const containerResolver = {
801
+ $isResolver: true,
802
+ resolve(handler, requestor) {
803
+ return requestor;
804
+ },
805
+ };
806
+ function isRegistry(obj) {
807
+ return typeof obj.register === "function";
808
+ }
809
+ function isSelfRegistry(obj) {
810
+ return isRegistry(obj) && typeof obj.registerInRequestor === "boolean";
811
+ }
812
+ function isRegisterInRequester(obj) {
813
+ return isSelfRegistry(obj) && obj.registerInRequestor;
814
+ }
815
+ function isClass(obj) {
816
+ return obj.prototype !== void 0;
817
+ }
818
+ const InstrinsicTypeNames = new Set([
819
+ "Array",
820
+ "ArrayBuffer",
821
+ "Boolean",
822
+ "DataView",
823
+ "Date",
824
+ "Error",
825
+ "EvalError",
826
+ "Float32Array",
827
+ "Float64Array",
828
+ "Function",
829
+ "Int8Array",
830
+ "Int16Array",
831
+ "Int32Array",
832
+ "Map",
833
+ "Number",
834
+ "Object",
835
+ "Promise",
836
+ "RangeError",
837
+ "ReferenceError",
838
+ "RegExp",
839
+ "Set",
840
+ "SharedArrayBuffer",
841
+ "String",
842
+ "SyntaxError",
843
+ "TypeError",
844
+ "Uint8Array",
845
+ "Uint8ClampedArray",
846
+ "Uint16Array",
847
+ "Uint32Array",
848
+ "URIError",
849
+ "WeakMap",
850
+ "WeakSet",
851
+ ]);
852
+ const factories = new Map();
853
+ /**
854
+ * @internal
855
+ */
856
+ export class ContainerImpl {
857
+ constructor(owner, config) {
858
+ this.owner = owner;
859
+ this.config = config;
860
+ this._parent = void 0;
861
+ this.registerDepth = 0;
862
+ this.isHandlingContextRequests = false;
863
+ this.resolvers = new Map();
864
+ this.resolvers.set(Container, containerResolver);
865
+ if (owner) {
866
+ owner.$$container$$ = this;
867
+ if ("addEventListener" in owner) {
868
+ Context.handle(owner, (e) => {
869
+ if (this.isHandlingContextRequests) {
870
+ try {
871
+ const value = this.get(e.context);
872
+ e.stopImmediatePropagation();
873
+ e.callback(value);
874
+ }
875
+ catch (_a) {
876
+ // Container failed to find the context, so we need to
877
+ // let the event propagate.
878
+ // TODO: Introduce a tryGet API to Container. Issue #4582
879
+ }
880
+ }
881
+ else if (e.context === Container &&
882
+ e.composedPath()[0] !== this.owner) {
883
+ e.stopImmediatePropagation();
884
+ e.callback(this);
885
+ }
886
+ });
887
+ }
888
+ }
889
+ }
890
+ get parent() {
891
+ if (this._parent === void 0) {
892
+ this._parent = this.config.parentLocator(this.owner);
893
+ }
894
+ return this._parent;
895
+ }
896
+ get depth() {
897
+ return this.parent === null ? 0 : this.parent.depth + 1;
898
+ }
899
+ get responsibleForOwnerRequests() {
900
+ return this.config.responsibleForOwnerRequests;
901
+ }
902
+ handleContextRequests(enable) {
903
+ this.isHandlingContextRequests = enable;
904
+ }
905
+ register(...params) {
906
+ if (++this.registerDepth === 100) {
907
+ // Most likely cause is trying to register a plain object that does not have a
908
+ // register method and is not a class constructor
909
+ throw FAST.error(1504 /* Message.cannotAutoregisterDependency */);
910
+ }
911
+ let current;
912
+ let keys;
913
+ let value;
914
+ let j;
915
+ let jj;
916
+ for (let i = 0, ii = params.length; i < ii; ++i) {
917
+ current = params[i];
918
+ if (!isObject(current)) {
919
+ continue;
920
+ }
921
+ if (isRegistry(current)) {
922
+ current.register(this);
923
+ }
924
+ else if (isClass(current)) {
925
+ Registration.singleton(current, current).register(this);
926
+ }
927
+ else {
928
+ keys = Object.keys(current);
929
+ j = 0;
930
+ jj = keys.length;
931
+ for (; j < jj; ++j) {
932
+ value = current[keys[j]];
933
+ if (!isObject(value)) {
934
+ continue;
935
+ }
936
+ // note: we could remove this if-branch and call this.register directly
937
+ // - the extra check is just a perf tweak to create fewer unnecessary arrays by the spread operator
938
+ if (isRegistry(value)) {
939
+ value.register(this);
940
+ }
941
+ else {
942
+ this.register(value);
943
+ }
944
+ }
945
+ }
946
+ }
947
+ --this.registerDepth;
948
+ return this;
949
+ }
950
+ registerResolver(key, resolver) {
951
+ validateKey(key);
952
+ const resolvers = this.resolvers;
953
+ const result = resolvers.get(key);
954
+ if (result == null) {
955
+ resolvers.set(key, resolver);
956
+ }
957
+ else if (result instanceof ResolverImpl &&
958
+ result.strategy === 4 /* ResolverStrategy.array */) {
959
+ result.state.push(resolver);
960
+ }
961
+ else {
962
+ resolvers.set(key, new ResolverImpl(key, 4 /* ResolverStrategy.array */, [result, resolver]));
963
+ }
964
+ return resolver;
965
+ }
966
+ registerTransformer(key, transformer) {
967
+ const resolver = this.getResolver(key);
968
+ if (resolver == null) {
969
+ return false;
970
+ }
971
+ if (resolver.getFactory) {
972
+ const factory = resolver.getFactory(this);
973
+ if (factory == null) {
974
+ return false;
975
+ }
976
+ // This type cast is a bit of a hacky one, necessary due to the duplicity of IResolverLike.
977
+ // Problem is that that interface's type arg can be of type Key, but the getFactory method only works on
978
+ // type Constructable. So the return type of that optional method has this additional constraint, which
979
+ // seems to confuse the type checker.
980
+ factory.registerTransformer(transformer);
981
+ return true;
982
+ }
983
+ return false;
984
+ }
985
+ getResolver(key, autoRegister = true) {
986
+ validateKey(key);
987
+ if (key.resolve !== void 0) {
988
+ return key;
989
+ }
990
+ /* eslint-disable-next-line @typescript-eslint/no-this-alias */
991
+ let current = this;
992
+ let resolver;
993
+ while (current != null) {
994
+ resolver = current.resolvers.get(key);
995
+ if (resolver == null) {
996
+ if (current.parent == null) {
997
+ const handler = isRegisterInRequester(key)
998
+ ? this
999
+ : current;
1000
+ return autoRegister ? this.jitRegister(key, handler) : null;
1001
+ }
1002
+ current = current.parent;
1003
+ }
1004
+ else {
1005
+ return resolver;
1006
+ }
1007
+ }
1008
+ return null;
1009
+ }
1010
+ has(key, searchAncestors = false) {
1011
+ return this.resolvers.has(key)
1012
+ ? true
1013
+ : searchAncestors && this.parent != null
1014
+ ? this.parent.has(key, true)
1015
+ : false;
1016
+ }
1017
+ get(key) {
1018
+ validateKey(key);
1019
+ if (key.$isResolver) {
1020
+ return key.resolve(this, this);
1021
+ }
1022
+ /* eslint-disable-next-line @typescript-eslint/no-this-alias */
1023
+ let current = this;
1024
+ let resolver;
1025
+ while (current != null) {
1026
+ resolver = current.resolvers.get(key);
1027
+ if (resolver == null) {
1028
+ if (current.parent == null) {
1029
+ const handler = isRegisterInRequester(key)
1030
+ ? this
1031
+ : current;
1032
+ resolver = this.jitRegister(key, handler);
1033
+ return resolver.resolve(current, this);
1034
+ }
1035
+ current = current.parent;
1036
+ }
1037
+ else {
1038
+ return resolver.resolve(current, this);
1039
+ }
1040
+ }
1041
+ throw FAST.error(1505 /* Message.cannotResolveKey */, { key });
1042
+ }
1043
+ getAll(key, searchAncestors = false) {
1044
+ validateKey(key);
1045
+ /* eslint-disable-next-line @typescript-eslint/no-this-alias */
1046
+ const requestor = this;
1047
+ let current = requestor;
1048
+ let resolver;
1049
+ if (searchAncestors) {
1050
+ let resolutions = emptyArray;
1051
+ while (current != null) {
1052
+ resolver = current.resolvers.get(key);
1053
+ if (resolver != null) {
1054
+ resolutions = resolutions.concat(
1055
+ /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
1056
+ buildAllResponse(resolver, current, requestor));
1057
+ }
1058
+ current = current.parent;
1059
+ }
1060
+ return resolutions;
1061
+ }
1062
+ else {
1063
+ while (current != null) {
1064
+ resolver = current.resolvers.get(key);
1065
+ if (resolver == null) {
1066
+ current = current.parent;
1067
+ if (current == null) {
1068
+ return emptyArray;
1069
+ }
1070
+ }
1071
+ else {
1072
+ return buildAllResponse(resolver, current, requestor);
1073
+ }
1074
+ }
1075
+ }
1076
+ return emptyArray;
1077
+ }
1078
+ getFactory(Type) {
1079
+ let factory = factories.get(Type);
1080
+ if (factory === void 0) {
1081
+ if (isNativeFunction(Type)) {
1082
+ throw FAST.error(1506 /* Message.cannotConstructNativeFunction */, {
1083
+ name: Type.name,
1084
+ });
1085
+ }
1086
+ factories.set(Type, (factory = new FactoryImpl(Type, DI.getDependencies(Type))));
1087
+ }
1088
+ return factory;
1089
+ }
1090
+ registerFactory(key, factory) {
1091
+ factories.set(key, factory);
1092
+ }
1093
+ createChild(config) {
1094
+ return new ContainerImpl(null, Object.assign({}, this.config, config, { parentLocator: () => this }));
1095
+ }
1096
+ jitRegister(keyAsValue, handler) {
1097
+ if (typeof keyAsValue !== "function") {
1098
+ throw FAST.error(1507 /* Message.cannotJITRegisterNonConstructor */, {
1099
+ value: keyAsValue,
1100
+ });
1101
+ }
1102
+ if (InstrinsicTypeNames.has(keyAsValue.name)) {
1103
+ throw FAST.error(1508 /* Message.cannotJITRegisterIntrinsic */, {
1104
+ value: keyAsValue.name,
1105
+ });
1106
+ }
1107
+ if (isRegistry(keyAsValue)) {
1108
+ const registrationResolver = keyAsValue.register(handler);
1109
+ if (!(registrationResolver instanceof Object) ||
1110
+ registrationResolver.resolve == null) {
1111
+ const newResolver = handler.resolvers.get(keyAsValue);
1112
+ if (newResolver != void 0) {
1113
+ return newResolver;
1114
+ }
1115
+ throw FAST.error(1510 /* Message.invalidResolver */);
1116
+ }
1117
+ return registrationResolver;
1118
+ }
1119
+ else if (keyAsValue.$isInterface) {
1120
+ throw FAST.error(1509 /* Message.cannotJITRegisterInterface */, {
1121
+ value: keyAsValue.name,
1122
+ });
1123
+ }
1124
+ else {
1125
+ const resolver = this.config.defaultResolver(keyAsValue, handler);
1126
+ handler.resolvers.set(keyAsValue, resolver);
1127
+ return resolver;
1128
+ }
1129
+ }
1130
+ }
1131
+ const cache = new WeakMap();
1132
+ function cacheCallbackResult(fun) {
1133
+ return function (handler, requestor, resolver) {
1134
+ if (cache.has(resolver)) {
1135
+ return cache.get(resolver);
1136
+ }
1137
+ const t = fun(handler, requestor, resolver);
1138
+ cache.set(resolver, t);
1139
+ return t;
1140
+ };
1141
+ }
1142
+ /**
1143
+ * You can use the resulting Registration of any of the factory methods
1144
+ * to register with the container.
1145
+ *
1146
+ * @example
1147
+ * ```
1148
+ * class Foo {}
1149
+ * const container = DI.createContainer();
1150
+ * container.register(Registration.instance(Foo, new Foo()));
1151
+ * container.get(Foo);
1152
+ * ```
1153
+ *
1154
+ * @public
1155
+ */
1156
+ export const Registration = Object.freeze({
1157
+ /**
1158
+ * Allows you to pass an instance.
1159
+ * Every time you request this {@link Key} you will get this instance back.
1160
+ *
1161
+ * @example
1162
+ * ```
1163
+ * Registration.instance(Foo, new Foo()));
1164
+ * ```
1165
+ *
1166
+ * @param key - The key to register the instance under.
1167
+ * @param value - The instance to return when the key is requested.
1168
+ */
1169
+ instance(key, value) {
1170
+ return new ResolverImpl(key, 0 /* ResolverStrategy.instance */, value);
1171
+ },
1172
+ /**
1173
+ * Creates an instance from the class.
1174
+ * Every time you request this {@link Key} you will get the same one back.
1175
+ *
1176
+ * @example
1177
+ * ```
1178
+ * Registration.singleton(Foo, Foo);
1179
+ * ```
1180
+ *
1181
+ * @param key - The key to register the singleton under.
1182
+ * @param value - The class to instantiate as a singleton when first requested.
1183
+ */
1184
+ singleton(key, value) {
1185
+ return new ResolverImpl(key, 1 /* ResolverStrategy.singleton */, value);
1186
+ },
1187
+ /**
1188
+ * Creates an instance from a class.
1189
+ * Every time you request this {@link Key} you will get a new instance.
1190
+ *
1191
+ * @example
1192
+ * ```
1193
+ * Registration.instance(Foo, Foo);
1194
+ * ```
1195
+ *
1196
+ * @param key - The key to register the instance type under.
1197
+ * @param value - The class to instantiate each time the key is requested.
1198
+ */
1199
+ transient(key, value) {
1200
+ return new ResolverImpl(key, 2 /* ResolverStrategy.transient */, value);
1201
+ },
1202
+ /**
1203
+ * Delegates to a callback function to provide the dependency.
1204
+ * Every time you request this {@link Key} the callback will be invoked to provide
1205
+ * the dependency.
1206
+ *
1207
+ * @example
1208
+ * ```
1209
+ * Registration.callback(Foo, () => new Foo());
1210
+ * Registration.callback(Bar, (c: Container) => new Bar(c.get(Foo)));
1211
+ * ```
1212
+ *
1213
+ * @param key - The key to register the callback for.
1214
+ * @param callback - The function that is expected to return the dependency.
1215
+ */
1216
+ callback(key, callback) {
1217
+ return new ResolverImpl(key, 3 /* ResolverStrategy.callback */, callback);
1218
+ },
1219
+ /**
1220
+ * Delegates to a callback function to provide the dependency and then caches the
1221
+ * dependency for future requests.
1222
+ *
1223
+ * @example
1224
+ * ```
1225
+ * Registration.cachedCallback(Foo, () => new Foo());
1226
+ * Registration.cachedCallback(Bar, (c: Container) => new Bar(c.get(Foo)));
1227
+ * ```
1228
+ *
1229
+ * @param key - The key to register the callback for.
1230
+ * @param callback - The function that is expected to return the dependency.
1231
+ * @remarks
1232
+ * If you pass the same Registration to another container, the same cached value will be used.
1233
+ * Should all references to the resolver returned be removed, the cache will expire.
1234
+ */
1235
+ cachedCallback(key, callback) {
1236
+ return new ResolverImpl(key, 3 /* ResolverStrategy.callback */, cacheCallbackResult(callback));
1237
+ },
1238
+ /**
1239
+ * Creates an alternate {@link Key} to retrieve an instance by.
1240
+ *
1241
+ * @example
1242
+ * ```
1243
+ * Register.singleton(Foo, Foo)
1244
+ * Register.aliasTo(Foo, MyFoos);
1245
+ *
1246
+ * container.getAll(MyFoos) // contains an instance of Foo
1247
+ * ```
1248
+ *
1249
+ * @param originalKey - The original key that has been registered.
1250
+ * @param aliasKey - The alias to the original key.
1251
+ */
1252
+ aliasTo(originalKey, aliasKey) {
1253
+ return new ResolverImpl(aliasKey, 5 /* ResolverStrategy.alias */, originalKey);
1254
+ },
1255
+ });
1256
+ /** @internal */
1257
+ export function validateKey(key) {
1258
+ if (key === null || key === void 0) {
1259
+ throw FAST.error(1511 /* Message.invalidKey */);
1260
+ }
1261
+ }
1262
+ function buildAllResponse(resolver, handler, requestor) {
1263
+ if (resolver instanceof ResolverImpl &&
1264
+ resolver.strategy === 4 /* ResolverStrategy.array */) {
1265
+ const state = resolver.state;
1266
+ let i = state.length;
1267
+ const results = new Array(i);
1268
+ while (i--) {
1269
+ results[i] = state[i].resolve(handler, requestor);
1270
+ }
1271
+ return results;
1272
+ }
1273
+ return [resolver.resolve(handler, requestor)];
1274
+ }
1275
+ const defaultFriendlyName = "(anonymous)";
1276
+ function isObject(value) {
1277
+ return (typeof value === "object" && value !== null) || typeof value === "function";
1278
+ }
1279
+ /**
1280
+ * Determine whether the value is a native function.
1281
+ *
1282
+ * @param fn - The function to check.
1283
+ * @returns `true` is the function is a native function, otherwise `false`
1284
+ */
1285
+ const isNativeFunction = (function () {
1286
+ const lookup = new WeakMap();
1287
+ let isNative = false;
1288
+ let sourceText = "";
1289
+ let i = 0;
1290
+ return function (fn) {
1291
+ isNative = lookup.get(fn);
1292
+ if (isNative === void 0) {
1293
+ sourceText = fn.toString();
1294
+ i = sourceText.length;
1295
+ // http://www.ecma-international.org/ecma-262/#prod-NativeFunction
1296
+ isNative =
1297
+ // 29 is the length of 'function () { [native code] }' which is the smallest length of a native function string
1298
+ i >= 29 &&
1299
+ // 100 seems to be a safe upper bound of the max length of a native function. In Chrome and FF it's 56, in Edge it's 61.
1300
+ i <= 100 &&
1301
+ // This whole heuristic *could* be tricked by a comment. Do we need to care about that?
1302
+ sourceText.charCodeAt(i - 1) === 0x7d && // }
1303
+ // TODO: the spec is a little vague about the precise constraints, so we do need to test this across various browsers to make sure just one whitespace is a safe assumption.
1304
+ sourceText.charCodeAt(i - 2) <= 0x20 && // whitespace
1305
+ sourceText.charCodeAt(i - 3) === 0x5d && // ]
1306
+ sourceText.charCodeAt(i - 4) === 0x65 && // e
1307
+ sourceText.charCodeAt(i - 5) === 0x64 && // d
1308
+ sourceText.charCodeAt(i - 6) === 0x6f && // o
1309
+ sourceText.charCodeAt(i - 7) === 0x63 && // c
1310
+ sourceText.charCodeAt(i - 8) === 0x20 && //
1311
+ sourceText.charCodeAt(i - 9) === 0x65 && // e
1312
+ sourceText.charCodeAt(i - 10) === 0x76 && // v
1313
+ sourceText.charCodeAt(i - 11) === 0x69 && // i
1314
+ sourceText.charCodeAt(i - 12) === 0x74 && // t
1315
+ sourceText.charCodeAt(i - 13) === 0x61 && // a
1316
+ sourceText.charCodeAt(i - 14) === 0x6e && // n
1317
+ sourceText.charCodeAt(i - 15) === 0x58; // [
1318
+ lookup.set(fn, isNative);
1319
+ }
1320
+ return isNative;
1321
+ };
1322
+ })();
1323
+ const isNumericLookup = {};
1324
+ function isArrayIndex(value) {
1325
+ switch (typeof value) {
1326
+ case "number":
1327
+ return value >= 0 && (value | 0) === value;
1328
+ case "string": {
1329
+ const result = isNumericLookup[value];
1330
+ if (result !== void 0) {
1331
+ return result;
1332
+ }
1333
+ const length = value.length;
1334
+ if (length === 0) {
1335
+ return (isNumericLookup[value] = false);
1336
+ }
1337
+ let ch = 0;
1338
+ for (let i = 0; i < length; ++i) {
1339
+ ch = value.charCodeAt(i);
1340
+ if ((i === 0 && ch === 0x30 && length > 1) /* must not start with 0 */ ||
1341
+ ch < 0x30 /* 0 */ ||
1342
+ ch > 0x39 /* 9 */) {
1343
+ return (isNumericLookup[value] = false);
1344
+ }
1345
+ }
1346
+ return (isNumericLookup[value] = true);
1347
+ }
1348
+ default:
1349
+ return false;
1350
+ }
1351
+ }