@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,169 @@
1
+ ---
2
+ title: Events
3
+ description: Dispatching and handling events in a Megh application.
4
+ ---
5
+
6
+ # Events
7
+
8
+ Events let one part of your application announce that something happened
9
+ without knowing who reacts to it. Megh's event system is typed, supports
10
+ synchronous, delayed and queued delivery, and can broadcast over Socket.IO.
11
+
12
+ ::: tip Generate them
13
+ `npx megh make:event UserCreated` and
14
+ `npx megh make:listener SendWelcomeEmail --event UserCreated` write both
15
+ files. See [Generators](/cli/generators#events).
16
+ :::
17
+
18
+ ## Defining an event
19
+
20
+ An event extends `MeghEvent<TPayload>`. The payload type is yours; the base
21
+ class fills in `name` and `timestamp`.
22
+
23
+ ```ts [events/user-created.event.ts]
24
+ import { MeghEvent } from '@meghjs/core';
25
+
26
+ export type UserCreatedPayload = {
27
+ userId: number;
28
+ name: string;
29
+ };
30
+
31
+ export class UserCreatedEvent extends MeghEvent<UserCreatedPayload> {}
32
+ ```
33
+
34
+ ## Defining a listener
35
+
36
+ A listener extends `MeghEventListener<TEvent>` and implements `handler`. It
37
+ may be synchronous or return a promise.
38
+
39
+ ```ts [listeners/user-created.listener.ts]
40
+ import { MeghEventListener } from '@meghjs/core';
41
+ import { UserCreatedEvent } from '../events/user-created.event';
42
+
43
+ export class UserCreatedListener extends MeghEventListener<UserCreatedEvent> {
44
+ async handler(event: UserCreatedEvent): Promise<void> {
45
+ console.log(`User created → id=${event.payload.userId}, name=${event.payload.name}`);
46
+ }
47
+ }
48
+ ```
49
+
50
+ ## Registering listeners
51
+
52
+ `EventRegistry` is a singleton. Register listeners once during app setup.
53
+
54
+ ```ts [app.ts]
55
+ import { EventRegistry } from '@meghjs/core';
56
+ import { UserCreatedEvent } from './events/user-created.event';
57
+ import { UserCreatedListener } from './listeners/user-created.listener';
58
+
59
+ const registry = EventRegistry.getInstance();
60
+
61
+ registry.register(UserCreatedEvent, new UserCreatedListener());
62
+ ```
63
+
64
+ An event may have several listeners — they run in registration order.
65
+
66
+ Use `once` for a listener that should fire a single time and then be discarded:
67
+
68
+ ```ts
69
+ registry.once(UserCreatedEvent, {
70
+ handler(event: UserCreatedEvent) {
71
+ console.log(`Sending welcome email to ${event.payload.name}`);
72
+ },
73
+ });
74
+ ```
75
+
76
+ ## Dispatching
77
+
78
+ ```ts [services/user.service.ts]
79
+ import { AppService, EventDispatcher } from '@meghjs/core';
80
+ import { UserCreatedEvent } from '../events/user-created.event';
81
+
82
+ @AppService
83
+ export class UserService {
84
+ private readonly dispatcher = new EventDispatcher();
85
+
86
+ async create(name: string) {
87
+ const userId = 1; // ...persist the user
88
+
89
+ await this.dispatcher.dispatch(new UserCreatedEvent({ userId, name }));
90
+
91
+ return { userId, name };
92
+ }
93
+ }
94
+ ```
95
+
96
+ By default listeners run synchronously, in the current tick, before `dispatch`
97
+ resolves.
98
+
99
+ ### Queued delivery
100
+
101
+ Pass `queue: true` to hand the event to the in-memory queue instead. Listener
102
+ failures are then retried:
103
+
104
+ ```ts
105
+ await dispatcher.dispatch(new UserCreatedEvent({ userId: 1, name: 'Tareq' }), {
106
+ queue: true,
107
+ retry: 3,
108
+ retryDelay: 500, // milliseconds between attempts
109
+ });
110
+ ```
111
+
112
+ `retry` and `retryDelay` are only accepted together with `queue: true`.
113
+
114
+ Jobs that still fail after their last retry are kept, up to 1000 of them, and
115
+ logged:
116
+
117
+ ```ts
118
+ import { EventQueue } from '@meghjs/core';
119
+
120
+ const queue = EventQueue.getInstance();
121
+ const failed = queue.getFailedJobs(); // FailedEventJob[]
122
+ queue.clearFailed();
123
+ await queue.whenIdle(); // useful in tests
124
+ ```
125
+
126
+ ### Delayed delivery
127
+
128
+ `delay` takes milliseconds or a duration string: `'500ms'`, `'5s'`, `'2m'`,
129
+ `'1h'`, `'1d'`. It also works together with `queue: true`.
130
+
131
+ ```ts
132
+ await dispatcher.dispatch(new UserCreatedEvent({ userId: 1, name: 'Tareq' }), {
133
+ delay: '5s', // fire listeners 5 seconds from now
134
+ });
135
+ ```
136
+
137
+ ### Broadcasting
138
+
139
+ Add a `broadcast` option to forward the event to Socket.IO as well as to the
140
+ local listeners. Clients receive `{ name, payload }` on the channel:
141
+
142
+ ```ts
143
+ await dispatcher.dispatch(event, {
144
+ broadcast: { type: 'socket', channel: 'user:create', room: 'admins' },
145
+ });
146
+ ```
147
+
148
+ Socket broadcast needs `app.useSocketIo()`. Without it, `dispatch` rejects and
149
+ the local listeners do not run.
150
+
151
+ ::: warning
152
+ Kafka and RabbitMQ broadcast are not implemented in 0.3.
153
+ `type: 'kafka'` and `type: 'rabbitmq'` throw.
154
+ :::
155
+
156
+ ::: info
157
+ A listener that throws is logged and does not stop the other listeners for that
158
+ event. With `queue: true`, the failure is retried according to `retry`.
159
+ :::
160
+
161
+ ### Listener registry
162
+
163
+ - Listeners are keyed by the event **class**, so two event classes with the same
164
+ name do not collide.
165
+ - `once` listeners fire exactly once, even when the event is dispatched
166
+ concurrently.
167
+ - `registry.getListeners(UserCreatedEvent)` takes the class or an event
168
+ instance. `registry.clear(UserCreatedEvent)` removes its listeners, and
169
+ `registry.clear()` removes all of them.
@@ -0,0 +1,141 @@
1
+ ---
2
+ title: File Uploads
3
+ description: Receiving and storing uploaded files safely.
4
+ ---
5
+
6
+ # File Uploads
7
+
8
+ Multipart support is an optional peer dependency:
9
+
10
+ ```sh
11
+ npm i @fastify/multipart
12
+ ```
13
+
14
+ Enable it on the app:
15
+
16
+ ```ts [app.ts]
17
+ app.useMultipart({
18
+ limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB per file
19
+ });
20
+ ```
21
+
22
+ The options go to `@fastify/multipart`. Megh sets `attachFieldsToBody: true`
23
+ (which `@UploadFile` needs) and a **10 MB** per-file limit unless you pass your
24
+ own `limits`. The smaller of this limit and `FileStorage`'s `maxFileSize`
25
+ (50 MB, below) wins, so raise both to accept bigger files.
26
+
27
+ ## Receiving a file
28
+
29
+ `@UploadFile('field')` injects one file and `@UploadFiles()` injects all of
30
+ them. Save them with the injected `FileStorage`:
31
+
32
+ ```ts [controllers/files.controller.ts]
33
+ import { ApiController, Post, UploadFile, MultipartFile, FileStorage } from '@meghjs/core';
34
+
35
+ @ApiController('/files')
36
+ export class FilesController {
37
+ constructor(private readonly storage: FileStorage) {}
38
+
39
+ @Post('/avatar')
40
+ async upload(@UploadFile('file') file: MultipartFile) {
41
+ return this.storage.save(file, { to: 'avatars' });
42
+ }
43
+ }
44
+ ```
45
+
46
+ `save` returns:
47
+
48
+ ```json
49
+ {
50
+ "filename": "3f9c0d0e-....png",
51
+ "originalFilename": "me.png",
52
+ "size": 48213,
53
+ "uploadPath": "/uploads/avatars/3f9c0d0e-....png",
54
+ "staticPath": "/static/avatars/3f9c0d0e-....png"
55
+ }
56
+ ```
57
+
58
+ Both paths are relative to `baseDir`, with the prefixes `/uploads/` and
59
+ `/static/`.
60
+
61
+ ## Safe defaults
62
+
63
+ `FileStorage` assumes uploads are untrusted:
64
+
65
+ | Default | Override |
66
+ |---------|----------|
67
+ | Saved under `<cwd>/public` | `configure({ baseDir })` |
68
+ | Random UUID filename that keeps the extension | `saveAs: 'name.png'` or `preserveFilename: true` |
69
+ | Never overwrites an existing file | `overwrite: true` |
70
+ | Only common safe extensions (images, PDF, office, text/CSV, zip, audio/video). HTML, SVG and JS are rejected | `allowedExtensions` |
71
+ | No MIME check | `allowedMimeTypes: ['image/*']` |
72
+ | 50 MB limit, enforced while streaming | `maxFileSize` |
73
+
74
+ Every path, including `to`, is confined to `baseDir`. Paths that try to escape
75
+ it, through `..` or a symlink, are rejected, both when saving and when reading.
76
+
77
+ ::: info
78
+ In 0.3.0, a file that breaks these rules gives a 500 response, not 400
79
+ or 413.
80
+ :::
81
+
82
+ ## Configuring
83
+
84
+ Set the defaults once, for example in a service constructor or at startup:
85
+
86
+ ```ts
87
+ storage.configure({
88
+ baseDir: 'public/uploads',
89
+ allowedMimeTypes: ['image/*'],
90
+ maxFileSize: 5_000_000,
91
+ });
92
+ ```
93
+
94
+ Override per call:
95
+
96
+ ```ts
97
+ await storage.save(file, {
98
+ to: 'documents',
99
+ saveAs: 'contract.pdf',
100
+ overwrite: true,
101
+ allowedExtensions: ['.pdf'],
102
+ });
103
+
104
+ await storage.saveAll(files, { to: 'gallery' });
105
+ ```
106
+
107
+ ## Image transforms
108
+
109
+ With `sharp` installed, resize or convert images as they are saved. The
110
+ extension follows the output format:
111
+
112
+ ```ts
113
+ await storage.save(file, {
114
+ to: 'avatars',
115
+ transform: { resize: { width: 256, height: 256 }, format: 'webp' },
116
+ });
117
+ ```
118
+
119
+ `storage.transform({...})` returns a scoped copy of the storage with that
120
+ transform applied, so concurrent requests never share transform settings.
121
+
122
+ ## Serving and removing files
123
+
124
+ `download`, `downloadAs`, `getUploadFile` and `remove` take paths **relative
125
+ to `baseDir`**. Anything outside it is rejected, and a missing file gives 404.
126
+
127
+ ```ts
128
+ @Get('/:name')
129
+ download(@Param('name') name: string) {
130
+ return this.storage.downloadAs(`documents/${name}`, name);
131
+ }
132
+ ```
133
+
134
+ Download responses get a safely encoded `Content-Disposition` header.
135
+
136
+ To serve the upload directory as static files, see `useStaticFiles`
137
+ (requires `@fastify/static`):
138
+
139
+ ```ts
140
+ app.useStaticFiles({ root: path.join(process.cwd(), 'public'), prefix: '/static/' });
141
+ ```
@@ -0,0 +1,81 @@
1
+ ---
2
+ title: Health Checks
3
+ description: Liveness and readiness endpoints for load balancers and orchestrators.
4
+ ---
5
+
6
+ # Health Checks
7
+
8
+ `app.useHealth()` adds two routes for load balancers, Kubernetes probes and
9
+ uptime monitors:
10
+
11
+ | Route | Answers | Use it for |
12
+ |-------|---------|------------|
13
+ | `GET /health` | `200 { "status": "ok" }` while the process serves requests | Liveness: restart the process when it stops answering |
14
+ | `GET /ready` | `200` when every check passes, `503` when one fails | Readiness: stop sending traffic until dependencies are back |
15
+
16
+ ```ts
17
+ app
18
+ .useMeghORM({ dialect: 'postgres', url: process.env.DATABASE_URL })
19
+ .useHealth({
20
+ checks: {
21
+ redis: () => redis.ping(),
22
+ },
23
+ });
24
+ ```
25
+
26
+ ```json
27
+ // GET /ready
28
+ {
29
+ "status": "ok",
30
+ "checks": {
31
+ "database": { "status": "up", "durationMs": 2 },
32
+ "redis": { "status": "up", "durationMs": 1 }
33
+ }
34
+ }
35
+ ```
36
+
37
+ Megh ORM registers the `database` check itself (`select 1`), so you only add
38
+ checks for the services you connect to yourself.
39
+
40
+ ## Checks
41
+
42
+ A check is a function. It passes unless it throws, rejects or returns
43
+ `false`. Checks run concurrently, and one that takes longer than `timeout`
44
+ counts as down.
45
+
46
+ ```ts
47
+ app.addHealthCheck('payments-api', async () => {
48
+ const res = await fetch('https://payments.internal/ping');
49
+ return res.ok;
50
+ });
51
+ ```
52
+
53
+ Plugins add checks with `ctx.addHealthCheck(name, check)`, the same way Megh
54
+ ORM does.
55
+
56
+ When a check fails, `/ready` answers 503 with the check marked `down`. The
57
+ failure reason is included as `error` only when `NODE_ENV=development`,
58
+ since it can describe internal hosts or credentials.
59
+
60
+ ## Options
61
+
62
+ | Option | Default | |
63
+ |--------|---------|---|
64
+ | `path` | `/health` | Liveness route |
65
+ | `readyPath` | `/ready` | Readiness route |
66
+ | `checks` | `{}` | Checks to add, by name |
67
+ | `timeout` | `5000` | Milliseconds before a check counts as failed |
68
+
69
+ Call `useHealth()` before `run()`. The routes are hidden from the OpenAPI
70
+ document and skip middleware (including global `useMiddlewares`) and
71
+ `@Authorized`, so probes still answer behind an API key check. Keep them
72
+ off the public internet if the check names are sensitive.
73
+
74
+ ## Kubernetes
75
+
76
+ ```yaml
77
+ livenessProbe:
78
+ httpGet: { path: /health, port: 4000 }
79
+ readinessProbe:
80
+ httpGet: { path: /ready, port: 4000 }
81
+ ```
@@ -0,0 +1,96 @@
1
+ ---
2
+ title: Logging
3
+ description: Structured logging with LoggerService.
4
+ ---
5
+
6
+ # Logging
7
+
8
+ `LoggerService` wraps [pino](https://getpino.io). Inject it anywhere:
9
+
10
+ ```ts [services/orders.service.ts]
11
+ import { AppService, LoggerService } from '@meghjs/core';
12
+
13
+ @AppService
14
+ export class OrdersService {
15
+ constructor(private readonly logger: LoggerService) {}
16
+
17
+ place(order: Order) {
18
+ this.logger.info('order placed', { orderId: order.id });
19
+ }
20
+
21
+ fail(error: Error) {
22
+ this.logger.error('order failed', error); // logged as { err }
23
+ }
24
+ }
25
+ ```
26
+
27
+ ## Output format
28
+
29
+ | `NODE_ENV` | Output |
30
+ |------------|--------|
31
+ | `development`, with `pino-pretty` installed | Pretty, colored lines |
32
+ | anything else, including unset | One JSON object per line |
33
+
34
+ Install `pino-pretty` as a dev dependency for readable local logs:
35
+
36
+ ```sh
37
+ npm i -D pino-pretty
38
+ ```
39
+
40
+ Megh's own logs (events, queues, workers, scheduler) go through the same
41
+ logger, so they share its format and level.
42
+
43
+ ## Configuring
44
+
45
+ All `LoggerService` instances share one pino root. Configure it once at
46
+ startup:
47
+
48
+ ```ts
49
+ import { LoggerService } from '@meghjs/core';
50
+
51
+ LoggerService.configure({ level: 'debug' }); // also: pretty, destination
52
+
53
+ const log = LoggerService.child({ module: 'billing' });
54
+ log.info('invoice sent');
55
+ ```
56
+
57
+ ## Request IDs
58
+
59
+ Every request gets an ID. Megh reuses the incoming `x-request-id` header
60
+ when it is short and log-safe (letters, digits, `_ . : -`, at most 128
61
+ characters), so an ID set by a proxy or the calling service carries
62
+ through; otherwise it generates a UUID. The ID is sent back in the
63
+ `x-request-id` response header.
64
+
65
+ Log lines written while a request is handled get a `reqId` field, from
66
+ `LoggerService` and from Megh's own logs alike:
67
+
68
+ ```json
69
+ {"level":30,"reqId":"7f9c…","msg":"charging card"}
70
+ ```
71
+
72
+ Read the ID anywhere in the request's call chain with `getRequestId()`,
73
+ for example to pass it to another service:
74
+
75
+ ```ts
76
+ import { getRequestId } from '@meghjs/core';
77
+
78
+ await fetch(url, { headers: { 'x-request-id': getRequestId() ?? '' } });
79
+ ```
80
+
81
+ Change the header or the generator, or turn request IDs off, when you
82
+ create the app:
83
+
84
+ ```ts
85
+ MeghApplication.getApp({
86
+ requestId: { header: 'x-correlation-id', generate: () => nanoid() },
87
+ });
88
+ MeghApplication.getApp({ requestId: false });
89
+ ```
90
+
91
+ `server.genReqId` in the Fastify options overrides Megh's generator.
92
+
93
+ ## Fastify request logs
94
+
95
+ Megh does not pass this logger to Fastify. To route Fastify's request logs
96
+ through the same pino instance, use `LoggerService.getPino()`.