### app.start(callback) — Start the application Source: https://context7.com/adonisjs/application/llms.txt Calls `start()` on all providers, fires `starting` hooks, imports preload files, invokes the user callback, calls `ready()` on providers, fires `ready` hooks, and sends `'ready'` to the parent process via IPC. Moves the application to the `ready` state. ```APIDOC ## app.start(callback) ### Description Starts the application by invoking `start()` on providers, executing `starting` hooks, importing preload files, running a user-provided callback, calling `ready()` on providers, executing `ready` hooks, and signaling readiness to the parent process. This transitions the application to the `ready` state. ### Method `await app.start(async (app) => { ... })` ### Usage Examples ```ts await app.init() await app.boot() app.starting(async (app) => { console.log('pre-start hook') }) await app.ready(async (app) => { // Called immediately if app is already ready console.log('app is ready, serving requests') }) await app.start(async (app) => { // Perform the actual startup work here (e.g., bind HTTP server) const server = app.container.make('server') await server.listen(3000) }) console.log(app.getState()) // 'ready' console.log(app.isReady) // true ``` ``` -------------------------------- ### Start the AdonisJS application Source: https://context7.com/adonisjs/application/llms.txt Initiates the application startup process, including calling start hooks, importing preload files, executing a user-defined callback, and preparing the application to serve requests. Use this to bind servers and start listening for incoming connections. ```typescript await app.init() await app.boot() app.starting(async (app) => { console.log('pre-start hook') }) await app.ready(async (app) => { // Called immediately if app is already ready console.log('app is ready, serving requests') }) await app.start(async (app) => { // Perform the actual startup work here (e.g., bind HTTP server) const server = app.container.make('server') await server.listen(3000) }) console.log(app.getState()) // 'ready' console.log(app.isReady) // true ``` -------------------------------- ### Implement a Custom Service Provider Source: https://context7.com/adonisjs/application/llms.txt Implement the `ContainerProviderContract` interface to define custom service providers. Implement lifecycle methods like `register`, `boot`, `start`, `ready`, and `shutdown` as needed for your provider's logic. ```typescript import type { ContainerProviderContract } from '@adonisjs/application/types' import type { Application } from '@adonisjs/application' export default class DatabaseProvider implements ContainerProviderContract { constructor(protected app: Application<{ db: DatabaseService }>) /** Called first — register IoC bindings */ register() { this.app.container.singleton('db', () => new DatabaseService()) } /** Called after all providers registered — boot services */ async boot() { const db = await this.app.container.make('db') await db.loadMigrations(this.app.migrationsPath()) } /** Called after all providers booted — use cross-provider bindings */ async start() { const db = await this.app.container.make('db') await db.connect() } /** Called when app is fully ready */ async ready() { console.log('DatabaseProvider ready') } /** Called during graceful shutdown */ async shutdown() { const db = await this.app.container.make('db') await db.close() } } ``` -------------------------------- ### app.init() Source: https://context7.com/adonisjs/application/llms.txt Initializes the application by parsing configuration, validating it, and setting up the IoC container. This method must be called before `boot()`. ```APIDOC ## app.init() ### Description Parses and validates `adonisrc.js`, fires `initiating` hooks, and instantiates the IoC container. The application moves to the `initiated` state. Must be called before `boot()`. ### Usage ```ts import { Application } from '@adonisjs/application' const app = new Application(new URL(import.meta.url), { environment: 'web' }) // Register a hook that runs BEFORE init app.initiating(async (app) => { app.info.set('appName', 'MyApp') app.info.set('version', { major: 1, minor: 0, patch: 0, prerelease: [], version: '1.0.0', toString: () => '1.0.0' }) console.log('About to initiate…') }) await app.init() console.log(app.getState()) // 'initiated' console.log(app.rcFile.typescript) // true console.log(app.container) // Container instance ``` ``` -------------------------------- ### app.boot() — Boot the application Source: https://context7.com/adonisjs/application/llms.txt Normalizes NODE_ENV, loads config files, registers and boots all service providers for the current environment, then fires `booted` hooks. Moves the application to the `booted` state. ```APIDOC ## app.boot() ### Description Boots the application by normalizing the environment, loading configurations, registering and booting service providers, and firing `booted` hooks. This action transitions the application to the `booted` state. ### Method `await app.boot()` ### Usage Examples ```ts await app.init() // Hook fires before providers are registered app.booting(async (app) => { console.log('booting – node env:', app.nodeEnvironment) }) // Hook fires after all providers have been booted await app.booted(async (app) => { // Called immediately if app is already booted console.log('All providers booted') }) await app.boot() console.log(app.getState()) // 'booted' console.log(app.isBooted) // true console.log(app.inProduction) // false (unless NODE_ENV=production) ``` ``` -------------------------------- ### Application Constructor Source: https://context7.com/adonisjs/application/llms.txt Instantiates the core Application class, setting up the application root and runtime environment. Supports type-safe container bindings. ```APIDOC ## new Application(appRoot, options) ### Description Creates an application instance for the specified root URL and runtime environment. The `environment` option determines which providers and preload files are activated. An optional `importer` function is required for dynamic module resolution. ### Parameters - **appRoot** (URL): The root URL of the application. - **options** (object): Configuration options for the application. - **environment** (string): The runtime environment ('web', 'console', 'test', 'repl', 'unknown'). - **importer** (function): A function for dynamic module resolution. ### Usage ```ts import { Application } from '@adonisjs/application' // Define container bindings type for full type-safety interface ContainerBindings { 'db': DatabaseService 'cache': CacheService } const app = new Application( new URL(import.meta.url), { environment: 'web', // 'web' | 'console' | 'test' | 'repl' | 'unknown' importer: (id) => import(id), } ) // Optionally supply RC contents inline (disables reading adonisrc.js from disk) app.rcContents({ typescript: true, providers: [() => import('./providers/app_provider.js')], }) // Optionally supply config inline (disables reading files from disk) app.useConfig({ app: { name: 'MyApp', key: 'secret' } }) console.log(app.getEnvironment()) // 'web' console.log(app.getState()) // 'created' ``` ``` -------------------------------- ### Boot the AdonisJS application Source: https://context7.com/adonisjs/application/llms.txt Initializes the application, loads configuration, registers and boots service providers, and fires lifecycle hooks. Use this to prepare the application for use. ```typescript await app.init() // Hook fires before providers are registered app.booting(async (app) => { console.log('booting – node env:', app.nodeEnvironment) }) // Hook fires after all providers have been booted await app.booted(async (app) => { // Called immediately if app is already booted console.log('All providers booted') }) await app.boot() console.log(app.getState()) // 'booted' console.log(app.isBooted) // true console.log(app.inProduction) // false (unless NODE_ENV=production) ``` -------------------------------- ### Path helpers Source: https://context7.com/adonisjs/application/llms.txt Utilities for constructing absolute file-system paths or URLs relative to the application's root directory. These helpers simplify file and resource access. ```APIDOC ## Path Helpers ### Description Provides a set of convenience methods for generating absolute file paths and URLs relative to the application's root directory. These functions abstract away the complexities of path manipulation. ### Available Helpers - **`app.makePath(segment1, segment2, ...)`**: Constructs an absolute file-system path. - **`app.makeURL(segment1, segment2, ...)`**: Constructs a URL object. - **`app.relativePath(absolutePath)`**: Converts an absolute path to a path relative to the application root. ### Typed Directory Shortcuts These helpers delegate to `makePath` using predefined directory configurations: - **`app.configPath(segment)`**: Path within the `config` directory. - **`app.publicPath(segment)`**: Path within the `public` directory. - **`app.httpControllersPath(segment)`**: Path within the `app/controllers` directory. - **`app.modelsPath(segment)`**: Path within the `app/models` directory. - **`app.migrationsPath(segment)`**: Path within the `database/migrations` directory. - **`app.seedersPath(segment)`**: Path within the `database/seeders` directory. - **`app.viewsPath(segment)`**: Path within the `resources/views` directory. - **`app.commandsPath(segment)`**: Path within the `commands` directory. - **`app.tmpPath(segment)`**: Path within the `tmp` directory. - **`app.servicesPath(segment)`**: Path within the `app/services` directory. - **`app.middlewarePath(segment)`**: Path within the `app/middleware` directory. - **`app.validatorsPath(segment)`**: Path within the `app/validators` directory. - **`app.policiesPath(segment)`**: Path within the `app/policies` directory. - **`app.eventsPath(segment)`**: Path within the `app/events` directory. - **`app.listenersPath(segment)`**: Path within the `app/listeners` directory. - **`app.generatedClientPath(segment)`**: Path within the `.adonisjs/client` directory. - **`app.generatedServerPath(segment)`**: Path within the `.adonisjs/server` directory. ### Usage Examples ```ts // Generic helpers app.makePath('config', 'database.ts') // → '/home/user/myapp/config/database.ts' app.makeURL('public', 'logo.png') // → URL { href: 'file:///home/user/myapp/public/logo.png' } app.relativePath('/home/user/myapp/app/controllers/users_controller.ts') // → 'app/controllers/users_controller.ts' // Typed directory shortcuts app.configPath('app.ts') // → '/config/app.ts' app.publicPath('css/app.css') // → '/public/css/app.css' app.httpControllersPath() // → '/app/controllers' app.modelsPath('user.ts') // → '/app/models/user.ts' app.migrationsPath() // → '/database/migrations' app.seedersPath() // → '/database/seeders' app.viewsPath('home.edge') // → '/resources/views/home.edge' app.commandsPath('greet.ts') // → '/commands/greet.ts' app.tmpPath('uploads') // → '/tmp/uploads' app.servicesPath('payment.ts') // → '/app/services/payment.ts' app.middlewarePath('auth.ts') // → '/app/middleware/auth.ts' app.validatorsPath('user.ts') // → '/app/validators/user.ts' app.policiesPath('post_policy.ts') // → '/app/policies/post_policy.ts' app.eventsPath() // → '/app/events' app.listenersPath() // → '/app/listeners' app.generatedClientPath() // → '/.adonisjs/client' app.generatedServerPath() // → '/.adonisjs/server' ``` ``` -------------------------------- ### app.setEnvironment(environment) — Switch runtime environment Source: https://context7.com/adonisjs/application/llms.txt Changes the active environment before the app is booted. Useful for test runners or REPL entry points that need to override the default environment. ```APIDOC ## app.setEnvironment(environment) ### Description Allows switching the application's runtime environment before it has been initialized or booted. This is particularly useful in testing scenarios or REPL environments where the default environment needs to be overridden. ### Method `app.setEnvironment(environment: string)` ### Parameters #### Path Parameters - **environment** (string) - Required - The desired runtime environment (e.g., 'web', 'test'). ### Usage Examples ```ts const app = new Application(new URL(import.meta.url), { environment: 'web' }) // Switch before init/boot app.setEnvironment('test') await app.init() await app.boot() console.log(app.getEnvironment()) // 'test' console.log(app.inTest) // true ``` ``` -------------------------------- ### app.import() and app.importDefault() Source: https://context7.com/adonisjs/application/llms.txt Dynamically import modules using the application's configured importer. `importDefault` specifically unwraps the default export. ```APIDOC ## `app.import(moduleIdentifier)` / `app.importDefault(moduleIdentifier)` — Dynamic module importing Delegates to the `importer` function supplied at construction. `importDefault` additionally unwraps the `.default` export with CommonJS/ESM interop. ### Usage ```ts const app = new Application(new URL(import.meta.url), { environment: 'web', importer: (id) => import(id), }) await app.init() await app.boot() // Import any module identifier const { default: Router } = await app.import('@adonisjs/core/router') // Import and unwrap the default export const UserController = await app.importDefault( './app/controllers/users_controller.js' ) ``` ``` -------------------------------- ### Initiate AdonisJS Application Lifecycle Source: https://context7.com/adonisjs/application/llms.txt Call the app.init() method to parse and validate adonisrc.js, fire 'initiating' hooks, and instantiate the IoC container. This transitions the application state to 'initiated' and must be called before app.boot(). You can register hooks to run before initialization. ```typescript import { Application } from '@adonisjs/application' const app = new Application(new URL(import.meta.url), { environment: 'web' }) // Register a hook that runs BEFORE init app.initiating(async (app) => { app.info.set('appName', 'MyApp') app.info.set('version', { major: 1, minor: 0, patch: 0, prerelease: [], version: '1.0.0', toString: () => '1.0.0' }) console.log('About to initiate…') }) await app.init() console.log(app.getState()) // 'initiated' console.log(app.rcFile.typescript) // true console.log(app.container) // Container instance ``` -------------------------------- ### Initialize AdonisJS Application Instance Source: https://context7.com/adonisjs/application/llms.txt Instantiate the Application class with the application root URL and runtime environment options. This constructor allows for defining container bindings with type-safety and optionally supplying RC contents or configuration inline, bypassing disk reads. ```typescript import { Application } from '@adonisjs/application' // Define container bindings type for full type-safety interface ContainerBindings { 'db': DatabaseService 'cache': CacheService } const app = new Application( new URL(import.meta.url), { environment: 'web', // 'web' | 'console' | 'test' | 'repl' | 'unknown' importer: (id) => import(id), } ) // Optionally supply RC contents inline (disables reading adonisrc.js from disk) app.rcContents({ typescript: true, providers: [() => import('./providers/app_provider.js')], }) // Optionally supply config inline (disables reading files from disk) app.useConfig({ app: { name: 'MyApp', key: 'secret' } }) console.log(app.getEnvironment()) // 'web' console.log(app.getState()) // 'created' ``` -------------------------------- ### app.terminate() — Graceful shutdown Source: https://context7.com/adonisjs/application/llms.txt Runs `terminating` hooks in reverse registration order, calls `shutdown()` on all providers, and moves the application to the `terminated` state. Idempotent — multiple calls are safely ignored. ```APIDOC ## app.terminate() ### Description Initiates a graceful shutdown of the application by executing `terminating` hooks in reverse order, calling `shutdown()` on all providers, and transitioning the application to the `terminated` state. This operation is idempotent. ### Method `await app.terminate()` ### Usage Examples ```ts // Register cleanup hooks app.terminating(async (app) => { console.log('Closing database connections…') await app.container.make('db').close() }) app.terminating(async (app) => { console.log('Flushing cache…') }) // Signal handling pattern app.listenOnce('SIGTERM', async () => { await app.terminate() process.exit(0) }) app.listenOnceIf(!app.inProduction, 'SIGINT', async () => { await app.terminate() process.exit(0) }) await app.terminate() console.log(app.getState()) // 'terminated' console.log(app.isTerminated) // true ``` ``` -------------------------------- ### Create Application Instances for Testing with AppFactory Source: https://context7.com/adonisjs/application/llms.txt Use `AppFactory` from `@adonisjs/application/factories` to build `Application` instances in tests without a real file system. Customize environment, importers, and RC file contents. ```typescript import { AppFactory } from '@adonisjs/application/factories' const factory = new AppFactory() // Create a basic app instance for testing const app = factory.create(new URL(import.meta.url)) // Customise environment / importer before creating const testApp = factory .merge({ environment: 'test' }) .create(new URL(import.meta.url), (id) => import(id)) // Supply inline RC contents so no adonisrc.js file is needed testApp.rcContents({ typescript: true, providers: [() => import('../providers/app_provider.js')], }) testApp.useConfig({ db: { connection: 'sqlite', filename: ':memory:' } }) await testApp.init() await testApp.boot() // Use in Japa tests import { test } from '@japa/runner' test('database service resolves', async ({ assert }) => { const db = await testApp.container.make('db') assert.instanceOf(db, DatabaseService) }) // Cleanup await testApp.terminate() ``` -------------------------------- ### Observe Provider Lifecycle Events with Tracing Channels Source: https://context7.com/adonisjs/application/llms.txt Use tracing channels to monitor provider lifecycle events and preload imports. Subscribe to specific events like `providerBoot` or `preloadImport` to log performance or track import activities. ```typescript import { tracingChannels } from '@adonisjs/application' const { providerRegister, providerBoot, providerStart, providerReady, providerShutdown, preloadImport, } = tracingChannels // Performance timing for each provider's boot phase providerBoot.subscribe({ asyncStart({ provider }) { console.time(`boot:${provider.constructor.name}`) }, asyncEnd({ provider }) { console.timeEnd(`boot:${provider.constructor.name}`) }, error({ provider }, error) { console.error(`boot failed: ${provider.constructor.name}`, error) }, }) // Monitor graceful shutdown providerShutdown.subscribe({ asyncStart({ provider }) { console.log('Shutting down:', provider.constructor.name) }, }) // Track preload file imports preloadImport.subscribe({ asyncStart({ file }) { console.log('Importing preload:', file.toString()) }, }) ``` -------------------------------- ### AdonisJS Path Helpers Source: https://context7.com/adonisjs/application/llms.txt Utilities for constructing absolute file-system paths or URLs relative to the application root. These helpers simplify accessing application directories like config, public, controllers, models, and more. ```typescript // Generic helpers app.makePath('config', 'database.ts') // → '/home/user/myapp/config/database.ts' app.makeURL('public', 'logo.png') // → URL { href: 'file:///home/user/myapp/public/logo.png' } app.relativePath('/home/user/myapp/app/controllers/users_controller.ts') // → 'app/controllers/users_controller.ts' // Typed directory shortcuts app.configPath('app.ts') // → '/config/app.ts' app.publicPath('css/app.css') // → '/public/css/app.css' app.httpControllersPath() // → '/app/controllers' app.modelsPath('user.ts') // → '/app/models/user.ts' app.migrationsPath() // → '/database/migrations' app.seedersPath() // → '/database/seeders' app.viewsPath('home.edge') // → '/resources/views/home.edge' app.commandsPath('greet.ts') // → '/commands/greet.ts' app.tmpPath('uploads') // → '/tmp/uploads' app.servicesPath('payment.ts') // → '/app/services/payment.ts' app.middlewarePath('auth.ts') // → '/app/middleware/auth.ts' app.validatorsPath('user.ts') // → '/app/validators/user.ts' app.policiesPath('post_policy.ts') // → '/app/policies/post_policy.ts' app.eventsPath() // → '/app/events' app.listenersPath() // → '/app/listeners' app.generatedClientPath() // → '/.adonisjs/client' app.generatedServerPath() // → '/.adonisjs/server' ``` -------------------------------- ### app.toJSON() Source: https://context7.com/adonisjs/application/llms.txt Serializes the application's current state into a plain JavaScript object. ```APIDOC ## `app.toJSON()` — Serialise application state Returns a plain object snapshot of the application suitable for logging or health-check endpoints. ### Usage ```ts console.log(app.toJSON()) // { // isReady: true, // isTerminating: false, // environment: 'web', // nodeEnvironment: 'development', // appName: 'MyApp', // version: '1.0.0', // adonisVersion: '6.0.0' // } ``` ``` -------------------------------- ### FeatureFlags Source: https://context7.com/adonisjs/application/llms.txt A utility for managing and evaluating feature flags, supporting static configurations and dynamic factories. ```APIDOC ## `FeatureFlags` — Conditional feature-flag evaluation A lightweight class that reads a static flags object or a factory function and exposes `enabled()`, `disabled()`, `has()`, and `when()` helpers. The `ExperimentalFlagsList` interface can be module-augmented to add package-specific flags. ### Usage ```ts import { FeatureFlags } from '@adonisjs/application' // Augment the global list (in your package's types file) declare module '@adonisjs/application/types' { interface ExperimentalFlagsList { useNewRouter: boolean legacyAuth: boolean } } // Static flags const flags = new FeatureFlags({ useNewRouter: true, legacyAuth: false }) flags.enabled('useNewRouter') // true flags.disabled('legacyAuth') // true flags.has('useNewRouter') // true const result = flags.when( 'useNewRouter', () => 'Using new router', () => 'Using legacy router' ) // → 'Using new router' // Dynamic factory (used by Application internally) const appFlags = new FeatureFlags(() => app.rcFile.experimental) if (appFlags.enabled('useNewRouter')) { // activate experimental router } ``` ``` -------------------------------- ### Dynamic Module Importing with app.import and app.importDefault Source: https://context7.com/adonisjs/application/llms.txt Use `app.import` to dynamically import any module by its identifier. `app.importDefault` additionally unwraps the default export, useful for CommonJS/ESM interop. Ensure the Application is initialized and booted before use. ```typescript const app = new Application(new URL(import.meta.url), { environment: 'web', importer: (id) => import(id), }) await app.init() await app.boot() // Import any module identifier const { default: Router } = await app.import('@adonisjs/core/router') // Import and unwrap the default export const UserController = await app.importDefault( './app/controllers/users_controller.js' ) ``` -------------------------------- ### Code Generation with StubsManager and Stub Source: https://context7.com/adonisjs/application/llms.txt Use `StubsManager` to locate and `Stub` to render and write stub template files. You can build stubs from packages, prepare them for a dry-run, override content, or copy stubs to the app's stubs directory. ```typescript // Create manager (usually via app.stubs.create()) const stubsManager = await app.stubs.create() // --- Build and generate a stub --- const stub = await stubsManager.build('make/controller.stub', { pkg: '@adonisjs/core', // source stubs from this package }) const result = await stub.generate({ entity: generators.createEntity('admin/users'), force: false, }) if (result.status === 'created') { console.log('Created:', result.destination) } else if (result.status === 'skipped') { console.log('Skipped:', result.skipReason) } else { console.log('Force created:', result.destination) } // --- Prepare without writing (dry-run) --- const prepared = await stub.prepare({ entity: generators.createEntity('user'), }) console.log(prepared.contents) // rendered file content console.log(prepared.destination) // absolute path where file would be written console.log(prepared.attributes) // metadata exported from the stub template // --- Override rendered content --- stub.replaceWith('// custom content').generate({ entity: generators.createEntity('user') }) // --- Copy stubs from a package to the app stubs directory --- const copied = await stubsManager.copy('make/controller.stub', { pkg: '@adonisjs/core', overwrite: false, }) console.log(copied) // ['/path/to/app/stubs/make/controller.stub'] ``` -------------------------------- ### defineConfig Helper Source: https://context7.com/adonisjs/application/llms.txt A type-safe helper function for defining the adonisrc.js configuration file, providing IntelliSense and compile-time validation. ```APIDOC ## defineConfig(config) ### Description A passthrough identity function that returns its argument unchanged. Its sole purpose is to add TypeScript IntelliSense and compile-time validation to the `adonisrc.js` file. ### Usage ```ts // adonisrc.ts import { defineConfig } from '@adonisjs/application' export default defineConfig({ typescript: true, directories: { config: 'config', httpControllers: 'app/controllers', }, providers: [ () => import('@adonisjs/core/providers/app_provider'), { file: () => import('./providers/database_provider.js'), environment: ['web', 'console'], }, ], preloads: [ () => import('./start/routes.js'), { file: () => import('./start/kernel.js'), environment: ['web'], }, ], metaFiles: [ { pattern: 'public/**', reloadServer: false }, 'resources/views/**/*.edge', ], tests: { suites: [ { name: 'unit', files: ['tests/unit/**/*.spec.ts'] }, { name: 'functional', files: ['tests/functional/**/*.spec.ts'], timeout: 30_000 }, ], forceExit: true, timeout: 2000, }, }) ``` ``` -------------------------------- ### Switch AdonisJS runtime environment Source: https://context7.com/adonisjs/application/llms.txt Allows changing the application's runtime environment before it is booted. This is particularly useful for test runners or REPLs that need to override the default environment. Ensure this is called before `app.init()`. ```typescript const app = new Application(new URL(import.meta.url), { environment: 'web' }) // Switch before init/boot app.setEnvironment('test') await app.init() await app.boot() console.log(app.getEnvironment()) // 'test' console.log(app.inTest) // true ``` -------------------------------- ### Scaffolding Name and Filename Generators Source: https://context7.com/adonisjs/application/llms.txt Use the `generators` singleton to derive class names, file names, and table names from raw entity input. It's used internally by Ace make commands and is available on `app.generators`. ```typescript import generators from '@adonisjs/application' // or: app.generators // Model generators.modelName('blog-posts') // 'BlogPost' generators.modelFileName('blog-posts') // 'blog_post.ts' generators.tableName('BlogPost') // 'blog_posts' // Controller (plural by default, singular for known names) generators.controllerName('users') // 'UsersController' generators.controllerName('admin') // 'AdminController' (singular list) generators.controllerName('posts', true) // 'PostController' (forced singular) generators.controllerFileName('users') // 'users_controller.ts' // Middleware / Provider / Policy / Factory / Service / Seeder generators.middlewareName('cors') // 'CorsMiddleware' generators.providerName('database') // 'DatabaseProvider' generators.policyName('users') // 'UserPolicy' generators.factoryName('users') // 'UserFactory' generators.serviceName('users') // 'UserService' generators.seederName('users') // 'UserSeeder' // Commands generators.commandName('make-user') // 'MakeUser' generators.commandTerminalName('MakeUser') // 'make:user' generators.commandFileName('MakeUser') // 'make_user.ts' // Validators generators.validatorName('create-post') // 'CreatePost' generators.validatorActionName('User', 'create') // 'createUserValidator' // Events / Listeners / Exceptions / Mailers / Views generators.eventName('user-registered') // 'UserRegistered' generators.listenerName('send-email') // 'SendEmail' generators.exceptionName('not-found') // 'NotFoundException' generators.mailerName('welcome-email') // 'WelcomeEmailNotification' generators.viewFileName('UserProfile') // 'user_profile.edge' generators.testFileName('UserController') // 'user_controller.spec.ts' // Path parsing generators.createEntity('admin/users') // { path: 'admin', name: 'users' } generators.importPath('app', 'models', 'user') // 'app/models/user' ``` -------------------------------- ### RcFileParser Source: https://context7.com/adonisjs/application/llms.txt Parses and validates the `adonisrc.js` configuration file, merging defaults and applying presets. ```APIDOC ## `RcFileParser` — Parse and validate adonisrc.js content Accepts a raw configuration object, merges it with defaults, validates every field, applies preset functions, and returns a fully-normalised `RcFile` object. ### Usage ```ts import { RcFileParser } from '@adonisjs/application' const parser = new RcFileParser({ typescript: true, providers: [ () => import('./providers/app_provider.js'), { file: () => import('./providers/database_provider.js'), environment: ['web'], }, ], preloads: [ { file: () => import('./start/routes.js'), environment: ['web', 'console'] }, ], metaFiles: ['public/**'], tests: { suites: [ { name: 'unit', files: ['tests/unit/**/*.spec.ts'] }, ], }, hooks: { buildFinished: [() => import('./hooks/post_build.js')], }, }) const rcFile = parser.parse() console.log(rcFile.typescript) // true console.log(rcFile.providers.length) // 2 console.log(rcFile.preloads[0].environment) // ['web', 'console'] console.log(rcFile.metaFiles[0]) // { pattern: 'public/**', reloadServer: true } console.log(rcFile.tests.suites[0].directories) // ['tests/unit'] console.log(rcFile.raw) // original input object ``` ``` -------------------------------- ### Define AdonisJS Application Configuration with defineConfig Source: https://context7.com/adonisjs/application/llms.txt Use defineConfig to create type-safe adonisrc.js configuration files. It provides IntelliSense and compile-time validation for your application's settings, including directories, providers, preloads, meta files, and testing configurations. ```typescript import { defineConfig } from '@adonisjs/application' export default defineConfig({ typescript: true, directories: { config: 'config', httpControllers: 'app/controllers', }, providers: [ () => import('@adonisjs/core/providers/app_provider'), { file: () => import('./providers/database_provider.js'), environment: ['web', 'console'], }, ], preloads: [ () => import('./start/routes.js'), { file: () => import('./start/kernel.js'), environment: ['web'], }, ], metaFiles: [ { pattern: 'public/**', reloadServer: false }, 'resources/views/**/*.edge', ], tests: { suites: [ { name: 'unit', files: ['tests/unit/**/*.spec.ts'] }, { name: 'functional', files: ['tests/functional/**/*.spec.ts'], timeout: 30_000 }, ], forceExit: true, timeout: 2000, }, }) ``` -------------------------------- ### Serializing Application State with app.toJSON Source: https://context7.com/adonisjs/application/llms.txt Obtain a plain object snapshot of the application's current state using `app.toJSON()`. This is suitable for logging purposes or for use in health-check endpoints. ```typescript console.log(app.toJSON()) // { // isReady: true, // isTerminating: false, // environment: 'web', // nodeEnvironment: 'development', // appName: 'MyApp', // version: '1.0.0', // adonisVersion: '6.0.0' // } ``` -------------------------------- ### app.notify() Source: https://context7.com/adonisjs/application/llms.txt Send IPC notifications to the parent process. Useful for signaling events like readiness or custom data. ```APIDOC ## `app.notify(message)` — IPC notification Sends a message to the parent process when the Node.js process was spawned with an IPC channel (e.g., by PM2 or the AdonisJS dev server). Used internally to signal `'ready'`. ### Usage ```ts // Notify parent process that app is ready app.notify('ready') // Send custom structured data app.notify({ event: 'cache:warmed', entries: 1024 }) ``` ``` -------------------------------- ### Gracefully terminate the AdonisJS application Source: https://context7.com/adonisjs/application/llms.txt Handles application shutdown by running terminating hooks, calling shutdown on providers, and moving the application to a terminated state. This method is idempotent and safe to call multiple times. ```typescript // Register cleanup hooks app.terminating(async (app) => { console.log('Closing database connections…') await app.container.make('db').close() }) app.terminating(async (app) => { console.log('Flushing cache…') }) // Signal handling pattern app.listenOnce('SIGTERM', async () => { await app.terminate() process.exit(0) }) app.listenOnceIf(!app.inProduction, 'SIGINT', async () => { await app.terminate() process.exit(0) }) await app.terminate() console.log(app.getState()) // 'terminated' console.log(app.isTerminated) // true ``` -------------------------------- ### Parsing and Validating RC File with RcFileParser Source: https://context7.com/adonisjs/application/llms.txt Use `RcFileParser` to parse and validate `adonisrc.js` content. It merges configurations with defaults, validates fields, applies presets, and returns a normalized `RcFile` object. Ensure necessary imports are present. ```typescript import { RcFileParser } from '@adonisjs/application' const parser = new RcFileParser({ typescript: true, providers: [ () => import('./providers/app_provider.js'), { file: () => import('./providers/database_provider.js'), environment: ['web'], }, ], preloads: [ { file: () => import('./start/routes.js'), environment: ['web', 'console'] }, ], metaFiles: ['public/**'], tests: { suites: [ { name: 'unit', files: ['tests/unit/**/*.spec.ts'] }, ], }, hooks: { buildFinished: [() => import('./hooks/post_build.js')], }, }) const rcFile = parser.parse() console.log(rcFile.typescript) // true console.log(rcFile.providers.length) // 2 console.log(rcFile.preloads[0].environment) // ['web', 'console'] console.log(rcFile.metaFiles[0]) // { pattern: 'public/**', reloadServer: true } console.log(rcFile.tests.suites[0].directories) // ['tests/unit'] console.log(rcFile.raw) // original input object ``` -------------------------------- ### IPC Notification with app.notify Source: https://context7.com/adonisjs/application/llms.txt Send messages to the parent process using `app.notify`. This is typically used when the Node.js process is spawned with an IPC channel, such as by PM2 or the AdonisJS dev server. It's used internally to signal readiness. ```typescript // Notify parent process that app is ready app.notify('ready') ``` ```typescript // Send custom structured data app.notify({ event: 'cache:warmed', entries: 1024 }) ``` -------------------------------- ### Handle RC File Validation Errors Source: https://context7.com/adonisjs/application/llms.txt Utilize named error constructors from `@adonisjs/application/errors` for programmatic error handling. Catch specific errors like `E_INVALID_PROVIDER` to manage configuration issues. ```typescript import { errors } from '@adonisjs/application' const { E_MISSING_METAFILE_PATTERN, E_MISSING_PRELOAD_FILE, E_INVALID_PRELOAD_FILE, E_MISSING_PROVIDER_FILE, E_INVALID_PROVIDER, E_MISSING_SUITE_NAME, E_MISSING_SUITE_FILES, E_UNKNOWN_ASSEMBLER_HOOK, E_INVALID_HOOKS_VALUE, E_INVALID_PRESETS_VALUE, E_INVALID_PRESET_FUNCTION, E_PRESET_EXECUTION_ERROR, } = errors try { const { RcFileParser } = await import('@adonisjs/application') new RcFileParser({ providers: [{ notAFunction: true }] }).parse() } catch (error) { if (error instanceof errors.E_INVALID_PROVIDER) { console.error('Provider misconfigured:', error.message) // → 'Invalid provider entry "…". The file property must be a function' } } ``` -------------------------------- ### AdonisJS Lifecycle Hook Factories Source: https://context7.com/adonisjs/application/llms.txt Use the `hooks` utility to create factory functions for wrapping callbacks used in `adonisrc.js` hooks configuration. These factories provide type information for callback parameters. ```typescript import { hooks } from '@adonisjs/application' // In adonisrc.ts hooks section: export default defineConfig({ hooks: { buildFinished: [ hooks.buildFinished((buildResult) => { console.log('Build complete, deploying…') }), ], devServerStarted: [ hooks.devServerStarted((server) => { console.log(`Dev server ready on port ${server.port}`) }), ], fileChanged: [ hooks.fileChanged((filePath) => { console.log('File changed:', filePath) }), ], testsFinished: [ hooks.testsFinished((results) => { console.log('Tests done, total failures:', results.failedCount) }), ], }, }) ``` -------------------------------- ### Conditional Feature Flag Evaluation with FeatureFlags Source: https://context7.com/adonisjs/application/llms.txt Manage conditional feature flags using the `FeatureFlags` class. It supports static flag objects or factory functions and provides helpers like `enabled()`, `disabled()`, `has()`, and `when()`. Augment `ExperimentalFlagsList` for package-specific flags. ```typescript import { FeatureFlags } from '@adonisjs/application' // Augment the global list (in your package's types file) declare module '@adonisjs/application/types' { interface ExperimentalFlagsList { useNewRouter: boolean legacyAuth: boolean } } // Static flags const flags = new FeatureFlags({ useNewRouter: true, legacyAuth: false }) flags.enabled('useNewRouter') // true flags.disabled('legacyAuth') // true flags.has('useNewRouter') // true const result = flags.when( 'useNewRouter', () => 'Using new router', () => 'Using legacy router' ) // → 'Using new router' // Dynamic factory (used by Application internally) const appFlags = new FeatureFlags(() => app.rcFile.experimental) if (appFlags.enabled('useNewRouter')) { // activate experimental router } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.