raiton 6.0.2-beta.3 → 6.1.1-beta.5

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 = "6.0.2-beta.3";
4820
+ var version = "6.1.1-beta.5";
4821
4821
 
4822
4822
  // source/bin/cli.ts
4823
4823
  var CLI = new Command;
@@ -6362,6 +6362,21 @@ class ThrowableResponse extends Error {
6362
6362
  };
6363
6363
  }
6364
6364
  }
6365
+ // source/framework/responses/helpers.ts
6366
+ function RaitonResponses(message, data, statusCode, metadata) {
6367
+ if (metadata) {
6368
+ if (metadata.error === undefined) {
6369
+ metadata.error = typeof data?.error === "boolean" ? data?.error : false;
6370
+ }
6371
+ metadata.errorStack = metadata.errorStack instanceof Error ? metadata.errorStack : Raiton.thread?.builder?.options?.serve ? Array.isArray(metadata.errorStack) ? metadata.errorStack : [] : undefined;
6372
+ }
6373
+ return {
6374
+ ...metadata,
6375
+ statusCode,
6376
+ message,
6377
+ data
6378
+ };
6379
+ }
6365
6380
  // source/core/controller/metadata.ts
6366
6381
  var import_reflect_metadata = __toESM(require_Reflect2(), 1);
6367
6382
  function getControllerMetadata(target) {
@@ -6597,6 +6612,29 @@ class Injection {
6597
6612
  this._classes.set(name_, { ...this._classes.get(this.normalizeName(name)), construct });
6598
6613
  return this;
6599
6614
  }
6615
+ static invalidate(name) {
6616
+ const name_ = this.normalizeName(name);
6617
+ if (this._instances.has(name_)) {
6618
+ const scopeInstances = this._instances.get(name_);
6619
+ for (const [scope, instance] of scopeInstances) {
6620
+ if (typeof instance.onUnmount === "function") {
6621
+ try {
6622
+ instance.onUnmount();
6623
+ } catch {}
6624
+ }
6625
+ }
6626
+ this._instances.delete(name_);
6627
+ }
6628
+ return this;
6629
+ }
6630
+ static invalidateCascade(name) {
6631
+ this.invalidate(name);
6632
+ const dependents = this.getDependents(name);
6633
+ for (const dep of dependents) {
6634
+ this.invalidateCascade(dep);
6635
+ }
6636
+ return this;
6637
+ }
6600
6638
  static getDependents(name) {
6601
6639
  return Array.from(this._dependents.get(this.normalizeName(name)) || []);
6602
6640
  }
@@ -6736,6 +6774,8 @@ class Injection {
6736
6774
  return this.get(name);
6737
6775
  }
6738
6776
  }
6777
+ // source/core/controller/tracker.ts
6778
+ var controllerRouteMap = new Map;
6739
6779
  // source/core/socket/metadata.ts
6740
6780
  var import_reflect_metadata3 = __toESM(require_Reflect2(), 1);
6741
6781
  var registry = new Map;
@@ -7019,6 +7059,36 @@ class HookStore {
7019
7059
  list.push(handler2);
7020
7060
  this.hooks.set(name, list);
7021
7061
  }
7062
+ remove(name, handler2) {
7063
+ if (!this.hooks.has(name))
7064
+ return;
7065
+ if (!handler2) {
7066
+ this.hooks.delete(name);
7067
+ return;
7068
+ }
7069
+ const list = this.hooks.get(name);
7070
+ const idx = list.indexOf(handler2);
7071
+ if (idx !== -1)
7072
+ list.splice(idx, 1);
7073
+ if (list.length === 0)
7074
+ this.hooks.delete(name);
7075
+ else
7076
+ this.hooks.set(name, list);
7077
+ }
7078
+ replace(name, oldHandler, newHandler) {
7079
+ if (!this.hooks.has(name)) {
7080
+ this.add(name, newHandler);
7081
+ return;
7082
+ }
7083
+ const list = this.hooks.get(name);
7084
+ const idx = list.indexOf(oldHandler);
7085
+ if (idx !== -1) {
7086
+ list[idx] = newHandler;
7087
+ } else {
7088
+ list.push(newHandler);
7089
+ }
7090
+ this.hooks.set(name, list);
7091
+ }
7022
7092
  async run(name, ctx) {
7023
7093
  const list = this.hooks.get(name);
7024
7094
  if (!list)
@@ -7067,6 +7137,35 @@ class MiddlewarePipeline {
7067
7137
  this.stack.push(mw);
7068
7138
  return this;
7069
7139
  }
7140
+ replace(name, mw) {
7141
+ const normalized = name.toLowerCase();
7142
+ for (let i = 0;i < this.stack.length; i++) {
7143
+ const entry = this.stack[i];
7144
+ let entryName;
7145
+ if (typeof entry === "function") {
7146
+ entryName = entry.name?.toLowerCase();
7147
+ } else if (typeof entry === "object" && entry !== null && "name" in entry) {
7148
+ entryName = entry.name?.toLowerCase();
7149
+ }
7150
+ if (entryName === normalized) {
7151
+ this.stack[i] = mw;
7152
+ return this;
7153
+ }
7154
+ }
7155
+ this.stack.push(mw);
7156
+ return this;
7157
+ }
7158
+ remove(name) {
7159
+ const normalized = name.toLowerCase();
7160
+ this.stack = this.stack.filter((entry) => {
7161
+ if (typeof entry === "function")
7162
+ return entry.name?.toLowerCase() !== normalized;
7163
+ if (typeof entry === "object" && entry !== null && "name" in entry)
7164
+ return entry.name?.toLowerCase() !== normalized;
7165
+ return true;
7166
+ });
7167
+ return this;
7168
+ }
7070
7169
  clear() {
7071
7170
  this.stack = [];
7072
7171
  return this;
@@ -7196,8 +7295,7 @@ var secureRateLimit = (opts = {}) => definePlugin((scope2) => {
7196
7295
  entry.count++;
7197
7296
  hits.set(ip, entry);
7198
7297
  if (entry.count > max) {
7199
- context.reply.status(429);
7200
- return context.send({ error: "Too many requests" });
7298
+ return context.send(RaitonResponses("Too many requests", null, 429 /* TOO_MANY_REQUESTS */, { error: true }));
7201
7299
  }
7202
7300
  await next();
7203
7301
  });
@@ -7208,8 +7306,7 @@ var secureBodyLimit = (maxBytes = 1e6) => definePlugin((scope2) => {
7208
7306
  scope2.use(async ({ context, next }) => {
7209
7307
  const len = Number(context.req.headers.get("content-length") ?? 0);
7210
7308
  if (len > maxBytes) {
7211
- context.reply.status(413);
7212
- return context.send({ error: "Payload too large" });
7309
+ return context.send(RaitonResponses("Payload too large", null, 413 /* PAYLOAD_TOO_LARGE */, { error: true }));
7213
7310
  }
7214
7311
  await next();
7215
7312
  });
@@ -7219,8 +7316,7 @@ var secureBodyLimit = (maxBytes = 1e6) => definePlugin((scope2) => {
7219
7316
  var secureMethodGuard = (allowed) => definePlugin((scope2) => {
7220
7317
  scope2.use(async ({ context, next }) => {
7221
7318
  if (!allowed.includes(context.req.method)) {
7222
- context.reply.status(405);
7223
- return context.send({ error: "Method not allowed" });
7319
+ return context.send(RaitonResponses("Method not allowed", null, 405 /* METHOD_NOT_ALLOWED */, { error: true }));
7224
7320
  }
7225
7321
  await next();
7226
7322
  });
@@ -7260,6 +7356,35 @@ class RaitonDirectories {
7260
7356
  }
7261
7357
 
7262
7358
  // source/framework/artifacts.ts
7359
+ var HMR_CHANNELS = {
7360
+ "hmr:di": [
7361
+ "service",
7362
+ "provider",
7363
+ "type",
7364
+ "interface",
7365
+ "repository",
7366
+ "database",
7367
+ "db",
7368
+ "util",
7369
+ "utility",
7370
+ "source",
7371
+ "use-case",
7372
+ "dto",
7373
+ "vm",
7374
+ "entity",
7375
+ "model",
7376
+ "schema",
7377
+ "validator",
7378
+ "strategy",
7379
+ "strategy-provider",
7380
+ "strategy-type"
7381
+ ],
7382
+ "hmr:controller": ["controller"],
7383
+ "hmr:socket": ["socket"],
7384
+ "hmr:middleware": ["middleware"],
7385
+ "hmr:hook": ["hook", "event", "listener"]
7386
+ };
7387
+
7263
7388
  class Artifacts {
7264
7389
  static types = new Set;
7265
7390
  static defaultTypes = [
@@ -7303,6 +7428,16 @@ class Artifacts {
7303
7428
  static is(filename) {
7304
7429
  return [...this.types].map((type) => isArtifact(filename, type)).some(Boolean);
7305
7430
  }
7431
+ static classify(filename) {
7432
+ for (const [channel, types] of Object.entries(HMR_CHANNELS)) {
7433
+ for (const type of types) {
7434
+ if (isArtifact(filename, type)) {
7435
+ return { channel, artifactType: type };
7436
+ }
7437
+ }
7438
+ }
7439
+ return null;
7440
+ }
7306
7441
  static reload(modulo, filename) {
7307
7442
  if (Raiton.thread?.builder.options.serve === false)
7308
7443
  return Logger.warn("Artifact reload is only available in development mode");
@@ -7315,6 +7450,61 @@ class Artifacts {
7315
7450
  }
7316
7451
  }
7317
7452
  }
7453
+ static reloadDi(modulo, filename) {
7454
+ if (Raiton.thread?.builder.options.serve === false)
7455
+ return Logger.warn("Artifact reload is only available in development mode");
7456
+ for (const mod of Object.values(modulo)) {
7457
+ const name = mod && typeof mod === "object" && "name" in mod ? mod.name : typeof mod === "function" ? mod.name ?? mod.constructor.name : undefined;
7458
+ if (typeof name === "string" && Injection.has(name)) {
7459
+ if (filename)
7460
+ Injection.registerArtifactPath(name, filename);
7461
+ Injection.updateConstruct(name, mod);
7462
+ Injection.invalidateCascade(name);
7463
+ }
7464
+ }
7465
+ }
7466
+ static reloadMiddleware(modulo, filename) {
7467
+ if (Raiton.thread?.builder.options.serve === false)
7468
+ return Logger.warn("Artifact reload is only available in development mode");
7469
+ const app = Raiton.thread?.application;
7470
+ if (!app)
7471
+ return;
7472
+ const rootScope = app.root;
7473
+ if (!rootScope?.middleware)
7474
+ return;
7475
+ for (const mod of Object.values(modulo)) {
7476
+ const name = mod && typeof mod === "object" && "name" in mod ? mod.name : typeof mod === "function" ? mod.name ?? mod.constructor.name : undefined;
7477
+ if (typeof name === "string") {
7478
+ if (typeof mod === "function") {
7479
+ const instance = new mod;
7480
+ rootScope.middleware.replace(name, instance);
7481
+ } else if (typeof mod === "object" && mod !== null) {
7482
+ rootScope.middleware.replace(name, mod);
7483
+ }
7484
+ }
7485
+ }
7486
+ }
7487
+ static reloadHook(modulo, filename) {
7488
+ if (Raiton.thread?.builder.options.serve === false)
7489
+ return Logger.warn("Artifact reload is only available in development mode");
7490
+ const app = Raiton.thread?.application;
7491
+ if (!app)
7492
+ return;
7493
+ const rootScope = app.root;
7494
+ if (!rootScope?.hooks)
7495
+ return;
7496
+ for (const mod of Object.values(modulo)) {
7497
+ const name = mod && typeof mod === "object" && "name" in mod ? mod.name : typeof mod === "function" ? mod.name ?? mod.constructor.name : undefined;
7498
+ if (typeof name === "string") {
7499
+ if (typeof mod === "function") {
7500
+ const instance = new mod;
7501
+ rootScope.hooks.replace(name, instance);
7502
+ } else if (typeof mod === "object" && mod !== null) {
7503
+ rootScope.hooks.replace(name, mod);
7504
+ }
7505
+ }
7506
+ }
7507
+ }
7318
7508
  }
7319
7509
  // source/core/command.ts
7320
7510
  class RaitonCommand {
@@ -7497,7 +7687,7 @@ class Application {
7497
7687
  Logger.warn(`Request out of application pathname: ${pathname} (expected prefix: ${this.config.pathname})`);
7498
7688
  }
7499
7689
  reply2.status(404);
7500
- return reply2.send({ error: false, statusCode: 404 });
7690
+ return reply2.send(RaitonResponses("Not Found", null, 404 /* NOT_FOUND */, { error: false }));
7501
7691
  }
7502
7692
  }
7503
7693
  const route2 = this.root.router.match(req2.method, pathname);
@@ -7506,7 +7696,7 @@ class Application {
7506
7696
  Logger.warn(`Route not found: ${req2.method} ${pathname}`);
7507
7697
  }
7508
7698
  reply2.status(404);
7509
- return reply2.send({ error: false, statusCode: 404 });
7699
+ return reply2.send(RaitonResponses("Not Found", null, 404 /* NOT_FOUND */, { error: false }));
7510
7700
  }
7511
7701
  try {
7512
7702
  context.params = route2.parameters;
@@ -7525,7 +7715,7 @@ class Application {
7525
7715
  console.error(e);
7526
7716
  }
7527
7717
  context.reply.status(500);
7528
- context.reply.send({ error: true, statusCode: 500, data: null });
7718
+ context.reply.send(RaitonResponses("Internal Server Error", null, 500 /* INTERNAL_SERVER_ERROR */, { error: true }));
7529
7719
  }
7530
7720
  };
7531
7721
  try {
@@ -7538,12 +7728,7 @@ class Application {
7538
7728
  ctx.reply.status(err.statusCode ?? 500);
7539
7729
  return ctx.reply.send(err.render());
7540
7730
  }
7541
- ctx.reply.send({
7542
- statusCode: 500,
7543
- error: true,
7544
- message: err.message ?? err,
7545
- data: null
7546
- });
7731
+ ctx.reply.send(RaitonResponses(err.message ?? err, null, 500 /* INTERNAL_SERVER_ERROR */, { error: true }));
7547
7732
  }
7548
7733
  }
7549
7734
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "raiton",
3
- "version": "6.0.2-beta.3",
3
+ "version": "6.1.1-beta.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Modular TypeScript Backend Framework with Dependency Injection, Plugins, Controllers, Middleware and Hot Reloading.",
@@ -2,7 +2,7 @@ import {Security, bodyParserPlugin} from "../framework/plugins";
2
2
  import {PluginScope} from './plugins/scope'
3
3
  import {RequestContext} from './context'
4
4
  import {ApplicationConfigInterface, ApplicationInterface} from "../types/application";
5
- import {HttpException, HttpMethod, ThrowableResponse} from "../framework";
5
+ import {HttpException, HttpMethod, ThrowableResponse, RaitonResponses, HttpStatus} from "../framework";
6
6
  import {RouteHandlerCallable} from "../types";
7
7
  import {Logger} from "@protorians/logger";
8
8
  import {RaitonConfig} from "./config";
@@ -141,7 +141,7 @@ export class Application implements ApplicationInterface {
141
141
  Logger.warn(`Request out of application pathname: ${pathname} (expected prefix: ${this.config.pathname})`)
142
142
  }
143
143
  reply.status(404)
144
- return reply.send({error: false, statusCode: 404})
144
+ return reply.send(RaitonResponses('Not Found', null, HttpStatus.NOT_FOUND, {error: false}))
145
145
  }
146
146
  }
147
147
 
@@ -155,7 +155,7 @@ export class Application implements ApplicationInterface {
155
155
  Logger.warn(`Route not found: ${req.method} ${pathname}`)
156
156
  }
157
157
  reply.status(404)
158
- return reply.send({error: false, statusCode: 404})
158
+ return reply.send(RaitonResponses('Not Found', null, HttpStatus.NOT_FOUND, {error: false}))
159
159
  }
160
160
 
161
161
  try {
@@ -177,7 +177,7 @@ export class Application implements ApplicationInterface {
177
177
  console.error(e)
178
178
  }
179
179
  context.reply.status(500)
180
- context.reply.send({error: true, statusCode: 500, data: null})
180
+ context.reply.send(RaitonResponses('Internal Server Error', null, HttpStatus.INTERNAL_SERVER_ERROR, {error: true}))
181
181
  }
182
182
  }
183
183
 
@@ -191,12 +191,7 @@ export class Application implements ApplicationInterface {
191
191
  ctx.reply.status(err.statusCode ?? 500)
192
192
  return ctx.reply.send(err.render())
193
193
  }
194
- ctx.reply.send({
195
- statusCode: 500,
196
- error: true,
197
- message: err.message ?? err,
198
- data: null
199
- })
194
+ ctx.reply.send(RaitonResponses(err.message ?? err, null, HttpStatus.INTERNAL_SERVER_ERROR, {error: true}))
200
195
  }
201
196
  }
202
197
  }
@@ -5,12 +5,11 @@ 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, isSocketArtifact} from "../framework";
9
8
  import {ControllerBuilder} from "./controller";
10
9
  import {watch} from "fs";
11
10
  import {LBadge, Logger} from "@protorians/logger";
12
11
  import {Throwable} from "../framework/exceptions";
13
- import {Artifacts} from "../framework/artifacts";
12
+ import {Artifacts, HMR_CHANNELS, HmrChannel} from "../framework/artifacts";
14
13
  import {build} from "esbuild";
15
14
  import {execSync, spawn, spawnSync} from "node:child_process";
16
15
 
@@ -53,18 +52,19 @@ export class RaitonBuilder implements BuilderInterface {
53
52
  protected async parse(filename: string, type?: WatchEventType) {
54
53
  if (!fs.existsSync(filename)) return;
55
54
 
55
+ const classification = Artifacts.classify(filename)
56
+ if (!classification) return
57
+
56
58
  const payload = {
57
59
  filename,
58
60
  timestamp: Date.now(),
59
61
  version: this._compiledVersionNumber,
60
- type
62
+ type,
63
+ channel: classification.channel,
64
+ artifactType: classification.artifactType,
61
65
  }
62
66
 
63
- // Logger.log(LBadge.info('HMR'), 'activated');
64
-
65
- if (Artifacts.is(filename) || isControllerArtifact(filename) || isSocketArtifact(filename))
66
- Raiton.signals.dispatch('hmr:artifact', payload)
67
-
67
+ Raiton.signals.dispatch(classification.channel as any, payload)
68
68
  return payload;
69
69
  }
70
70
 
@@ -112,27 +112,72 @@ export class RaitonBuilder implements BuilderInterface {
112
112
  await this.initialize()
113
113
 
114
114
  if (this.options.hmr && this.options.serve) {
115
- Raiton.signals.listen(
116
- 'hmr:artifact',
117
- async ({filename, version, timestamp}) => {
118
- const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
119
-
120
- if (isControllerArtifact(filename) || isSocketArtifact(filename)) {
121
- await ControllerBuilder.build({filename, version, timestamp})
122
- } else if (Artifacts.is(filename)) {
123
- Artifacts.reload(imported, filename)
124
- }
125
-
126
- Logger.log(LBadge.debug('HMR'), (path.relative(this.workdir, filename)))
127
- }
128
- )
129
- // this.parsing();
115
+ this.listenHmrDi()
116
+ this.listenHmrController()
117
+ this.listenHmrSocket()
118
+ this.listenHmrMiddleware()
119
+ this.listenHmrHook()
130
120
  this.watching();
131
121
  }
132
122
 
133
123
  return this;
134
124
  }
135
125
 
126
+ protected listenHmrDi(): void {
127
+ Raiton.signals.listen(
128
+ 'hmr:di',
129
+ async ({filename, version, timestamp}) => {
130
+ const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
131
+ Artifacts.reloadDi(imported, filename)
132
+ Logger.log(LBadge.debug('HMR'), `[di] ${path.relative(this.workdir, filename)}`)
133
+ }
134
+ )
135
+ }
136
+
137
+ protected listenHmrController(): void {
138
+ Raiton.signals.listen(
139
+ 'hmr:controller',
140
+ async ({filename, version, timestamp}) => {
141
+ const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
142
+ await ControllerBuilder.recompile(imported, filename)
143
+ Logger.log(LBadge.debug('HMR'), `[controller] ${path.relative(this.workdir, filename)}`)
144
+ }
145
+ )
146
+ }
147
+
148
+ protected listenHmrSocket(): void {
149
+ Raiton.signals.listen(
150
+ 'hmr:socket',
151
+ async ({filename, version, timestamp}) => {
152
+ const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
153
+ await ControllerBuilder.build({filename, version, timestamp})
154
+ Logger.log(LBadge.debug('HMR'), `[socket] ${path.relative(this.workdir, filename)}`)
155
+ }
156
+ )
157
+ }
158
+
159
+ protected listenHmrMiddleware(): void {
160
+ Raiton.signals.listen(
161
+ 'hmr:middleware',
162
+ async ({filename, version, timestamp}) => {
163
+ const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
164
+ Artifacts.reloadMiddleware(imported, filename)
165
+ Logger.log(LBadge.debug('HMR'), `[middleware] ${path.relative(this.workdir, filename)}`)
166
+ }
167
+ )
168
+ }
169
+
170
+ protected listenHmrHook(): void {
171
+ Raiton.signals.listen(
172
+ 'hmr:hook',
173
+ async ({filename, version, timestamp}) => {
174
+ const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
175
+ Artifacts.reloadHook(imported, filename)
176
+ Logger.log(LBadge.debug('HMR'), `[hook] ${path.relative(this.workdir, filename)}`)
177
+ }
178
+ )
179
+ }
180
+
136
181
  protected async build(thread: ThreadInterface): Promise<this> {
137
182
  if (!this._source) throw new Error('Application source not found');
138
183
  if (!this._out) throw new Error('Application output not found');
@@ -7,6 +7,7 @@ import {RaitonThread} from "../thread";
7
7
  import {Injection} from "../injection";
8
8
  import {isControllerArtifact, isSocketArtifact} from "../../framework";
9
9
  import path from "node:path";
10
+ import {ControllerRouteTracker} from "./tracker";
10
11
 
11
12
  export class ControllerBuilder {
12
13
 
@@ -46,4 +47,25 @@ export class ControllerBuilder {
46
47
  return compilated;
47
48
  }
48
49
 
49
- }
50
+ static async recompile(modulo: any, filename: string): Promise<void> {
51
+ const app = RaitonThread.current?.application
52
+ if (!app) return
53
+
54
+ for (const mod of Object.values(modulo)) {
55
+ const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
56
+ typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
57
+ );
58
+
59
+ if (typeof name === 'string' && typeof mod === 'function') {
60
+ Injection.invalidateCascade(name)
61
+ const rootScope = (app as any).root
62
+ if (rootScope?.router) {
63
+ ControllerRouteTracker.removeRoutes(name, rootScope.router)
64
+ }
65
+ Injection.updateConstruct(name, mod as any)
66
+ if (filename) Injection.registerArtifactPath(name, filename)
67
+ compileController(mod, app)
68
+ }
69
+ }
70
+ }
71
+ }
@@ -3,6 +3,7 @@ import {getControllerMetadata} from "..";
3
3
  import {createHandler} from "../router";
4
4
  import {Injection} from "../injection";
5
5
  import {ControllerMetaInterface} from "../../types";
6
+ import {ControllerRouteTracker} from "./tracker";
6
7
 
7
8
  export function compileController(
8
9
  ControllerClass: any,
@@ -10,13 +11,23 @@ export function compileController(
10
11
  ) {
11
12
  const instance: any = Injection.resolve<typeof ControllerClass>(ControllerClass)
12
13
  const metadata: ControllerMetaInterface = getControllerMetadata(ControllerClass.prototype)
14
+ const name = ControllerClass.name
13
15
 
14
- for (const route of metadata.routes)
15
- app.route(
16
+ const rootScope = (app as any).root
17
+ if (rootScope?.router) {
18
+ ControllerRouteTracker.removeRoutes(name, rootScope.router)
19
+ }
20
+
21
+ const routes: any[] = []
22
+ for (const route of metadata.routes) {
23
+ const registered = app.route(
16
24
  route.method as any,
17
25
  `${metadata.prefix ?? ''}${route.path}`,
18
26
  createHandler(instance, route, metadata),
19
27
  )
28
+ routes.push(registered)
29
+ }
20
30
 
31
+ ControllerRouteTracker.setRoutes(name, routes)
21
32
  return instance;
22
33
  }
@@ -1,3 +1,4 @@
1
1
  export * from "./metadata"
2
2
  export * from "./compiler"
3
- export * from "./builder"
3
+ export * from "./builder"
4
+ export * from "./tracker"
@@ -0,0 +1,26 @@
1
+ import {Route} from "../router"
2
+
3
+ const controllerRouteMap = new Map<string, Route[]>()
4
+
5
+ export class ControllerRouteTracker {
6
+ static getRoutes(controllerName: string): Route[] {
7
+ return controllerRouteMap.get(controllerName) || []
8
+ }
9
+
10
+ static setRoutes(controllerName: string, routes: Route[]): void {
11
+ controllerRouteMap.set(controllerName, routes)
12
+ }
13
+
14
+ static removeRoutes(controllerName: string, router: { remove(route: Route): void }): void {
15
+ const routes = controllerRouteMap.get(controllerName)
16
+ if (!routes) return
17
+ for (const route of routes) {
18
+ router.remove(route)
19
+ }
20
+ controllerRouteMap.delete(controllerName)
21
+ }
22
+
23
+ static clear(): void {
24
+ controllerRouteMap.clear()
25
+ }
26
+ }
@@ -9,6 +9,34 @@ export class HookStore {
9
9
  this.hooks.set(name, list)
10
10
  }
11
11
 
12
+ remove(name: HookNameType, handler?: HookHandlerCallable) {
13
+ if (!this.hooks.has(name)) return
14
+ if (!handler) {
15
+ this.hooks.delete(name)
16
+ return
17
+ }
18
+ const list = this.hooks.get(name)!
19
+ const idx = list.indexOf(handler)
20
+ if (idx !== -1) list.splice(idx, 1)
21
+ if (list.length === 0) this.hooks.delete(name)
22
+ else this.hooks.set(name, list)
23
+ }
24
+
25
+ replace(name: HookNameType, oldHandler: HookHandlerCallable, newHandler: HookHandlerCallable) {
26
+ if (!this.hooks.has(name)) {
27
+ this.add(name, newHandler)
28
+ return
29
+ }
30
+ const list = this.hooks.get(name)!
31
+ const idx = list.indexOf(oldHandler)
32
+ if (idx !== -1) {
33
+ list[idx] = newHandler
34
+ } else {
35
+ list.push(newHandler)
36
+ }
37
+ this.hooks.set(name, list)
38
+ }
39
+
12
40
  async run(name: HookNameType, ctx: any) {
13
41
  const list = this.hooks.get(name)
14
42
  if (!list) return
@@ -61,6 +61,29 @@ export class Injection {
61
61
  return this;
62
62
  }
63
63
 
64
+ static invalidate(name: string): typeof this {
65
+ const name_ = this.normalizeName(name);
66
+ if (this._instances.has(name_)) {
67
+ const scopeInstances = this._instances.get(name_)!;
68
+ for (const [scope, instance] of scopeInstances) {
69
+ if (typeof instance.onUnmount === 'function') {
70
+ try { instance.onUnmount() } catch { /* noop */ }
71
+ }
72
+ }
73
+ this._instances.delete(name_);
74
+ }
75
+ return this;
76
+ }
77
+
78
+ static invalidateCascade(name: string): typeof this {
79
+ this.invalidate(name);
80
+ const dependents = this.getDependents(name);
81
+ for (const dep of dependents) {
82
+ this.invalidateCascade(dep);
83
+ }
84
+ return this;
85
+ }
86
+
64
87
  static getDependents(name: string): string[] {
65
88
  return Array.from(this._dependents.get(this.normalizeName(name)) || []);
66
89
  }
@@ -9,6 +9,36 @@ export class MiddlewarePipeline {
9
9
  return this;
10
10
  }
11
11
 
12
+ replace(name: string, mw: MiddlewareType): this {
13
+ const normalized = name.toLowerCase()
14
+ for (let i = 0; i < this.stack.length; i++) {
15
+ const entry = this.stack[i]
16
+ let entryName: string | undefined
17
+ if (typeof entry === 'function') {
18
+ entryName = entry.name?.toLowerCase()
19
+ } else if (typeof entry === 'object' && entry !== null && 'name' in entry) {
20
+ entryName = (entry as any).name?.toLowerCase()
21
+ }
22
+ if (entryName === normalized) {
23
+ this.stack[i] = mw
24
+ return this
25
+ }
26
+ }
27
+ this.stack.push(mw)
28
+ return this;
29
+ }
30
+
31
+ remove(name: string): this {
32
+ const normalized = name.toLowerCase()
33
+ this.stack = this.stack.filter(entry => {
34
+ if (typeof entry === 'function') return entry.name?.toLowerCase() !== normalized
35
+ if (typeof entry === 'object' && entry !== null && 'name' in entry)
36
+ return (entry as any).name?.toLowerCase() !== normalized
37
+ return true
38
+ })
39
+ return this;
40
+ }
41
+
12
42
  clear(): this {
13
43
  this.stack = []
14
44
  return this;
@@ -4,6 +4,7 @@ import {Raiton} from "..";
4
4
  import {HttpException} from "../../framework/exceptions";
5
5
  import {ThrowableResponse} from "../../framework/responses/http-throwable";
6
6
  import {collectRouteArguments, validateDtoArguments, validateResponse, runMiddlewares} from "./handler.utils";
7
+ import {RaitonResponses, HttpStatus} from "../../framework";
7
8
 
8
9
  export function createHandler(
9
10
  instance: any,
@@ -33,16 +34,18 @@ export function createHandler(
33
34
  return err.render()
34
35
  }
35
36
 
36
- return {
37
- statusCode: 500,
38
- error: true,
39
- message: err.message ?? err,
40
- data: null,
41
- stack: isDevelopment
42
- ? (typeof err.stack === 'string' ? err.stack.split('\n')
43
- : [String(err.stack || err.toString() || err.message || err.name || 'Unknown error')])
44
- .map((l: any) => typeof l === 'string' ? l.trim() : String(l)) : undefined
45
- };
37
+ return RaitonResponses(
38
+ err.message ?? err,
39
+ null,
40
+ HttpStatus.INTERNAL_SERVER_ERROR,
41
+ {
42
+ error: true,
43
+ errorStack: isDevelopment
44
+ ? (typeof err.stack === 'string' ? err.stack.split('\n')
45
+ : [String(err.stack || err.toString() || err.message || err.name || 'Unknown error')])
46
+ .map((l: any) => typeof l === 'string' ? l.trim() : String(l)) : undefined
47
+ }
48
+ );
46
49
  }
47
50
  };
48
51
 
@@ -1,5 +1,10 @@
1
- import {registerSocket} from "./metadata";
1
+ import {registerSocket, unregisterSocket, getSocketMetadata} from "./metadata";
2
+ import {Injection} from "../injection";
2
3
 
3
4
  export function compileSocket(SocketClass: any) {
5
+ const metadata = getSocketMetadata(SocketClass.prototype || SocketClass)
6
+ const namespace = metadata.namespace || '/'
7
+ unregisterSocket(namespace)
8
+ Injection.invalidateCascade(SocketClass.name)
4
9
  return registerSocket(SocketClass);
5
10
  }
@@ -28,6 +28,15 @@ export function registerSocket(construct: any): SocketRegistryEntryInterface {
28
28
  return entry;
29
29
  }
30
30
 
31
+ export function unregisterSocket(constructOrNamespace: string | any): boolean {
32
+ if (typeof constructOrNamespace === 'string') {
33
+ return registry.delete(constructOrNamespace);
34
+ }
35
+ const metadata = getSocketMetadata(constructOrNamespace.prototype || constructOrNamespace);
36
+ const namespace = metadata.namespace || '/';
37
+ return registry.delete(namespace);
38
+ }
39
+
31
40
  export function getSocketRegistry(): Map<string, SocketRegistryEntryInterface> {
32
41
  return registry;
33
42
  }
@@ -4,6 +4,47 @@ import type {ConstructorType} from "../types";
4
4
  import {Raiton} from "../core/raiton";
5
5
  import {isArtifact} from "./utilities";
6
6
 
7
+ export type HmrChannel =
8
+ | 'hmr:di'
9
+ | 'hmr:controller'
10
+ | 'hmr:socket'
11
+ | 'hmr:middleware'
12
+ | 'hmr:hook'
13
+
14
+ export interface ArtifactClassification {
15
+ channel: HmrChannel
16
+ artifactType: string
17
+ }
18
+
19
+ export const HMR_CHANNELS: Record<HmrChannel, readonly string[]> = {
20
+ 'hmr:di': [
21
+ 'service',
22
+ 'provider',
23
+ 'type',
24
+ 'interface',
25
+ 'repository',
26
+ 'database',
27
+ 'db',
28
+ 'util',
29
+ 'utility',
30
+ 'source',
31
+ 'use-case',
32
+ 'dto',
33
+ 'vm',
34
+ 'entity',
35
+ 'model',
36
+ 'schema',
37
+ 'validator',
38
+ 'strategy',
39
+ 'strategy-provider',
40
+ 'strategy-type',
41
+ ],
42
+ 'hmr:controller': ['controller'],
43
+ 'hmr:socket': ['socket'],
44
+ 'hmr:middleware': ['middleware'],
45
+ 'hmr:hook': ['hook', 'event', 'listener'],
46
+ }
47
+
7
48
  export class Artifacts {
8
49
 
9
50
  static readonly types: Set<string> = new Set();
@@ -54,6 +95,17 @@ export class Artifacts {
54
95
  .some(Boolean)
55
96
  }
56
97
 
98
+ static classify(filename: string): ArtifactClassification | null {
99
+ for (const [channel, types] of Object.entries(HMR_CHANNELS)) {
100
+ for (const type of types) {
101
+ if (isArtifact(filename, type)) {
102
+ return {channel: channel as HmrChannel, artifactType: type}
103
+ }
104
+ }
105
+ }
106
+ return null
107
+ }
108
+
57
109
  static reload(modulo: any, filename?: string) {
58
110
 
59
111
  if (Raiton.thread?.builder.options.serve === false)
@@ -74,4 +126,82 @@ export class Artifacts {
74
126
  }
75
127
 
76
128
  }
129
+
130
+ static reloadDi(modulo: any, filename?: string) {
131
+
132
+ if (Raiton.thread?.builder.options.serve === false)
133
+ return Logger.warn(
134
+ 'Artifact reload is only available in development mode'
135
+ )
136
+
137
+ for (const mod of Object.values(modulo)) {
138
+ const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
139
+ typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
140
+ );
141
+
142
+ if (typeof name === 'string' && Injection.has(name)) {
143
+ if (filename) Injection.registerArtifactPath(name, filename);
144
+ Injection.updateConstruct(name, mod as ConstructorType)
145
+ Injection.invalidateCascade(name)
146
+ }
147
+ }
148
+ }
149
+
150
+ static reloadMiddleware(modulo: any, filename?: string) {
151
+
152
+ if (Raiton.thread?.builder.options.serve === false)
153
+ return Logger.warn(
154
+ 'Artifact reload is only available in development mode'
155
+ )
156
+
157
+ const app = Raiton.thread?.application
158
+ if (!app) return
159
+
160
+ const rootScope = (app as any).root
161
+ if (!rootScope?.middleware) return
162
+
163
+ for (const mod of Object.values(modulo)) {
164
+ const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
165
+ typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
166
+ );
167
+
168
+ if (typeof name === 'string') {
169
+ if (typeof mod === 'function') {
170
+ const instance = new (mod as ConstructorType)()
171
+ rootScope.middleware.replace(name, instance)
172
+ } else if (typeof mod === 'object' && mod !== null) {
173
+ rootScope.middleware.replace(name, mod)
174
+ }
175
+ }
176
+ }
177
+ }
178
+
179
+ static reloadHook(modulo: any, filename?: string) {
180
+
181
+ if (Raiton.thread?.builder.options.serve === false)
182
+ return Logger.warn(
183
+ 'Artifact reload is only available in development mode'
184
+ )
185
+
186
+ const app = Raiton.thread?.application
187
+ if (!app) return
188
+
189
+ const rootScope = (app as any).root
190
+ if (!rootScope?.hooks) return
191
+
192
+ for (const mod of Object.values(modulo)) {
193
+ const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
194
+ typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
195
+ );
196
+
197
+ if (typeof name === 'string') {
198
+ if (typeof mod === 'function') {
199
+ const instance = new (mod as ConstructorType)()
200
+ rootScope.hooks.replace(name, instance)
201
+ } else if (typeof mod === 'object' && mod !== null) {
202
+ rootScope.hooks.replace(name, mod)
203
+ }
204
+ }
205
+ }
206
+ }
77
207
  }
@@ -1,7 +1,7 @@
1
1
  import {GuardOptions} from "../../types";
2
2
  import {Middleware} from "./middleware.decorator";
3
3
  import {RaitonGuards} from "../../core/guards";
4
- import {HttpStatus} from "../enums";
4
+ import {HttpStatus, RaitonResponses} from "..";
5
5
 
6
6
  export function createGuardDecoration({name, handler}: GuardOptions) {
7
7
  return Middleware(async ({next, context}) => {
@@ -15,9 +15,6 @@ export function createGuardDecoration({name, handler}: GuardOptions) {
15
15
  if (response) return next()
16
16
 
17
17
  context.reply.status(HttpStatus.FORBIDDEN)
18
- return context.reply.send({
19
- error: true,
20
- message: 'Forbidden'
21
- });
18
+ return context.reply.send(RaitonResponses('Forbidden', null, HttpStatus.FORBIDDEN, {error: true}));
22
19
  });
23
20
  }
@@ -1,5 +1,6 @@
1
1
  import {definePlugin} from "../../../core/plugins";
2
2
  import {MiddlewareParametersInterface} from "../../../types";
3
+ import {RaitonResponses, HttpStatus} from "../..";
3
4
 
4
5
 
5
6
  export const secureBodyLimit = (maxBytes = 1_000_000) =>
@@ -10,8 +11,7 @@ export const secureBodyLimit = (maxBytes = 1_000_000) =>
10
11
  )
11
12
 
12
13
  if (len > maxBytes) {
13
- context.reply.status(413)
14
- return context.send({ error: 'Payload too large' })
14
+ return context.send(RaitonResponses('Payload too large', null, HttpStatus.PAYLOAD_TOO_LARGE, {error: true}))
15
15
  }
16
16
 
17
17
  await next()
@@ -1,13 +1,13 @@
1
1
  import {definePlugin} from "../../../core/plugins";
2
2
  import {ContextInterface, MiddlewareParametersInterface, MiddlewareNextCallable} from "../../../types";
3
+ import {RaitonResponses, HttpStatus} from "../..";
3
4
 
4
5
 
5
6
  export const secureMethodGuard = (allowed: string[]) =>
6
7
  definePlugin((scope) => {
7
8
  scope.use(async ({context, next}: MiddlewareParametersInterface) => {
8
9
  if (!allowed.includes(context.req.method)) {
9
- context.reply.status(405)
10
- return context.send({ error: 'Method not allowed' })
10
+ return context.send(RaitonResponses('Method not allowed', null, HttpStatus.METHOD_NOT_ALLOWED, {error: true}))
11
11
  }
12
12
  await next()
13
13
  })
@@ -1,5 +1,6 @@
1
1
  import {definePlugin} from "../../../core/plugins";
2
2
  import {ContextInterface, MiddlewareParametersInterface, MiddlewareNextCallable} from "../../../types";
3
+ import {RaitonResponses, HttpStatus} from "../..";
3
4
 
4
5
 
5
6
  export interface RateLimitOptions {
@@ -33,8 +34,7 @@ export const secureRateLimit = (
33
34
  hits.set(ip, entry)
34
35
 
35
36
  if (entry.count > max) {
36
- context.reply.status(429)
37
- return context.send({error: 'Too many requests'})
37
+ return context.send(RaitonResponses('Too many requests', null, HttpStatus.TOO_MANY_REQUESTS, {error: true}))
38
38
  }
39
39
 
40
40
  await next()
@@ -12,7 +12,9 @@ export function RaitonResponses(
12
12
  ) {
13
13
 
14
14
  if (metadata) {
15
- metadata.error = typeof data?.error === 'boolean' ? data?.error : false
15
+ if (metadata.error === undefined) {
16
+ metadata.error = typeof data?.error === 'boolean' ? data?.error : false
17
+ }
16
18
  metadata.errorStack = (metadata.errorStack instanceof Error)
17
19
  ? metadata.errorStack
18
20
  : (Raiton.thread?.builder?.options?.serve
@@ -6,6 +6,7 @@ import {Logger} from "@protorians/logger";
6
6
  import {getRealIp} from "../../utilities";
7
7
  import {findSocketForPath} from "../../../core/socket";
8
8
  import {Injection} from "../../../core/injection";
9
+ import {RaitonResponses, HttpStatus} from "../..";
9
10
 
10
11
  export const bunRuntime: RuntimeAdapterInterface = {
11
12
  createServer(handler, options?: RuntimeServerOptionsInterface) {
@@ -50,11 +51,11 @@ export const bunRuntime: RuntimeAdapterInterface = {
50
51
  : entry.metadata.events.find((item: any) => item.type === 'message')
51
52
 
52
53
  if (!event) {
53
- ws.send(JSON.stringify({
54
- statusCode: 404,
55
- message: `Socket event "${eventName ?? 'message'}" not found`,
56
- data: null
57
- }))
54
+ ws.send(JSON.stringify(RaitonResponses(
55
+ `Socket event "${eventName ?? 'message'}" not found`,
56
+ null,
57
+ HttpStatus.NOT_FOUND
58
+ )))
58
59
  return
59
60
  }
60
61
 
@@ -64,11 +65,11 @@ export const bunRuntime: RuntimeAdapterInterface = {
64
65
  }
65
66
  } catch (e: any) {
66
67
  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
- }))
68
+ ws.send(JSON.stringify(RaitonResponses(
69
+ 'Internal server error',
70
+ null,
71
+ HttpStatus.INTERNAL_SERVER_ERROR
72
+ )))
72
73
  }
73
74
  },
74
75
  async close(ws: any) {
@@ -1,4 +1,5 @@
1
1
  import {WatchEventType} from "node:fs";
2
+ import type {HmrChannel} from "../framework/artifacts";
2
3
 
3
4
  export interface StartCommandOptionsInterface {
4
5
  develop?: boolean;
@@ -46,4 +47,6 @@ export interface BuilderHMRDeclarationInterface {
46
47
  timestamp?: number;
47
48
  version?: number;
48
49
  type?: WatchEventType
50
+ channel?: HmrChannel
51
+ artifactType?: string
49
52
  }
@@ -4,4 +4,9 @@ export interface RaitonSignalMapInterface {
4
4
  ready?: undefined;
5
5
  errors: any;
6
6
  'hmr:artifact': BuilderHMRDeclarationInterface;
7
+ 'hmr:di': BuilderHMRDeclarationInterface;
8
+ 'hmr:controller': BuilderHMRDeclarationInterface;
9
+ 'hmr:socket': BuilderHMRDeclarationInterface;
10
+ 'hmr:middleware': BuilderHMRDeclarationInterface;
11
+ 'hmr:hook': BuilderHMRDeclarationInterface;
7
12
  }