raiton 5.9.5-beta.16 → 6.0.0-beta.1

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.
@@ -4817,7 +4817,7 @@ var {
4817
4817
  Help
4818
4818
  } = import__.default;
4819
4819
  // package.json
4820
- var version = "5.9.5-beta.16";
4820
+ var version = "6.0.0-beta.1";
4821
4821
 
4822
4822
  // source/bin/cli.ts
4823
4823
  var CLI = new Command;
@@ -6261,6 +6261,7 @@ var METADATA_KEYS = {
6261
6261
  API_TAGS: Symbol("api:tags"),
6262
6262
  API_OPERATION: Symbol("api:operation"),
6263
6263
  API_SECURITY: Symbol("api:security"),
6264
+ API_PROPERTY: Symbol("api:property"),
6264
6265
  ROUTE_INTERACTION: Symbol("route:interaction")
6265
6266
  };
6266
6267
  // source/framework/responses/http.ts
@@ -6738,6 +6739,9 @@ class Injection {
6738
6739
  return this.get(name);
6739
6740
  }
6740
6741
  }
6742
+ // source/core/socket/metadata.ts
6743
+ var import_reflect_metadata3 = __toESM(require_Reflect2(), 1);
6744
+ var registry = new Map;
6741
6745
  // source/framework/plugins/body-parser.plugin.ts
6742
6746
  function bodyParserPlugin() {
6743
6747
  return {
@@ -6890,8 +6894,6 @@ function decode(data) {
6890
6894
  return data;
6891
6895
  return new TextDecoder().decode(data);
6892
6896
  }
6893
- // source/core/socket/metadata.ts
6894
- var import_reflect_metadata3 = __toESM(require_Reflect2(), 1);
6895
6897
  // source/framework/decorators/routable.decorator.ts
6896
6898
  function stabilizeRoute(meta, { path: path3, method, propertyKey }) {
6897
6899
  return {
package/docs/README.md CHANGED
@@ -118,14 +118,26 @@ bun raiton dev
118
118
  | `raiton/types/*` | `source/types/*.ts` |
119
119
  | `raiton/commands/*` | `source/commands/*.ts` |
120
120
 
121
- ## Conventions de commits
122
-
123
- | Préfixe | Domaine |
124
- |---------|---------|
125
- | `core:` | Noyau (Application, Router, DI, etc.) |
126
- | `framework:` | Décorateurs, runtime, plugins |
127
- | `cli:` | Ligne de commande |
128
- | `docs:` | Documentation |
129
- | `types:` | Définitions de types |
130
- | `fix:` | Correction de bug |
131
- | `chore:` | Maintenance |
121
+ ### Fonctionnalités
122
+ Il faut toujours prioriser sur l'existant des fonctionnalités existantes avant de créer de nouvelles fonctionnalités.
123
+
124
+ ### Commits
125
+ Les commits doivent être des commits logiques séparés par domaine, par fonctionnalité ou par objectif dans l'ordre de modifications des fichiers.
126
+ Utiliser les préfixes suivants :
127
+
128
+ | Préfixe | Usage |
129
+ |------------------|-------|
130
+ | `feat` | Nouvelle fonctionnalité |
131
+ | `fix` | Correction de bug |
132
+ | `breaking change`| Changement cassant (rétro-incompatible) |
133
+ | `release` | Préparation de release |
134
+ | `upgrade` | Mise à jour de dépendances |
135
+ | `update` | Mise à jour de code existant (sans ajout de fonctionnalité) |
136
+ | `add` | Ajout de code mineur (logs, helpers, fichiers de config) |
137
+ | `refactor` | Refactoring sans changement de comportement |
138
+ | `chore` | Tâches internes (build, config, CI, workspace) |
139
+ | `docs` | Documentation uniquement |
140
+ | `remove` | Suppression de code ou de fichiers |
141
+ | `deprecate` | Marquage d'une fonctionnalité comme dépréciée |
142
+
143
+ Executer ```bun run version``` pour mettre à jour la version de l'application automatiquement
@@ -141,11 +141,39 @@ interface SocketMetaInterface {
141
141
  }
142
142
  ```
143
143
 
144
+ Utilisez `getSocketMetadata(target)` de `source/core/socket/metadata.ts` pour lire les métadonnées d'une classe socket.
145
+
144
146
  ## Notes
145
147
 
146
- - La fonctionnalité socket est en développement — le runtime sous-jacent est à implémenter
147
- - Les décorateurs stockent les métadonnées mais le traitement effectif dépendra de l'adaptateur socket
148
- - Utilisez `getSocketMetadata(target)` de `source/core/socket/metadata.ts` pour lire les métadonnées
148
+ - Le runtime socket est implémenté pour l'adaptateur **Bun** (`source/framework/runtime/bun/server.ts`). Les requests avec l'en-tête `Upgrade: websocket` sont routées vers le namespace socket correspondant ; les autres restent traitées par le router HTTP.
149
+ - Le namespace est matché sur le `pathname` de la request. Le préfixe d'application (`prefix`, ex. `/api`) est automatiquement pris en compte : `ws://host/notifications` et `ws://host/api/notifications` atteignent tous deux un socket enregistré sur `/notifications`.
150
+ - Une **instance transiente** de la classe socket est créée par connexion via le conteneur d'injection : chaque client possède son propre état. La même instance reçoit `connect`, `message` et `disconnect`.
151
+ - Les artifacts `.socket.ts` sont scannés automatiquement au boot (comme les contrôleurs) et rechargés en HMR.
152
+
153
+ ### Protocole de messages
154
+
155
+ Le client envoie des trames JSON `{ event, data }` :
156
+
157
+ ```typescript
158
+ ws.send(JSON.stringify({
159
+ event: 'mon-evenement',
160
+ data: { cle: 'valeur' }
161
+ }))
162
+ ```
163
+
164
+ - `event` : nom de l'événement (`@OnSocketEvent(name)`) ou du message (`@OnSocketMessage(name)`).
165
+ - `data` : payload passé au handler.
166
+ - Sans champ `event`, la trame est routée vers un handler de type `message` (payload brut).
167
+
168
+ Si un handler **retourne une valeur** (par ex. `RaitonResponses(...)`), le runtime l'envoie automatiquement au client sous forme de trame JSON.
169
+
170
+ | Cas | Comportement |
171
+ |-----|--------------|
172
+ | Événement trouvé | Appel du handler, réponse éventuelle renvoyée au client |
173
+ | Événement inconnu | Réponse `{ statusCode: 404, message: "Socket event \"...\" not found", data: null }` |
174
+ | Erreur dans le handler | Réponse `{ statusCode: 500, message: "Internal server error", data: null }` |
175
+
176
+ ### Métadonnées socket
149
177
 
150
178
  ---
151
179
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "raiton",
3
- "version": "5.9.5-beta.16",
3
+ "version": "6.0.0-beta.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Modular TypeScript Backend Framework with Dependency Injection, Plugins, Controllers, Middleware and Hot Reloading.",
@@ -5,7 +5,7 @@ import fs, {WatchEventType} from "node:fs";
5
5
  import type {BuilderConfigInterface, BuilderInterface, ThreadInterface,} from "../types";
6
6
  import {RaitonThread} from "./thread";
7
7
  import {Raiton} from "./raiton";
8
- import {isControllerArtifact} from "../framework";
8
+ import {isControllerArtifact, isSocketArtifact} from "../framework";
9
9
  import {ControllerBuilder} from "./controller";
10
10
  import {watch} from "fs";
11
11
  import {LBadge, Logger} from "@protorians/logger";
@@ -66,6 +66,10 @@ export class RaitonBuilder implements BuilderInterface {
66
66
  Raiton.signals.dispatch('hmr:controller', payload)
67
67
  }
68
68
 
69
+ if (isSocketArtifact(filename)) {
70
+ Raiton.signals.dispatch('hmr:socket', payload)
71
+ }
72
+
69
73
  if (Artifacts.is(filename))
70
74
  Artifacts.reload(
71
75
  await import(`${filename}?v=${payload.version || 1}&t=${payload.timestamp || Date.now()}`),
@@ -125,6 +129,12 @@ export class RaitonBuilder implements BuilderInterface {
125
129
  await ControllerBuilder.build({filename, version, timestamp})
126
130
  }
127
131
  )
132
+ Raiton.signals.listen(
133
+ 'hmr:socket',
134
+ async ({filename, version, timestamp}) => {
135
+ await ControllerBuilder.build({filename, version, timestamp})
136
+ }
137
+ )
128
138
  // this.parsing();
129
139
  this.watching();
130
140
  }
@@ -2,9 +2,10 @@ import fs from "node:fs";
2
2
  import {BuilderHMRDeclarationInterface} from "../../types";
3
3
  import {LBadge, Logger} from "@protorians/logger";
4
4
  import {compileController} from "./compiler";
5
+ import {compileSocket} from "../socket/builder";
5
6
  import {RaitonThread} from "../thread";
6
7
  import {Injection} from "../injection";
7
- import {isControllerArtifact} from "../../framework";
8
+ import {isControllerArtifact, isSocketArtifact} from "../../framework";
8
9
  import path from "node:path";
9
10
 
10
11
  export class ControllerBuilder {
@@ -22,19 +23,26 @@ export class ControllerBuilder {
22
23
  }
23
24
 
24
25
  static async build<T>({filename, version, timestamp}: BuilderHMRDeclarationInterface): Promise<T | undefined> {
25
- if (!isControllerArtifact(filename))
26
+ const isController = isControllerArtifact(filename);
27
+ const isSocket = isSocketArtifact(filename);
28
+
29
+ if (!isController && !isSocket)
26
30
  return undefined;
27
31
 
28
32
  const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
29
- const controller = imported.default || imported || undefined;
33
+ const artifact = imported.default || imported || undefined;
30
34
 
31
- if (!controller) return undefined;
35
+ if (!artifact) return undefined;
32
36
  if (!RaitonThread.current?.application) return undefined;
33
37
 
34
- const compilated = compileController(controller, RaitonThread.current.application);
35
- const name = controller.name || (typeof controller === 'function' ? controller.name : undefined);
38
+ const name = artifact.name || (typeof artifact === 'function' ? artifact.name : undefined);
36
39
  if (name) Injection.registerArtifactPath(name, filename);
37
40
 
41
+ if (isSocket) {
42
+ return compileSocket(artifact) as any;
43
+ }
44
+
45
+ const compilated = compileController(artifact, RaitonThread.current.application);
38
46
  return compilated;
39
47
  }
40
48
 
@@ -0,0 +1,5 @@
1
+ import {registerSocket} from "./metadata";
2
+
3
+ export function compileSocket(SocketClass: any) {
4
+ return registerSocket(SocketClass);
5
+ }
@@ -1 +1,2 @@
1
1
  export * from "./metadata"
2
+ export * from "./builder"
@@ -1,7 +1,15 @@
1
- import {SocketMetaInterface} from "../../types";
1
+ import {ConstructorType, SocketMetaInterface} from "../../types";
2
2
  import {METADATA_KEYS} from "../../framework";
3
3
  import "reflect-metadata";
4
4
 
5
+ export interface SocketRegistryEntryInterface {
6
+ namespace: string;
7
+ construct: ConstructorType;
8
+ metadata: SocketMetaInterface;
9
+ }
10
+
11
+ const registry = new Map<string, SocketRegistryEntryInterface>();
12
+
5
13
  export function getSocketMetadata(target: any): SocketMetaInterface {
6
14
  let metadata = Reflect.getMetadata(METADATA_KEYS.SOCKETS, target);
7
15
  if (!metadata) {
@@ -11,3 +19,48 @@ export function getSocketMetadata(target: any): SocketMetaInterface {
11
19
 
12
20
  return metadata;
13
21
  }
22
+
23
+ export function registerSocket(construct: any): SocketRegistryEntryInterface {
24
+ const metadata = getSocketMetadata(construct.prototype || construct);
25
+ const namespace = metadata.namespace || '/';
26
+ const entry: SocketRegistryEntryInterface = {namespace, construct, metadata};
27
+ registry.set(namespace, entry);
28
+ return entry;
29
+ }
30
+
31
+ export function getSocketRegistry(): Map<string, SocketRegistryEntryInterface> {
32
+ return registry;
33
+ }
34
+
35
+ export function getSocketForNamespace(namespace: string): SocketRegistryEntryInterface | undefined {
36
+ return registry.get(normalizePath(namespace));
37
+ }
38
+
39
+ export function findSocketForPath(pathname: string, prefix?: string): SocketRegistryEntryInterface | undefined {
40
+ const normalized = normalizePath(pathname);
41
+
42
+ if (registry.has(normalized)) return registry.get(normalized);
43
+
44
+ if (prefix && prefix !== '/') {
45
+ const withoutPrefix = normalized.startsWith(prefix)
46
+ ? (normalized.substring(prefix.length) || '/')
47
+ : null;
48
+ if (withoutPrefix && registry.has(withoutPrefix)) return registry.get(withoutPrefix);
49
+
50
+ const withPrefix = `${prefix}${normalized}`;
51
+ if (registry.has(withPrefix)) return registry.get(withPrefix);
52
+ }
53
+
54
+ return undefined;
55
+ }
56
+
57
+ export function clearSocketRegistry(): void {
58
+ registry.clear();
59
+ }
60
+
61
+ function normalizePath(pathname: string): string {
62
+ if (pathname.length > 1 && pathname.endsWith('/')) {
63
+ return pathname.slice(0, -1);
64
+ }
65
+ return pathname;
66
+ }
@@ -103,7 +103,10 @@ export class RaitonThread implements ThreadInterface {
103
103
  const displayHostname = (hostname === '0.0.0.0') ? (this.getNetworkIp() || 'localhost') : hostname;
104
104
  const prefix = this.application.config.prefix
105
105
 
106
- this.runtimeServer = this.runtime.createServer(this.application.handle.bind(this.application))
106
+ this.runtimeServer = this.runtime.createServer(
107
+ this.application.handle.bind(this.application),
108
+ {prefix}
109
+ )
107
110
 
108
111
  await this.runtimeServer.listen(port, hostname)
109
112
 
@@ -15,6 +15,7 @@ export const METADATA_KEYS = {
15
15
  API_TAGS: Symbol('api:tags'),
16
16
  API_OPERATION: Symbol('api:operation'),
17
17
  API_SECURITY: Symbol('api:security'),
18
+ API_PROPERTY: Symbol('api:property'),
18
19
  // Route interaction metadata key
19
20
  ROUTE_INTERACTION: Symbol('route:interaction'),
20
21
  }
@@ -32,11 +32,10 @@ export interface ApiResponseOptions {
32
32
  */
33
33
  export function ApiResponse(options: ApiResponseOptions) {
34
34
  return function (target: any, propertyKey: string | symbol) {
35
- const responses = Reflect.getMetadata(METADATA_KEYS.API_RESPONSES, target) || {};
36
- if (!responses[propertyKey]) {
37
- responses[propertyKey] = [];
38
- }
39
- responses[propertyKey].push(options);
35
+ const responses = Reflect.getOwnMetadata(METADATA_KEYS.API_RESPONSES, target) || {};
36
+ const methodResponses = responses[propertyKey] ? [...responses[propertyKey]] : [];
37
+ methodResponses.push(options);
38
+ responses[propertyKey] = methodResponses;
40
39
  Reflect.defineMetadata(METADATA_KEYS.API_RESPONSES, responses, target);
41
40
  };
42
41
  }
@@ -30,8 +30,6 @@ export interface ApiTagOptions {
30
30
  */
31
31
  export function ApiTags(...tags: (string | ApiTagOptions)[]) {
32
32
  return function (target: any, propertyKey?: string | symbol) {
33
- const tagsMetadata = Reflect.getMetadata(METADATA_KEYS.API_TAGS, target) || [];
34
-
35
33
  // Convert string tags to objects
36
34
  const processedTags = tags.map(tag =>
37
35
  typeof tag === 'string' ? {name: tag} : tag
@@ -39,11 +37,12 @@ export function ApiTags(...tags: (string | ApiTagOptions)[]) {
39
37
 
40
38
  if (propertyKey) {
41
39
  // Method-level decorator
42
- const methodTags = Reflect.getMetadata(METADATA_KEYS.API_TAGS, target, propertyKey) || [];
43
- Reflect.defineMetadata(METADATA_KEYS.API_TAGS, [...methodTags, ...processedTags], target, propertyKey);
40
+ const existingTags = Reflect.getOwnMetadata(METADATA_KEYS.API_TAGS, target, propertyKey) || [];
41
+ Reflect.defineMetadata(METADATA_KEYS.API_TAGS, [...existingTags, ...processedTags], target, propertyKey);
44
42
  } else {
45
43
  // Class-level decorator
46
- Reflect.defineMetadata(METADATA_KEYS.API_TAGS, [...tagsMetadata, ...processedTags], target);
44
+ const existingTags = Reflect.getOwnMetadata(METADATA_KEYS.API_TAGS, target) || [];
45
+ Reflect.defineMetadata(METADATA_KEYS.API_TAGS, [...existingTags, ...processedTags], target);
47
46
  }
48
47
  };
49
48
  }
@@ -108,14 +107,13 @@ export interface ApiSecurityOptions {
108
107
  */
109
108
  export function ApiSecurity(...security: ApiSecurityOptions[]) {
110
109
  return function (target: any, propertyKey?: string | symbol) {
111
- const securities = Reflect.getMetadata(METADATA_KEYS.API_SECURITY, target) || [];
112
-
113
110
  if (propertyKey) {
114
111
  // Method-level decorator
115
- const methodSecurities = Reflect.getMetadata(METADATA_KEYS.API_SECURITY, target, propertyKey) || [];
112
+ const methodSecurities = Reflect.getOwnMetadata(METADATA_KEYS.API_SECURITY, target, propertyKey) || [];
116
113
  Reflect.defineMetadata(METADATA_KEYS.API_SECURITY, [...methodSecurities, ...security], target, propertyKey);
117
114
  } else {
118
115
  // Class-level decorator
116
+ const securities = Reflect.getOwnMetadata(METADATA_KEYS.API_SECURITY, target) || [];
119
117
  Reflect.defineMetadata(METADATA_KEYS.API_SECURITY, [...securities, ...security], target);
120
118
  }
121
119
  };
@@ -180,25 +178,43 @@ export function ApiParam(name: string, options: {
180
178
  enum?: any[]
181
179
  }) {
182
180
  return function (target: any, propertyKey: string | symbol) {
183
- const params = Reflect.getMetadata(METADATA_KEYS.API_PARAMETERS, target) || {};
184
- if (!params[propertyKey]) {
185
- params[propertyKey] = [];
186
- }
187
- params[propertyKey].push({name, ...options});
181
+ const params = Reflect.getOwnMetadata(METADATA_KEYS.API_PARAMETERS, target, propertyKey) || {};
182
+ const methodParams = params[propertyKey] ? [...params[propertyKey]] : [];
183
+ methodParams.push({name, ...options});
184
+ params[propertyKey] = methodParams;
188
185
 
189
186
  if (options.enum) {
190
- Reflect.defineMetadata(
191
- METADATA_KEYS.API_ENUMS,
192
- {
193
- [propertyKey]: options.enum
194
- },
195
- target
196
- );
187
+ const enums = Reflect.getOwnMetadata(METADATA_KEYS.API_ENUMS, target) || {};
188
+ enums[propertyKey] = options.enum;
189
+ Reflect.defineMetadata(METADATA_KEYS.API_ENUMS, enums, target);
197
190
  }
198
191
  Reflect.defineMetadata(METADATA_KEYS.API_PARAMETERS, params, target, propertyKey);
199
192
  };
200
193
  }
201
194
 
195
+ /**
196
+ * Decorator to define a property of a DTO for OpenAPI
197
+ * @param options Property options
198
+ */
199
+ export function ApiProperty(options: {
200
+ type?: any;
201
+ description?: string;
202
+ example?: any;
203
+ required?: boolean;
204
+ enum?: any[];
205
+ isArray?: boolean;
206
+ } = {}) {
207
+ return function (target: any, propertyKey: string | symbol) {
208
+ const properties = Reflect.getOwnMetadata(METADATA_KEYS.API_PROPERTY, target.constructor) || {};
209
+ properties[propertyKey] = {
210
+ ...options,
211
+ // If type is not provided, try to infer it using design:type
212
+ type: options.type || Reflect.getMetadata('design:type', target, propertyKey)
213
+ };
214
+ Reflect.defineMetadata(METADATA_KEYS.API_PROPERTY, properties, target.constructor);
215
+ };
216
+ }
217
+
202
218
  /**
203
219
  * Decorator to add query parameter metadata (shortcut for ApiParam with in: 'query')
204
220
  * @param name Parameter name
@@ -8,7 +8,7 @@ import { Raiton } from "../../core/raiton";
8
8
  * Represents a route interaction that can be rendered with context data
9
9
  */
10
10
  export class RouteInteractionDescriptor {
11
- constructor(private template: string) {
11
+ constructor(public readonly template: string) {
12
12
  }
13
13
 
14
14
  /**
@@ -1,4 +1,4 @@
1
- import {getSocketMetadata} from "../../core/socket";
1
+ import {getSocketMetadata, registerSocket} from "../../core/socket";
2
2
  import {Injectable} from "..";
3
3
  import {LifetimeEnum} from "@protorians/core";
4
4
  import {SocketEventType} from "../../types";
@@ -10,6 +10,7 @@ export function Socket(namespace = '/') {
10
10
 
11
11
  const meta = getSocketMetadata(target.prototype || target)
12
12
  meta.namespace = namespace;
13
+ registerSocket(target)
13
14
  }
14
15
  }
15
16
 
@@ -1,21 +1,118 @@
1
- import {RuntimeAdapterInterface} from '../../../types'
1
+ import {
2
+ RuntimeAdapterInterface,
3
+ RuntimeServerOptionsInterface,
4
+ } from '../../../types'
2
5
  import {Logger} from "@protorians/logger";
3
6
  import {getRealIp} from "../../utilities";
7
+ import {findSocketForPath} from "../../../core/socket";
8
+ import {Injection} from "../../../core/injection";
4
9
 
5
10
  export const bunRuntime: RuntimeAdapterInterface = {
6
- createServer(handler) {
11
+ createServer(handler, options?: RuntimeServerOptionsInterface) {
7
12
  if (typeof Bun === 'undefined') throw new Error(
8
13
  'bun is not installed, please run `npm install bun`'
9
14
  )
10
15
 
11
16
  let server: any
12
17
 
18
+ const socketHandlers = {
19
+ async open(ws: any) {
20
+ try {
21
+ const entry = ws.data?.socketEntry
22
+ if (!entry) return
23
+
24
+ const instance: any = Injection.resolve(entry.construct)
25
+ if (!instance) return
26
+
27
+ ws.data.instance = instance
28
+
29
+ const connect = entry.metadata.events.find((event: any) => event.type === 'connect')
30
+ if (connect) await instance[connect.propertyKey]?.()
31
+ } catch (e: any) {
32
+ Logger.error('Socket connect failed', e.message ?? e)
33
+ try { ws.close(1011, 'Internal error') } catch { /* noop */ }
34
+ }
35
+ },
36
+ async message(ws: any, message: any) {
37
+ try {
38
+ const instance = ws.data?.instance
39
+ if (!instance) return
40
+
41
+ let payload: any = message
42
+ if (typeof message === 'string') {
43
+ try { payload = JSON.parse(message) } catch { /* keep raw string */ }
44
+ }
45
+
46
+ const entry = ws.data.socketEntry
47
+ const eventName = payload && typeof payload === 'object' ? payload.event : undefined
48
+ const event = eventName
49
+ ? entry.metadata.events.find((item: any) => item.name === eventName && (item.type === 'event' || item.type === 'message'))
50
+ : entry.metadata.events.find((item: any) => item.type === 'message')
51
+
52
+ if (!event) {
53
+ ws.send(JSON.stringify({
54
+ statusCode: 404,
55
+ message: `Socket event "${eventName ?? 'message'}" not found`,
56
+ data: null
57
+ }))
58
+ return
59
+ }
60
+
61
+ const response = await instance[event.propertyKey]?.(payload?.data ?? payload)
62
+ if (response !== undefined) {
63
+ ws.send(JSON.stringify(response))
64
+ }
65
+ } catch (e: any) {
66
+ Logger.error('Socket message failed', e.message ?? e)
67
+ ws.send(JSON.stringify({
68
+ statusCode: 500,
69
+ message: 'Internal server error',
70
+ data: null
71
+ }))
72
+ }
73
+ },
74
+ async close(ws: any) {
75
+ try {
76
+ const instance = ws.data?.instance
77
+ if (!instance) return
78
+
79
+ const entry = ws.data.socketEntry
80
+ const disconnect = entry.metadata.events.find((event: any) => event.type === 'disconnect')
81
+ if (disconnect) await instance[disconnect.propertyKey]?.()
82
+ } catch (e: any) {
83
+ Logger.error('Socket disconnect failed', e.message ?? e)
84
+ }
85
+ }
86
+ }
87
+
13
88
  return {
14
89
  async listen(port, hostname) {
15
90
  server = Bun.serve({
16
91
  port,
17
92
  hostname,
93
+ websocket: socketHandlers,
18
94
  fetch: async (request: Request, server: any) => {
95
+ const upgrade = request.headers.get('upgrade')?.toLowerCase()
96
+
97
+ if (upgrade === 'websocket') {
98
+ const pathname = new URL(request.url).pathname
99
+ const socketEntry = findSocketForPath(pathname, options?.prefix)
100
+
101
+ if (socketEntry) {
102
+ if (server.upgrade(request, {
103
+ data: {
104
+ socketEntry,
105
+ url: request.url,
106
+ headers: request.headers
107
+ }
108
+ })) {
109
+ return undefined
110
+ }
111
+
112
+ return new Response('WebSocket upgrade failed', {status: 400})
113
+ }
114
+ }
115
+
19
116
  let responseBody: any
20
117
  let statusCode = 200
21
118
  const headers = new Headers()
@@ -79,4 +176,4 @@ export const bunRuntime: RuntimeAdapterInterface = {
79
176
  }
80
177
  }
81
178
  }
82
- }
179
+ }
@@ -2,7 +2,8 @@ import type {
2
2
  RuntimeAdapterInterface,
3
3
  RuntimeHandlerCallable,
4
4
  RuntimeInterface,
5
- RuntimeServerInterface
5
+ RuntimeServerInterface,
6
+ RuntimeServerOptionsInterface
6
7
  } from "../../types";
7
8
  import {RuntimeType} from "../enums/runtime.enum";
8
9
  import {nodeRuntime} from "./node/server";
@@ -46,7 +47,7 @@ export class Runtime implements RuntimeInterface {
46
47
  }
47
48
  }
48
49
 
49
- createServer(handler: RuntimeHandlerCallable): RuntimeServerInterface {
50
- return this.adapter().createServer(handler)
50
+ createServer(handler: RuntimeHandlerCallable, options?: RuntimeServerOptionsInterface): RuntimeServerInterface {
51
+ return this.adapter().createServer(handler, options)
51
52
  }
52
53
  }
@@ -2,6 +2,8 @@ import type {ParamMetaInterface} from "../../types";
2
2
  import {METADATA_KEYS, Parametrable} from "../index";
3
3
  import {PluginScope} from "../../core";
4
4
  import {RaitonConfig} from "../../core/config";
5
+ import {getSocketRegistry} from "../../core/socket";
6
+ import {RaitonThread} from "../../core/thread";
5
7
 
6
8
  /**
7
9
  * Generate the OpenAPI specification object
@@ -78,17 +80,19 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
78
80
  responses: {}
79
81
  };
80
82
 
81
- const operationMetadata = Reflect.getMetadata(METADATA_KEYS.API_OPERATION, controllerClass, routeMeta.propertyKey);
83
+ const controllerPrototype = controllerClass?.prototype ?? controllerClass;
84
+
85
+ const operationMetadata = Reflect.getMetadata(METADATA_KEYS.API_OPERATION, controllerPrototype, routeMeta.propertyKey);
82
86
  if (operationMetadata) {
83
87
  Object.assign(operation, operationMetadata);
84
88
  }
85
89
 
86
- const methodTags = Reflect.getMetadata(METADATA_KEYS.API_TAGS, controllerClass, routeMeta.propertyKey);
90
+ const methodTags = Reflect.getMetadata(METADATA_KEYS.API_TAGS, controllerPrototype, routeMeta.propertyKey);
87
91
  if (methodTags) {
88
92
  operation.tags = methodTags;
89
93
  }
90
94
 
91
- const methodSecurity = Reflect.getMetadata(METADATA_KEYS.API_SECURITY, controllerClass, routeMeta.propertyKey);
95
+ const methodSecurity = Reflect.getMetadata(METADATA_KEYS.API_SECURITY, controllerPrototype, routeMeta.propertyKey);
92
96
  if (methodSecurity) {
93
97
  operation.security = methodSecurity;
94
98
  }
@@ -103,7 +107,7 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
103
107
  operation.security = [...(operation.security || []), ...classSecurity];
104
108
  }
105
109
 
106
- const params: ParamMetaInterface[] = Reflect.getMetadata(METADATA_KEYS.ROUTE_PARAMETERS, controllerClass)?.[routeMeta.propertyKey] || [];
110
+ const params: ParamMetaInterface[] = Reflect.getMetadata(METADATA_KEYS.ROUTE_PARAMETERS, controllerPrototype)?.[routeMeta.propertyKey] || [];
107
111
 
108
112
  let bodyParam: ParamMetaInterface | undefined;
109
113
  const otherParams = params.filter(p => {
@@ -114,7 +118,7 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
114
118
  return true;
115
119
  });
116
120
 
117
- const apiParameters = Reflect.getMetadata(METADATA_KEYS.API_PARAMETERS, controllerClass)?.[routeMeta.propertyKey] || [];
121
+ const apiParameters = Reflect.getMetadata(METADATA_KEYS.API_PARAMETERS, controllerPrototype, routeMeta.propertyKey)?.[routeMeta.propertyKey] || [];
118
122
  for (const param of apiParameters) {
119
123
  let inLocation: string;
120
124
  switch (param.in) {
@@ -145,78 +149,9 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
145
149
  };
146
150
 
147
151
  if (param.type) {
148
- const typeName = typeof param.type === 'function' ? param.type.name : typeof param.type;
149
- let schemaType = 'string'; // default
150
-
151
- if (typeof param.type === 'function' && param.type.name) {
152
- switch (param.type.name) {
153
- case 'String':
154
- schemaType = 'string';
155
- break;
156
- case 'Number':
157
- schemaType = 'number';
158
- break;
159
- case 'Boolean':
160
- schemaType = 'boolean';
161
- break;
162
- case 'Object':
163
- schemaType = 'object';
164
- break;
165
- case 'Array':
166
- schemaType = 'array';
167
- break;
168
- default:
169
- // For custom classes, treat as object
170
- schemaType = 'object';
171
- break;
172
- }
173
- } else if (typeof param.type === 'string') {
174
- switch (param.type.toLowerCase()) {
175
- case 'string':
176
- schemaType = 'string';
177
- break;
178
- case 'number':
179
- case 'int':
180
- case 'float':
181
- case 'double':
182
- schemaType = 'number';
183
- break;
184
- case 'boolean':
185
- schemaType = 'boolean';
186
- break;
187
- case 'object':
188
- schemaType = 'object';
189
- break;
190
- case 'array':
191
- schemaType = 'array';
192
- break;
193
- default:
194
- schemaType = 'string'; // fallback
195
- break;
196
- }
197
- }
198
-
199
- paramObj.schema = {
200
- type: schemaType,
201
- ...(param.default !== undefined ? {default: param.default} : {})
202
- };
203
-
204
- // Handle array items if needed (simplified)
205
- if (schemaType === 'array' && param.type && typeof param.type === 'function' && param.type.name) {
206
- switch (param.type.name) {
207
- case 'String':
208
- paramObj.schema.items = {type: 'string'};
209
- break;
210
- case 'Number':
211
- paramObj.schema.items = {type: 'number'};
212
- break;
213
- case 'Boolean':
214
- paramObj.schema.items = {type: 'boolean'};
215
- break;
216
- default:
217
- paramObj.schema.items = {type: 'string'}; // generic
218
- break;
219
- }
152
+ paramObj.schema = getSchemaFromType(param.type);
153
+ if (param.default !== undefined) {
154
+ paramObj.schema.default = param.default;
220
155
  }
221
156
  }
222
157
 
@@ -281,7 +216,7 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
281
216
  }
282
217
 
283
218
  // Check for explicit API request body decorator
284
- const apiRequestBody = Reflect.getMetadata(METADATA_KEYS.API_REQUEST_BODY, controllerClass, routeMeta.propertyKey);
219
+ const apiRequestBody = Reflect.getMetadata(METADATA_KEYS.API_REQUEST_BODY, controllerPrototype, routeMeta.propertyKey);
285
220
  if (apiRequestBody) {
286
221
  // Use explicit API request body definition
287
222
  const bodyRequired = apiRequestBody.required ?? true;
@@ -303,31 +238,8 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
303
238
  // Fallback to automatic body parameter detection
304
239
  // Determine if the body param has a metatype that is a class (DTO)
305
240
  let bodySchema: any = {type: 'object'}; // default
306
- if (bodyParam.metatype && typeof bodyParam.metatype === 'function' && 'prototype' in bodyParam.metatype) {
307
- // It's a class; we treat it as object for simplicity
308
- bodySchema = {type: 'object'};
309
- } else {
310
- // If metatype is a primitive type like String, Number, Boolean, etc.
311
- const typeName = bodyParam.metatype?.name;
312
- switch (typeName) {
313
- case 'String':
314
- bodySchema = {type: 'string'};
315
- break;
316
- case 'Number':
317
- bodySchema = {type: 'number'};
318
- break;
319
- case 'Boolean':
320
- bodySchema = {type: 'boolean'};
321
- break;
322
- case 'Object':
323
- bodySchema = {type: 'object'};
324
- break;
325
- case 'Array':
326
- bodySchema = {type: 'array', items: {type: 'string'}}; // generic
327
- break;
328
- default:
329
- bodySchema = {type: 'object'};
330
- }
241
+ if (bodyParam.metatype) {
242
+ bodySchema = getSchemaFromType(bodyParam.metatype);
331
243
  }
332
244
  operation.requestBody = {
333
245
  required: true,
@@ -340,7 +252,7 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
340
252
  }
341
253
 
342
254
  // Check for API response decorators first
343
- const apiResponses = Reflect.getMetadata(METADATA_KEYS.API_RESPONSES, controllerClass)?.[routeMeta.propertyKey] || [];
255
+ const apiResponses = Reflect.getMetadata(METADATA_KEYS.API_RESPONSES, controllerPrototype)?.[routeMeta.propertyKey] || [];
344
256
 
345
257
  if (apiResponses.length > 0) {
346
258
  // Use decorator-defined responses
@@ -367,7 +279,7 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
367
279
  }
368
280
  } else {
369
281
  // Fallback to return type detection
370
- const returnType = Reflect.getMetadata('design:returntype', controllerClass, routeMeta.propertyKey);
282
+ const returnType = Reflect.getMetadata('design:returntype', controllerPrototype, routeMeta.propertyKey);
371
283
  if (returnType) {
372
284
  // Handle Promise<T> -> T
373
285
  let resolvedType = returnType;
@@ -395,6 +307,94 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
395
307
  (spec.paths[path] as any)[method] = operation;
396
308
  }
397
309
 
310
+ // Document registered WebSocket sockets as POST operations (one per event)
311
+ const prefix = RaitonThread.current?.application?.config?.prefix ?? '';
312
+ const sockets = getSocketRegistry();
313
+
314
+ for (const [, socketEntry] of sockets) {
315
+ const {namespace, construct, metadata} = socketEntry;
316
+ const classTags = Reflect.getMetadata(METADATA_KEYS.API_TAGS, construct) || [];
317
+ const socketPrototype = construct?.prototype ?? construct;
318
+
319
+ for (const event of metadata.events) {
320
+ if (event.type !== 'event' && event.type !== 'message') continue;
321
+ if (!event.name) continue;
322
+
323
+ const channelPath = `${prefix}${namespace}`.replace(/\/+/g, '/') || '/';
324
+ const eventPath = `${channelPath}/${event.name}`.replace(/\/+/g, '/');
325
+
326
+ if (!spec.paths[eventPath]) {
327
+ spec.paths[eventPath] = {};
328
+ }
329
+
330
+ const operation: any = {
331
+ parameters: [],
332
+ responses: {}
333
+ };
334
+
335
+ const operationMetadata = Reflect.getMetadata(METADATA_KEYS.API_OPERATION, socketPrototype, event.propertyKey);
336
+ if (operationMetadata) {
337
+ Object.assign(operation, operationMetadata);
338
+ }
339
+
340
+ const methodTags = Reflect.getMetadata(METADATA_KEYS.API_TAGS, socketPrototype, event.propertyKey);
341
+ operation.tags = [...(methodTags || []), ...classTags];
342
+
343
+ const apiResponses = Reflect.getMetadata(METADATA_KEYS.API_RESPONSES, socketPrototype)?.[event.propertyKey] || [];
344
+
345
+ if (apiResponses.length > 0) {
346
+ for (const response of apiResponses) {
347
+ const statusCode = String(response.status);
348
+ let responseContent = undefined;
349
+
350
+ if (response.type) {
351
+ const responseSchema = getSchemaFromType(response.type);
352
+ responseContent = response.isArray
353
+ ? {type: 'array', items: responseSchema}
354
+ : responseSchema;
355
+ }
356
+
357
+ operation.responses[statusCode] = {
358
+ description: response.description || '',
359
+ ...(responseContent ? {content: {'application/json': {schema: responseContent}}} : {})
360
+ };
361
+ }
362
+ } else {
363
+ operation.responses['200'] = {
364
+ description: 'Successful response'
365
+ };
366
+ }
367
+
368
+ const apiRequestBody = Reflect.getMetadata(METADATA_KEYS.API_REQUEST_BODY, socketPrototype, event.propertyKey);
369
+ const dataSchema = apiRequestBody?.type
370
+ ? getSchemaFromType(apiRequestBody.type)
371
+ : {type: 'object'};
372
+
373
+ operation.requestBody = {
374
+ required: apiRequestBody?.required ?? true,
375
+ content: {
376
+ 'application/json': {
377
+ schema: {
378
+ type: 'object',
379
+ properties: {
380
+ event: {type: 'string', enum: [event.name], example: event.name},
381
+ data: dataSchema
382
+ },
383
+ required: ['event', 'data']
384
+ }
385
+ }
386
+ }
387
+ };
388
+
389
+ operation['x-websocket'] = {
390
+ channel: channelPath,
391
+ event: event.name
392
+ };
393
+
394
+ (spec.paths[eventPath] as any).post = operation;
395
+ }
396
+ }
397
+
398
398
  return spec;
399
399
  }
400
400
 
@@ -403,12 +403,16 @@ export async function generateOpenApiSpec(scope: PluginScope, opts: any): Promis
403
403
  * This is a simplified implementation; for production use, consider using
404
404
  * a library like @sinclair/typebox or class-transformer to generate schemas.
405
405
  */
406
- export function getSchemaFromType(type: any): any {
406
+ export function getSchemaFromType(type: any, visited: Set<any> = new Set()): any {
407
407
  if (typeof type !== 'function') {
408
408
  // Not a constructor; fallback to basic type detection
409
409
  return getPrimitiveTypeSchema(typeof type);
410
410
  }
411
411
 
412
+ if (visited.has(type)) {
413
+ return {type: 'object', description: 'Circular reference'};
414
+ }
415
+
412
416
  const typeName = type.name;
413
417
  switch (typeName) {
414
418
  case 'String':
@@ -430,9 +434,50 @@ export function getSchemaFromType(type: any): any {
430
434
  format: 'date-time'
431
435
  };
432
436
  default:
433
- // For custom classes (DTOs, entities, etc.), we treat as object.
434
- // In a more advanced implementation, we could inspect the class properties
435
- // and generate properties from them (especially if decorated with @ApiProperty etc.)
437
+ // For custom classes (DTOs, entities, etc.), check for @ApiProperty
438
+ // We use Reflect.getMetadata to support inheritance of properties
439
+ const properties = Reflect.getMetadata(METADATA_KEYS.API_PROPERTY, type);
440
+
441
+ if (properties) {
442
+ visited.add(type);
443
+ const schema: any = {
444
+ type: 'object',
445
+ properties: {},
446
+ required: []
447
+ };
448
+
449
+ for (const [key, options] of Object.entries(properties) as [string, any][]) {
450
+ let propSchema: any;
451
+ const propType = options.type;
452
+
453
+ if (options.isArray) {
454
+ propSchema = {
455
+ type: 'array',
456
+ items: propType ? getSchemaFromType(propType, new Set(visited)) : {type: 'string'}
457
+ };
458
+ } else if (propType) {
459
+ propSchema = getSchemaFromType(propType, new Set(visited));
460
+ } else {
461
+ propSchema = {type: 'string'};
462
+ }
463
+
464
+ if (options.description) propSchema.description = options.description;
465
+ if (options.example) propSchema.example = options.example;
466
+ if (options.enum) propSchema.enum = options.enum;
467
+
468
+ schema.properties[key] = propSchema;
469
+ if (options.required) {
470
+ schema.required.push(key);
471
+ }
472
+ }
473
+
474
+ if (schema.required.length === 0) {
475
+ delete schema.required;
476
+ }
477
+
478
+ return schema;
479
+ }
480
+
436
481
  return {type: 'object'};
437
482
  }
438
483
  }
@@ -4,4 +4,5 @@ export interface RaitonSignalMapInterface {
4
4
  ready?: undefined;
5
5
  errors: any;
6
6
  'hmr:controller': BuilderHMRDeclarationInterface;
7
+ 'hmr:socket': BuilderHMRDeclarationInterface;
7
8
  }
@@ -8,6 +8,10 @@ export interface RuntimeServerInterface {
8
8
  handle?(request: Request): Promise<Response>
9
9
  }
10
10
 
11
+ export interface RuntimeServerOptionsInterface {
12
+ prefix?: string;
13
+ }
14
+
11
15
  export interface RuntimeRequestInterface {
12
16
  method: string
13
17
  url: string
@@ -38,7 +42,7 @@ export interface RuntimeReplyInterface {
38
42
  }
39
43
 
40
44
  export interface RuntimeAdapterInterface {
41
- createServer(handler: RuntimeHandlerCallable): RuntimeServerInterface
45
+ createServer(handler: RuntimeHandlerCallable, options?: RuntimeServerOptionsInterface): RuntimeServerInterface
42
46
  }
43
47
 
44
48