-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
registry.ts
731 lines (578 loc) · 19.3 KB
/
registry.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
import { Factory } from '@ember/-internals/owner';
import { dictionary, intern } from '@ember/-internals/utils';
import { assert } from '@ember/debug';
import { DEBUG } from '@glimmer/env';
import Container, { ContainerOptions, LazyInjection } from './container';
export interface Injection {
property: string;
specifier: string;
}
export type ResolveOptions = {
specifier?: string;
};
export interface TypeOptions {
instantiate?: boolean;
singleton?: boolean;
}
export interface KnownForTypeResult {
[fullName: string]: boolean;
}
export interface IRegistry {
describe(fullName: string): string;
getInjections(fullName: string): Injection[];
getOption<K extends keyof TypeOptions>(
fullName: string,
optionName: K
): TypeOptions[K] | undefined;
getOptions(fullName: string): TypeOptions;
getOptionsForType(type: string): TypeOptions;
getTypeInjections(type: string): Injection[];
knownForType(type: string): KnownForTypeResult;
makeToString<T, C>(factory: Factory<T, C>, fullName: string): string;
normalizeFullName(fullName: string): string;
resolve<T, C>(fullName: string, options?: ResolveOptions): Factory<T, C> | undefined;
}
export type NotResolver = {
knownForType: never;
lookupDescription: never;
makeToString: never;
normalize: never;
resolve: never;
};
export type Resolve = <T, C>(name: string) => Factory<T, C> | undefined;
export interface Resolver {
knownForType?: (type: string) => KnownForTypeResult;
lookupDescription?: (fullName: string) => string;
makeToString?: <T, C>(factory: Factory<T, C>, fullName: string) => string;
normalize?: (fullName: string) => string;
resolve: Resolve;
}
export interface RegistryOptions {
fallback?: IRegistry;
registrations?: { [key: string]: object };
resolver?: Resolver | (Resolve & NotResolver);
}
const VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/;
/**
A registry used to store factory and option information keyed
by type.
A `Registry` stores the factory and option information needed by a
`Container` to instantiate and cache objects.
The API for `Registry` is still in flux and should not be considered stable.
@private
@class Registry
@since 1.11.0
*/
export default class Registry implements IRegistry {
readonly _failSet: Set<string>;
resolver: Resolver | (Resolve & NotResolver) | null;
readonly fallback: IRegistry | null;
readonly registrations: { [key: string]: object };
readonly _injections: { [key: string]: Injection[] };
_localLookupCache: { [key: string]: object };
readonly _normalizeCache: { [key: string]: string };
readonly _options: { [key: string]: TypeOptions };
readonly _resolveCache: { [key: string]: object };
readonly _typeInjections: { [key: string]: Injection[] };
readonly _typeOptions: { [key: string]: TypeOptions };
constructor(options: RegistryOptions = {}) {
this.fallback = options.fallback || null;
this.resolver = options.resolver || null;
this.registrations = dictionary(options.registrations || null);
this._typeInjections = dictionary(null);
this._injections = dictionary(null);
this._localLookupCache = Object.create(null);
this._normalizeCache = dictionary(null);
this._resolveCache = dictionary(null);
this._failSet = new Set();
this._options = dictionary(null);
this._typeOptions = dictionary(null);
}
/**
A backup registry for resolving registrations when no matches can be found.
@private
@property fallback
@type Registry
*/
/**
An object that has a `resolve` method that resolves a name.
@private
@property resolver
@type Resolver
*/
/**
@private
@property registrations
@type InheritingDict
*/
/**
@private
@property _typeInjections
@type InheritingDict
*/
/**
@private
@property _injections
@type InheritingDict
*/
/**
@private
@property _normalizeCache
@type InheritingDict
*/
/**
@private
@property _resolveCache
@type InheritingDict
*/
/**
@private
@property _options
@type InheritingDict
*/
/**
@private
@property _typeOptions
@type InheritingDict
*/
/**
Creates a container based on this registry.
@private
@method container
@param {Object} options
@return {Container} created container
*/
container(options?: ContainerOptions) {
return new Container(this, options);
}
/**
Registers a factory for later injection.
Example:
```javascript
let registry = new Registry();
registry.register('model:user', Person, {singleton: false });
registry.register('fruit:favorite', Orange);
registry.register('communication:main', Email, {singleton: false});
```
@private
@method register
@param {String} fullName
@param {Function} factory
@param {Object} options
*/
register<T, C>(fullName: string, factory: Factory<T, C>, options: object = {}): void {
assert('fullName must be a proper full name', this.isValidFullName(fullName));
assert(`Attempting to register an unknown factory: '${fullName}'`, factory !== undefined);
let normalizedName = this.normalize(fullName);
assert(
`Cannot re-register: '${fullName}', as it has already been resolved.`,
!this._resolveCache[normalizedName]
);
this._failSet.delete(normalizedName);
this.registrations[normalizedName] = factory;
this._options[normalizedName] = options;
}
/**
Unregister a fullName
```javascript
let registry = new Registry();
registry.register('model:user', User);
registry.resolve('model:user').create() instanceof User //=> true
registry.unregister('model:user')
registry.resolve('model:user') === undefined //=> true
```
@private
@method unregister
@param {String} fullName
*/
unregister(fullName: string): void {
assert('fullName must be a proper full name', this.isValidFullName(fullName));
let normalizedName = this.normalize(fullName);
this._localLookupCache = Object.create(null);
delete this.registrations[normalizedName];
delete this._resolveCache[normalizedName];
delete this._options[normalizedName];
this._failSet.delete(normalizedName);
}
/**
Given a fullName return the corresponding factory.
By default `resolve` will retrieve the factory from
the registry.
```javascript
let registry = new Registry();
registry.register('api:twitter', Twitter);
registry.resolve('api:twitter') // => Twitter
```
Optionally the registry can be provided with a custom resolver.
If provided, `resolve` will first provide the custom resolver
the opportunity to resolve the fullName, otherwise it will fallback
to the registry.
```javascript
let registry = new Registry();
registry.resolver = function(fullName) {
// lookup via the module system of choice
};
// the twitter factory is added to the module system
registry.resolve('api:twitter') // => Twitter
```
@private
@method resolve
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] the fullname of the request source (used for local lookups)
@return {Function} fullName's factory
*/
resolve<T, C>(fullName: string): Factory<T, C> | undefined {
let factory = resolve<T, C>(this, this.normalize(fullName));
if (factory === undefined && this.fallback !== null) {
factory = (this.fallback as any).resolve(...arguments);
}
return factory;
}
/**
A hook that can be used to describe how the resolver will
attempt to find the factory.
For example, the default Ember `.describe` returns the full
class name (including namespace) where Ember's resolver expects
to find the `fullName`.
@private
@method describe
@param {String} fullName
@return {string} described fullName
*/
describe(fullName: string): string {
if (this.resolver !== null && this.resolver.lookupDescription) {
return this.resolver.lookupDescription(fullName);
} else if (this.fallback !== null) {
return this.fallback.describe(fullName);
} else {
return fullName;
}
}
/**
A hook to enable custom fullName normalization behavior
@private
@method normalizeFullName
@param {String} fullName
@return {string} normalized fullName
*/
normalizeFullName(fullName: string): string {
if (this.resolver !== null && this.resolver.normalize) {
return this.resolver.normalize(fullName);
} else if (this.fallback !== null) {
return this.fallback.normalizeFullName(fullName);
} else {
return fullName;
}
}
/**
Normalize a fullName based on the application's conventions
@private
@method normalize
@param {String} fullName
@return {string} normalized fullName
*/
normalize(fullName: string): string {
return (
this._normalizeCache[fullName] ||
(this._normalizeCache[fullName] = this.normalizeFullName(fullName))
);
}
/**
@method makeToString
@private
@param {any} factory
@param {string} fullName
@return {function} toString function
*/
makeToString<T, C>(factory: Factory<T, C>, fullName: string): string {
if (this.resolver !== null && this.resolver.makeToString) {
return this.resolver.makeToString(factory, fullName);
} else if (this.fallback !== null) {
return this.fallback.makeToString(factory, fullName);
} else {
return typeof factory === 'string' ? factory : factory.name ?? '(unknown class)';
}
}
/**
Given a fullName check if the container is aware of its factory
or singleton instance.
@private
@method has
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] the fullname of the request source (used for local lookups)
@return {Boolean}
*/
has(fullName: string) {
if (!this.isValidFullName(fullName)) {
return false;
}
return has(this, this.normalize(fullName));
}
/**
Allow registering options for all factories of a type.
```javascript
let registry = new Registry();
let container = registry.container();
// if all of type `connection` must not be singletons
registry.optionsForType('connection', { singleton: false });
registry.register('connection:twitter', TwitterConnection);
registry.register('connection:facebook', FacebookConnection);
let twitter = container.lookup('connection:twitter');
let twitter2 = container.lookup('connection:twitter');
twitter === twitter2; // => false
let facebook = container.lookup('connection:facebook');
let facebook2 = container.lookup('connection:facebook');
facebook === facebook2; // => false
```
@private
@method optionsForType
@param {String} type
@param {Object} options
*/
optionsForType(type: string, options: TypeOptions) {
this._typeOptions[type] = options;
}
getOptionsForType(type: string): TypeOptions {
let optionsForType = this._typeOptions[type];
if (optionsForType === undefined && this.fallback !== null) {
optionsForType = this.fallback.getOptionsForType(type);
}
return optionsForType;
}
/**
@private
@method options
@param {String} fullName
@param {Object} options
*/
options(fullName: string, options: TypeOptions) {
let normalizedName = this.normalize(fullName);
this._options[normalizedName] = options;
}
getOptions(fullName: string): TypeOptions {
let normalizedName = this.normalize(fullName);
let options = this._options[normalizedName];
if (options === undefined && this.fallback !== null) {
options = this.fallback.getOptions(fullName);
}
return options;
}
getOption<K extends keyof TypeOptions>(
fullName: string,
optionName: K
): TypeOptions[K] | undefined {
let options = this._options[fullName];
if (options !== undefined && options[optionName] !== undefined) {
return options[optionName];
}
let type = fullName.split(':')[0];
options = this._typeOptions[type];
if (options && options[optionName] !== undefined) {
return options[optionName];
} else if (this.fallback !== null) {
return this.fallback.getOption(fullName, optionName);
}
return undefined;
}
/**
Used only via `injection`.
Provides a specialized form of injection, specifically enabling
all objects of one type to be injected with a reference to another
object.
For example, provided each object of type `controller` needed a `router`.
one would do the following:
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('router:main', Router);
registry.register('controller:user', UserController);
registry.register('controller:post', PostController);
registry.typeInjection('controller', 'router', 'router:main');
let user = container.lookup('controller:user');
let post = container.lookup('controller:post');
user.router instanceof Router; //=> true
post.router instanceof Router; //=> true
// both controllers share the same router
user.router === post.router; //=> true
```
@private
@method typeInjection
@param {String} type
@param {String} property
@param {String} fullName
*/
typeInjection(type: string, property: string, fullName: string): void {
assert('fullName must be a proper full name', this.isValidFullName(fullName));
let fullNameType = fullName.split(':')[0];
assert(`Cannot inject a '${fullName}' on other ${type}(s).`, fullNameType !== type);
let injections = this._typeInjections[type] || (this._typeInjections[type] = []);
injections.push({ property, specifier: fullName });
}
/**
Defines injection rules.
These rules are used to inject dependencies onto objects when they
are instantiated.
Two forms of injections are possible:
* Injecting one fullName on another fullName
* Injecting one fullName on a type
Example:
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('source:main', Source);
registry.register('model:user', User);
registry.register('model:post', Post);
// injecting one fullName on another fullName
// eg. each user model gets a post model
registry.injection('model:user', 'post', 'model:post');
// injecting one fullName on another type
registry.injection('model', 'source', 'source:main');
let user = container.lookup('model:user');
let post = container.lookup('model:post');
user.source instanceof Source; //=> true
post.source instanceof Source; //=> true
user.post instanceof Post; //=> true
// and both models share the same source
user.source === post.source; //=> true
```
@private
@method injection
@param {String} factoryName
@param {String} property
@param {String} injectionName
*/
injection(fullName: string, property: string, injectionName: string) {
assert(
`Invalid injectionName, expected: 'type:name' got: ${injectionName}`,
this.isValidFullName(injectionName)
);
let normalizedInjectionName = this.normalize(injectionName);
if (fullName.indexOf(':') === -1) {
return this.typeInjection(fullName, property, normalizedInjectionName);
}
assert('fullName must be a proper full name', this.isValidFullName(fullName));
let normalizedName = this.normalize(fullName);
let injections = this._injections[normalizedName] || (this._injections[normalizedName] = []);
injections.push({ property, specifier: normalizedInjectionName });
}
/**
@private
@method knownForType
@param {String} type the type to iterate over
*/
knownForType(type: string): KnownForTypeResult {
let localKnown = dictionary(null);
let registeredNames = Object.keys(this.registrations);
for (let index = 0; index < registeredNames.length; index++) {
let fullName = registeredNames[index];
let itemType = fullName.split(':')[0];
if (itemType === type) {
localKnown[fullName] = true;
}
}
let fallbackKnown, resolverKnown;
if (this.fallback !== null) {
fallbackKnown = this.fallback.knownForType(type);
}
if (this.resolver !== null && this.resolver.knownForType) {
resolverKnown = this.resolver.knownForType(type);
}
return Object.assign({}, fallbackKnown, localKnown, resolverKnown);
}
isValidFullName(fullName: string): boolean {
return VALID_FULL_NAME_REGEXP.test(fullName);
}
getInjections(fullName: string) {
let injections = this._injections[fullName];
if (this.fallback !== null) {
let fallbackInjections = this.fallback.getInjections(fullName);
if (fallbackInjections !== undefined) {
injections =
injections === undefined ? fallbackInjections : injections.concat(fallbackInjections);
}
}
return injections;
}
getTypeInjections(type: string): Injection[] {
let injections = this._typeInjections[type];
if (this.fallback !== null) {
let fallbackInjections = this.fallback.getTypeInjections(type);
if (fallbackInjections !== undefined) {
injections =
injections === undefined ? fallbackInjections : injections.concat(fallbackInjections);
}
}
return injections;
}
}
export declare class DebugRegistry extends Registry {
normalizeInjectionsHash(hash: { [key: string]: LazyInjection }): Injection[];
validateInjections(injections: Injection[]): void;
}
if (DEBUG) {
const proto = Registry.prototype as DebugRegistry;
proto.normalizeInjectionsHash = function (hash: { [key: string]: LazyInjection }) {
let injections: Injection[] = [];
for (let key in hash) {
if (Object.prototype.hasOwnProperty.call(hash, key)) {
let { specifier } = hash[key];
assert(
`Expected a proper full name, given '${specifier}'`,
this.isValidFullName(specifier)
);
injections.push({
property: key,
specifier,
});
}
}
return injections;
};
proto.validateInjections = function (injections: Injection[]) {
if (!injections) {
return;
}
for (let i = 0; i < injections.length; i++) {
let { specifier } = injections[i];
assert(`Attempting to inject an unknown injection: '${specifier}'`, this.has(specifier));
}
};
}
function resolve<T, C>(registry: Registry, _normalizedName: string): Factory<T, C> | undefined {
let normalizedName = _normalizedName;
let cached = registry._resolveCache[normalizedName];
if (cached !== undefined) {
return cached as Factory<T, C>;
}
if (registry._failSet.has(normalizedName)) {
return;
}
let resolved: Factory<T, C> | undefined;
if (registry.resolver) {
resolved = registry.resolver.resolve<T, C>(normalizedName);
}
if (resolved === undefined) {
resolved = registry.registrations[normalizedName] as Factory<T, C> | undefined;
}
if (resolved === undefined) {
registry._failSet.add(normalizedName);
} else {
registry._resolveCache[normalizedName] = resolved;
}
return resolved;
}
function has(registry: Registry, fullName: string) {
return registry.resolve(fullName) !== undefined;
}
const privateNames: { [key: string]: string } = dictionary(null);
const privateSuffix = `${Math.random()}${Date.now()}`.replace('.', '');
export function privatize([fullName]: TemplateStringsArray): string {
let name = privateNames[fullName];
if (name) {
return name;
}
let [type, rawName] = fullName.split(':');
return (privateNames[fullName] = intern(`${type}:${rawName}-${privateSuffix}`));
}