/
application.ts
851 lines (745 loc) · 20.6 KB
/
application.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
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
/*
* @adonisjs/application
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import Hooks from '@poppinss/hooks'
import { fileURLToPath } from 'node:url'
import { join, relative } from 'node:path'
import { Container } from '@adonisjs/fold'
import Macroable from '@poppinss/macroable'
import type { HookHandler } from '@poppinss/hooks/types'
import { importDefault, RuntimeException } from '@poppinss/utils'
import debug from './debug.js'
import generators from './generators.js'
import { ConfigManager } from './managers/config.js'
import { RcFileManager } from './managers/rc_file.js'
import { NodeEnvManager } from './managers/node_env.js'
import { PreloadsManager } from './managers/preloads.js'
import { ProvidersManager } from './managers/providers.js'
import type {
Importer,
SemverNode,
HooksState,
AppEnvironments,
ApplicationStates,
} from './types.js'
/**
* Application class manages the state of an AdonisJS application. It includes
*
* - Setting up the base features like importing config and setting up logger.
* - Parsing the "adonisrc.js" file
* - Setting up the IoC container
* - Registering an booting providers
* - Invoking lifecycle methods on the providers and hooks
*/
export class Application<ContainerBindings extends Record<any, any>> extends Macroable {
/**
* Importer function to import modules from the application
* context
*/
#importer?: Importer
/**
* Flag to know if we have started the termination
* process
*/
#terminating: boolean = false
/**
* The environment in which the app is running. Currently we track
* pm2 only
*/
#surroundedEnvironment = {
pm2: false,
}
/**
* Application root. The path must end with '/'
*/
#appRoot: URL
/**
* Current application environment
*/
#environment: AppEnvironments
/**
* Current state of the application
*/
#state: ApplicationStates = 'created'
/**
* Managers for sub-features
*/
#configManager: ConfigManager
#rcFileManager: RcFileManager
#nodeEnvManager: NodeEnvManager
#preloadsManager: PreloadsManager
#providersManager: ProvidersManager
/**
* Lifecycle hooks
*/
#hooks = new Hooks<{
initiating: HooksState<ContainerBindings>
booting: HooksState<ContainerBindings>
booted: HooksState<ContainerBindings>
starting: HooksState<ContainerBindings>
ready: HooksState<ContainerBindings>
terminating: HooksState<ContainerBindings>
}>()
/**
* Store info metadata about the app.
*/
info: Map<'appName' | 'version' | 'adonisVersion' | string, any> = new Map()
/**
* Returns the application name from the info map
*/
get appName() {
return this.info.get('appName') || 'adonisjs_app'
}
/**
* Returns the application version from the info map
*/
get version(): SemverNode | null {
return this.info.get('version') || null
}
/**
* The parsed version for the "@adonisjs/core" package.
*/
get adonisVersion(): SemverNode | null {
return this.info.get('adonisVersion') || null
}
/**
* The URL for the root of the application
*/
get appRoot() {
return this.#appRoot
}
/**
* A boolean to know if the application has been booted
*/
get isBooted() {
return this.#state !== 'created' && this.#state !== 'initiated'
}
/**
* A boolean to know if the application is ready
*/
get isReady() {
return this.#state === 'ready'
}
/**
* A boolean to know if the application has been terminated
*/
get isTerminated() {
return this.#state === 'terminated'
}
/**
* A boolean to know if the application is in the middle of getting
* terminating
*/
get isTerminating() {
return this.#terminating && this.#state !== 'terminated'
}
/**
* Reference to the config class. The value is defined
* after the "init" method call
*/
get config() {
return this.#configManager.config
}
/**
* Reference to the parsed rc file. The value is defined
* after the "init" method call
*/
get rcFile() {
return this.#rcFileManager.rcFile
}
/**
* Normalized current NODE_ENV
*/
get nodeEnvironment() {
return this.#nodeEnvManager.nodeEnvironment
}
/**
* Return true when `this.nodeEnvironment === 'production'`
*/
get inProduction(): boolean {
return this.nodeEnvironment === 'production'
}
/**
* Return true when `this.nodeEnvironment === 'development'`
*/
get inDev(): boolean {
return this.nodeEnvironment === 'development'
}
/**
* Returns true when `this.nodeEnvironment === 'test'`
*/
get inTest(): boolean {
return this.nodeEnvironment === 'test'
}
/**
* Find if the process is managed and run under
* pm2
*/
get managedByPm2() {
return this.#surroundedEnvironment.pm2
}
/**
* Reference to scaffolding generators
*/
get generators() {
return generators
}
/**
* Reference to the stubs module to scaffold
* resources or eject stubs
*/
stubs = {
create: async () => {
const { StubsManager } = await import('./stubs/manager.js')
return new StubsManager(this, this.makePath(this.rcFile.directories.stubs))
},
}
/**
* A flag to know if VineJS provider is configured. When set
* to true, you may import `@vinejs/vine` package
*/
usingVineJS: boolean = false
/**
* A flag to know if Edge provider is configured. When set
* to true, you may import `edge.js` package
*/
usingEdgeJS: boolean = false
/**
* Reference to the AdonisJS IoC container. The value is defined
* after the "init" method call
*/
declare container: Container<ContainerBindings>
constructor(appRoot: URL, options: { environment: AppEnvironments; importer?: Importer }) {
super()
this.#appRoot = appRoot
this.#importer = options.importer
this.#environment = options.environment
this.#nodeEnvManager = new NodeEnvManager()
this.#configManager = new ConfigManager(this.appRoot)
this.#rcFileManager = new RcFileManager(this.appRoot)
this.#providersManager = new ProvidersManager({
environment: this.#environment,
providersState: [this],
})
this.#preloadsManager = new PreloadsManager({
environment: this.#environment,
})
this.#surroundedEnvironment.pm2 = !!process.env.pm2_id
if (debug.enabled) {
debug('app environment :%O', {
pm2: this.#surroundedEnvironment.pm2,
environment: this.#environment,
nodeEnv: this.#nodeEnvManager.nodeEnvironment,
})
}
}
/**
* Instantiate the application container
*/
#instantiateContainer() {
this.container = new Container<ContainerBindings>()
}
/**
* The current environment in which the application
* is running
*/
getEnvironment() {
return this.#environment
}
/**
* Switch the environment in which the app is running. The
* environment can only be changed before the app is
* booted.
*/
setEnvironment(environment: AppEnvironments): this {
if (this.#state !== 'created' && this.#state !== 'initiated') {
throw new RuntimeException('Cannot switch environment once the app has been booted')
}
debug('switching environment { from:"%s", to: "%s" }', this.#environment, environment)
this.#environment = environment
this.#preloadsManager.setEnvironment(environment)
this.#providersManager.setEnvironment(environment)
return this
}
/**
* The current state of the application.
*/
getState() {
return this.#state
}
/**
* Specify the contents of the "adonisrc.js" file as
* an object. Calling this method will disable loading
* the "adonisrc.js" file from the disk.
*/
rcContents(value: Record<string, any>): this {
this.#rcFileManager.rcContents(value)
return this
}
/**
* Define the config values to use when booting the
* config provider. Calling this method disables
* reading files from the config directory.
*/
useConfig(values: Record<any, any>): this {
this.#configManager.useConfig(values)
return this
}
/**
* Notify the parent process when the Node.js process is spawned with an IPC channel.
* The arguments accepted are same as "process.send"
*/
notify(
message: any,
sendHandle?: any,
options?: {
swallowErrors?: boolean | undefined
},
callback?: (error: Error | null) => void
) {
if (process.send) {
process.send(message, sendHandle, options, callback)
}
}
/**
* Listen for a process signal. This method is same as calling
* "process.on(signal)"
*/
listen(signal: NodeJS.Signals, callback: NodeJS.SignalsListener): this {
process.on(signal, callback)
return this
}
/**
* Listen for a process signal once. This method is same as calling
* "process.once(signal)"
*/
listenOnce(signal: NodeJS.Signals, callback: NodeJS.SignalsListener): this {
process.once(signal, callback)
return this
}
/**
* Listen for a process signal conditionally.
*/
listenIf(conditional: boolean, signal: NodeJS.Signals, callback: NodeJS.SignalsListener): this {
if (conditional) {
process.on(signal, callback)
}
return this
}
/**
* Listen for a process signal once conditionally.
*/
listenOnceIf(
conditional: boolean,
signal: NodeJS.Signals,
callback: NodeJS.SignalsListener
): this {
if (conditional) {
process.once(signal, callback)
}
return this
}
/**
* Register hooks that are called before the app starts
* the initiating process
*/
initiating(
handler: HookHandler<[Application<ContainerBindings>], [Application<ContainerBindings>]>
): this {
this.#hooks.add('initiating', handler)
return this
}
/**
* Initiate the application. Calling this method performs following
* operations.
*
* - Parses the "adonisrc.js" file
* - Validate and set environment variables
* - Loads the application config from the configured config dir.
* - Configures the logger
* - Instantiates the IoC container
*/
async init() {
if (this.#state !== 'created') {
debug('cannot initiate app from state "%s"', this.#state)
return
}
debug('initiating app')
/**
* Metadata management is not considering part
* of initiating the app
*/
this.#instantiateContainer()
/**
* Notify we are about to initiate the app
*/
await this.#hooks.runner('initiating').run(this)
/**
* Initiate essentials
*/
await this.#rcFileManager.process()
/**
* Cleanup registered hooks
*/
this.#hooks.clear('initiating')
this.#state = 'initiated'
}
/**
* Register hooks that are called before the app boot
* process starts
*/
booting(
handler: HookHandler<[Application<ContainerBindings>], [Application<ContainerBindings>]>
): this {
this.#hooks.add('booting', handler)
return this
}
/**
* Boot the application. Calling this method performs the following
* operations.
*
* - Resolve providers and call the "register" method on them.
* - Call the "boot" method on providers
* - Run the "booted" hooks
*/
async boot() {
if (this.#state !== 'initiated') {
debug('cannot boot app from state "%s"', this.#state)
return
}
debug('booting app')
/**
* Execute booting hooks
*/
await this.#hooks.runner('booting').run(this)
this.#hooks.clear('booting')
/**
* Process node env and config files
*/
this.#nodeEnvManager.process()
await this.#configManager.process(this.rcFile.directories.config)
/**
* Boot providers
*/
this.#providersManager.use(this.rcFile.providers)
await this.#providersManager.register()
await this.#providersManager.boot()
/**
* Notify the app is booted
*/
await this.#hooks.runner('booted').run(this)
this.#hooks.clear('booted')
this.#state = 'booted'
}
/**
* Register a hook to get notified when the application has
* been booted.
*
* The hook will be called immediately if the app has already
* been booted.
*/
async booted(
handler: HookHandler<[Application<ContainerBindings>], [Application<ContainerBindings>]>
): Promise<void> {
if (this.isBooted) {
await handler(this)
} else {
this.#hooks.add('booted', handler)
}
}
/**
* Register hooks that are called when the app is starting
*/
starting(
handler: HookHandler<[Application<ContainerBindings>], [Application<ContainerBindings>]>
): this {
this.#hooks.add('starting', handler)
return this
}
/**
* Start the application. Calling this method performs the following
* operations.
*
* - Run the "start" lifecycle hooks on all the providers
* - Start the application by invoking the supplied callback
* - Run the "ready" lifecycle hooks on all the providers
* - Run the "ready" application hooks
*/
async start(callback: (app: this) => void | Promise<void>) {
if (this.#state !== 'booted') {
debug('cannot start app from state "%s"', this.#state)
return
}
debug('starting app')
/**
* Pre start phase
*/
await this.#providersManager.start()
await this.#hooks.runner('starting').run(this)
this.#hooks.clear('starting')
await this.#preloadsManager.use(this.rcFile.preloads).import()
/**
* Callback to perform start of the application
*/
await callback(this)
/**
* Post start phase
*/
await this.#providersManager.ready()
await this.#hooks.runner('ready').run(this)
this.#hooks.clear('ready')
/**
* App ready
*/
this.#state = 'ready'
/**
* Notify process is ready
*/
debug('application ready')
this.notify('ready')
}
/**
* Register hooks that are called when the app is
* ready
*/
async ready(
handler: HookHandler<[Application<ContainerBindings>], [Application<ContainerBindings>]>
): Promise<void> {
if (this.isReady) {
await handler(this)
} else {
this.#hooks.add('ready', handler)
}
}
/**
* Register hooks that are called before the app is
* terminated.
*/
terminating(
handler: HookHandler<[Application<ContainerBindings>], [Application<ContainerBindings>]>
): this {
this.#hooks.add('terminating', handler)
return this
}
/**
* Terminate application gracefully. Calling this method performs
* the following operations.
*
* - Run "shutdown" hooks on all the providers
* - Run "terminating" app lifecycle hooks
*/
async terminate() {
if (this.#state === 'created' || this.#state === 'terminated') {
debug('cannot terminate app from state "%s"', this.#state)
return
}
debug('terminating app')
this.#terminating = true
await this.#hooks.runner('terminating').run(this)
await this.#providersManager.shutdown()
this.#hooks.clear('terminating')
this.#state = 'terminated'
}
/**
* Returns relative path to a file from the app root
*/
relativePath(absolutePath: string) {
return relative(fileURLToPath(this.appRoot), absolutePath)
}
/**
* Returns URL to a path from the application root.
*/
makeURL(...paths: string[]): URL {
return new URL(join(...paths), this.#appRoot)
}
/**
* Returns file system path from the application root.
*/
makePath(...paths: string[]): string {
return fileURLToPath(this.makeURL(...paths))
}
/**
* Makes path to the config directory
*/
configPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.config, ...paths)
}
/**
* Makes path to the public directory
*/
publicPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.public, ...paths)
}
/**
* Makes path to the providers directory
*/
providersPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.providers, ...paths)
}
/**
* Makes path to the factories directory
*/
factoriesPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.factories, ...paths)
}
/**
* Makes path to the migrations directory
*/
migrationsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.migrations, ...paths)
}
/**
* Makes path to the seeders directory
*/
seedersPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.seeders, ...paths)
}
/**
* Makes path to the language files directory
*/
languageFilesPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.languageFiles, ...paths)
}
/**
* Makes path to the views directory
*/
viewsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.views, ...paths)
}
/**
* Makes path to the start directory
*/
startPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.start, ...paths)
}
/**
* Makes path to the tmp directory
*/
tmpPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.tmp, ...paths)
}
/**
* Makes path to the contracts directory
* @deprecated
*/
contractsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.contracts, ...paths)
}
/**
* Makes path to the http controllers directory
*/
httpControllersPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.httpControllers, ...paths)
}
/**
* Makes path to the models directory
*/
modelsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.models, ...paths)
}
/**
* Makes path to the services directory
*/
servicesPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.services, ...paths)
}
/**
* Makes path to the exceptions directory
*/
exceptionsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.exceptions, ...paths)
}
/**
* Makes path to the mailers directory
*/
mailersPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.mailers, ...paths)
}
/**
* Makes path to the mails directory
*/
mailsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.mails, ...paths)
}
/**
* Makes path to the middleware directory
*/
middlewarePath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.middleware, ...paths)
}
/**
* Makes path to the policies directory
*/
policiesPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.policies, ...paths)
}
/**
* Makes path to the validators directory
*/
validatorsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.validators, ...paths)
}
/**
* Makes path to the commands directory
*/
commandsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.commands, ...paths)
}
/**
* Makes path to the events directory
*/
eventsPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.events, ...paths)
}
/**
* Makes path to the listeners directory
*/
listenersPath(...paths: string[]): string {
return this.makePath(this.rcFile.directories.listeners, ...paths)
}
/**
* Import a module by identifier. This method uses the importer function
* defined at the time of creating the application instance and throws
* an error if no importer was defined.
*/
import(moduleIdentifier: string) {
if (!this.#importer) {
throw new RuntimeException(
`Cannot import "${moduleIdentifier}". Register a module importer with the application first.`
)
}
return this.#importer(moduleIdentifier)
}
/**
* Import a module by identifier. This method uses the importer function
* defined at the time of creating the application instance and throws
* an error if no importer was defined.
*/
importDefault<T extends object>(moduleIdentifier: string) {
if (!this.#importer) {
throw new RuntimeException(
`Cannot import "${moduleIdentifier}". Register a module importer with the application first.`
)
}
return importDefault<T>(() => this.#importer!(moduleIdentifier))
}
/**
* JSON representation of the application
*/
toJSON() {
return {
isReady: this.isReady,
isTerminating: this.isTerminating,
environment: this.#environment,
nodeEnvironment: this.nodeEnvironment,
appName: this.appName,
version: this.version ? this.version.toString() : null,
adonisVersion: this.adonisVersion ? this.adonisVersion.toString() : null,
}
}
}