raiton 5.7.0-beta.5 → 5.9.5-beta.16

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 (46) hide show
  1. package/build/bin/index.mjs +92 -6
  2. package/docs/README.md +131 -0
  3. package/docs/cli/README.md +81 -0
  4. package/docs/cli/commands.md +167 -0
  5. package/docs/cli/hmr.md +121 -0
  6. package/docs/core/README.md +67 -0
  7. package/docs/core/application.md +149 -0
  8. package/docs/core/builder-thread.md +231 -0
  9. package/docs/core/config.md +124 -0
  10. package/docs/core/controller.md +120 -0
  11. package/docs/core/injection.md +226 -0
  12. package/docs/core/middleware.md +172 -0
  13. package/docs/core/plugin-scope.md +171 -0
  14. package/docs/core/router.md +122 -0
  15. package/docs/framework/README.md +96 -0
  16. package/docs/framework/base-classes.md +214 -0
  17. package/docs/framework/decorators/README.md +60 -0
  18. package/docs/framework/decorators/controllable.md +151 -0
  19. package/docs/framework/decorators/injection.md +186 -0
  20. package/docs/framework/decorators/middleware.md +167 -0
  21. package/docs/framework/decorators/openapi.md +254 -0
  22. package/docs/framework/decorators/parametrable.md +248 -0
  23. package/docs/framework/decorators/socket.md +152 -0
  24. package/docs/framework/encryption.md +183 -0
  25. package/docs/framework/env.md +88 -0
  26. package/docs/framework/plugins/README.md +50 -0
  27. package/docs/framework/plugins/body-parser.md +138 -0
  28. package/docs/framework/plugins/openapi.md +217 -0
  29. package/docs/framework/plugins/security.md +159 -0
  30. package/docs/framework/responses.md +180 -0
  31. package/docs/framework/runtime.md +138 -0
  32. package/docs/types/README.md +206 -0
  33. package/package.json +1 -1
  34. package/scripts/update-version.ts +1 -0
  35. package/source/core/application.ts +30 -5
  36. package/source/core/artifacts/artifact.ts +1 -1
  37. package/source/core/router/handler.ts +5 -9
  38. package/source/core/router/handler.utils.ts +1 -2
  39. package/source/framework/constants/decorators.constant.ts +2 -0
  40. package/source/framework/decorators/index.ts +2 -1
  41. package/source/framework/decorators/route-interaction.decorator.ts +188 -0
  42. package/source/framework/decorators/socket.decorator.ts +4 -4
  43. package/source/framework/exceptions/http-exception.ts +17 -0
  44. package/source/types/router.ts +5 -0
  45. package/source/types/thread.ts +4 -1
  46. package/examples/user-controller.example.ts +0 -53
@@ -0,0 +1,67 @@
1
+ # Module Core (`source/core/`)
2
+
3
+ Le noyau de Raiton gère le cycle de vie de l'application, le routage, le middleware, l'injection de dépendances, les plugins et la configuration.
4
+
5
+ > **Navigation :** [← docs/](../README.md) | [↑ Index](../README.md) | [application.md →](application.md)
6
+
7
+ ## Table des matières
8
+
9
+ | Fichier | Description |
10
+ |---------|-------------|
11
+ | [application.md](application.md) | Classe `Application` — configuration, routes, middleware |
12
+ | [router.md](router.md) | Système de routage — `Router`, `RouteMatcher` |
13
+ | [middleware.md](middleware.md) | Pipeline middleware — `MiddlewarePipeline` |
14
+ | [controller.md](controller.md) | Contrôleurs — `ControllerBuilder`, compilation |
15
+ | [injection.md](injection.md) | Injection de dépendances — `Injection`, scopes |
16
+ | [plugin-scope.md](plugin-scope.md) | Système de plugins — `PluginScope` |
17
+ | [config.md](config.md) | Configuration — `RaitonConfig` |
18
+ | [builder-thread.md](builder-thread.md) | Build et thread — `RaitonBuilder`, `RaitonThread` |
19
+
20
+ ```
21
+ core/
22
+ ├── application.ts → Application — point d'entrée de l'app HTTP
23
+ ├── builder.ts → RaitonBuilder — build, serve, HMR
24
+ ├── thread.ts → RaitonThread — cycle de vie, serveur
25
+ ├── context.ts → RequestContext — état de la requête
26
+ ├── raiton.ts → Ration — signaux, thread (statique)
27
+ ├── server.ts → Server — config serveur (singleton)
28
+ ├── hooks.ts → HookStore — hooks de cycle de vie
29
+ ├── guards.ts → RaitonGuards — registre de guards
30
+ ├── commands.ts → RaitonCommands — moissonnage de commandes
31
+ ├── command.ts → RaitonCommand — classe de base CLI
32
+ ├── directories.ts → RaitonDirectories — chemins de travail
33
+ ├── bytes.util.ts → parseBytes, formatBytes
34
+ ├── process.util.ts → until (attente conditionnelle)
35
+ ├── config/
36
+ │ ├── config.ts → RaitonConfig — chargeur de config
37
+ │ └── define.ts → defineConfig — builder depuis package.json
38
+ ├── controller/
39
+ │ ├── metadata.ts → getControllerMetadata
40
+ │ ├── compiler.ts → compileController
41
+ │ └── builder.ts → ControllerBuilder
42
+ ├── router/
43
+ │ ├── router.ts → Router
44
+ │ ├── route.ts → Route
45
+ │ ├── matcher.ts → RouteMatcher
46
+ │ ├── handler.ts → createHandler
47
+ │ └── handler.utils.ts → collecte d'arguments, validation
48
+ ├── middleware/
49
+ │ ├── compose.ts → middlewareCompose (Koa-style)
50
+ │ └── pipeline.ts → MiddlewarePipeline
51
+ ├── plugins/
52
+ │ ├── plugin.ts → definePlugin
53
+ │ └── scope.ts → PluginScope
54
+ ├── injection/
55
+ │ └── injection.ts → Injection (conteneur DI)
56
+ ├── socket/
57
+ │ └── metadata.ts → getSocketMetadata
58
+ ├── artifacts/
59
+ │ ├── artifact.ts → Artifact
60
+ │ └── runner.ts → artifactRunner (stub)
61
+ └── helpers/
62
+ └── raiton.ts → helper raiton (stub)
63
+ ```
64
+
65
+ ---
66
+
67
+ [← docs/](../README.md) | [↑ Index](../README.md) | [application.md →](application.md)
@@ -0,0 +1,149 @@
1
+ # `Application`
2
+
3
+ **Fichier :** `source/core/application.ts`
4
+ **Import :** `import { Application } from "raiton/core"`
5
+
6
+ > **Navigation :** [← core/](README.md) | [↑ core/](README.md) | [router.md →](router.md)
7
+
8
+ La classe `Application` est le point d'entrée principal pour configurer et exécuter votre application HTTP.
9
+
10
+ ## Constructeur
11
+
12
+ ```typescript
13
+ const app = new Application({
14
+ port: 3000, // Port d'écoute (défaut: 5712)
15
+ hostname: "0.0.0.0", // Hôte (défaut: "localhost")
16
+ protocole: "http", // Protocole (défaut: "http")
17
+ pathname: "/", // Chemin racine
18
+ prefix: "/api", // Préfixe global des routes
19
+ develop: false, // Mode développement (stack traces)
20
+ verbose: false, // Logs détaillés
21
+ workdir: process.cwd(), // Répertoire de travail
22
+ })
23
+ ```
24
+
25
+ ## Propriétés
26
+
27
+ | Propriété | Type | Description |
28
+ |-----------|------|-------------|
29
+ | `config` | `ApplicationConfigInterface` | Configuration fournie au constructeur |
30
+ | `version` | `string` | Version depuis `RaitonConfig` ou `"0.0.1"` |
31
+ | `hostname` | `string` (getter) | URL complète calculée (`http://localhost:3000/`) |
32
+
33
+ ## Méthodes
34
+
35
+ ### `setOption(key, value)` / `setOptions(options)`
36
+
37
+ Modifier la configuration après instanciation :
38
+
39
+ ```typescript
40
+ app.setOption("port", 4000)
41
+ app.setOptions({ port: 4000, verbose: true })
42
+ ```
43
+
44
+ ### `register(plugin)`
45
+
46
+ Enregistrer un plugin :
47
+
48
+ ```typescript
49
+ app.register(monPlugin)
50
+ app.register({ name: "mon-plugin", setup: (scope) => { /* ... */ } })
51
+ ```
52
+
53
+ Un plugin est un objet avec une méthode `setup(scope: PluginScope)`. Voir [plugin-scope.md](plugin-scope.md).
54
+
55
+ ### `use(mw)`
56
+
57
+ Ajouter un middleware global :
58
+
59
+ ```typescript
60
+ app.use(async ({ context, next }) => {
61
+ console.log(`Requête: ${context.req.method} ${context.req.url}`)
62
+ await next()
63
+ })
64
+ ```
65
+
66
+ ### `get(path, handler, version?)` / `post()` / `put()` / `patch()` / `delete()` / `options()` / `head()` / `trace()`
67
+
68
+ Déclarer une route manuellement :
69
+
70
+ ```typescript
71
+ app.get("/health", async (ctx) => {
72
+ return { status: "ok" }
73
+ })
74
+
75
+ app.post("/users", async (ctx) => {
76
+ const { name, email } = ctx.req.body
77
+ return { id: 1, name, email }
78
+ }, "v2") // version optionnelle
79
+ ```
80
+
81
+ ### `handle(req, reply)`
82
+
83
+ Point d'entrée du traitement des requêtes. Appelé par le runtime. Déconseillé en usage direct.
84
+
85
+ ```typescript
86
+ // Usage interne uniquement
87
+ const response = await app.handle(incomingRequest, serverResponse)
88
+ ```
89
+
90
+ ## Flux de traitement d'une requête
91
+
92
+ ```
93
+ app.handle(req, reply)
94
+ │
95
+ ├─ 1. Création de RequestContext
96
+ ├─ 2. Hook 'onRequest'
97
+ ├─ 3. MiddlewarePipeline.run(ctx, handler)
98
+ │ ├─ bodyParserPlugin (parsing body automatique)
99
+ │ ├─ Security plugins (CORS, headers...)
100
+ │ └─ middlewares personnalisés
101
+ ├─ 4. Router.match(method, pathname)
102
+ │ └─ Si non trouvé → 404
103
+ ├─ 5. Exécution du handler de route
104
+ │ ├─ Paramètres injectés (@Param, @Query, @Body...)
105
+ │ ├─ Validation DTO si applicable
106
+ │ └─ Réponse → reply.send()
107
+ └─ 6. Hook 'onResponse'
108
+ ```
109
+
110
+ ## Exemple complet
111
+
112
+ ```typescript
113
+ import "reflect-metadata"
114
+ import { Application } from "raiton/core"
115
+ import { ThreadInterface } from "raiton/types"
116
+
117
+ export default async function (thread: ThreadInterface) {
118
+ const app = new Application({
119
+ port: 3000,
120
+ prefix: "/api",
121
+ verbose: true,
122
+ })
123
+
124
+ // Middleware global
125
+ app.use(async ({ context, next }) => {
126
+ const start = Date.now()
127
+ await next()
128
+ const ms = Date.now() - start
129
+ context.reply.header("X-Response-Time", `${ms}ms`)
130
+ })
131
+
132
+ // Routes manuelles
133
+ app.get("/ping", () => ({ pong: true }))
134
+ app.post("/echo", (ctx) => ctx.req.body)
135
+
136
+ return await thread.setup({ application: app }).run()
137
+ }
138
+ ```
139
+
140
+ ## Accès statique au conteneur DI
141
+
142
+ ```typescript
143
+ Application.container === Injection // Vrai
144
+ Application.container.get("monService")
145
+ ```
146
+
147
+ ---
148
+
149
+ [← core/](README.md) | [↑ core/](README.md) | [router.md →](router.md)
@@ -0,0 +1,231 @@
1
+ # Builder et Thread
2
+
3
+ **Fichiers :** `source/core/builder.ts`, `source/core/thread.ts`
4
+ **Import :** `import { RaitonBuilder, RaitonThread } from "raiton/core"`
5
+
6
+ > **Navigation :** [← config.md](config.md) | [↑ core/](README.md)
7
+
8
+ ## `RaitonBuilder`
9
+
10
+ Orchestre le build et le serve de l'application.
11
+
12
+ ```typescript
13
+ class RaitonBuilder {
14
+ readonly workdir: string
15
+ readonly options: BuilderConfigInterface
16
+
17
+ source: string | null // Dossier source (ex: ./source)
18
+ out: string | null // Dossier de sortie (ex: .raiton/server/)
19
+ bootstrapper: string | null // Chemin du fichier de bootstrap
20
+ bootstrapperFile: string | null // Nom du fichier de bootstrap
21
+ watcher: fs.FSWatcher | undefined // Watcher HMR
22
+ }
23
+ ```
24
+
25
+ ### `builder.prepare()`
26
+
27
+ Initialise les chemins et active le HMR si demandé :
28
+
29
+ ```typescript
30
+ async prepare(): Promise<this> {
31
+ 1. initialize() → résout source, out, bootstrapper
32
+ 2. Si options.hmr && options.serve:
33
+ - Écoute le signal 'hmr:controller'
34
+ - Active le watcher sur le dossier source
35
+ }
36
+ ```
37
+
38
+ **Résolution des chemins :**
39
+
40
+ ```typescript
41
+ source = path.resolve(workdir, RaitonConfig.get('rootDir') || './')
42
+ out = path.resolve(workdir, RaitonDirectories.server(workdir)) // .raiton/server/
43
+ bootstrapper = path.join(source, RaitonDirectories.bootstrapFile) // main.ts
44
+ ```
45
+
46
+ ### `builder.boot()`
47
+
48
+ Point d'entrée principal. Importe le bootstrapper et exécute :
49
+
50
+ ```typescript
51
+ async boot(): Promise<any> {
52
+ 1. import du bootstrapper (main.ts)
53
+ 2. Création de RaitonThread
54
+ 3. Exécution du bootstrapper → app = await bootstrapper.default(thread)
55
+ 4. Si pas en mode serve → builder.build(thread) (compile avec tsc)
56
+ }
57
+ ```
58
+
59
+ ### `builder.build(thread)`
60
+
61
+ Compile l'application avec TypeScript :
62
+
63
+ ```typescript
64
+ execSync(`npx tsc -p tsconfig.json --outDir ${out} --noEmit`)
65
+ ```
66
+
67
+ Note : utilise `--noEmit` — la compilation réelle est faite par le script npm `build`.
68
+
69
+ ### Watcher HMR
70
+
71
+ ```typescript
72
+ protected watching(): this {
73
+ this._watcher = watch(this._source, { recursive: true }, (event, relativePath) => {
74
+ if (this._source && relativePath) {
75
+ this.parse(path.join(this._source, relativePath))
76
+ }
77
+ })
78
+ }
79
+
80
+ protected async parse(filename: string) {
81
+ if (isControllerArtifact(filename)) {
82
+ Raiton.signals.dispatch('hmr:controller', {filename, ...})
83
+ }
84
+ if (Artifacts.is(filename)) {
85
+ Artifacts.reload(await import(`${filename}?v=${version}&t=${timestamp}`), filename)
86
+ }
87
+ }
88
+ ```
89
+
90
+ ### Utilisation typique
91
+
92
+ ```typescript
93
+ // Mode développement
94
+ const builder = new RaitonBuilder(process.cwd(), {
95
+ serve: true,
96
+ hmr: true,
97
+ })
98
+ await builder.prepare()
99
+ await builder.boot()
100
+
101
+ // Mode build seul
102
+ const builder = new RaitonBuilder(process.cwd())
103
+ await builder.boot() // compile sans démarrer le serveur
104
+ ```
105
+
106
+ ## `RaitonThread`
107
+
108
+ Gère le cycle de vie du serveur HTTP.
109
+
110
+ ```typescript
111
+ class RaitonThread {
112
+ static current: RaitonThread | null // Instance courante
113
+ application: ApplicationInterface | null
114
+ runtime: RuntimeAdapterInterface | null
115
+ runtimeServer: RuntimeServerInterface | null
116
+ readonly appDir: string // process.cwd()
117
+ }
118
+ ```
119
+
120
+ ### `thread.setup({application, runtime})`
121
+
122
+ Configure le thread avant le démarrage :
123
+
124
+ ```typescript
125
+ thread.setup({
126
+ application: app,
127
+ runtime: RuntimeType.Bun, // ou RuntimeType.Node (détection auto si omis)
128
+ })
129
+
130
+ // Détection automatique :
131
+ const defaultRuntime = typeof Bun !== 'undefined' ? RuntimeType.Bun : RuntimeType.Node
132
+ ```
133
+
134
+ **Effets :**
135
+ 1. Crée l'adaptateur runtime (`Bun.serve` ou `node:http`)
136
+ 2. Enregistre `bodyParserPlugin()` dans l'application
137
+ 3. Sauvegarde la référence de l'application
138
+
139
+ ### `thread.run()`
140
+
141
+ Démarre l'application :
142
+
143
+ ```typescript
144
+ async run(): Promise<this> {
145
+ 1. ControllerBuilder.scan(source) → scanne et compile les contrôleurs
146
+ 2. Si options.serve :
147
+ - Écoute SIGINT/SIGTERM → stop()
148
+ - Crée le serveur : runtime.createServer(application.handle)
149
+ - Démarre l'écoute : listen(port, hostname)
150
+ - Affiche les URLs d'accès (localhost + LAN)
151
+ }
152
+ ```
153
+
154
+ ### `thread.stop()`
155
+
156
+ Arrête proprement l'application :
157
+
158
+ ```typescript
159
+ async stop(): Promise<void> {
160
+ await Injection.shutdown() // Appelle onUnmount() sur toutes les instances
161
+ process.exit(0)
162
+ }
163
+ ```
164
+
165
+ ### `thread.restart()`
166
+
167
+ Envoie un signal de redémarrage au processus parent :
168
+
169
+ ```typescript
170
+ restart(): void {
171
+ process.send?.(EventMessageEnum.RESTART)
172
+ }
173
+ ```
174
+
175
+ ### `thread.sleep(ms)` / `thread.wait(condition)`
176
+
177
+ Utilitaires d'attente :
178
+
179
+ ```typescript
180
+ await thread.sleep(1000) // Attend 1 seconde
181
+ await thread.wait(() => fileExists) // Attend qu'une condition soit vraie
182
+ ```
183
+
184
+ ### Accès statique
185
+
186
+ ```typescript
187
+ if (RaitonThread.current) {
188
+ console.log("Thread actif")
189
+ }
190
+ ```
191
+
192
+ ## Exemple complet : cycle de vie
193
+
194
+ ```typescript
195
+ import "reflect-metadata"
196
+ import { Application, RaitonBuilder, RaitonThread } from "raiton/core"
197
+ import { ThreadInterface } from "raiton/types"
198
+
199
+ // 1. Définition du bootstrapper (source/main.ts)
200
+ export default async function (thread: ThreadInterface) {
201
+ const app = new Application({ port: 3000 })
202
+ return await thread.setup({ application: app }).run()
203
+ }
204
+ ```
205
+
206
+ ```typescript
207
+ // 2. Ce qu'il se passe dans le CLI
208
+ const builder = new RaitonBuilder(process.cwd(), {
209
+ serve: true,
210
+ hmr: true, // Mode dev
211
+ })
212
+
213
+ await builder.prepare()
214
+ // → RaitonConfig.sync()
215
+ // → Résout source, out, bootstrapper
216
+ // → Active le watcher
217
+
218
+ await builder.boot()
219
+ // → Import de main.ts
220
+ // → RaitonThread créé
221
+ // → bootstrapper.default(thread)
222
+ // → new Application()
223
+ // → thread.setup({ application })
224
+ // → thread.run()
225
+ // → ControllerBuilder.scan()
226
+ // → HTTP Server listen(3000)
227
+ ```
228
+
229
+ ---
230
+
231
+ [← config.md](config.md) | [↑ core/](README.md)
@@ -0,0 +1,124 @@
1
+ # Configuration
2
+
3
+ **Fichiers :** `source/core/config/`
4
+ **Import :** `import { RaitonConfig, defineConfig } from "raiton/core"`
5
+
6
+ > **Navigation :** [← plugin-scope.md](plugin-scope.md) | [↑ core/](README.md) | [builder-thread.md →](builder-thread.md)
7
+
8
+ ## `RaitonConfig`
9
+
10
+ Charge la configuration depuis un fichier `raiton.config.json` ou `raiton.config.js`/`.mjs` situé à la racine du projet.
11
+
12
+ ```typescript
13
+ class RaitonConfig {
14
+ static current: Map<keyof ConfigurableInterface, any>
15
+ static get<K>(key: K): ConfigurableInterface[K] | undefined
16
+ static sync(workdir: string): Promise<Map<...>>
17
+ }
18
+ ```
19
+
20
+ ### `RaitonConfig.sync(workdir)`
21
+
22
+ Charge la configuration de manière asynchrone. Appelée automatiquement par le bootstrapper.
23
+
24
+ **Ordre de chargement :**
25
+
26
+ 1. Cherche `raiton.config.json` dans le répertoire de travail
27
+ 2. Si non trouvé, cherche `raiton.config.js` puis `raiton.config.mjs`
28
+ 3. Fusionne avec la configuration par défaut
29
+
30
+ **Configuration par défaut :**
31
+
32
+ ```typescript
33
+ {
34
+ rootDir: ".",
35
+ version: "0.0.1"
36
+ }
37
+ ```
38
+
39
+ ### `RaitonConfig.get(key)`
40
+
41
+ ```typescript
42
+ const rootDir = RaitonConfig.get("rootDir") // "./" par défaut
43
+ const version = RaitonConfig.get("version") // "0.0.1" par défaut
44
+ const port = RaitonConfig.get("port") // Défini dans le fichier
45
+ ```
46
+
47
+ ### Fichier JSON (`raiton.config.json`)
48
+
49
+ ```json
50
+ {
51
+ "rootDir": "./source",
52
+ "version": "1.0.0",
53
+ "port": 3000,
54
+ "hostname": "0.0.0.0",
55
+ "protocole": "http",
56
+ "pathname": "/",
57
+ "artifacts": {
58
+ "types": ["controller", "socket", "service"]
59
+ }
60
+ }
61
+ ```
62
+
63
+ ### Fichier JS (`raiton.config.js`)
64
+
65
+ ```javascript
66
+ export default {
67
+ rootDir: "./source",
68
+ version: "1.0.0",
69
+ port: 3000,
70
+ artifacts: {
71
+ types: ["controller", "socket"],
72
+ },
73
+ }
74
+ ```
75
+
76
+ ## `defineConfig`
77
+
78
+ Utilitaire pour construire la configuration à partir de `package.json` :
79
+
80
+ ```typescript
81
+ import { defineConfig } from "raiton/core"
82
+
83
+ defineConfig({
84
+ // Inspecte package.json pour extraire version, name, etc.
85
+ rootDir: "./app",
86
+ })
87
+ ```
88
+
89
+ ## Interface `ConfigurableInterface`
90
+
91
+ ```typescript
92
+ interface ConfigurableInterface {
93
+ rootDir?: string
94
+ version?: string
95
+ port?: number
96
+ hostname?: string
97
+ protocole?: string
98
+ pathname?: string
99
+ artifacts?: {
100
+ types: string[]
101
+ }
102
+ }
103
+ ```
104
+
105
+ ## Utilisation typique
106
+
107
+ ```bash
108
+ .
109
+ ├── raiton.config.json ← Configuration Raiton
110
+ ├── package.json
111
+ └── source/ ← rootDir par défaut
112
+ ```
113
+
114
+ ```typescript
115
+ // Le bootstrapper appelle automatiquement :
116
+ await RaitonConfig.sync(process.cwd())
117
+
118
+ // Ensuite, l'application peut lire la config :
119
+ const rootDir = RaitonConfig.get("rootDir") // "./source"
120
+ ```
121
+
122
+ ---
123
+
124
+ [← plugin-scope.md](plugin-scope.md) | [↑ core/](README.md) | [builder-thread.md →](builder-thread.md)
@@ -0,0 +1,120 @@
1
+ # Contrôleurs
2
+
3
+ **Fichiers :** `source/core/controller/`
4
+ **Import :** `import { ControllerBuilder, compileController, getControllerMetadata } from "raiton/core"`
5
+
6
+ > **Navigation :** [← middleware.md](middleware.md) | [↑ core/](README.md) | [injection.md →](injection.md)
7
+
8
+ ## `compileController`
9
+
10
+ Compile un contrôleur décoré en routes enregistrées dans l'application.
11
+
12
+ ```typescript
13
+ compileController(HelloController, app)
14
+ // 1. Résout l'instance via Injection.resolve(HelloController)
15
+ // 2. Lit les métadonnées du contrôleur (getControllerMetadata)
16
+ // 3. Pour chaque route décorée :
17
+ // - Combine le préfixe du contrôleur + chemin de la route
18
+ // - Crée le handler via createHandler
19
+ // - Enregistre dans l'application via app.route()
20
+ ```
21
+
22
+ ### Fonctionnement interne
23
+
24
+ ```typescript
25
+ // Ce qu'il se passe quand vous appelez compileController(HelloController, app) :
26
+ const instance = Injection.resolve(HelloController)
27
+ const metadata = getControllerMetadata(HelloController.prototype)
28
+
29
+ for (const route of metadata.routes) {
30
+ app.route(
31
+ route.method,
32
+ `${metadata.prefix}${route.path}`,
33
+ createHandler(instance, route, metadata),
34
+ )
35
+ }
36
+ ```
37
+
38
+ ## `ControllerBuilder`
39
+
40
+ Scanne et compile tous les contrôleurs d'un répertoire.
41
+
42
+ ```typescript
43
+ class ControllerBuilder {
44
+ static scan(source: string): Promise<void>
45
+ static build(options: { filename: string; version: number; timestamp: number }): Promise<void>
46
+ }
47
+ ```
48
+
49
+ ### `ControllerBuilder.scan(directory)`
50
+
51
+ Parcourt récursivement un dossier et compile tous les contrôleurs trouvés :
52
+
53
+ ```typescript
54
+ // Appelé automatiquement par RaitonThread.run()
55
+ await ControllerBuilder.scan("./source")
56
+ // Parcourt tous les fichiers, détecte les contrôleurs via les métadonnées
57
+ // Les compile et enregistre leurs routes dans l'application courante
58
+ ```
59
+
60
+ ### `ControllerBuilder.build()`
61
+
62
+ Recompile un seul contrôleur (utilisé par le HMR lors d'un changement de fichier) :
63
+
64
+ ```typescript
65
+ // Appelé par le watcher HMR via le signal 'hmr:controller'
66
+ await ControllerBuilder.build({
67
+ filename: "./source/controllers/user.controller.ts",
68
+ version: 2,
69
+ timestamp: 1700000000000,
70
+ })
71
+ ```
72
+
73
+ ## `getControllerMetadata`
74
+
75
+ Accède ou crée les métadonnées d'un contrôleur :
76
+
77
+ ```typescript
78
+ import { getControllerMetadata } from "raiton/core"
79
+
80
+ function getControllerMetadata(target: any): ControllerMetaInterface
81
+ ```
82
+
83
+ ```typescript
84
+ interface ControllerMetaInterface {
85
+ prefix: string // Préfixe de route (ex: "/users")
86
+ routes: RouteMetaInterface[] // Routes déclarées
87
+ middlewares: Record<string, any> // Middlewares attachés
88
+ }
89
+ ```
90
+
91
+ ## Cycle de vie complet
92
+
93
+ ```typescript
94
+ // 1. Définition du contrôleur avec décorateurs
95
+ @Controllable("/users")
96
+ export class UserController {
97
+ @Get("/:id")
98
+ getUser(@Param("id") id: string) {
99
+ return { id }
100
+ }
101
+ }
102
+
103
+ // 2. Au démarrage, RaitonThread.run() appelle ControllerBuilder.scan()
104
+ // 3. Pour chaque contrôleur trouvé, compileController() est appelé
105
+ // 4. Injection.resolve() crée une instance (singleton ou transient selon @Injectable)
106
+ // 5. Les routes sont enregistrées dans le router de l'application
107
+ ```
108
+
109
+ ## Détection des fichiers contrôleurs
110
+
111
+ La fonction utilitaire `isControllerArtifact(filename)` du framework détermine si un fichier est un contrôleur :
112
+
113
+ ```typescript
114
+ isControllerArtifact("user.controller.ts") // true
115
+ isControllerArtifact("user.service.ts") // false
116
+
117
+ ---
118
+
119
+ [← middleware.md](middleware.md) | [↑ core/](README.md) | [injection.md →](injection.md)
120
+ ```