@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.
- package/LICENSE +21 -0
- package/README.md +141 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +37 -0
- package/dist/docs/advanced/caching.md +72 -0
- package/dist/docs/advanced/database.md +328 -0
- package/dist/docs/advanced/events.md +169 -0
- package/dist/docs/advanced/file-uploads.md +141 -0
- package/dist/docs/advanced/health.md +81 -0
- package/dist/docs/advanced/logging.md +96 -0
- package/dist/docs/advanced/mail.md +439 -0
- package/dist/docs/advanced/orm/migrations.md +210 -0
- package/dist/docs/advanced/orm/models.md +291 -0
- package/dist/docs/advanced/orm/queries.md +169 -0
- package/dist/docs/advanced/orm/query-builder.md +120 -0
- package/dist/docs/advanced/orm/relations.md +179 -0
- package/dist/docs/advanced/orm/seeding.md +129 -0
- package/dist/docs/advanced/orm.md +145 -0
- package/dist/docs/advanced/plugins.md +90 -0
- package/dist/docs/advanced/queue.md +217 -0
- package/dist/docs/advanced/scheduler.md +253 -0
- package/dist/docs/advanced/testing.md +257 -0
- package/dist/docs/advanced/views.md +335 -0
- package/dist/docs/ai/mcp.md +162 -0
- package/dist/docs/cli/basic.md +133 -0
- package/dist/docs/cli/database.md +112 -0
- package/dist/docs/cli/generators.md +605 -0
- package/dist/docs/cli/scaffold/auth.md +172 -0
- package/dist/docs/cli/scaffold/domains.md +224 -0
- package/dist/docs/cli/scaffold/index.md +77 -0
- package/dist/docs/cli/scaffold/rbac.md +118 -0
- package/dist/docs/cli/scaffold/templates.md +235 -0
- package/dist/docs/core-concept/authentication.md +162 -0
- package/dist/docs/core-concept/configuration.md +268 -0
- package/dist/docs/core-concept/controller.md +350 -0
- package/dist/docs/core-concept/dependency-injection.md +213 -0
- package/dist/docs/core-concept/error-handling.md +185 -0
- package/dist/docs/core-concept/middleware.md +143 -0
- package/dist/docs/core-concept/request-context.md +110 -0
- package/dist/docs/core-concept/validation.md +355 -0
- package/dist/docs/getting-started/application.md +233 -0
- package/dist/docs/getting-started/installation.md +166 -0
- package/dist/docs/getting-started/introduction.md +136 -0
- package/dist/docs/getting-started/upgrading-0.4.md +125 -0
- package/dist/docs/getting-started/upgrading-0.5.md +293 -0
- package/dist/docs/getting-started/upgrading-0.6.md +251 -0
- package/dist/docs/getting-started/upgrading-0.7.md +225 -0
- package/dist/docs/getting-started/upgrading-megh.md +91 -0
- package/dist/docs/getting-started/upgrading-next.md +12 -0
- package/dist/docs/getting-started/upgrading.md +137 -0
- package/dist/docs/getting-started/usage.md +194 -0
- package/dist/docs/index.md +58 -0
- package/dist/docs/microservices/openapi.md +387 -0
- package/dist/docs/microservices/websocket.md +165 -0
- package/dist/docs/production/deployment.md +256 -0
- package/dist/docs/production/security.md +307 -0
- package/dist/docs/reference/api.md +999 -0
- package/dist/docs/reference/faq.md +227 -0
- package/dist/docs/reference/versioning.md +105 -0
- package/dist/docs.d.ts +30 -0
- package/dist/docs.js +126 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +22 -0
- package/dist/megh.d.ts +59 -0
- package/dist/megh.js +207 -0
- package/dist/prompts.d.ts +3 -0
- package/dist/prompts.js +47 -0
- package/dist/result.d.ts +18 -0
- package/dist/result.js +48 -0
- package/dist/server.d.ts +17 -0
- package/dist/server.js +40 -0
- package/dist/tools/context.d.ts +11 -0
- package/dist/tools/context.js +2 -0
- package/dist/tools/database.d.ts +8 -0
- package/dist/tools/database.js +58 -0
- package/dist/tools/docs.d.ts +3 -0
- package/dist/tools/docs.js +63 -0
- package/dist/tools/generate.d.ts +10 -0
- package/dist/tools/generate.js +177 -0
- package/dist/tools/project.d.ts +3 -0
- package/dist/tools/project.js +84 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- package/package.json +58 -4
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Testing
|
|
3
|
+
description: Unit testing controllers and services, and sending requests to your routes with MeghTest.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Testing
|
|
7
|
+
|
|
8
|
+
`MeghTest` helps with two kinds of test:
|
|
9
|
+
|
|
10
|
+
- **Unit tests**: build a controller or service with its dependencies, and call
|
|
11
|
+
its methods.
|
|
12
|
+
- **Route tests**: send requests to your app without opening a port.
|
|
13
|
+
|
|
14
|
+
The examples use [Vitest](https://vitest.dev), which `megh new` sets up.
|
|
15
|
+
|
|
16
|
+
## Setup
|
|
17
|
+
|
|
18
|
+
Megh's constructor injection needs decorator metadata, which Vitest's default
|
|
19
|
+
transform (esbuild) doesn't emit. Use SWC instead:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm i -D vitest unplugin-swc @swc/core
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```ts [vitest.config.mts]
|
|
26
|
+
import swc from 'unplugin-swc';
|
|
27
|
+
import { defineConfig } from 'vitest/config';
|
|
28
|
+
|
|
29
|
+
export default defineConfig({
|
|
30
|
+
plugins: [swc.vite()],
|
|
31
|
+
test: {
|
|
32
|
+
environment: 'node',
|
|
33
|
+
include: ['src/**/*.spec.ts'],
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`megh new` generates this file, plus `vitest.e2e.config.mts` for
|
|
39
|
+
`test/**/*.e2e-spec.ts`.
|
|
40
|
+
|
|
41
|
+
::: tip Generated tests
|
|
42
|
+
`megh make:service`, `make:controller`, `make:resource` and the other
|
|
43
|
+
generators write a `.spec.ts` next to the file they create, and
|
|
44
|
+
`megh make:test <name>` writes one for a file you already have. See
|
|
45
|
+
[CLI: Tests](/cli/generators#tests).
|
|
46
|
+
:::
|
|
47
|
+
|
|
48
|
+
## Unit tests
|
|
49
|
+
|
|
50
|
+
`MeghTest.getController` and `MeghTest.getProvider` resolve a class through
|
|
51
|
+
[dependency injection](/core-concept/dependency-injection), with its
|
|
52
|
+
dependencies built for you:
|
|
53
|
+
|
|
54
|
+
```ts [src/controllers/home.controller.spec.ts]
|
|
55
|
+
import { beforeAll, describe, expect, it } from 'vitest';
|
|
56
|
+
import { MeghTest } from '@meghjs/core';
|
|
57
|
+
import { HomeController } from './home.controller';
|
|
58
|
+
|
|
59
|
+
describe('HomeController', () => {
|
|
60
|
+
let controller: HomeController;
|
|
61
|
+
|
|
62
|
+
beforeAll(() => {
|
|
63
|
+
controller = MeghTest.getController(HomeController);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('returns a greeting', () => {
|
|
67
|
+
expect(controller.sayHello()).toEqual({ message: 'Hello World!' });
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Replacing dependencies
|
|
73
|
+
|
|
74
|
+
Pass stand-ins as the second argument, in constructor parameter order:
|
|
75
|
+
|
|
76
|
+
```ts [src/services/user.service.spec.ts]
|
|
77
|
+
import { afterEach, expect, it, vi } from 'vitest';
|
|
78
|
+
import { MeghTest } from '@meghjs/core';
|
|
79
|
+
import { UserService } from './user.service';
|
|
80
|
+
|
|
81
|
+
// constructor(private users: UserRepository, private mailer: MailerService)
|
|
82
|
+
const users = { create: vi.fn(async (data) => ({ id: 1, ...data })) };
|
|
83
|
+
const mailer = { send: vi.fn() };
|
|
84
|
+
|
|
85
|
+
afterEach(() => MeghTest.clean());
|
|
86
|
+
|
|
87
|
+
it('sends a welcome mail', async () => {
|
|
88
|
+
const service = MeghTest.getProvider(UserService, [users, mailer]);
|
|
89
|
+
|
|
90
|
+
await service.register('a@example.com');
|
|
91
|
+
|
|
92
|
+
expect(mailer.send).toHaveBeenCalledWith('a@example.com', 'Welcome!');
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
How this works matters:
|
|
97
|
+
|
|
98
|
+
- Every call builds a **new** instance. The stand-ins are used for that
|
|
99
|
+
instance only; nothing is registered in the shared container, so other
|
|
100
|
+
classes and other tests never see them.
|
|
101
|
+
- Parameters you don't pass are resolved from the container as usual.
|
|
102
|
+
- Only constructor parameters are matched. For `inject()` fields, register
|
|
103
|
+
the stand-in with `MeghContainer.set(MailerService, fake)` before resolving
|
|
104
|
+
the class.
|
|
105
|
+
|
|
106
|
+
`MeghTest.clean()` drops every built instance in the container, so the next
|
|
107
|
+
test starts fresh. Values set for tokens and strings are kept. See
|
|
108
|
+
[Testing in Dependency Injection](/core-concept/dependency-injection#testing).
|
|
109
|
+
|
|
110
|
+
::: info Before 0.6.5
|
|
111
|
+
Stand-ins were registered in the shared container, and a class that was
|
|
112
|
+
already built was returned as-is, ignoring them.
|
|
113
|
+
:::
|
|
114
|
+
|
|
115
|
+
## Route tests
|
|
116
|
+
|
|
117
|
+
`MeghTest.from(app)` wraps an app so you can send requests to it. Requests go
|
|
118
|
+
through Fastify's `inject()`, so no port is opened:
|
|
119
|
+
|
|
120
|
+
```ts [test/users.e2e-spec.ts]
|
|
121
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
122
|
+
import { MeghTest, TestApplication } from '@meghjs/core';
|
|
123
|
+
import app from '../src/app';
|
|
124
|
+
|
|
125
|
+
describe('Users API', () => {
|
|
126
|
+
let http: TestApplication;
|
|
127
|
+
|
|
128
|
+
beforeAll(async () => {
|
|
129
|
+
http = MeghTest.from(app);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
afterAll(() => app.close());
|
|
133
|
+
|
|
134
|
+
it('lists users', async () => {
|
|
135
|
+
const res = await http.get('/users');
|
|
136
|
+
|
|
137
|
+
expect(res.statusCode).toBe(200);
|
|
138
|
+
expect(res.json()).toBeInstanceOf(Array);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('rejects an invalid body', async () => {
|
|
142
|
+
const res = await http.post('/users', { payload: { email: 'nope' } });
|
|
143
|
+
|
|
144
|
+
expect(res.statusCode).toBe(400);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
This uses the app exported from `src/app.ts`, so middleware, authentication,
|
|
150
|
+
exception filters and other `use*` settings apply. Keep `app.run()` in
|
|
151
|
+
`src/serve.ts`, as `megh new` does, so importing the app doesn't start it.
|
|
152
|
+
|
|
153
|
+
`TestApplication` has `get`, `post`, `put`, `patch`, `delete` and `options`.
|
|
154
|
+
Each takes a URL and Fastify's inject options (`payload`, `headers`, `query`,
|
|
155
|
+
`cookies`, ...). The response has `statusCode`, `headers`, `body` (a string)
|
|
156
|
+
and `json()`.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
await http.get('/me', { headers: { authorization: `Bearer ${token}` } });
|
|
160
|
+
await http.get('/users', { query: { page: '2' } });
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`http.getController(Controller, deps?)` is the same as
|
|
164
|
+
`MeghTest.getController`.
|
|
165
|
+
|
|
166
|
+
### Just a few controllers
|
|
167
|
+
|
|
168
|
+
`MeghTest.createTestApplication` builds a fresh app with only the controllers
|
|
169
|
+
you list:
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
const http = MeghTest.createTestApplication({ controllers: [UserController] });
|
|
173
|
+
const res = await http.get('/users');
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
It returns only the `TestApplication`, so there is no app to `close()`. Use
|
|
177
|
+
`MeghTest.from(app)` when you need middleware, a database, or teardown.
|
|
178
|
+
|
|
179
|
+
### What `from()` does and doesn't do
|
|
180
|
+
|
|
181
|
+
`MeghTest.from(app)` maps the controllers you passed to `useControllers([...])`
|
|
182
|
+
and installs the error handler. Each request waits until the controllers are
|
|
183
|
+
mapped, and a mapping error (such as a class that isn't an `@ApiController`)
|
|
184
|
+
is thrown by the request. It does not call `run()`, so:
|
|
185
|
+
|
|
186
|
+
- Controllers from `useControllers({ auto: true })` are not found. List them.
|
|
187
|
+
- Inline routes (`app.mapGet`, `app.mapPost`, ...) are not mapped, and return
|
|
188
|
+
404.
|
|
189
|
+
- `onInit` and `onReady` hooks don't run. MeghORM's connection is still
|
|
190
|
+
created, but the startup connection check is skipped.
|
|
191
|
+
- Scheduled tasks don't start.
|
|
192
|
+
- The OpenAPI document and Socket.IO are not set up.
|
|
193
|
+
|
|
194
|
+
Call `from()` once per app, for example in `beforeAll`. Calling it again maps
|
|
195
|
+
the routes a second time, which fails.
|
|
196
|
+
|
|
197
|
+
## Teardown
|
|
198
|
+
|
|
199
|
+
Call `app.close()` after the tests. It closes the Fastify instance, queue
|
|
200
|
+
workers, the cache and the database connection (through the `onClose` hooks),
|
|
201
|
+
so the test process can exit:
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
afterAll(() => app.close());
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## Queues in tests
|
|
208
|
+
|
|
209
|
+
Code that dispatches jobs needs Redis by default. Switch to an in-memory
|
|
210
|
+
[queue driver](/advanced/queue#running-without-redis) instead:
|
|
211
|
+
|
|
212
|
+
| Driver | Behaviour |
|
|
213
|
+
|--------|-----------|
|
|
214
|
+
| `memory` | Jobs run asynchronously in-process and honour `delay` |
|
|
215
|
+
| `sync` | `dispatch()` runs the job before it resolves and ignores `delay` |
|
|
216
|
+
|
|
217
|
+
The driver is picked when a queue is created. If `src/app.ts` calls
|
|
218
|
+
`useWorker([...])`, its queues are created as soon as the app is imported, so
|
|
219
|
+
set the driver in the environment:
|
|
220
|
+
|
|
221
|
+
```ts [vitest.e2e.config.mts]
|
|
222
|
+
import swc from 'unplugin-swc';
|
|
223
|
+
import { defineConfig } from 'vitest/config';
|
|
224
|
+
|
|
225
|
+
export default defineConfig({
|
|
226
|
+
plugins: [swc.vite()],
|
|
227
|
+
test: {
|
|
228
|
+
include: ['test/**/*.e2e-spec.ts'],
|
|
229
|
+
env: { MEGH_QUEUE_DRIVER: 'memory' },
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Otherwise call `setQueueDriver('memory')` before anything resolves the queue.
|
|
235
|
+
With `memory`, wait for jobs to finish and reset between tests:
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
import { resetMemoryQueues, waitForMemoryQueues } from '@meghjs/core';
|
|
239
|
+
|
|
240
|
+
afterEach(() => resetMemoryQueues());
|
|
241
|
+
|
|
242
|
+
it('sends a welcome mail on signup', async () => {
|
|
243
|
+
await http.post('/signup', { payload: { email: 'a@example.com' } });
|
|
244
|
+
await waitForMemoryQueues();
|
|
245
|
+
|
|
246
|
+
expect(mailer.sent).toHaveLength(1);
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
## Environment
|
|
251
|
+
|
|
252
|
+
`MeghTest` doesn't change `NODE_ENV`. Vitest sets it to `test`, which Megh
|
|
253
|
+
treats as production: `app.isDevelopment()` is false and 5xx responses hide
|
|
254
|
+
their message. Assert on status codes rather than 5xx error text.
|
|
255
|
+
|
|
256
|
+
`.env` is loaded in tests the same way as in the app. See
|
|
257
|
+
[Configuration](/core-concept/configuration).
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Views
|
|
3
|
+
description: Server-rendered HTML with Blade-style templates.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Views
|
|
7
|
+
|
|
8
|
+
<!-- v-pre: the page shows {{ }} template syntax, which Vue would otherwise evaluate. -->
|
|
9
|
+
|
|
10
|
+
:::: v-pre
|
|
11
|
+
|
|
12
|
+
Megh ships a template engine modelled on Laravel Blade: `{{ }}` echoes,
|
|
13
|
+
`@if` / `@foreach` directives, layouts, includes, stacks and `<x-component>`
|
|
14
|
+
tags. Templates compile to JavaScript once and are cached, so a render is a
|
|
15
|
+
function call. It has no dependencies.
|
|
16
|
+
|
|
17
|
+
## Setup
|
|
18
|
+
|
|
19
|
+
Point the app at your views folder. It defaults to `<cwd>/views`:
|
|
20
|
+
|
|
21
|
+
```ts [app.ts]
|
|
22
|
+
import path from "path";
|
|
23
|
+
|
|
24
|
+
app.useViews({ root: path.join(process.cwd(), "views") });
|
|
25
|
+
app.getViews().share("appName", "My App"); // available in every view
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
| Option | Default | Meaning |
|
|
29
|
+
| ----------- | -------------------------------------- | ----------------------------------------------------------------------------- |
|
|
30
|
+
| `root` | `<cwd>/views` | Folder holding the views |
|
|
31
|
+
| `extension` | `.megh.html` | Template file extension |
|
|
32
|
+
| `cache` | `false` only in `NODE_ENV=development` | `false` recompiles a file when it changes, so edits show up without a restart |
|
|
33
|
+
| `maxDepth` | `100` | Guard against a view including itself forever |
|
|
34
|
+
|
|
35
|
+
View names use dots: `layouts.app` is `views/layouts/app.megh.html`. Names
|
|
36
|
+
that would leave the views folder (`../secret`) are rejected.
|
|
37
|
+
|
|
38
|
+
`megh new myapp --mvc` sets all of this up with a layout and a home page, and
|
|
39
|
+
`megh make:view pages.about` adds a page. See [CLI](/cli/basic#application).
|
|
40
|
+
|
|
41
|
+
## Returning a view
|
|
42
|
+
|
|
43
|
+
Return `Results.View` (or the `view` shorthand) from a controller or a
|
|
44
|
+
`mapGet` handler. It is sent as `text/html; charset=utf-8`:
|
|
45
|
+
|
|
46
|
+
```ts [controllers/home.controller.ts]
|
|
47
|
+
import { ApiController, Get, Results, view } from "@meghjs/core";
|
|
48
|
+
|
|
49
|
+
@ApiController("/")
|
|
50
|
+
export class HomeController {
|
|
51
|
+
@Get("/")
|
|
52
|
+
index() {
|
|
53
|
+
return Results.View("home", { user: { name: "Ana" }, todos });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
@Get("/gone")
|
|
57
|
+
gone() {
|
|
58
|
+
return view("errors.404", {}, 404).header("cache-control", "no-store");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
app.mapGet("/about", () => view("about"));
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
If a template throws, nothing has been sent yet, so the error goes through the
|
|
66
|
+
normal error handler and the client gets a 500.
|
|
67
|
+
|
|
68
|
+
::: warning Per-request data
|
|
69
|
+
`share()` data is global to the engine, which every request uses. Pass the
|
|
70
|
+
current user, CSRF token and similar values to `Results.View` instead.
|
|
71
|
+
:::
|
|
72
|
+
|
|
73
|
+
You can also render to a string anywhere, for example for an email:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { getViewEngine } from "@meghjs/core";
|
|
77
|
+
|
|
78
|
+
const html = getViewEngine().render("emails.welcome", { user });
|
|
79
|
+
const inline = getViewEngine().renderString("Hi {{ name }}", { name: "Ana" });
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Syntax
|
|
83
|
+
|
|
84
|
+
| Syntax | Meaning |
|
|
85
|
+
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
|
|
86
|
+
| `{{ expr }}` | Echo, HTML-escaped. `expr` is any JS expression |
|
|
87
|
+
| `{!! expr !!}` | Echo raw (unescaped). Only use it on trusted HTML |
|
|
88
|
+
| `{{-- comment --}}` | Removed at compile time, tags inside it included |
|
|
89
|
+
| `@{{ x }}` / `@@if` | Literal `{{ x }}` / `@if` (for Vue/Alpine) |
|
|
90
|
+
| `@if(c)` `@elseif(c)` `@else` `@endif` | Conditionals |
|
|
91
|
+
| `@unless(c)` … `@endunless` | `if (!c)` |
|
|
92
|
+
| `@isset(a.b.c)` … `@endisset` | True if the path exists and isn't null. Never throws. Takes `@else` / `@elseif` |
|
|
93
|
+
| `@foreach(items as item)` / `@foreach(obj as key => value)` | Arrays, Maps, Sets, iterables and plain objects |
|
|
94
|
+
| `loop.index` `.iteration` `.first` `.last` `.count` `.remaining` `.even` `.odd` `.depth` `.parent` | Like Blade's `$loop` |
|
|
95
|
+
| `@for(let i = 0; i < 3; i++)` … `@endfor`, `@while(c)` … `@endwhile` | Plain JS loops |
|
|
96
|
+
| `@break` `@continue` / `@break(cond)` | Loop control |
|
|
97
|
+
| `@js(const x = 1)` / `@js … @endjs` | Raw JS (Blade's `@php`) |
|
|
98
|
+
| `@json(value)` | JSON that's safe inside `<script>` |
|
|
99
|
+
| `@csrf` `@method('PUT')` | Hidden form inputs (`@csrf` reads `csrfToken`), see [Forms](#forms) |
|
|
100
|
+
| `@include('partials.nav', { extra })` | Render another view |
|
|
101
|
+
| `@extends('layouts.app')` | Use a layout |
|
|
102
|
+
| `@section('name')` … `@endsection` / `@section('title', 'Home')` | Define a section |
|
|
103
|
+
| `@yield('name', 'default')` | Print a section |
|
|
104
|
+
| `@section('sidebar')` … `@show` | Define and print at once (inside layouts) |
|
|
105
|
+
| `@parent` | Inside a child section: insert the layout's version |
|
|
106
|
+
| `@push('scripts')` … `@endpush` / `@stack('scripts')` | Collect content from many views |
|
|
107
|
+
| `<x-alert type="error" :count="n">` … `</x-alert>` | Component, `views/components/alert.megh.html` |
|
|
108
|
+
| `<x-slot:title>` … `</x-slot>` | Named slot. The rest is `{{ slot }}` |
|
|
109
|
+
| `@react(props)` … `@endreact` | React component mounted in the browser ([below](#react)) |
|
|
110
|
+
|
|
111
|
+
A directive glued to a word is plain text, which keeps `support@example.com`
|
|
112
|
+
intact: write `done @endif`, not `done@endif`. Only registered directive names
|
|
113
|
+
are recognised, so `@media` in CSS stays as is.
|
|
114
|
+
|
|
115
|
+
## Layouts
|
|
116
|
+
|
|
117
|
+
```html [views/layouts/app.megh.html]
|
|
118
|
+
<!doctype html>
|
|
119
|
+
<html>
|
|
120
|
+
<head>
|
|
121
|
+
<title>@yield('title', 'My App')</title>
|
|
122
|
+
@stack('styles')
|
|
123
|
+
</head>
|
|
124
|
+
<body>
|
|
125
|
+
@include('partials.nav')
|
|
126
|
+
<main>@yield('content')</main>
|
|
127
|
+
@stack('scripts')
|
|
128
|
+
</body>
|
|
129
|
+
</html>
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
```html [views/home.megh.html]
|
|
133
|
+
@extends('layouts.app')
|
|
134
|
+
|
|
135
|
+
@section('title', 'Home')
|
|
136
|
+
|
|
137
|
+
@section('content')
|
|
138
|
+
<h1>Hello, {{ user.name }}</h1>
|
|
139
|
+
|
|
140
|
+
<x-alert type="warning">
|
|
141
|
+
<x-slot:title>Heads up</x-slot>
|
|
142
|
+
You have {{ todos.length }} todos.
|
|
143
|
+
</x-alert>
|
|
144
|
+
|
|
145
|
+
<ul>
|
|
146
|
+
@foreach(todos as todo)
|
|
147
|
+
<li>{{ loop.iteration }}. {{ todo.title }}@if(todo.done) ✓@endif</li>
|
|
148
|
+
@endforeach
|
|
149
|
+
</ul>
|
|
150
|
+
@endsection
|
|
151
|
+
|
|
152
|
+
@push('scripts')
|
|
153
|
+
<script>window.todos = @json(todos);</script>
|
|
154
|
+
@endpush
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
```html [views/components/alert.megh.html]
|
|
158
|
+
<div class="alert alert-{{ type }}">
|
|
159
|
+
@isset(title)<strong>{{ title }}</strong>@endisset {{ slot }}
|
|
160
|
+
</div>
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
The child renders first and fills its sections, then the layout renders and
|
|
164
|
+
`@yield`s them. Anything the child prints outside a section is dropped, as in
|
|
165
|
+
Blade.
|
|
166
|
+
|
|
167
|
+
## React
|
|
168
|
+
|
|
169
|
+
An `@react` block holds a React component written in JSX (or TSX). Megh
|
|
170
|
+
compiles it once, on the server, and the page gets an empty element plus a
|
|
171
|
+
`<script type="module">` that mounts the component in the browser. The
|
|
172
|
+
expression in `@react(...)` becomes the component's props:
|
|
173
|
+
|
|
174
|
+
```html [views/dashboard.megh.html]
|
|
175
|
+
@react({ todos, user: user.name })
|
|
176
|
+
import { useState } from "react";
|
|
177
|
+
|
|
178
|
+
function App({ todos, user }: { todos: Todo[]; user: string }) {
|
|
179
|
+
const [q, setQ] = useState("");
|
|
180
|
+
const shown = todos.filter((t) => t.title.includes(q));
|
|
181
|
+
return (
|
|
182
|
+
<div style={{ padding: 8 }}>
|
|
183
|
+
<input value={q} onChange={(e) => setQ(e.target.value)} />
|
|
184
|
+
<p>{shown.length} todos for {user}</p>
|
|
185
|
+
</div>
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
@endreact
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
- The block must define a component named `App`, or `export default` one.
|
|
192
|
+
- `React` is available without importing it, and `import ... from "react"` works.
|
|
193
|
+
- The block body is not parsed as a template, so `{{ }}` is a JSX style object
|
|
194
|
+
there, not an echo. Server data reaches the component only through props,
|
|
195
|
+
which are serialised with the same escaping as `@json`.
|
|
196
|
+
- Each block is its own island with its own id. A page can have several.
|
|
197
|
+
|
|
198
|
+
Compiling JSX needs `@swc/core`:
|
|
199
|
+
|
|
200
|
+
```sh
|
|
201
|
+
npm install @swc/core
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Where React comes from
|
|
205
|
+
|
|
206
|
+
Bare imports are rewritten to URLs, like an import map. By default React 19
|
|
207
|
+
loads from [esm.sh](https://esm.sh). Change the URLs to self-host, and add
|
|
208
|
+
entries for other packages your components import:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
app.useViews({
|
|
212
|
+
react: {
|
|
213
|
+
imports: {
|
|
214
|
+
react: "/static/vendor/react.mjs",
|
|
215
|
+
"react/jsx-runtime": "/static/vendor/react-jsx-runtime.mjs",
|
|
216
|
+
"react-dom/client": "/static/vendor/react-dom-client.mjs",
|
|
217
|
+
"canvas-confetti": "https://esm.sh/canvas-confetti@1.9.3",
|
|
218
|
+
},
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Relative and absolute URLs (`/static/chart.js`, `https://…`) are left as
|
|
224
|
+
they are. Any other bare import is an error at compile time, because the
|
|
225
|
+
browser could not load it.
|
|
226
|
+
|
|
227
|
+
::: tip
|
|
228
|
+
Islands render in the browser only. The server sends an empty element, so the
|
|
229
|
+
content appears once the scripts load. If your Content Security Policy blocks
|
|
230
|
+
inline scripts, allow them for these pages, for example with a nonce.
|
|
231
|
+
:::
|
|
232
|
+
|
|
233
|
+
## Forms
|
|
234
|
+
|
|
235
|
+
A browser form can only send GET or POST. To reach a PUT, PATCH or DELETE
|
|
236
|
+
route, turn on method override and add `@method()` to the form:
|
|
237
|
+
|
|
238
|
+
```ts [app.ts]
|
|
239
|
+
app.useMethodOverride();
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
```html [views/todos/show.megh.html]
|
|
243
|
+
<form method="post" action="/todos/{{ todo.id }}">
|
|
244
|
+
@csrf
|
|
245
|
+
@method('DELETE')
|
|
246
|
+
<button>Delete</button>
|
|
247
|
+
</form>
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The form POSTs with a hidden `_method` field, and Megh routes the request to
|
|
251
|
+
`@Delete('/:id')`. Only `PUT`, `PATCH` and `DELETE` are accepted, and only from
|
|
252
|
+
the body of a form POST: `application/x-www-form-urlencoded` or
|
|
253
|
+
`multipart/form-data`. A `_method` in a query string or a JSON body is ignored.
|
|
254
|
+
|
|
255
|
+
`useMethodOverride()` also parses urlencoded bodies for `@Body()`, unless you
|
|
256
|
+
registered a parser for that type yourself. The hidden `_method` and `_token`
|
|
257
|
+
fields are removed from the parsed body, so your DTO does not need to declare
|
|
258
|
+
them.
|
|
259
|
+
|
|
260
|
+
### File uploads
|
|
261
|
+
|
|
262
|
+
For a form with a file input, add `enctype="multipart/form-data"`, call
|
|
263
|
+
`app.useMultipart()`, and put `@method()` **before** the file input:
|
|
264
|
+
|
|
265
|
+
```html
|
|
266
|
+
<form method="post" action="/todos/{{ todo.id }}" enctype="multipart/form-data">
|
|
267
|
+
@csrf
|
|
268
|
+
@method('PUT')
|
|
269
|
+
<input name="title" value="{{ todo.title }}">
|
|
270
|
+
<input name="photo" type="file" accept="image/*">
|
|
271
|
+
<button>Save</button>
|
|
272
|
+
</form>
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
@Put('/:id')
|
|
277
|
+
async update(@Param('id') id: number, @Body() body: any, @UploadFile('photo') photo: MultipartFile | null) {
|
|
278
|
+
const title = body.title?.value;
|
|
279
|
+
// ...
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
To find `_method`, Megh reads only the text fields that come before the first
|
|
284
|
+
file, at most 64 KB, and never reads the upload into memory. A `_method` placed
|
|
285
|
+
after a file input is ignored, and the request stays a POST.
|
|
286
|
+
|
|
287
|
+
::: info
|
|
288
|
+
On multipart routes `@Body()` holds the `@fastify/multipart` parts
|
|
289
|
+
(`body.title.value`), and DTO validation does not run. Validate the fields
|
|
290
|
+
yourself; [File Uploads](/advanced/file-uploads) covers saving the file.
|
|
291
|
+
:::
|
|
292
|
+
|
|
293
|
+
## Custom directives
|
|
294
|
+
|
|
295
|
+
A directive returns JavaScript source. Append to `__out` to print, and use
|
|
296
|
+
`__rt.escape()` to escape:
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
app
|
|
300
|
+
.getViews()
|
|
301
|
+
.directive("money", (args) => `__out += __rt.escape(formatMoney(${args}));`);
|
|
302
|
+
// {{-- in a view --}} @money(order.total)
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Scope
|
|
306
|
+
|
|
307
|
+
- **Includes** see the view's data plus the extras you pass, but not variables
|
|
308
|
+
created inside the template. Inside a loop, write
|
|
309
|
+
`@include('row', { row })`.
|
|
310
|
+
- **Components** are isolated: they only see their props and slots.
|
|
311
|
+
- **Stacks** render in order. A `@push` that runs after its `@stack` has
|
|
312
|
+
printed won't appear. A page pushing into its layout works, because the
|
|
313
|
+
child renders first.
|
|
314
|
+
|
|
315
|
+
## Errors
|
|
316
|
+
|
|
317
|
+
Errors name the template and line, with the original error in `err.cause`:
|
|
318
|
+
|
|
319
|
+
```
|
|
320
|
+
TemplateError: ReferenceError: nope is not defined (home:12)
|
|
321
|
+
Unclosed @if (home:4)
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
To see the generated code, use `compileTemplate(src).source`.
|
|
325
|
+
|
|
326
|
+
## Security
|
|
327
|
+
|
|
328
|
+
- **Templates are code.** `{{ }}` runs arbitrary JavaScript. Never compile
|
|
329
|
+
templates written by users.
|
|
330
|
+
- **Escaping is HTML-only.** `{{ }}` is safe in element text and in quoted
|
|
331
|
+
attributes. It is not safe in `href` (`javascript:` URLs; validate them),
|
|
332
|
+
inside `<script>` (use `@json`), in unquoted attributes or in `style`.
|
|
333
|
+
- **Rendering is synchronous.** Load your data before returning the view.
|
|
334
|
+
|
|
335
|
+
::::
|