@meghjs/mcp 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
@@ -0,0 +1,179 @@
1
+ ---
2
+ title: Relations
3
+ description: "MeghORM relations: hasMany, hasOne, belongsTo and belongsToMany, eager loading, relation queries and counts."
4
+ ---
5
+
6
+ # Relations
7
+
8
+ Relations connect models. Declare them with decorators, then load them with `with()`, filter by them with `whereHas()` and count them with `withCount()`.
9
+
10
+ ```ts
11
+ @Table()
12
+ class User extends Model {
13
+ @PrimaryKey()
14
+ @AutoIncrement()
15
+ id?: number;
16
+
17
+ @HasMany(() => Post)
18
+ posts?: Post[]; // posts.user_id → users.id
19
+
20
+ @HasOne(() => Profile)
21
+ profile?: Profile | null; // profiles.user_id → users.id
22
+ }
23
+
24
+ @Table()
25
+ class Post extends Model {
26
+ @PrimaryKey()
27
+ @AutoIncrement()
28
+ id?: number;
29
+
30
+ @Column()
31
+ user_id!: number;
32
+
33
+ @BelongsTo(() => User, { foreignKey: 'user_id' })
34
+ author?: User | null;
35
+ }
36
+ ```
37
+
38
+ Type a relation field with the model it loads: `Post[]` for `@HasMany`,
39
+ `Profile | null` for `@HasOne` and `@BelongsTo`. The field is `undefined`
40
+ until the relation is loaded, so declare it with `?`. A field typed with a
41
+ model, or an array of models, is a relation rather than a column:
42
+ `create()` and `where()` leave it out, and `with('posts')` type-checks and
43
+ returns `Post[]`. The related class is passed as a function, so models can
44
+ refer to each other in any order, even from files that import each other.
45
+
46
+ ::: warning Circular imports in ES module builds
47
+ Keep the `| null` on `@HasOne` and `@BelongsTo` fields, or use the
48
+ `HasOne<Profile>` / `BelongsTo<User>` types. A field typed with the bare model
49
+ (`author?: User`) makes TypeScript's decorator metadata read `User` while its
50
+ file is still loading. When two models import each other, an app compiled to
51
+ ES modules then fails on startup with
52
+ `ReferenceError: Cannot access 'User' before initialization`. CommonJS builds
53
+ are not affected, and `Post[]` fields are always fine.
54
+ :::
55
+
56
+ Each decorator also has a field type of the same name (`posts?: HasMany<Post>`,
57
+ `author?: BelongsTo<User>`), which works the same way. Many-to-many keeps
58
+ its `BelongsToMany<Role, Pivot>` type, because a plain `Role[]` can't carry the
59
+ pivot columns or `attach()` / `detach()` ([below](#many-to-many)).
60
+
61
+ Key defaults:
62
+
63
+ | Relation | Foreign key default | Options |
64
+ |---|---|---|
65
+ | `@HasMany(() => Post)` | `<owner class>_id` on the related table, e.g. `user_id` | `foreignKey`, `localKey` |
66
+ | `@HasOne(() => Profile)` | same as `HasMany` | `foreignKey`, `localKey` |
67
+ | `@BelongsTo(() => User)` | `<field name>_id` on this table, e.g. `author_id` | `foreignKey`, `ownerKey` |
68
+
69
+ ## Eager loading
70
+
71
+ Load relations with `with()`. Use dots for nested relations:
72
+
73
+ ```ts
74
+ const users = await User.with('posts.comments', 'profile').get();
75
+
76
+ users[0].posts; // Post[]
77
+ users[0].profile; // Profile | null
78
+ users[0].posts[0].author; // compile error: not loaded
79
+ ```
80
+
81
+ Each relation level is one query, however many rows there are:
82
+
83
+ ```sql
84
+ select * from users
85
+ select * from posts where user_id in (?, ?)
86
+ select * from comments where post_id in (?, ?, ?)
87
+ select * from profiles where user_id in (?, ?)
88
+ ```
89
+
90
+ ## Querying by relation
91
+
92
+ `whereHas()` keeps rows that have a related row; `whereDoesntHave()` keeps
93
+ those that don't. Narrow the related rows with a callback, and follow nested
94
+ relations with dots:
95
+
96
+ ```ts
97
+ await User.whereHas('posts').get();
98
+ await User.whereHas('posts', (q) => q.where('published', true)).get();
99
+ await User.whereHas('posts.comments', (q) => q.where('body', 'like', '%megh%')).get();
100
+ await User.whereDoesntHave('roles').delete();
101
+ ```
102
+
103
+ Each one runs as an `EXISTS` subquery, so it works with `count()`,
104
+ `paginate()`, `update()` and `delete()` too. Soft-deleted related rows don't
105
+ count.
106
+
107
+ ## Counting related rows
108
+
109
+ `withCount()` adds a `<relation>_count` number to each result, without loading
110
+ the rows:
111
+
112
+ ```ts
113
+ const users = await User.withCount('posts', 'roles').get();
114
+ users[0].posts_count; // number
115
+
116
+ await User.query().withCount('posts', (q) => q.where('published', true)).get();
117
+ ```
118
+
119
+ Counts appear in JSON but are never written back by `save()`.
120
+
121
+ ## Creating related rows
122
+
123
+ `related()` on a `hasMany` or `hasOne` relation creates rows with the foreign
124
+ key already set (on a `belongsTo` it throws, since this row holds the key):
125
+
126
+ ```ts
127
+ const post = await user.related('posts').create({ title: 'Hello' }); // user_id set
128
+ await user.related('posts').createMany([{ title: 'A' }, { title: 'B' }]);
129
+ await user.related('posts').save(existingPost); // moves it to this user
130
+ await user.related('posts').query().where('published', true).get();
131
+ const profile = await user.related('profile').get(); // Profile | null
132
+ ```
133
+
134
+ ## Many-to-many
135
+
136
+ ```ts
137
+ @Table()
138
+ class User extends Model {
139
+ @PrimaryKey()
140
+ @AutoIncrement()
141
+ id?: number;
142
+
143
+ @BelongsToMany(() => Role, { pivotColumns: ['granted_by'] })
144
+ roles?: BelongsToMany<Role, { granted_by: string | null }>;
145
+ }
146
+ ```
147
+
148
+ Type many-to-many fields with `BelongsToMany<Role, Pivot>`, not `Role[]`: the
149
+ second argument types each loaded role's `pivot`, and the type tells
150
+ `related('roles')` to offer `attach()`, `detach()` and `sync()`.
151
+
152
+ The pivot table defaults to both snake_case class names, sorted and joined:
153
+ `role_user`, with the columns `user_id` and `role_id`. Override any of these
154
+ with options:
155
+
156
+ ```ts
157
+ @BelongsToMany(() => Role, {
158
+ table: 'user_roles',
159
+ foreignPivotKey: 'member_id',
160
+ relatedPivotKey: 'role_id',
161
+ })
162
+ roles!: BelongsToMany<Role>;
163
+ ```
164
+
165
+ Loaded models carry their pivot row in `pivot`, which also appears in JSON:
166
+
167
+ ```ts
168
+ const user = await User.with('roles').firstOrFail();
169
+ user.roles[0].pivot.granted_by; // string | null
170
+ ```
171
+
172
+ Change the links through `related()`:
173
+
174
+ ```ts
175
+ await user.related('roles').attach([adminRole, 3], { granted_by: 'root' }); // models or keys
176
+ await user.related('roles').detach(adminRole); // or detach() for all
177
+ await user.related('roles').sync([1, 2]); // → { attached, detached }, in one transaction
178
+ const roles = await user.related('roles').get();
179
+ ```
@@ -0,0 +1,129 @@
1
+ ---
2
+ title: Seeding and Factories
3
+ description: Filling the database with seeders, and building fake rows with model factories and Faker.
4
+ ---
5
+
6
+ # Seeding and Factories
7
+
8
+ Seeders put rows in the database; factories make rows with fake values. A seeder often uses factories, and tests use factories on their own.
9
+
10
+ ## Seeding
11
+
12
+ Seeders fill the database with rows for development, tests and demos. Each
13
+ file in `src/database/seeders/` exports `defineSeeder({ run })`, and is named
14
+ after its file without `.seeder.ts`:
15
+
16
+ ```ts [src/database/seeders/users.seeder.ts]
17
+ import { DB, defineSeeder } from '@meghjs/core';
18
+ import { Role } from '../../models/role.model';
19
+ import { User } from '../../models/user.model';
20
+
21
+ export default defineSeeder({
22
+ async run() {
23
+ const admin = await Role.findByOrFail('name', 'Admin');
24
+ await User.create({ name: 'Ann', email: 'ann@example.com', role_id: admin.id! });
25
+ await DB.table('settings').insert([{ key: 'theme', value: 'dark' }]);
26
+ },
27
+ });
28
+ ```
29
+
30
+ The `database` seeder is the entry point. `call()` runs other seeders by
31
+ name, in order:
32
+
33
+ ```ts [src/database/seeders/database.seeder.ts]
34
+ export default defineSeeder({
35
+ async run({ call }) {
36
+ await call('roles', 'users');
37
+ },
38
+ });
39
+ ```
40
+
41
+ Run them with `npx megh db:seed` (see [CLI: Seeders](/cli/database#seeders)).
42
+ Without a `database` seeder, every seeder runs in file-name order. A run is
43
+ one transaction, which models, `DB.table()` and the `db` passed to `run()`
44
+ all use, so a failing seeder saves nothing. A seeder that calls itself,
45
+ directly or through others, is reported as a loop.
46
+
47
+ ### Seeding from code
48
+
49
+ `Seeders` runs them from code, for example in test setup:
50
+
51
+ ```ts
52
+ import { Model, Seeders } from '@meghjs/core';
53
+
54
+ const seeders = new Seeders(Model.db(), { folder: `${__dirname}/database/seeders` });
55
+ await seeders.run(); // the database seeder, else all; returns the names that ran
56
+ await seeders.run('roles'); // one seeder
57
+ ```
58
+
59
+ Pass `seeders: { roles: defineSeeder({ run }) }` instead of `folder` to define
60
+ them inline, and `transaction: false` to commit each statement as it runs. A
61
+ failure throws a `SeedError` whose `seeder` names the seeder that failed.
62
+
63
+ ## Factories
64
+
65
+ A factory builds rows of a model with fake values from
66
+ [Faker](https://fakerjs.dev), for seeders and tests. Install Faker in the app
67
+ (`npm install -D @faker-js/faker`), then define the factory, or generate one
68
+ with [`megh make:factory user`](/cli/database#factories):
69
+
70
+ ```ts [src/database/factories/user.factory.ts]
71
+ import { defineFactory } from '@meghjs/core';
72
+ import { User } from '../../models/user.model';
73
+ import { RoleFactory } from './role.factory';
74
+
75
+ export const UserFactory = defineFactory(User, ({ faker, sequence }) => ({
76
+ name: faker.person.fullName(),
77
+ email: `user${sequence}@${faker.internet.domainName()}`,
78
+ is_active: true,
79
+ role_id: RoleFactory,
80
+ }));
81
+ ```
82
+
83
+ The definition gets `faker` and `sequence` (1 for the first row this factory
84
+ builds, then 2, 3, …). Its values are typed from the model, like `create()`'s.
85
+
86
+ ```ts
87
+ await UserFactory.create(); // one saved row
88
+ await UserFactory.createMany(10); // ten, each with its own values
89
+ await UserFactory.create({ name: 'Ann' }); // override some values
90
+ const user = await UserFactory.make(); // an unsaved instance; user.save() inserts it
91
+ const body = await UserFactory.raw(); // just the values, e.g. for a POST in a test
92
+ ```
93
+
94
+ `state()` returns a new factory with more values applied. Keep the ones you
95
+ reuse as constants:
96
+
97
+ ```ts
98
+ export const InactiveUser = UserFactory.state({ is_active: false });
99
+ export const Admin = UserFactory.state(({ sequence }) => ({ name: `Admin ${sequence}` }));
100
+
101
+ await InactiveUser.createMany(3);
102
+ ```
103
+
104
+ A value that is another factory creates a related row and uses its primary
105
+ key: `role_id: RoleFactory` gives each user its own role. To share one, pass
106
+ the key: `UserFactory.createMany(5, { role_id: admin.id })`.
107
+
108
+ Inside a seeder, factories run in its transaction like every other query, so
109
+ a failing seed saves nothing:
110
+
111
+ ```ts [src/database/seeders/users.seeder.ts]
112
+ export default defineSeeder({
113
+ async run() {
114
+ const admin = await RoleFactory.create({ name: 'Admin' });
115
+ await UserFactory.createMany(20, { role_id: admin.id });
116
+ },
117
+ });
118
+ ```
119
+
120
+ `useFaker()` changes the Faker instance factories use, for a locale or for
121
+ repeatable values:
122
+
123
+ ```ts
124
+ import { fakerDE } from '@faker-js/faker';
125
+ import { useFaker } from '@meghjs/core';
126
+
127
+ useFaker(fakerDE);
128
+ fakerDE.seed(42); // the same values on every run
129
+ ```
@@ -0,0 +1,145 @@
1
+ ---
2
+ title: MeghORM
3
+ description: Megh's built-in, type-safe ORM on Kysely. Installing a driver, connecting, and where to find models, queries, relations, migrations and seeding.
4
+ ---
5
+
6
+ # MeghORM
7
+
8
+ `@meghjs/core` includes its own ORM. You describe tables with decorators, and
9
+ column names, value types and loaded relations are checked by TypeScript. Use
10
+ it through models, or as a query builder when you need SQL-level control.
11
+
12
+ ```ts
13
+ const users = await User.where('email', 'like', '%@acme.io')
14
+ .with('posts.comments')
15
+ .orderBy('name')
16
+ .get();
17
+
18
+ users[0].posts[0].comments[0].body; // typed
19
+ User.where('emial', 'x'); // compile error: '"emial"' is not assignable to '"id" | "email" | "name"'
20
+ ```
21
+
22
+ These pages cover everything the ORM does, so you don't need another library's docs.
23
+
24
+ ## Installation
25
+
26
+ The ORM ships with `@meghjs/core`. Install only the driver for your database:
27
+
28
+ ::: code-group
29
+ ```sh [PostgreSQL]
30
+ npm i pg
31
+ ```
32
+ ```sh [MySQL]
33
+ npm i mysql2
34
+ ```
35
+ ```sh [SQLite]
36
+ npm i better-sqlite3
37
+ ```
38
+ ```sh [SQL Server]
39
+ npm i tedious tarn
40
+ ```
41
+ :::
42
+
43
+ ## Connecting
44
+
45
+ Call `useMeghORM()` with the connection settings. Megh creates the connection
46
+ and its pool, checks it when the app starts, and closes it on shutdown:
47
+
48
+ ```ts [app.ts]
49
+ import { Megh } from '@meghjs/core';
50
+
51
+ const app = Megh.createApplication();
52
+ app.useMeghORM({ dialect: 'postgres', url: process.env.DATABASE_URL });
53
+ ```
54
+
55
+ With no arguments, the settings come from the environment (and `.env`), which
56
+ is also where the [migration commands](/advanced/orm/migrations) read them:
57
+
58
+ ```sh [.env]
59
+ DATABASE_URL=postgres://app:secret@localhost:5432/app
60
+ ```
61
+
62
+ ```ts
63
+ app.useMeghORM(); // reads DATABASE_URL
64
+ ```
65
+
66
+ The URL scheme picks the database, so `dialect` is optional with a URL:
67
+
68
+ | Database | URL |
69
+ |---|---|
70
+ | PostgreSQL | `postgres://user:pass@host:5432/db` |
71
+ | MySQL / MariaDB | `mysql://user:pass@host:3306/db` |
72
+ | SQL Server | `mssql://user:pass@host:1433/db` (or `sqlserver://`). Add `?encrypt=false` or `?trustServerCertificate=true` for local servers |
73
+ | SQLite | `sqlite:./database.sqlite`, or `sqlite::memory:` |
74
+
75
+ Instead of a URL, give the parts:
76
+
77
+ ```ts
78
+ app.useMeghORM({
79
+ dialect: 'mysql',
80
+ host: 'localhost',
81
+ port: 3306,
82
+ user: 'app',
83
+ password: process.env.DB_PASSWORD,
84
+ database: 'app',
85
+ pool: { max: 20 },
86
+ });
87
+ ```
88
+
89
+ | Option | Environment variable | |
90
+ |---|---|---|
91
+ | `dialect` | `DB_DIALECT` | `postgres`, `mysql`, `sqlite` or `mssql` |
92
+ | `url` | `DATABASE_URL` | Connection URL |
93
+ | `host`, `port` | `DB_HOST`, `DB_PORT` | |
94
+ | `user`, `password` | `DB_USER`, `DB_PASSWORD` | |
95
+ | `database` | `DB_NAME` | Database name; for SQLite, the file path |
96
+ | `pool.min`, `pool.max` | `DB_POOL_MIN`, `DB_POOL_MAX` | Pool size. `max` defaults to 10 |
97
+ | `ssl` | | `true` or driver TLS options (Postgres, MySQL). SQL Server encrypts unless `false` |
98
+ | `trustServerCertificate` | | SQL Server: accept a self-signed certificate |
99
+ | `naming` | | `"preserve"` (default) or `"snake_case"`. See [Column names](/advanced/orm/models#column-names) |
100
+
101
+ Settings passed to `useMeghORM()` override the environment. To build them
102
+ in an `@AppConfig` class ([example](/advanced/database#using-a-config-class)), pass the class:
103
+
104
+ ```ts
105
+ @AppConfig
106
+ class DatabaseConfig extends MeghConfig<DatabaseOptions> {
107
+ config(env: Environment): DatabaseOptions {
108
+ return { url: env.get('DATABASE_URL'), pool: { max: Number(env.get('POOL')) || 10 } };
109
+ }
110
+ }
111
+
112
+ app.useMeghORM(DatabaseConfig);
113
+ ```
114
+
115
+ If the database can't be reached, `app.run()` fails with the reason and where
116
+ it tried to connect (without the password). A missing driver is reported with
117
+ the `npm install` command to run.
118
+
119
+ Outside an app, in scripts and tests, connect with
120
+ `Model.useConnection(createDatabase(resolveDatabaseOptions({ url })))`.
121
+
122
+ ::: details Upgrading from `useDatabase(kysely)`
123
+ `app.useDatabase(db)` still works, with a deprecation warning, for apps that
124
+ create their own Kysely instance. Replace it with `useMeghORM()` and delete
125
+ `src/database/connection.ts`: the migration commands now connect from
126
+ `DATABASE_URL` too.
127
+ :::
128
+
129
+ ## Guides
130
+
131
+ | Page | What it covers |
132
+ |---|---|
133
+ | [Models](/advanced/orm/models) | Decorators, keys, column names, timestamps, soft deletes, casts |
134
+ | [Queries](/advanced/orm/queries) | Where clauses, aggregates, scopes, pagination, writes, transactions |
135
+ | [Relations](/advanced/orm/relations) | hasMany, hasOne, belongsTo, belongsToMany, eager loading |
136
+ | [Query Builder](/advanced/orm/query-builder) | `DB.table()` queries and raw SQL |
137
+ | [Migrations](/advanced/orm/migrations) | The schema builder and the migration runner |
138
+ | [Seeding and Factories](/advanced/orm/seeding) | Seeders, model factories and Faker |
139
+
140
+ To use TypeORM or Knex instead, see [TypeORM and Knex](/advanced/database).
141
+
142
+ ## Testing
143
+
144
+ The ORM is tested against SQLite. The MySQL path for reading back inserted
145
+ rows, which has no `RETURNING`, is implemented but not yet covered by tests.
@@ -0,0 +1,90 @@
1
+ ---
2
+ title: Plugins
3
+ description: Add features to a Megh app from a separate package.
4
+ ---
5
+
6
+ # Plugins
7
+
8
+ A plugin is a package that adds features to a Megh app: new `app.use*`
9
+ methods, services in the container, lifecycle hooks and Fastify hooks.
10
+ Installing a plugin is enough; Megh finds it among the app's dependencies
11
+ when the app is created.
12
+
13
+ ## Writing a plugin
14
+
15
+ Export a plugin from the package and point to it from `package.json`:
16
+
17
+ ```ts [src/plugin.ts]
18
+ import { definePlugin, Token } from '@meghjs/core';
19
+ import { createClient, type Client } from 'some-db';
20
+
21
+ export const DB = new Token<Client>('DB');
22
+
23
+ export default definePlugin({
24
+ name: '@acme/db',
25
+ register(ctx) {
26
+ ctx.extend('useDb', function (url: string) {
27
+ const client = createClient(url);
28
+ ctx.container.set(DB, client);
29
+ ctx.onInit(() => client.connect());
30
+ ctx.onClose(() => client.disconnect());
31
+ return ctx.app;
32
+ });
33
+ },
34
+ });
35
+
36
+ declare module '@meghjs/core' {
37
+ interface MeghApplication {
38
+ /** Connect to the database when the app starts. */
39
+ useDb(url: string): MeghApplication;
40
+ }
41
+ }
42
+ ```
43
+
44
+ ```json [package.json]
45
+ {
46
+ "name": "@acme/db",
47
+ "main": "dist/index.js",
48
+ "megh": { "plugin": "./dist/plugin.js" },
49
+ "peerDependencies": { "@meghjs/core": "^0.6.0" }
50
+ }
51
+ ```
52
+
53
+ List `@meghjs/core` as a **peer dependency**, not a dependency, so the plugin
54
+ shares the app's container instead of getting its own copy.
55
+
56
+ `register(ctx)` runs once, when the app is created, and must be synchronous so
57
+ the methods it adds exist as soon as `createApplication()` returns. Do async
58
+ work in `ctx.onInit`. The context gives you:
59
+
60
+ | Member | Use |
61
+ |--------|-----|
62
+ | `ctx.extend(name, fn)` | Add `app[name]`. Throws if core or another plugin already defines it. |
63
+ | `ctx.container` | The app's container (`get`, `set`, `has`) |
64
+ | `ctx.onInit` / `ctx.onReady` / `ctx.onClose` | [Lifecycle hooks](/getting-started/application#lifecycle-hooks) |
65
+ | `ctx.http` | The Fastify instance, for Fastify hooks and plugins |
66
+ | `ctx.logger` | A logger tagged with the plugin's name |
67
+ | `ctx.app` | The application |
68
+
69
+ If a plugin needs another one to register first, name it in `dependsOn`:
70
+
71
+ ```ts
72
+ definePlugin({ name: '@acme/audit', dependsOn: ['@acme/db'], register(ctx) { /* ... */ } });
73
+ ```
74
+
75
+ ## Registering plugins explicitly
76
+
77
+ Discovery reads the app's `package.json`, which a bundled app doesn't have at
78
+ runtime. Pass plugins yourself in that case, or in tests:
79
+
80
+ ```ts
81
+ import db from '@acme/db/plugin';
82
+
83
+ const app = Megh.createApplication({
84
+ plugins: [db],
85
+ autoloadPlugins: false, // optional: skip discovery
86
+ });
87
+ ```
88
+
89
+ An explicit plugin replaces a discovered one with the same name.
90
+ `app.getPlugins()` lists the registered plugins in registration order.