@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,439 @@
1
+ ---
2
+ title: Mail
3
+ description: Send email with mailable classes, over SMTP or a provider's API, now or from a queue.
4
+ ---
5
+
6
+ # Mail
7
+
8
+ Megh sends email through **mailables**: one class per kind of email, holding
9
+ its subject, body and attachments. The injected `Mailer` sends them through a
10
+ **mailer**, which is SMTP or a provider's HTTP API. Mail can be sent straight
11
+ away or queued.
12
+
13
+ SMTP goes through [Nodemailer](https://nodemailer.com), an optional peer
14
+ dependency:
15
+
16
+ ```sh
17
+ npm i nodemailer
18
+ ```
19
+
20
+ The SendGrid, Mailgun, Postmark and Resend mailers call the provider's API with
21
+ Node's built-in `fetch`, so they need no extra package.
22
+
23
+ ## Turning mail on
24
+
25
+ ```ts [src/app.ts]
26
+ app.useMail();
27
+ ```
28
+
29
+ `useMail()` reads its settings from `MEGH_MAIL_*` variables in `.env`:
30
+
31
+ ```ini [.env]
32
+ MEGH_MAIL_MAILER=smtp
33
+ MEGH_MAIL_HOST=smtp.example.com
34
+ MEGH_MAIL_PORT=587
35
+ MEGH_MAIL_USERNAME=apikey
36
+ MEGH_MAIL_PASSWORD=secret
37
+ MEGH_MAIL_ENCRYPTION=tls
38
+ MEGH_MAIL_FROM_ADDRESS=hello@example.com
39
+ MEGH_MAIL_FROM_NAME="Example"
40
+ ```
41
+
42
+ Anything passed to `useMail()` overrides `.env`, either as an object or as an
43
+ `@AppConfig` class that returns one:
44
+
45
+ ```ts
46
+ app.useMail({ from: 'Shop <shop@example.com>' });
47
+ app.useMail(MailSettings); // @AppConfig class MailSettings extends MeghConfig<MailConfig>
48
+ ```
49
+
50
+ [Setting it up](#setting-it-up) lists the steps for a new project.
51
+
52
+ ### Which mailer is used
53
+
54
+ `MEGH_MAIL_MAILER` (or `default` in `useMail()`) names the mailer. When it is
55
+ not set:
56
+
57
+ | Situation | Mailer |
58
+ | --- | --- |
59
+ | `MEGH_MAIL_HOST` is set | `smtp` |
60
+ | `NODE_ENV=development` | `log`: messages are written to the log, not sent |
61
+ | `NODE_ENV=test` | `array`: messages are kept in memory |
62
+ | Otherwise (production) | none. `useMail()` throws at startup |
63
+
64
+ The last row is deliberate: a production app with no mailer fails when it
65
+ starts, instead of dropping mail without anyone noticing.
66
+
67
+ The default mailer is also checked at startup. A missing host, API key or
68
+ domain fails `useMail()` with the setting to fix, for example:
69
+
70
+ ```
71
+ [Megh Mail] The default mailer "sendgrid" needs an API key: set MEGH_MAIL_SENDGRID_API_KEY or apiKey.
72
+ ```
73
+
74
+ Other mailers are checked the first time they are used.
75
+
76
+ ## Writing a mailable
77
+
78
+ Generate one with the CLI:
79
+
80
+ ```sh
81
+ npx megh make:mail OrderShipped
82
+ ```
83
+
84
+ ```ts [src/mail/order-shipped.mail.ts]
85
+ import { Mailable } from '@meghjs/core';
86
+ import { Order } from '../models/order.model';
87
+
88
+ export class OrderShippedMail extends Mailable {
89
+ constructor(private readonly order: Order) {
90
+ super();
91
+ }
92
+
93
+ envelope() {
94
+ return {
95
+ subject: `Order #${this.order.id} has shipped`,
96
+ replyTo: 'support@example.com',
97
+ };
98
+ }
99
+
100
+ content() {
101
+ return {
102
+ html: `<p>Your order is on its way. Track it at ${this.order.trackingUrl}.</p>`,
103
+ text: `Your order is on its way. Track it at ${this.order.trackingUrl}.`,
104
+ };
105
+ }
106
+
107
+ attachments() {
108
+ return [{ filename: 'invoice.pdf', path: `storage/invoices/${this.order.id}.pdf` }];
109
+ }
110
+ }
111
+ ```
112
+
113
+ | Method | Returns | Notes |
114
+ | --- | --- | --- |
115
+ | `envelope()` | `{ subject?, from?, replyTo?, to?, cc?, bcc?, headers? }` | All optional. The subject defaults to the class name as words (`OrderShippedMail` → "Order Shipped Mail"). `from` overrides `MEGH_MAIL_FROM_*`. |
116
+ | `content()` | `{ html?, text? }` | Required. Give `html`, `text` or both. |
117
+ | `attachments()` | `MailAttachment[]` | Optional. Each is `{ filename?, content?, path?, contentType?, cid? }`. `path` is a file, a `data:` URI, or an `http(s)` URL when `allowUrlAccess` is on. See [Attachment paths](#attachment-paths). |
118
+
119
+ Each method may be `async`, to load data or render a template.
120
+
121
+ An address can be written as `'ann@example.com'`, `'Ann <ann@example.com>'` or
122
+ `{ name: 'Ann', address: 'ann@example.com' }`. Addresses, subjects and headers
123
+ that contain a line break are rejected, so user input cannot inject headers.
124
+
125
+ Each address must be a single `local@domain`. Megh rejects one that contains
126
+ a space, `,`, `;`, `<`, `>` or `"`, such as `'ann@example.com, evil@example.com'`,
127
+ so an address taken from user input (a password reset, an invite, a contact
128
+ form) can't add a second recipient. Pass several addresses as separate
129
+ arguments instead: `to('ann@example.com', 'lee@example.com')`. A display name
130
+ with a comma must be quoted (`'"Lee, Ann" <ann@example.com>'`) or given as an
131
+ object.
132
+
133
+ ### Inline images
134
+
135
+ Give the attachment a `cid` and use it in the HTML:
136
+
137
+ ```ts
138
+ content() {
139
+ return { html: `<img src="cid:logo"> Welcome!` };
140
+ }
141
+
142
+ attachments() {
143
+ return [{ filename: 'logo.png', path: 'public/logo.png', cid: 'logo' }];
144
+ }
145
+ ```
146
+
147
+ ### Attachment paths
148
+
149
+ An attachment's `path` is read when the message is sent. If any part of it
150
+ comes from user input (`{ path: dto.file }`), a client could make the app
151
+ read `/etc/passwd` or fetch `http://169.254.169.254/` (cloud metadata) and
152
+ mail the result out. Megh checks every path when the message is built, for
153
+ every mailer, SMTP included:
154
+
155
+ | Option on `useMail()` | Default | |
156
+ |---|---|---|
157
+ | `allowUrlAccess` | `false` | Allow `http(s)://` paths. Other schemes are always refused. |
158
+ | `allowFileAccess` | `true` | Allow local file paths. |
159
+ | `attachmentRoot` | | Only read files inside this folder. Relative paths resolve against it, and symlinks can't lead out. |
160
+
161
+ ```ts
162
+ app.useMail({
163
+ attachmentRoot: 'storage/invoices', // invoice.pdf → storage/invoices/invoice.pdf
164
+ allowUrlAccess: true, // only if every URL is yours
165
+ });
166
+ ```
167
+
168
+ A refused path throws `MailError` before anything is sent. `content` (a
169
+ string or `Buffer`) and `data:` URIs are always allowed, so the safest way to
170
+ attach something from user input is to read it yourself and pass `content`.
171
+
172
+ ## Sending
173
+
174
+ Inject `Mailer` like any service:
175
+
176
+ ```ts [src/services/order.service.ts]
177
+ import { AppService, Mailer } from '@meghjs/core';
178
+ import { OrderShippedMail } from '../mail/order-shipped.mail';
179
+
180
+ @AppService
181
+ export class OrderService {
182
+ constructor(private readonly mailer: Mailer) {}
183
+
184
+ async ship(order: Order) {
185
+ // ...
186
+ await this.mailer.to(order.customerEmail).send(new OrderShippedMail(order));
187
+ }
188
+ }
189
+ ```
190
+
191
+ `to()`, `cc()` and `bcc()` each take one or more addresses and can be chained:
192
+
193
+ ```ts
194
+ await this.mailer
195
+ .to(order.customerEmail)
196
+ .cc('sales@example.com')
197
+ .bcc(['audit@example.com', 'archive@example.com'])
198
+ .send(new OrderShippedMail(order));
199
+ ```
200
+
201
+ Recipients returned by `envelope()` are added to these. `send()` resolves to
202
+ `{ mailer, message, messageId?, response? }`: the mailer used, the built
203
+ message, and the provider's message ID and raw reply.
204
+
205
+ To use a mailer other than the default, name it:
206
+
207
+ ```ts
208
+ await this.mailer.mailer('postmark').to(user.email).send(new ReceiptMail(user));
209
+ ```
210
+
211
+ ## Mailers
212
+
213
+ | Mailer | Settings in `.env` | `useMail({ mailers })` options |
214
+ | --- | --- | --- |
215
+ | `smtp` | `MEGH_MAIL_HOST`, `MEGH_MAIL_PORT`, `MEGH_MAIL_USERNAME`, `MEGH_MAIL_PASSWORD`, `MEGH_MAIL_ENCRYPTION` | `host`, `port`, `username`, `password`, `encryption`, `options` |
216
+ | `sendgrid` | `MEGH_MAIL_SENDGRID_API_KEY` | `apiKey`, `endpoint`, `timeout` |
217
+ | `mailgun` | `MEGH_MAIL_MAILGUN_API_KEY`, `MEGH_MAIL_MAILGUN_DOMAIN`, `MEGH_MAIL_MAILGUN_ENDPOINT` | `apiKey`, `domain`, `endpoint`, `timeout` |
218
+ | `postmark` | `MEGH_MAIL_POSTMARK_TOKEN`, `MEGH_MAIL_POSTMARK_MESSAGE_STREAM` | `token`, `messageStream`, `endpoint`, `timeout` |
219
+ | `resend` | `MEGH_MAIL_RESEND_API_KEY` | `apiKey`, `endpoint`, `timeout` |
220
+ | `failover` | `MEGH_MAIL_FAILOVER=sendgrid,smtp` | `mailers: string[]` |
221
+ | `log` | | |
222
+ | `array` | | |
223
+
224
+ ### SMTP encryption
225
+
226
+ | `MEGH_MAIL_ENCRYPTION` | Meaning | Usual port |
227
+ | --- | --- | --- |
228
+ | `ssl` | TLS from the first byte | 465 |
229
+ | `tls` | STARTTLS, and refuse to send without it | 587 |
230
+ | `none` | Plain, upgraded with STARTTLS when the server offers it | 25 or 1025 |
231
+
232
+ Left unset, port 465 means `ssl` and any other port means `none`. Extra
233
+ [Nodemailer transport options](https://nodemailer.com/smtp/) (pooling, timeouts,
234
+ DKIM) go in `options`:
235
+
236
+ ```ts
237
+ app.useMail({
238
+ mailers: { smtp: { transport: 'smtp', options: { pool: true, maxConnections: 5 } } },
239
+ });
240
+ ```
241
+
242
+ ### Regional endpoints
243
+
244
+ EU accounts use a different API host:
245
+
246
+ ```ini
247
+ MEGH_MAIL_MAILGUN_ENDPOINT=https://api.eu.mailgun.net
248
+ ```
249
+
250
+ ```ts
251
+ app.useMail({
252
+ mailers: { sendgrid: { transport: 'sendgrid', endpoint: 'https://api.eu.sendgrid.com' } },
253
+ });
254
+ ```
255
+
256
+ A mailer passed to `useMail()` is merged over the same mailer from `.env`, so
257
+ this keeps `MEGH_MAIL_SENDGRID_API_KEY`. A mailer with a different `transport`
258
+ replaces it instead.
259
+
260
+ ### Failover
261
+
262
+ A `failover` mailer tries each mailer in order until one sends. Each failure is
263
+ logged as a warning:
264
+
265
+ ```ini
266
+ MEGH_MAIL_MAILER=failover
267
+ MEGH_MAIL_FAILOVER=sendgrid,smtp
268
+ ```
269
+
270
+ When every mailer fails, the error lists each reason. At startup, a failover
271
+ default checks that every mailer in its list is configured, so a wrong backup
272
+ key is caught before an outage.
273
+
274
+ ### Your own mailer
275
+
276
+ Any object with a `send(message)` method is a mailer:
277
+
278
+ ```ts
279
+ import { MailMessage, MailTransport } from '@meghjs/core';
280
+
281
+ class SparkPostTransport implements MailTransport {
282
+ async send(message: MailMessage) {
283
+ const res = await fetch('https://api.sparkpost.com/api/v1/transmissions', {
284
+ method: 'POST',
285
+ headers: { Authorization: process.env.SPARKPOST_KEY!, 'Content-Type': 'application/json' },
286
+ body: JSON.stringify(toSparkPost(message)),
287
+ });
288
+ return { messageId: (await res.json()).results.id };
289
+ }
290
+ }
291
+
292
+ app.useMail({ default: 'sparkpost', mailers: { sparkpost: new SparkPostTransport() } });
293
+ ```
294
+
295
+ `message` is fully built: `from`, `to`, `cc`, `bcc` and `replyTo` as
296
+ `{ name?, address }` objects, plus `subject`, `html`, `text`, `attachments` and
297
+ `headers`. An optional `close()` method is called when the app shuts down.
298
+
299
+ ### Errors
300
+
301
+ When a provider refuses a message, `send()` throws a `MailTransportError` with
302
+ `provider`, `status` (the HTTP status) and `body` (the provider's response).
303
+ Mistakes in a mailable, such as no recipients, no sender or no body, throw a
304
+ `MailError` that names the class.
305
+
306
+ ## Queueing mail
307
+
308
+ Sending inside a request makes the client wait for the mail server. Queue the
309
+ mail instead, and a worker sends it in the background. Queueing uses
310
+ [Megh's queue](/advanced/queue), so it needs `bullmq` and Redis (or the
311
+ `memory` driver):
312
+
313
+ ```ts [src/app.ts]
314
+ app.useMail({ queue: true });
315
+ ```
316
+
317
+ ```ts
318
+ await this.mailer.to(user.email).queue(new WelcomeMail(user));
319
+ await this.mailer.to(user.email).later(60_000, new ReminderMail(user)); // in a minute
320
+ await this.mailer.to(user.email).later(new Date('2026-12-24T09:00:00Z'), new GreetingMail(user));
321
+ ```
322
+
323
+ `queue()` and `later()` resolve to `{ mailer, message, jobId, delay }`.
324
+
325
+ The message is **built when you queue it**, and the job holds that built
326
+ message. The worker only delivers it, through the mailer named when it was
327
+ queued. Two consequences:
328
+
329
+ - A mistake in the mailable throws from `queue()`, in your request, not later
330
+ in the worker.
331
+ - An attachment given by `path` is read when the mail is sent, so the file must
332
+ exist where the worker runs. `Buffer` attachments travel inside the job.
333
+
334
+ ### Queue options
335
+
336
+ ```ts
337
+ app.useMail({
338
+ queue: {
339
+ name: 'mail', // the default
340
+ adapter: { connection: { host: '127.0.0.1', port: 6379 } },
341
+ driver: 'bullmq', // or 'memory' / 'sync'; defaults to MEGH_QUEUE_DRIVER
342
+ worker: { concurrency: 5 }, // or false: see below
343
+ jobOptions: { attempts: 5 },
344
+ },
345
+ });
346
+ ```
347
+
348
+ By default a job is tried 3 times, 10 then 20 seconds apart. Sent jobs are
349
+ removed, since they hold email addresses. Failed jobs are kept, so you can
350
+ inspect them.
351
+
352
+ The worker starts as soon as `useMail({ queue })` runs, so mail queued before a
353
+ restart is still sent. In a process that should only queue mail, while another
354
+ process sends it, pass `worker: false`.
355
+
356
+ Calling `queue()` without the `queue` option throws, instead of quietly
357
+ creating a queue.
358
+
359
+ ## Testing
360
+
361
+ `Mailer.fake()` records mail instead of sending it, and gives you assertions.
362
+ The mailable is still built, so a broken one fails the test.
363
+
364
+ ```ts
365
+ import { Mailer } from '@meghjs/core';
366
+
367
+ it('sends a welcome mail', async () => {
368
+ const mail = Mailer.fake();
369
+
370
+ await signup.register('ann@example.com');
371
+
372
+ mail.assertSent(WelcomeMail, (sent) => sent.hasTo('ann@example.com'));
373
+ mail.assertNotSent(PasswordResetMail);
374
+ mail.restore();
375
+ });
376
+ ```
377
+
378
+ | Assertion | Passes when |
379
+ | --- | --- |
380
+ | `assertSent(Type, check?)` | A `Type` was sent with `send()` (and passed `check`) |
381
+ | `assertSent(Type, n)` | A `Type` was sent exactly `n` times |
382
+ | `assertNotSent(Type, check?)` | No `Type` (passing `check`) was sent |
383
+ | `assertNothingSent()` | Nothing was sent |
384
+ | `assertSentCount(n)` | `n` messages were sent in all |
385
+ | `assertQueued(Type, check? \| n)` | A `Type` was queued with `queue()` or `later()` |
386
+ | `assertNotQueued(Type, check?)` | No `Type` (passing `check`) was queued |
387
+ | `assertNothingQueued()` | Nothing was queued |
388
+
389
+ The `check` receives a `SentMail`:
390
+
391
+ - `sent.mailable`: your instance.
392
+ - `sent.message`: the built message.
393
+ - `sent.delay`: for queued mail, the delay in milliseconds.
394
+ - `sent.hasTo(address)`, `hasCc()`, `hasBcc()` and `hasFrom()`: compare
395
+ addresses case-insensitively.
396
+
397
+ `sent`, `queued`, `sentOf(Type, check?)` and `queuedOf(Type, check?)` give you
398
+ the recorded mail itself.
399
+
400
+ A failed assertion explains itself, and points out mail that was queued when
401
+ you expected it sent, or the reverse:
402
+
403
+ ```
404
+ Expected WelcomeMail to be sent, but it was not. Nothing was sent. It was queued instead; use assertQueued().
405
+ ```
406
+
407
+ ## Setting it up
408
+
409
+ 1. Install the SMTP transport: `npm i nodemailer`. The API mailers don't need
410
+ it.
411
+ 2. Call `app.useMail()` in `src/app.ts`.
412
+ 3. Generate a mailable: `npx megh make:mail Welcome`.
413
+ 4. Add the mail settings to `.env`:
414
+
415
+ ```ini [.env]
416
+ # Mail: app.useMail(). With no MEGH_MAIL_MAILER, mail goes to the log in
417
+ # development, and the app will not start in production until one is set.
418
+ # MEGH_MAIL_MAILER=smtp
419
+ # MEGH_MAIL_HOST=127.0.0.1
420
+ # MEGH_MAIL_PORT=1025
421
+ # MEGH_MAIL_USERNAME=
422
+ # MEGH_MAIL_PASSWORD=
423
+ # MEGH_MAIL_ENCRYPTION=tls
424
+ # Or an API mailer: sendgrid, mailgun, postmark or resend.
425
+ # MEGH_MAIL_SENDGRID_API_KEY=
426
+ MEGH_MAIL_FROM_ADDRESS=hello@example.com
427
+ MEGH_MAIL_FROM_NAME="Shop"
428
+ ```
429
+
430
+ `npm run start:dev` then writes every mail to the console. To see real
431
+ messages during development, run a local mail catcher such as
432
+ [Mailpit](https://mailpit.axllent.org) and point SMTP at it:
433
+
434
+ ```ini
435
+ MEGH_MAIL_HOST=127.0.0.1
436
+ MEGH_MAIL_PORT=1025
437
+ ```
438
+
439
+ Mailpit's inbox is at `http://localhost:8025`.
@@ -0,0 +1,210 @@
1
+ ---
2
+ title: Migrations
3
+ description: Creating and changing tables with MeghORM migrations and the schema builder.
4
+ ---
5
+
6
+ # Migrations
7
+
8
+ A migration is a file in `src/database/migrations` whose default export is
9
+ `defineMigration({ up, down })`. Both functions receive the schema builder.
10
+ `down` undoes `up`, so the migration can be rolled back. Migrations run in
11
+ file-name order, so names start with a timestamp.
12
+
13
+ Create one with the CLI:
14
+
15
+ ```sh
16
+ npx megh make:migration create_users_table
17
+ ```
18
+
19
+ ```ts [src/database/migrations/20261101093000_create_users_table.ts]
20
+ import { defineMigration } from '@meghjs/core';
21
+
22
+ export default defineMigration({
23
+ async up(schema) {
24
+ await schema.create('users', (table) => {
25
+ table.id();
26
+ table.string('email').unique();
27
+ table.string('name').nullable();
28
+ table.boolean('active').default(true);
29
+ table.foreignId('team_id').constrained().cascadeOnDelete();
30
+ table.timestamps();
31
+ });
32
+ },
33
+
34
+ async down(schema) {
35
+ await schema.drop('users');
36
+ },
37
+ });
38
+ ```
39
+
40
+ The same migration runs on PostgreSQL, MySQL, SQLite and SQL Server. Each
41
+ column type becomes the right SQL type for the database, and statements are
42
+ issued the way each one needs them.
43
+
44
+ The name picks the template:
45
+
46
+ - `create_<table>_table` gives a create-table migration.
47
+ - `add_<x>_to_<table>_table` (also `remove`/`drop`/`alter`/`change`/`update`,
48
+ with `to`/`from`/`in`/`on`) gives an alter-table one.
49
+ - Anything else gives an empty migration.
50
+
51
+ `--create <table>` and `--table <table>` choose the template explicitly.
52
+
53
+ ## Tables
54
+
55
+ | | |
56
+ |---|---|
57
+ | `schema.create(name, (table) => …)` | Create a table |
58
+ | `schema.table(name, (table) => …)` | Change a table |
59
+ | `schema.drop(name)` / `schema.dropIfExists(name)` | Drop a table |
60
+ | `schema.rename(from, to)` | Rename a table |
61
+ | `schema.hasTable(name)` / `schema.hasColumn(table, column)` | Check what exists |
62
+ | `schema.raw(sql)` | Run SQL as written, for anything else |
63
+
64
+ ## Columns
65
+
66
+ Columns are `NOT NULL` unless marked `nullable()`.
67
+
68
+ | Method | PostgreSQL | MySQL | SQLite | SQL Server |
69
+ |---|---|---|---|---|
70
+ | `id(name = 'id')`, `increments(name)` | `integer` identity | `int auto_increment` | `integer autoincrement` | `int identity` |
71
+ | `bigIncrements(name)` | `bigint` identity | `bigint auto_increment` | `integer autoincrement` | `bigint identity` |
72
+ | `string(name, length = 255)` | `varchar` | `varchar` | `varchar` | `nvarchar` |
73
+ | `text(name)` | `text` | `text` | `text` | `nvarchar(max)` |
74
+ | `integer(name)` | `integer` | `int` | `integer` | `int` |
75
+ | `bigInteger(name)` | `bigint` | `bigint` | `integer` | `bigint` |
76
+ | `float(name)` | `real` | `float` | `real` | `real` |
77
+ | `double(name)` | `double precision` | `double` | `real` | `float` |
78
+ | `decimal(name, precision = 8, scale = 2)` | `numeric` | `decimal` | `numeric` | `decimal` |
79
+ | `boolean(name)` | `boolean` | `boolean` | `integer` | `bit` |
80
+ | `date(name)` | `date` | `date` | `date` | `date` |
81
+ | `datetime(name)` | `timestamp` | `datetime` | `datetime` | `datetime2` |
82
+ | `timestamp(name)` | `timestamptz` | `datetime` | `datetime` | `datetimeoffset` |
83
+ | `time(name)` | `time` | `time` | `time` | `time` |
84
+ | `json(name)` | `jsonb` | `json` | `text` | `nvarchar(max)` |
85
+ | `uuid(name)` | `uuid` | `char(36)` | `varchar(36)` | `uniqueidentifier` |
86
+ | `binary(name)` | `bytea` | `blob` | `blob` | `varbinary(max)` |
87
+ | `foreignId(name)` | `integer` | `int` | `integer` | `int` |
88
+ | `timestamps()` | nullable `created_at` and `updated_at`, for `@CreatedAt` / `@UpdatedAt` | | | |
89
+ | `softDeletes(name = 'deleted_at')` | nullable timestamp, for `@DeletedAt` | | | |
90
+
91
+ `id()` is a 32-bit integer, so drivers return it as a number. `bigIncrements()`
92
+ holds more rows, but PostgreSQL and MySQL drivers return 64-bit integers as
93
+ strings.
94
+
95
+ Modifiers, chained after a column:
96
+
97
+ | | |
98
+ |---|---|
99
+ | `.nullable()` | Allow `NULL` |
100
+ | `.unique()` | Unique index |
101
+ | `.primary()` | Primary key |
102
+ | `.default(value)` | Default value. Booleans, dates and objects are converted for the database |
103
+ | `.useCurrent()` | Default to the current time |
104
+ | `.autoIncrement()` | Numbered by the database |
105
+ | `.constrained(table?, column = 'id')` | Foreign key. The table comes from the column name: `team_id` → `teams` |
106
+ | `.references('teams.id')` | Foreign key to a given table and column |
107
+ | `.onDelete(action)`, `.onUpdate(action)` | `'cascade'`, `'set null'`, `'restrict'`, `'no action'`, `'set default'` |
108
+ | `.cascadeOnDelete()`, `.nullOnDelete()` | Shorthands. `nullOnDelete()` also makes the column nullable |
109
+
110
+ ## Indexes and keys
111
+
112
+ ```ts
113
+ await schema.create('posts', (table) => {
114
+ table.id();
115
+ table.integer('author_id');
116
+ table.string('slug');
117
+ table.unique(['author_id', 'slug']); // posts_author_id_slug_unique
118
+ table.index('slug'); // posts_slug_index
119
+ table.foreign('author_id').references('users.id').cascadeOnDelete();
120
+ });
121
+ ```
122
+
123
+ Indexes and keys are named `<table>_<columns>_<index|unique|foreign>`, so you
124
+ can drop them by their columns: `table.dropIndex(['slug'])`,
125
+ `table.dropUnique([...])`, `table.dropForeign(['author_id'])`.
126
+ `table.primary(['a', 'b'])` declares a primary key over several columns.
127
+
128
+ ## Changing tables
129
+
130
+ ```ts
131
+ await schema.table('users', (table) => {
132
+ table.string('phone').nullable();
133
+ table.foreignId('company_id').nullable().constrained();
134
+ table.renameColumn('name', 'full_name');
135
+ table.dropColumn('legacy');
136
+ });
137
+ ```
138
+
139
+ A column added to an existing table must be `nullable()` or have a
140
+ `default()`, because rows already in the table need a value.
141
+
142
+ SQLite can't add a foreign key or primary key to an existing column, or drop
143
+ one. Declare them in `schema.create()`, or add the foreign key together with
144
+ its new column (`foreignId(...).constrained()`), which SQLite supports. Doing
145
+ otherwise throws a `SchemaError` that explains this.
146
+
147
+ ::: details Migrations written against Kysely
148
+ Migration files that export `up(db)` / `down(db)` functions taking the Kysely
149
+ instance still run, in order with the others. New migrations use the schema
150
+ builder.
151
+ :::
152
+
153
+ Then run them:
154
+
155
+ | Command | |
156
+ |---|---|
157
+ | `megh migrate` | Run pending migrations |
158
+ | `megh migrate:status` | Show which have run (`--json` for JSON) |
159
+ | `megh migrate:rollback` | Undo the last migration; `--step <n>` for more |
160
+ | `megh migrate:reset` | Undo every migration |
161
+ | `megh migrate:refresh` | Undo every migration, then run them all again |
162
+
163
+ The commands compile `src/` with SWC, load `.env`, and connect the way
164
+ `app.useMeghORM()` does: from `DATABASE_URL` or the `DB_*` variables. Settings
165
+ that aren't secret can go in `package.json`, as can a different migrations
166
+ folder:
167
+
168
+ ```json [package.json]
169
+ {
170
+ "megh": {
171
+ "database": { "dialect": "postgres", "pool": { "max": 2 } },
172
+ "migrations": "migrations"
173
+ }
174
+ }
175
+ ```
176
+
177
+ A project that still has `src/database/connection.ts` exporting a Kysely
178
+ instance keeps using it, as does `"database": "path/to/module.ts"`.
179
+
180
+ A failing migration stops the run, and the error names it. What happens to
181
+ the migrations before it depends on the database:
182
+
183
+ - **PostgreSQL and SQL Server** support transactional DDL, so the whole run is
184
+ one transaction: a failure rolls back every migration in that run.
185
+ - **MySQL and SQLite** don't, so migrations that ran before the failure stay
186
+ applied. The error lists them.
187
+
188
+ Executed migrations are recorded in Kysely's `kysely_migration` table, so
189
+ projects already using Kysely migrations keep their history.
190
+
191
+ ## Running migrations from code
192
+
193
+ `Migrations` runs the same operations from code, for example in test setup or
194
+ at deploy time:
195
+
196
+ ```ts
197
+ import { Migrations, Model } from '@meghjs/core';
198
+
199
+ // After app.useMeghORM() (or Model.useConnection()):
200
+ const migrations = new Migrations(Model.db(), { folder: `${__dirname}/database/migrations` });
201
+ await migrations.latest(); // names that ran
202
+ await migrations.rollback(2);
203
+ await migrations.status(); // [{ name, executedAt }]
204
+ ```
205
+
206
+ Pass `migrations: { name: defineMigration({ up, down }) }` instead of `folder` to define them
207
+ inline, and `table` / `lockTable` to change the bookkeeping table names. A
208
+ failed run throws a `MigrationError` with `migration` (the one that failed) and
209
+ `completed` (those that ran before it; on PostgreSQL and SQL Server they were
210
+ rolled back with it).