@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,58 @@
1
+ ---
2
+ layout: home
3
+
4
+ hero:
5
+ name: MEGH
6
+ text: TypeScript-first web framework built on Fastify
7
+ tagline: Decorator-based routing, dependency injection, validation and OpenAPI docs, with minimal boilerplate.
8
+ image:
9
+ src: /megh-logo.svg
10
+ alt: Megh
11
+ actions:
12
+ - theme: brand
13
+ text: Get Started
14
+ link: /getting-started/introduction
15
+ - theme: alt
16
+ text: Moving from Avleon
17
+ link: /getting-started/upgrading-megh
18
+ - theme: alt
19
+ text: GitHub
20
+ link: https://github.com/meghjs/megh
21
+
22
+ features:
23
+ - title: Decorator-based routing
24
+ details: Controllers, route methods and parameter decorators, with DTOs validated and whitelisted by compiled, class-validator-compatible decorators.
25
+ - title: Secure by default
26
+ details: Deny-by-default authorization, confined file storage and production-safe error responses.
27
+ - title: Batteries included
28
+ details: MeghORM type-safe models and migrations, server-rendered views, events, BullMQ queues, scheduling, caching, Socket.IO and structured logging.
29
+ - title: Ready for AI assistants
30
+ details: The Megh MCP server gives Claude Code, Cursor and VS Code the Megh docs, a view of your project and the CLI generators.
31
+ link: /ai/mcp
32
+ linkText: Set it up
33
+ ---
34
+
35
+ ## Hello, Megh
36
+
37
+ ::: code-group
38
+ ```ts [welcome.controller.ts]
39
+ import { ApiController, Get } from '@meghjs/core';
40
+
41
+ @ApiController
42
+ export class WelcomeController {
43
+ @Get()
44
+ sayHello() {
45
+ return 'Hello, Megh!';
46
+ }
47
+ }
48
+ ```
49
+
50
+ ```ts [app.ts]
51
+ import { Megh } from '@meghjs/core';
52
+ import { WelcomeController } from './welcome.controller';
53
+
54
+ const app = Megh.createApplication();
55
+ app.useControllers([WelcomeController]);
56
+ app.run(); // or app.run(4000)
57
+ ```
58
+ :::
@@ -0,0 +1,387 @@
1
+ ---
2
+ title: OpenAPI
3
+ description: "Generating API documentation from your controllers: typed options, request bodies and responses from DTOs and models, and secured routes."
4
+ ---
5
+
6
+ # OpenAPI
7
+
8
+ Megh generates an OpenAPI document from your controllers and serves a browsable
9
+ UI. Request bodies and query strings come from your DTOs, responses from
10
+ `@ApiResponse()` with a DTO or MeghORM model, and the errors a route can return
11
+ from what its controller declares. The UI packages are optional peer
12
+ dependencies. Install the one you use:
13
+
14
+ ::: code-group
15
+ ```sh [Swagger UI]
16
+ npm i @fastify/swagger @fastify/swagger-ui
17
+ ```
18
+ ```sh [Scalar]
19
+ npm i @fastify/swagger @scalar/fastify-api-reference
20
+ ```
21
+ :::
22
+
23
+ ## Enabling
24
+
25
+ ```sh
26
+ npx megh make:config openapi
27
+ ```
28
+
29
+ ::: code-group
30
+ ```ts [config/openapi.config.ts]
31
+ import { AppConfig, MeghConfig, Environment, OpenApiUiOptions } from '@meghjs/core';
32
+
33
+ @AppConfig
34
+ export class OpenApiConfig extends MeghConfig<OpenApiUiOptions> {
35
+ config(env: Environment): OpenApiUiOptions {
36
+ return {
37
+ info: {
38
+ title: 'My API',
39
+ version: '1.0.0',
40
+ description: 'API documentation',
41
+ },
42
+ routePrefix: '/docs',
43
+ };
44
+ }
45
+ }
46
+ ```
47
+
48
+ ```ts [app.ts]
49
+ import { Megh } from '@meghjs/core';
50
+ import { OpenApiConfig } from './config/openapi.config';
51
+ import { WelcomeController } from './controllers/welcome.controller';
52
+
53
+ const app = Megh.createApplication();
54
+
55
+ if (app.isDevelopment()) {
56
+ app.useOpenApi(OpenApiConfig);
57
+ }
58
+
59
+ app.useControllers([WelcomeController]);
60
+
61
+ export default app;
62
+ ```
63
+ :::
64
+
65
+ The UI is then served at `routePrefix` — `http://localhost:4000/docs` above.
66
+
67
+ `isDevelopment()` is true only when `NODE_ENV=development`. With `NODE_ENV`
68
+ unset, the guard above turns the docs off.
69
+
70
+ `OpenApiUiOptions` is fully typed, so your editor completes and checks every
71
+ option, down to Swagger UI's settings. `useOpenApi` also accepts a plain
72
+ options object if you do not need a config class:
73
+
74
+ ```ts
75
+ app.useOpenApi({
76
+ info: { title: 'My API', version: '1.0.0' },
77
+ routePrefix: '/docs',
78
+ });
79
+ ```
80
+
81
+ ### Options
82
+
83
+ | Option | Description |
84
+ |--------|-------------|
85
+ | `info` | Title, version and description. Defaults to `{ title: 'API', version: '1.0.0' }` |
86
+ | `routePrefix` | Where the UI is served. Defaults to `/swagger`; the JSON document is at `<routePrefix>/json` |
87
+ | `provider` | `'default'` (Swagger UI) or `'scalar'` |
88
+ | `auth` | Security scheme for `@Authorized` routes: `'bearer'`, `'apiKey'` or any OpenAPI security scheme. See [Securing routes](#securing-routes) |
89
+ | `servers` | Base URLs the API is served from |
90
+ | `tags` | Tag descriptions. Each controller is a tag, named after the class without `Controller` |
91
+ | `security` | Security requirement for every route. Prefer `auth`, which applies to `@Authorized` routes only |
92
+ | `components` | Extra schemas, responses and security schemes, merged into the generated ones |
93
+ | `externalDocs` | A link to more documentation |
94
+ | `uiConfig` | Swagger UI settings: `docExpansion`, `persistAuthorization`, `filter`, … |
95
+ | `scalar` | Scalar settings, with `provider: 'scalar'` |
96
+ | `logo` | Swagger UI top-bar logo. Defaults to the Megh logo |
97
+ | `theme` | Swagger UI `title`, `css`, `js` and `favicon`. Defaults to the Megh favicon |
98
+ | `openapi` | OpenAPI version of the document. Defaults to `3.0.3` |
99
+ | `paths` | Extra paths documented as given, for routes outside Megh |
100
+
101
+ For example, keep the "Authorize" credentials across reloads and start with
102
+ operations collapsed:
103
+
104
+ ```ts
105
+ app.useOpenApi({
106
+ info: { title: 'My API', version: '1.0.0' },
107
+ uiConfig: { docExpansion: 'list', persistAuthorization: true },
108
+ });
109
+ ```
110
+
111
+ ### Logo and favicon
112
+
113
+ Swagger UI shows the Megh logo and favicon. To use your own, pass a `logo`
114
+ (an image as a string or `Buffer`, with its MIME type) and a `favicon` in `theme`:
115
+
116
+ ```ts
117
+ import { readFileSync } from 'fs';
118
+
119
+ app.useOpenApi({
120
+ info: { title: 'My API', version: '1.0.0' },
121
+ logo: {
122
+ type: 'image/svg+xml',
123
+ content: readFileSync('public/logo.svg'),
124
+ href: 'https://example.com', // where the logo links to; defaults to the app root
125
+ },
126
+ theme: {
127
+ title: 'My API docs',
128
+ favicon: [
129
+ { filename: 'favicon.png', rel: 'icon', type: 'image/png', sizes: '32x32', content: readFileSync('public/favicon.png') },
130
+ ],
131
+ },
132
+ });
133
+ ```
134
+
135
+ Set `logo: null` for Swagger UI's own logo.
136
+
137
+ ### Scalar UI
138
+
139
+ To use [Scalar](https://scalar.com) instead of Swagger UI, install
140
+ `@scalar/fastify-api-reference` and set the provider:
141
+
142
+ ```ts
143
+ app.useOpenApi({
144
+ info: { title: 'My API', version: '1.0.0' },
145
+ provider: 'scalar',
146
+ scalar: { layout: 'modern', darkMode: true },
147
+ });
148
+ ```
149
+
150
+ The CLI can wire this up for you — pick *Scalar UI* when running `megh new`.
151
+
152
+ ## Documenting routes
153
+
154
+ Use `@OpenApi` on a controller or a route method to enrich the generated
155
+ document. The route decorators take the same options as `openapi`:
156
+ `@Get('/', { openapi: { summary: 'List users' } })`.
157
+
158
+ ```ts [controllers/welcome.controller.ts]
159
+ import { ApiController, Get, OpenApi } from '@meghjs/core';
160
+
161
+ @OpenApi({ tags: ['welcome'] })
162
+ @ApiController('/welcome')
163
+ export class WelcomeController {
164
+ @OpenApi({
165
+ summary: 'Say hello',
166
+ description: 'Returns a greeting.',
167
+ response: {
168
+ 200: { description: 'A greeting' },
169
+ },
170
+ })
171
+ @Get()
172
+ sayHello() {
173
+ return 'Hello world!';
174
+ }
175
+ }
176
+ ```
177
+
178
+ Useful `@OpenApi` fields:
179
+
180
+ | Field | Description |
181
+ |-------|-------------|
182
+ | `summary` / `description` | Human-readable text |
183
+ | `tags` | Groups the route in the UI |
184
+ | `params` / `query` / `headers` | Document inputs |
185
+ | `requestBody` | Document the body |
186
+ | `response` | Responses keyed by status code. See [Responses](#responses) |
187
+ | `deprecated` | Mark the route deprecated |
188
+ | `exclude` | Hide the route from the document |
189
+ | `security` | Per-route security requirements |
190
+
191
+ For example, documenting inputs:
192
+
193
+ ```ts
194
+ @OpenApi({
195
+ params: { id: { type: 'string', example: 'abc-123' } },
196
+ query: { page: { type: 'integer', example: 1 } },
197
+ })
198
+ @Get('/:id')
199
+ findOne(@Param('id') id: string) {
200
+ return { id };
201
+ }
202
+ ```
203
+
204
+ ### Query parameters
205
+
206
+ `@Query()` parameters are documented automatically, in the order of the
207
+ method's parameters:
208
+
209
+ ```ts
210
+ @Get()
211
+ index(@Query() query: ListUsersQuery, @Query('role') role: string) {
212
+ return this.userService.paginate(query);
213
+ }
214
+ ```
215
+
216
+ A DTO (`@Query() query: ListUsersQuery`) becomes one query parameter per
217
+ property, with its type and validation constraints (`@Min(1)` as
218
+ `minimum: 1`, `@MaxLength(255)` as `maxLength`, …). A property is required
219
+ when it has `@IsNotEmpty()` or `@IsDefined()`, as for body DTOs. A single
220
+ value (`@Query('role') role: string`) becomes one parameter, typed from the
221
+ parameter's type and required unless you pass `{ required: false }`.
222
+
223
+ This is documentation only: the values are still validated by the DTO. A
224
+ parameter given in `@OpenApi({ query })` takes precedence over the generated
225
+ one of the same name.
226
+
227
+ To show a date format, add it to the DTO property with `@OpenApiProperty`:
228
+
229
+ ```ts
230
+ @IsOptional()
231
+ @OpenApiProperty({ format: 'date', example: '2026-11-10' })
232
+ @Matches(/^\d{4}-\d{2}-\d{2}$/)
233
+ @IsDateString({ strict: true })
234
+ startDate?: string;
235
+ ```
236
+
237
+ ### Request bodies
238
+
239
+ A `@Body()` DTO is documented automatically as a required
240
+ `application/json` body (or `multipart/form-data` when it has a
241
+ `format: 'binary'` field). Nested DTOs become `$ref`s under
242
+ `components.schemas`.
243
+
244
+ `requestBody` refines or replaces that. It only affects the document, and
245
+ validation still comes from the DTO:
246
+
247
+ ```ts
248
+ // Describe the DTO body
249
+ @OpenApi({ requestBody: { description: 'The new user' } })
250
+ @Post()
251
+ create(@Body() body: CreateUserDto) {}
252
+
253
+ // Inline schema with an example; `required` defaults to true
254
+ @OpenApi({
255
+ requestBody: {
256
+ required: false,
257
+ schema: { type: 'object', properties: { q: { type: 'string' } } },
258
+ example: { q: 'megh' },
259
+ },
260
+ })
261
+
262
+ // One schema per media type (schemas may be DTO classes)
263
+ @OpenApi({
264
+ requestBody: {
265
+ content: {
266
+ 'application/json': { schema: CreateUserDto },
267
+ 'text/csv': { schema: { type: 'string' } },
268
+ },
269
+ },
270
+ })
271
+ ```
272
+
273
+ `requestBody` also takes a DTO class (`requestBody: CreateUserDto`) or a
274
+ `$ref` to `#/components/requestBodies/*`. Use `contentType` to document
275
+ `schema` under other media types, and `examples` / `encoding` as in the
276
+ OpenAPI spec.
277
+
278
+ ## Responses
279
+
280
+ Document what a route returns with `@ApiResponse(status, type)`. The type is a
281
+ DTO class, a MeghORM model, `[Class]` for an array, `Paginated(Class)` for a
282
+ page, or a JSON schema:
283
+
284
+ ```ts [controllers/user.controller.ts]
285
+ import { ApiController, ApiResponse, Body, Get, Paginated, Param, Post, Query } from '@meghjs/core';
286
+ import { User } from '../models/user.model';
287
+
288
+ @ApiController('/users')
289
+ export class UserController {
290
+ @Get()
291
+ @ApiResponse(200, Paginated(User)) // { data: User[], meta }
292
+ index(@Query() query: ListUsersQuery) {
293
+ return this.users.paginate(query);
294
+ }
295
+
296
+ @Get('/:id')
297
+ @ApiResponse(200, User)
298
+ @ApiResponse(404) // the error shape
299
+ show(@Param('id') id: number) {
300
+ return this.users.findOrFail(id);
301
+ }
302
+
303
+ @Post()
304
+ @ApiResponse(201, { type: UserDto, description: 'The new user' })
305
+ create(@Body() body: CreateUserDto) {
306
+ return this.users.create(body);
307
+ }
308
+ }
309
+ ```
310
+
311
+ A model is documented from its column decorators: each column's type,
312
+ nullability and length, and nothing else, so the schema follows the model as
313
+ it changes. A DTO is documented from its validation decorators (Megh's or
314
+ class-validator's), as
315
+ request bodies are. `@ApiResponse` on the controller class applies to every
316
+ route in it.
317
+
318
+ Responses are documentation only: the handler's return value is sent as it is,
319
+ so fields outside the documented schema (loaded relations, `withCount()`
320
+ counts) still reach the client. `@OpenApi({ response: { 200: User } })` works
321
+ the same way. A plain JSON schema there (`{ 200: { type: 'object', … } }`) is
322
+ also Fastify's response schema, which serializes the reply and drops fields
323
+ it doesn't list.
324
+
325
+ `megh make:resource` writes these annotations for you: a page of the model for
326
+ `index`, the model for `show`, `create` and `update`, and `404` where the
327
+ service calls `findOrFail()`.
328
+
329
+ ::: info Why not from the return type?
330
+ TypeScript's types don't exist at runtime, so Megh can't read that `show()`
331
+ returns a `Promise<User>`. Name the type once in `@ApiResponse`.
332
+ :::
333
+
334
+ ### Errors
335
+
336
+ Megh adds the errors a route can return from what its controller declares, so
337
+ you don't document them by hand:
338
+
339
+ | When | Response |
340
+ |------|----------|
341
+ | The route validates a `@Body()` or `@Query()` DTO | `400` with the validation error shape: `{ code, status, message, errors: [{ path, constraints }] }` |
342
+ | The route or its controller is `@Authorized` | `401` and `403` |
343
+ | `@ApiResponse(404)` (any `4xx`/`5xx`) with no type | That status with Megh's error shape: `{ code, status, message, data? }` |
344
+
345
+ An `@ApiResponse` for the same status replaces the generated one.
346
+
347
+ ## Securing routes
348
+
349
+ Set `auth` and every `@Authorized` route gets the security scheme, so the
350
+ "Authorize" button applies to it and the UI shows its lock icon:
351
+
352
+ ```ts
353
+ app.useOpenApi({
354
+ info: { title: 'My API', version: '1.0.0' },
355
+ auth: 'bearer', // Authorization: Bearer <JWT>
356
+ });
357
+ ```
358
+
359
+ `'apiKey'` documents an `X-API-Key` header instead. For anything else, pass an
360
+ OpenAPI security scheme: `auth: { type: 'apiKey', in: 'query', name: 'token' }`.
361
+ Routes without `@Authorized` stay open.
362
+
363
+ ## Inline routes
364
+
365
+ Routes registered with `mapGet` and friends return a chainable object, so they
366
+ can carry their own OpenAPI metadata:
367
+
368
+ ```ts [app.ts]
369
+ import { Megh } from '@meghjs/core';
370
+
371
+ const app = Megh.createApplication();
372
+
373
+ app.mapGet('/', () => 'Welcome to Megh.').useOpenApi({
374
+ tags: ['welcome'],
375
+ summary: 'Root greeting',
376
+ });
377
+
378
+ export default app;
379
+ ```
380
+
381
+ The same object also exposes `useMiddleware`:
382
+
383
+ ```ts
384
+ app.mapGet('/secret', handler)
385
+ .useMiddleware([ApiKeyMiddleware])
386
+ .useOpenApi({ tags: ['internal'] });
387
+ ```
@@ -0,0 +1,165 @@
1
+ ---
2
+ title: WebSocket
3
+ description: Realtime communication with Socket.IO.
4
+ ---
5
+
6
+ # WebSocket
7
+
8
+ Megh's realtime layer is built on [Socket.IO](https://socket.io). It and its
9
+ Fastify adapter are optional peer dependencies:
10
+
11
+ ```sh
12
+ npm i socket.io fastify-socket.io
13
+ ```
14
+
15
+ ## Enabling websockets
16
+
17
+ Call `useSocketIo` during app setup. Options are passed straight through to the
18
+ Socket.IO server.
19
+
20
+ ```ts [app.ts]
21
+ import { Megh } from '@meghjs/core';
22
+ import { ChatSubscriber } from './subscribers/chat.subscriber';
23
+
24
+ const app = Megh.createApplication();
25
+
26
+ app.useSocketIo({
27
+ cors: { origin: '*' },
28
+ });
29
+
30
+ export default app;
31
+ ```
32
+
33
+ The server is created when the app runs; connecting clients are wired to your
34
+ subscribers automatically.
35
+
36
+ ## Subscribing to events
37
+
38
+ Mark any service method with `@Subscribe('event')` to handle an incoming
39
+ client event. The class must be registered with the container — `@AppService`
40
+ does that.
41
+
42
+ ```ts [subscribers/chat.subscriber.ts]
43
+ import { AppService, Subscribe } from '@meghjs/core';
44
+
45
+ @AppService
46
+ export class ChatSubscriber {
47
+ @Subscribe('message')
48
+ onMessage(payload: { room: string; text: string }) {
49
+ console.log(`[${payload.room}] ${payload.text}`);
50
+ }
51
+
52
+ @Subscribe('typing')
53
+ onTyping(payload: { user: string }) {
54
+ console.log(`${payload.user} is typing`);
55
+ }
56
+ }
57
+ ```
58
+
59
+ Handlers run inside a socket context, so the originating socket is available
60
+ through `SocketContextService` for the duration of the call.
61
+
62
+ ## Emitting to clients
63
+
64
+ Inject `SocketEventDispatcher` to push events out:
65
+
66
+ ```ts [services/chat.service.ts]
67
+ import { AppService, SocketEventDispatcher } from '@meghjs/core';
68
+
69
+ @AppService
70
+ export class ChatService {
71
+ constructor(private readonly socket: SocketEventDispatcher) {}
72
+
73
+ async announce(text: string) {
74
+ await this.socket.dispatch('announcement', { text });
75
+ }
76
+
77
+ async toRoom(room: string, text: string) {
78
+ await this.socket.dispatch('message', { text }, { room });
79
+ }
80
+
81
+ async toEveryoneElse(room: string, text: string) {
82
+ // skips the socket that triggered the current handler
83
+ await this.socket.dispatch('message', { text }, { room, broadcast: true });
84
+ }
85
+ }
86
+ ```
87
+
88
+ `dispatch` accepts:
89
+
90
+ | Option | Description |
91
+ |--------|-------------|
92
+ | `room` | Emit only to this room |
93
+ | `broadcast` | Exclude the current socket |
94
+ | `transports` | Defaults to `['socket']`, the only transport in 1.0. Any other value throws. |
95
+ | `retry` | Attempts on failure |
96
+ | `retryDelay` | Base delay in ms; backs off per attempt |
97
+
98
+ ## Authentication
99
+
100
+ With `app.useAuthentication(Handler)` registered, the same handler runs once
101
+ on each Socket.IO handshake. What it returns becomes `socket.data.user`:
102
+
103
+ - a user: the socket is connected as that user;
104
+ - `null` or `undefined`: the socket connects as a guest, and
105
+ `@PrivateChannel` listeners ignore it;
106
+ - a thrown error: the connection is refused, and the client's
107
+ `connect_error` has the message `Unauthorized`.
108
+
109
+ The handler gets a request-shaped object: the handshake `headers`, `query`,
110
+ `auth` and `ip`. Browsers can't set headers on a WebSocket, so a token sent
111
+ as `auth.token` arrives as `authorization: Bearer <token>`, and a handler
112
+ that reads the HTTP header works unchanged:
113
+
114
+ ```ts [client]
115
+ const socket = io('https://api.example.com', { auth: { token } });
116
+ ```
117
+
118
+ ## Private channels
119
+
120
+ `@PrivateChannel` restricts a subscriber method to a channel derived from the
121
+ connecting socket — use it for per-user streams. Its listeners only run for
122
+ sockets with a `socket.data.user`:
123
+
124
+ ```ts
125
+ import { AppService, Subscribe, PrivateChannel } from '@meghjs/core';
126
+
127
+ @AppService
128
+ export class NotificationSubscriber {
129
+ @PrivateChannel((socket) => `user:${socket.handshake.auth.userId}`)
130
+ @Subscribe('notify')
131
+ onNotify(payload: unknown) {
132
+ // only reachable on the caller's own channel
133
+ }
134
+ }
135
+ ```
136
+
137
+ ## Reaching the raw server
138
+
139
+ For anything the helpers do not cover, resolve the Socket.IO `Server` itself:
140
+
141
+ ```ts
142
+ import { MeghContainer, SocketIoServer } from '@meghjs/core';
143
+
144
+ const io = MeghContainer.get(SocketIoServer);
145
+ io.emit('ping', Date.now());
146
+ ```
147
+
148
+ ::: warning
149
+ `SocketIoServer` is only registered once the app is running and websockets are
150
+ enabled. Resolving it during module load will fail.
151
+ :::
152
+
153
+ Resolve services through `MeghContainer`. Megh has its own container and no
154
+ longer installs `typedi`.
155
+
156
+ ## Broadcasting events
157
+
158
+ The [event system](/advanced/events) can forward a dispatched event to Socket.IO,
159
+ which keeps domain events and realtime delivery in one place:
160
+
161
+ ```ts
162
+ await dispatcher.dispatch(new UserCreatedEvent({ userId, name }), {
163
+ broadcast: { type: 'socket', channel: 'user:create' },
164
+ });
165
+ ```