-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplicationContext.js
More file actions
889 lines (837 loc) · 36.4 KB
/
ApplicationContext.js
File metadata and controls
889 lines (837 loc) · 36.4 KB
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/* eslint-disable import/extensions */
import { LoggerFactory } from '@alt-javascript/logger';
import { ConfigFactory, EphemeralConfig } from '@alt-javascript/config';
import {
Context, Component, Property, Scopes,
} from './context/index.js';
import BeanPostProcessor from './BeanPostProcessor.js';
import ApplicationEventPublisher from './events/ApplicationEventPublisher.js';
import ContextRefreshedEvent from './events/ContextRefreshedEvent.js';
import ContextClosedEvent from './events/ContextClosedEvent.js';
// ---------------------------------------------------------------------------
// Lodash-free helpers (replaced lodash dependency with native equivalents)
// ---------------------------------------------------------------------------
/** Lowercase the first character of a string. Equivalent to _.lowerFirst(). */
function lowerFirst(str) {
if (!str) return str;
return str[0].toLowerCase() + str.slice(1);
}
/** Return elements in a that are also in b. Equivalent to _.intersection(). */
function intersection(a, b) {
return a.filter((x) => b.includes(x));
}
// ---------------------------------------------------------------------------
/**
* Spring-inspired IoC application context for JavaScript.
*
* Manages the lifecycle of components (singletons and prototypes):
* parsing context definitions, creating instances, autowiring dependencies,
* running bean post-processors, publishing lifecycle events, and registering
* shutdown destroyers.
*
* Lifecycle phases (in order):
* 1. parseContexts — resolve context definitions from config and explicit contexts
* 2. registerEventPublisher — create the ApplicationEventPublisher singleton
* 3. createSingletons — instantiate all singleton components (with constructor arg resolution)
* 4. injectSingletonDependencies — autowire property-based and explicit dependencies
* 5. detectBeanPostProcessors — find BeanPostProcessor instances
* 6. postProcessBeforeInitialization — run pre-init hooks
* 7. detectEventListeners — find components with onApplicationEvent method
* 8. initialiseSingletons — call setApplicationContext() then init(), respecting dependsOn order
* 9. postProcessAfterInitialization — run post-init hooks
* 10. registerSingletonDestroyers — register stop() and destroy() for shutdown
* 11. publishContextRefreshedEvent — notify listeners context is ready
*
* @example
* const context = new Context([new Singleton(MyService)]);
* const appCtx = new ApplicationContext({ contexts: [context], config });
* await appCtx.start();
* const svc = appCtx.get('myService');
*/
export default class ApplicationContext {
// eslint-disable-next-line
static DEFAULT_CONTEXT_NAME = 'default';
static DEFAULT_CONFIG_CONTEXT_PATH = 'context';
/**
* Create a new ApplicationContext.
*
* @param {object|Array<Context>} options - context array or options object
* @param {Array<Context>} [options.contexts] - component context definitions
* @param {string[]} [options.profiles] - active profiles for conditional component activation
* @param {string} [options.name='default'] - context name for logging
* @param {string} [options.configContextPath='context'] - config key containing context definitions
* @param {object} [options.config] - config object with has()/get() interface
*/
constructor(options) {
const contexts = options?.contexts || options;
if (Array.isArray(contexts)) {
this.contexts = contexts;
} else {
this.contexts = (contexts ? [contexts] : []);
}
this.components = {};
this.profiles = options?.profiles
|| (typeof (process) !== 'undefined' && process?.env?.NODE_ACTIVE_PROFILES)
|| undefined;
this.name = options?.name || ApplicationContext.DEFAULT_CONTEXT_NAME;
this.configContextPath = options?.configContextPath
|| (typeof (process) !== 'undefined' && process?.env?.NODE_CONFIG_CONTEXT_PATH)
|| ApplicationContext.DEFAULT_CONFIG_CONTEXT_PATH;
this.config = options?.config || new EphemeralConfig({});
if (options?.config) {
// eslint-disable-next-line no-param-reassign
delete options.config;
}
if (options?.profiles) {
// eslint-disable-next-line no-param-reassign
delete options.profiles;
}
if (options?.configContextPath) {
// eslint-disable-next-line no-param-reassign
delete options.configContextPath;
}
this.logger = LoggerFactory.getLogger('@alt-javascript/cdi/ApplicationContext', this.config);
}
/**
* Start the application context — runs the full lifecycle (prepare + run).
*
* @param {object} [options]
* @param {boolean} [options.run=true] - if false, skips the run phase (no start()/run() calls on components)
*/
async start(options) {
this.logger.verbose('Application context starting.');
await this.lifeCycle(options);
this.logger.verbose('Application context started.');
}
/**
* Execute the full lifecycle: prepare phase then run phase.
* @param {object} [options] - passed through to run()
*/
async lifeCycle(options) {
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle started.`);
await this.prepare();
return this.run(options);
}
/**
* Prepare phase: parse contexts, create singletons, wire dependencies,
* run post-processors, initialise, and publish ContextRefreshedEvent.
*/
async prepare() {
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle prepare phase started.`);
await this.parseContexts();
this.registerEventPublisher();
this.createSingletons();
this.injectSingletonDependencies();
this.detectBeanPostProcessors();
this.postProcessBeforeInitialization();
this.detectEventListeners();
this.initialiseSingletons();
this.postProcessAfterInitialization();
this.registerSingletonDestroyers();
this.publishContextRefreshedEvent();
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle prepare phase completed.`);
}
/** Detect and load context component definitions from the config object. */
detectConfigContext() {
this.logger.verbose('Detecting config contexts started.');
if (this.config) {
if (this.config.has(this.configContextPath)) {
this.logger.verbose(`Detected config context at ${this.configContextPath}, adding context.`);
this.contexts.push(this.config.get(this.configContextPath));
}
}
this.logger.verbose('Detecting config contexts completed.');
}
/** Parse all context definitions: config-driven, explicit, and global framework components. */
async parseContexts() {
this.logger.verbose('Parsing configured contexts started.');
this.detectConfigContext();
for (let i = 0; i < this.contexts.length; i++) {
if (this.contexts[i]) {
if (this.contexts[i]?.constructor?.name === 'Context') {
// eslint-disable-next-line no-await-in-loop
await this.parseContextComponents(this.contexts[i]);
} else {
// eslint-disable-next-line no-await-in-loop
await this.parseContextComponents(new Context(this.contexts[i]));
}
} else {
const msg = `ApplicationContext (${this.name}) received a nullish context.`;
this.logger.error(msg);
throw new Error(msg);
}
}
// Register default infrastructure components so beans with `this.logger = null`,
// `this.config = null`, etc. are always autowired — even when no explicit
// loggerFactory or config is in the provided contexts.
// When Boot.boot() provides these via the root context, those take precedence
// (they're parsed first, registration is first-write wins).
if (!this.components.loggerFactory) {
await this.deriveContextComponent({
Reference: LoggerFactory,
name: 'loggerFactory',
});
}
if (!this.components.logger) {
await this.deriveContextComponent({
scope: Scopes.PROTOTYPE,
wireFactory: 'loggerFactory',
factoryFunction: 'getLogger',
name: 'logger',
});
}
if (!this.components.config) {
await this.deriveContextComponent({
Reference: this.config,
name: 'config',
});
}
this.logger.verbose('Parsing configured contexts completed.');
}
async deriveContextComponent(contextComponent) {
if (contextComponent.name || contextComponent.Reference || contextComponent.factory) {
await this.parseContextComponent(contextComponent);
} else {
const contextKeys = Object.keys(contextComponent);
for (let i = 0; i < contextKeys.length; i++) {
const name = contextKeys[i];
const component = contextComponent[name];
component.name = name;
// eslint-disable-next-line no-await-in-loop
await this.parseContextComponent(component);
}
}
}
async parseContextComponents(context) {
this.logger.verbose('Processing context components started');
if (context.components) {
if (Array.isArray(context.components)) {
for (let i = 0; i < context.components.length; i++) {
// eslint-disable-next-line no-await-in-loop
await this.deriveContextComponent(context.components[i]);
}
}
}
this.logger.verbose('Processing context components completed');
}
/**
* Parse a single component definition into the internal registry.
* Handles: profiles, conditions, primary resolution, scope detection, constructorArgs, dependsOn.
* @param {object} componentArg - raw component definition
*/
async parseContextComponent(componentArg) {
let component = componentArg;
if (component?.constructor?.name !== 'Component'
&& component?.constructor?.name !== 'Singleton'
&& component?.constructor?.name !== 'Prototype') {
component = new Component(
component, component.name,
component.qualifier,
component.scope,
component.properties, component.profiles,
);
component.require = componentArg.require;
}
const constructr = component?.Reference?.prototype?.constructor;
const $component = {};
$component.isClass = constructr !== undefined;
$component.name = lowerFirst(component.name) || lowerFirst(constructr.name);
$component.qualifier = component.qualifier || lowerFirst(constructr?.qualifier);
$component.scope = component.scope || lowerFirst(constructr?.scope) || Scopes.SINGLETON;
$component.Reference = component.Reference;
$component.factory = component.factory;
$component.factoryFunction = component.factoryFunction;
$component.factoryArgs = component.factoryArgs;
$component.wireFactory = component.wireFactory;
$component.constructorArgs = componentArg.constructorArgs || component.constructorArgs;
$component.dependsOn = componentArg.dependsOn || component.dependsOn;
$component.primary = componentArg.primary || component.primary || false;
// TODO - dynamic import (async)
if (component.require) {
try {
// eslint-disable-next-line
let module = await import(/* @vite-ignore */ component.require);
$component.Reference = module.default;
$component.isClass = ($component?.Reference?.prototype?.constructor !== undefined);
} catch (err) {
this.logger.error(err);
}
}
$component.properties = component.properties || constructr?.properties;
$component.profiles = component.profiles || constructr?.profiles;
if (!$component.profiles) {
$component.profiles = [];
}
if (typeof $component.profiles === 'string') {
$component.profiles = $component.profiles.split(',');
}
$component.isActive = $component.profiles.length === 0;
const activeProfiles = this.profiles?.split(',') || [];
if (activeProfiles.length > 0 && !$component.isActive) {
$component.isActive = intersection(activeProfiles, $component.profiles).length > 0;
if ($component.isActive === false) {
let negations = $component.profiles.filter((profile) => profile.startsWith('!'));
negations = negations.map((profile) => profile.substring(1));
$component.isActive = negations.length > 0
&& intersection(activeProfiles, negations).length === 0;
}
}
if ($component.isActive) {
// Evaluate condition if present (from componentArg, e.g. conditionalOnProperty)
const condition = componentArg.condition;
if (condition && typeof condition === 'function') {
const activeProfiles = this.profiles?.split(',') || [];
const conditionResult = condition(this.config, this.components, activeProfiles);
if (!conditionResult) {
this.logger.verbose(`Condition failed for component (${$component.name}), skipping registration`);
return;
}
this.logger.verbose(`Condition passed for component (${$component.name})`);
}
if (!this.components[$component.name]) {
this.components[$component.name] = $component;
this.logger.verbose(`Added application context component (${$component.name}) with ${$component.scope} scope`);
} else if ($component.primary && !this.components[$component.name].primary) {
this.logger.verbose(`Primary component (${$component.name}) replacing existing non-primary`);
this.components[$component.name] = $component;
} else if (!$component.primary && this.components[$component.name].primary) {
this.logger.verbose(`Skipping non-primary duplicate (${$component.name}), primary already registered`);
} else {
const msg = `Duplicate definition of application context component (${$component.name})`;
this.logger.error(msg);
throw new Error(msg);
}
} else {
this.logger.verbose(`Skipped inactive application context component (${$component.name}), with scope ${$component.scope}`);
}
}
/**
* Create all singleton instances. Resolves constructor args from the context,
* with circular dependency detection via a creation stack.
*/
createSingletons() {
this.logger.verbose('Creating singletons started');
this._creationStack = [];
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON && !component.instance) {
this._createSingleton(component);
}
}
this._creationStack = null;
this.logger.verbose('Creating singletons completed');
}
/**
* Create a single singleton instance. Called recursively for constructor arg resolution.
* Detects circular constructor dependencies via _creationStack.
* @param {object} component - internal component record
* @throws {Error} if circular constructor dependency detected
*/
_createSingleton(component) {
// Cycle detection for constructor injection
if (this._creationStack.includes(component.name)) {
const cycle = [...this._creationStack, component.name].join(' → ');
const msg = `Circular dependency detected: ${cycle}`;
this.logger.error(msg);
throw new Error(msg);
}
this._creationStack.push(component.name);
if (component.isClass) {
if (component.constructorArgs && Array.isArray(component.constructorArgs)) {
const resolvedArgs = component.constructorArgs.map((arg) => {
if (typeof arg === 'string' && this.components[arg]) {
const dep = this.components[arg];
// If dependency is a singleton that hasn't been created yet, create it now
if (dep.scope === Scopes.SINGLETON && !dep.instance) {
this._createSingleton(dep);
}
return dep.instance || dep.Reference;
}
return arg;
});
component.instance = new component.Reference(...resolvedArgs);
this.logger.verbose(`Created singleton (${component.name}) with constructor args [${component.constructorArgs.join(', ')}]`);
} else {
component.instance = new component.Reference();
}
} else if (typeof component.factory === 'function') {
let args = component.factoryArgs;
if (!Array.isArray(args)) {
args = [args];
}
// eslint-disable-next-line new-cap
component.instance = new component.factory(...args);
} else {
component.instance = component.Reference;
}
this.logger.verbose(`Created singleton (${component.name})`);
this._creationStack.pop();
}
resolveConfigPlaceHolder(placeholderArg) {
const placeholder = placeholderArg.substring(2, placeholderArg.length - 1);
const tuple = placeholder.split(':');
const path = tuple[0];
const rawDefault = tuple[1] || undefined;
const defaultValue = rawDefault !== undefined
? (() => { try { return JSON.parse(rawDefault); } catch { return rawDefault; } })()
: undefined;
let returnValue = null;
try {
returnValue = this.config.get(path, defaultValue);
} catch (e) {
const msg = `Failed to resolve placeholder component property value (${path}) from config.`;
this.logger.error(msg);
throw new Error(msg);
}
return returnValue;
}
/**
* Autowire a component's dependencies by matching null instance properties
* against registered component names (implicit autowiring), or properties
* marked with 'Autowired' string value (explicit autowiring).
* @param {object} instance - the component instance
* @param {object} component - internal component record
*/
autowireComponentDependencies(instance, component) {
const insKeys = Object.keys(instance);
for (let j = 0; j < insKeys.length; j++) {
const property = instance[insKeys[j]];
const autowire = property?.name === 'Autowired'
|| (typeof property === 'string' && property.toLowerCase()) === 'autowired';
if (autowire) {
// eslint-disable-next-line no-param-reassign
instance[insKeys[j]] = this.get(insKeys[j], undefined, component);
this.logger.verbose(`Explicitly autowired component (${component.name}) property (${insKeys[j]}) from context.`);
} else if (instance[insKeys[j]] == null) {
// eslint-disable-next-line no-param-reassign
instance[insKeys[j]] = this.get(insKeys[j], (instance[insKeys[j]] || null), component);
if (instance[insKeys[j]] != null) {
this.logger.verbose(`Implicitly autowired null component (${component.name}) property (${insKeys[j]}) from context.`);
}
} else if (typeof instance[insKeys[j]] === 'string' && instance[insKeys[j]].startsWith('${')) {
try {
// eslint-disable-next-line no-param-reassign
instance[insKeys[j]] = this.resolveConfigPlaceHolder(instance[insKeys[j]]);
} catch (e) {
const msg = `Failed to explicitly autowired placeholder component (${component.name}) property value (${insKeys[j]}) from config.`;
this.logger.error(msg);
throw new Error(msg);
}
this.logger.verbose(`Explicitly autowired placeholder component (${component.name}) property value (${insKeys[j]}) from config.`);
}
}
}
wireComponentProperty(component, propertyArg) {
let property = propertyArg;
if (propertyArg?.constructor?.name !== 'Property') {
property = new Property();
property.name = propertyArg.name;
property.reference = propertyArg?.reference;
property.value = propertyArg?.value;
property.path = propertyArg?.path;
property.defaultValue = propertyArg?.defaultValue;
property.factory = propertyArg?.factory;
property.function = propertyArg?.function;
property.args = propertyArg?.args;
}
if (typeof property.name === 'string') {
if (property.reference) {
// eslint-disable-next-line no-param-reassign
component.instance[property.name] = this.get(property.reference, undefined, component);
this.logger.verbose(`Explicitly wired component (${component.name}) property (${property.name}) with context reference (${property.reference}).`);
}
if (property.value) {
// eslint-disable-next-line no-param-reassign
component.instance[property.name] = property.value;
this.logger.verbose(`Explicitly wired component (${component.name}) property (${property.name}) with value (${property.value}).`);
}
if (property.path) {
// eslint-disable-next-line no-param-reassign
component.instance[property.name] = this.config.get(property.path, property.defaultValue);
this.logger.verbose(`Explicitly wired component (${component.name}) property (${property.name}) from config path (${property.path}).`);
}
}
}
wireComponentDependencies(component) {
if (component.properties) {
if (!Array.isArray(component.properties)) {
// eslint-disable-next-line no-param-reassign
component.properties = [component.properties];
}
for (let i = 0; i < component.properties.length; i++) {
this.wireComponentProperty(component, component.properties[i]);
}
}
}
/** Wire all singleton dependencies (autowire + explicit wiring). */
injectSingletonDependencies() {
this.logger.verbose('Injecting singletons dependencies started');
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON) {
this.autowireComponentDependencies(component.instance, component);
this.wireComponentDependencies(component);
}
}
this.logger.verbose('Injecting singleton dependencies completed');
}
/**
* Topological sort of singleton components respecting dependsOn declarations.
* Components without dependsOn come first (in original order), then
* components are ordered so dependencies are initialized before dependents.
*
* @returns {Array<string>} ordered component names
*/
_topologicalSort() {
const keys = Object.keys(this.components).filter(
(k) => this.components[k].scope === Scopes.SINGLETON,
);
// Validate dependsOn references exist
for (const key of keys) {
const deps = this.components[key].dependsOn;
if (deps) {
const depList = Array.isArray(deps) ? deps : [deps];
for (const dep of depList) {
if (!this.components[dep]) {
const msg = `Component (${key}) dependsOn (${dep}) which does not exist in the context`;
this.logger.error(msg);
throw new Error(msg);
}
}
}
}
// Build adjacency list
const graph = new Map();
const inDegree = new Map();
for (const key of keys) {
graph.set(key, []);
inDegree.set(key, 0);
}
for (const key of keys) {
const deps = this.components[key].dependsOn;
if (deps) {
const depList = Array.isArray(deps) ? deps : [deps];
for (const dep of depList) {
if (graph.has(dep)) {
graph.get(dep).push(key);
inDegree.set(key, inDegree.get(key) + 1);
}
}
}
}
// Kahn's algorithm
const queue = keys.filter((k) => inDegree.get(k) === 0);
const sorted = [];
while (queue.length > 0) {
const node = queue.shift();
sorted.push(node);
for (const neighbor of graph.get(node)) {
inDegree.set(neighbor, inDegree.get(neighbor) - 1);
if (inDegree.get(neighbor) === 0) {
queue.push(neighbor);
}
}
}
if (sorted.length !== keys.length) {
const remaining = keys.filter((k) => !sorted.includes(k));
const msg = `Circular dependsOn detected involving: ${remaining.join(', ')}`;
this.logger.error(msg);
throw new Error(msg);
}
return sorted;
}
/**
* Initialise singletons in topological order (respecting dependsOn).
* Calls setApplicationContext() (aware interface) then init() on each singleton.
*/
initialiseSingletons() {
this.logger.verbose('Initialising singletons started');
const orderedKeys = this._topologicalSort();
for (let i = 0; i < orderedKeys.length; i++) {
const component = this.components[orderedKeys[i]];
// Aware interface: inject ApplicationContext reference
if (typeof component.instance?.setApplicationContext === 'function') {
component.instance.setApplicationContext(this);
this.logger.verbose(`Called setApplicationContext on singleton (${component.name})`);
}
if (typeof component.instance.init === 'function') {
component.instance.init();
} else if (typeof component.init === 'string') {
component.instance[component.init]();
}
this.logger.verbose(`Initialised singleton (${component.name})`);
}
this.logger.verbose('Initialising singletons completed');
}
/**
* Register a process-exit destroyer function.
* @param {Function} destroyer - called on process exit (SIGINT/SIGTERM)
*/
static registerDestroyer(destroyer) {
if (typeof (process) !== 'undefined' && destroyer) {
// process.on('exit', destroyer?.bind());
// catches ctrl+c event
process.on('SIGINT', destroyer?.bind());
// catches "kill pid" (for example: nodemon restart)
process.on('SIGUSR1', destroyer?.bind());
process.on('SIGUSR2', destroyer?.bind());
// catches uncaught exceptions
process.on('uncaughtException', destroyer?.bind());
}
}
/** Register stop() and destroy() methods on singletons for ordered shutdown. */
async registerSingletonDestroyers() {
this.logger.verbose('Registering singleton destroyers started');
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON) {
let destroyer = null;
if (typeof component.instance.stop === 'function') {
const stopper = () => component.instance.stop(component.instance);
ApplicationContext.registerDestroyer(stopper);
this.logger.verbose(`Registering singleton (${component.name}) stop lifecycle`);
}
if (typeof component.instance.destroy === 'function') {
destroyer = () => component.instance.destroy(component.instance);
} else if (typeof component.destroy === 'string') {
destroyer = () => component.instance[component.destroy](component.instance);
}
ApplicationContext.registerDestroyer(destroyer);
this.logger.verbose(`Registering singleton (${component.name}) destroyer`);
}
}
// Register context shutdown: publish ContextClosedEvent, then log completion
ApplicationContext.registerDestroyer(() => {
this.publishContextClosedEvent();
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle completed.`);
});
this.logger.verbose('Registering singleton destroyers completed');
}
/**
* Auto-register ApplicationEventPublisher as a context-managed singleton
* if not already provided by user configuration.
*/
/** Register the ApplicationEventPublisher as a context singleton. */
registerEventPublisher() {
if (!this.components.applicationEventPublisher) {
this.eventPublisher = new ApplicationEventPublisher();
this.components.applicationEventPublisher = {
name: 'applicationEventPublisher',
scope: Scopes.SINGLETON,
isClass: false,
instance: this.eventPublisher,
properties: [],
profiles: [],
isActive: true,
};
this.logger.verbose('Registered applicationEventPublisher as context singleton');
} else {
this.eventPublisher = this.components.applicationEventPublisher.instance;
}
}
/**
* Find all singleton components whose instances are BeanPostProcessors.
* Stores them in order for lifecycle hook invocation.
*/
/** Find BeanPostProcessor instances among registered singletons. */
detectBeanPostProcessors() {
this.beanPostProcessors = [];
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON && component.instance instanceof BeanPostProcessor) {
this.beanPostProcessors.push(component);
this.logger.verbose(`Detected BeanPostProcessor (${component.name})`);
}
}
}
/**
* Call postProcessBeforeInitialization on all BeanPostProcessors for each
* singleton (except BeanPostProcessors themselves — they're already initialized).
*/
postProcessBeforeInitialization() {
if (this.beanPostProcessors.length === 0) return;
this.logger.verbose('Post-process before initialization started');
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON && !(component.instance instanceof BeanPostProcessor)) {
for (let j = 0; j < this.beanPostProcessors.length; j++) {
const bpp = this.beanPostProcessors[j];
const result = bpp.instance.postProcessBeforeInitialization(component.instance, component.name);
if (result !== undefined && result !== null) {
component.instance = result;
}
this.logger.verbose(`BeanPostProcessor (${bpp.name}) postProcessBeforeInitialization called for (${component.name})`);
}
}
}
this.logger.verbose('Post-process before initialization completed');
}
/**
* Call postProcessAfterInitialization on all BeanPostProcessors for each
* singleton (except BeanPostProcessors themselves).
*/
postProcessAfterInitialization() {
if (this.beanPostProcessors.length === 0) return;
this.logger.verbose('Post-process after initialization started');
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON && !(component.instance instanceof BeanPostProcessor)) {
for (let j = 0; j < this.beanPostProcessors.length; j++) {
const bpp = this.beanPostProcessors[j];
const result = bpp.instance.postProcessAfterInitialization(component.instance, component.name);
if (result !== undefined && result !== null) {
component.instance = result;
}
this.logger.verbose(`BeanPostProcessor (${bpp.name}) postProcessAfterInitialization called for (${component.name})`);
}
}
}
this.logger.verbose('Post-process after initialization completed');
}
/**
* Detect singletons with an onApplicationEvent method and subscribe them
* to all events via the event publisher.
*/
/** Find singletons with onApplicationEvent() method and register them as event listeners. */
detectEventListeners() {
if (!this.eventPublisher) return;
this.logger.verbose('Detecting event listeners started');
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON
&& component.instance
&& typeof component.instance.onApplicationEvent === 'function') {
this.eventPublisher.on('*', (event) => component.instance.onApplicationEvent(event));
this.logger.verbose(`Registered event listener (${component.name}) via onApplicationEvent convention`);
}
}
this.logger.verbose('Detecting event listeners completed');
}
/**
* Publish ContextRefreshedEvent after prepare() completes.
*/
publishContextRefreshedEvent() {
if (!this.eventPublisher) return;
const event = new ContextRefreshedEvent(this);
this.eventPublisher.publish(event);
this.logger.verbose(`Published ContextRefreshedEvent for ApplicationContext (${this.name})`);
}
/**
* Publish ContextClosedEvent during shutdown.
*/
publishContextClosedEvent() {
if (!this.eventPublisher) return;
const event = new ContextClosedEvent(this);
this.eventPublisher.publish(event);
this.logger.verbose(`Published ContextClosedEvent for ApplicationContext (${this.name})`);
}
/**
* Run phase: call start() then run() on singletons that implement the lifecycle interface.
* @param {object} [options]
* @param {boolean} [options.run=true] - if false, skip the run phase entirely
*/
async run(options) {
if (!(options) || options?.run) {
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle run phase started.`);
const keys = Object.keys(this.components);
for (let i = 0; i < keys.length; i++) {
const component = this.components[keys[i]];
if (component.scope === Scopes.SINGLETON) {
// Lifecycle interface: start()
if (typeof component.instance.start === 'function'
&& component.instance.start !== this.start) {
component.instance.start();
this.logger.verbose(`Started lifecycle component (${component.name})`);
}
if (typeof component.run === 'string') {
component.instance[component.run]();
} else if (typeof component.instance.run === 'function') {
component.instance.run();
}
}
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle run phase completed.`);
}
} else {
this.logger.verbose(`ApplicationContext (${this.name}) skipping lifecycle run phase.`);
}
this.logger.verbose(`ApplicationContext (${this.name}) lifecycle completed.`);
}
/**
* Retrieve a component instance by name.
*
* For singletons, returns the existing instance. For prototypes, creates a new
* instance on each call. If the component is not found, returns defaultValue or
* throws if no default is provided.
*
* @param {string} reference - component name
* @param {*} [defaultValue] - returned if component not found
* @param {*} [targetArgs] - arguments passed to prototype factory functions
* @returns {*} the component instance
* @throws {Error} if component not found and no defaultValue provided
*/
get(reference, defaultValue, targetArgs) {
if (this.components[reference]) {
this.logger.verbose(`Found component (${reference})`);
if (this.components[reference].scope === Scopes.SINGLETON) {
this.logger.verbose(`Component (${reference}) is scoped as (${Scopes.SINGLETON}), returning existing instance.`);
return this.components[reference].instance;
}
let prototype = null;
if (this.components[reference].isClass) {
this.logger.verbose(`Component (${reference}) is scoped as (${Scopes.PROTOTYPE}), returning new instance.`);
prototype = new this.components[reference].Reference();
} else if (typeof this.components[reference].Reference === 'function') {
let args = targetArgs || this.components[reference].factoryArgs;
if (!Array.isArray(args)) {
args = [args];
}
prototype = this.components[reference].Reference(...args);
} else if (typeof this.components[reference].factory === 'function') {
let args = this.components[reference].factoryArgs;
if (!Array.isArray(args)) {
args = [args];
}
prototype = this.components[reference].factory(...args);
} else if (typeof this.components[reference].factory === 'string' && typeof this.components[reference].factoryFunction === 'string') {
let args = this.components[reference].factoryArgs;
if (!Array.isArray(args)) {
args = [args];
}
prototype = this.get(
this.components[reference].factory,
)[this.components[reference].factoryFunction](...args);
} else if (typeof this.components[reference].wireFactory === 'function') {
let args = targetArgs;
if (!Array.isArray(args)) {
args = [args];
}
prototype = this.components[reference].wireFactory(...args);
} else if (typeof this.components[reference].wireFactory === 'string' && typeof this.components[reference].factoryFunction === 'string') {
let args = targetArgs;
if (!Array.isArray(args)) {
args = [args];
}
const factory = this.get(this.components[reference].wireFactory);
prototype = factory[this.components[reference].factoryFunction](...args);
} else {
this.logger.verbose(`Component (${reference}) is scoped as (${Scopes.PROTOTYPE}), returning reference.`);
prototype = this.components[reference].Reference;
}
this.autowireComponentDependencies(prototype, this.components[reference]);
return prototype;
}
if (typeof defaultValue === 'undefined') {
const msg = `Failed component reference lookup for (${reference})`;
this.logger.error(msg);
throw new Error(msg);
}
return defaultValue;
}
}