raiton 3.1.1 → 5.4.0-beta.2

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 (120) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +38 -3
  3. package/build/bin/index.mjs +822 -524
  4. package/examples/user-controller.example.ts +53 -0
  5. package/package.json +8 -10
  6. package/scripts/update-version.ts +1 -1
  7. package/source/bin/bootstrapper.ts +1 -1
  8. package/source/bin/cli-tools.ts +2 -0
  9. package/source/commands/build.command.ts +2 -1
  10. package/source/commands/develop.command.ts +2 -1
  11. package/source/commands/start.command.ts +15 -10
  12. package/source/core/application.ts +42 -33
  13. package/source/core/artifacts/artifact.ts +10 -0
  14. package/source/core/artifacts/index.ts +1 -0
  15. package/source/core/artifacts/runner.ts +3 -0
  16. package/source/core/builder.ts +44 -15
  17. package/source/core/config/define.ts +1 -1
  18. package/source/core/controller/builder.ts +1 -1
  19. package/source/core/controller/metadata.ts +1 -1
  20. package/source/core/hooks.ts +0 -8
  21. package/source/core/index.ts +15 -14
  22. package/source/core/injection/injection.ts +9 -6
  23. package/source/core/middleware/compose.ts +1 -1
  24. package/source/core/middleware/pipeline.ts +2 -8
  25. package/source/core/plugins/scope.ts +18 -6
  26. package/source/core/router/handler.ts +26 -80
  27. package/source/core/router/handler.utils.ts +135 -0
  28. package/source/core/router/matcher.ts +13 -9
  29. package/source/core/router/router.ts +6 -2
  30. package/source/core/socket/index.ts +1 -0
  31. package/source/core/socket/metadata.ts +13 -0
  32. package/source/core/thread.ts +23 -20
  33. package/source/{sdk → framework}/artifacts.ts +8 -1
  34. package/source/framework/constants/decorators.constant.ts +17 -0
  35. package/source/framework/decorators/api-response.decorator.ts +127 -0
  36. package/source/framework/decorators/api.decorator.ts +185 -0
  37. package/source/framework/decorators/index.ts +9 -0
  38. package/source/{sdk/decorators/parametrable.ts → framework/decorators/parametrable.decorator.ts} +1 -1
  39. package/source/framework/decorators/socket.decorator.ts +41 -0
  40. package/source/{sdk → framework}/encryption.ts +2 -1
  41. package/source/{sdk → framework}/enums/encrypted.enum.ts +2 -2
  42. package/source/{sdk → framework}/enums/http-parameters.enum.ts +1 -0
  43. package/source/{sdk → framework}/enums/runtime.enum.ts +2 -2
  44. package/source/{sdk → framework}/env.ts +2 -2
  45. package/source/{sdk → framework}/exceptions/http-exception.ts +1 -1
  46. package/source/{sdk → framework}/index.ts +3 -2
  47. package/source/{sdk → framework}/plugins/body-parser.plugin.ts +28 -11
  48. package/source/framework/plugins/index.ts +3 -0
  49. package/source/framework/plugins/openapi.plugin.ts +98 -0
  50. package/source/framework/plugins/security/cors.ts +78 -0
  51. package/source/{sdk → framework}/responses/helpers.ts +4 -3
  52. package/source/{sdk → framework}/responses/http-throwable.ts +2 -2
  53. package/source/{sdk → framework}/responses/http.ts +3 -3
  54. package/source/{sdk → framework}/runtime/bun/server.ts +6 -2
  55. package/source/framework/runtime/deno/server.ts +104 -0
  56. package/source/{sdk → framework}/runtime/index.ts +18 -13
  57. package/source/framework/runtime/node/reply.ts +37 -0
  58. package/source/framework/runtime/node/request.ts +47 -0
  59. package/source/framework/runtime/node/server.ts +32 -0
  60. package/source/framework/runtime/web/server.ts +73 -0
  61. package/source/{sdk → framework}/utilities/artifact.util.ts +3 -0
  62. package/source/framework/utilities/cookie.util.ts +11 -0
  63. package/source/{sdk → framework}/utilities/index.ts +3 -1
  64. package/source/framework/utilities/openapi.utils.ts +497 -0
  65. package/source/framework/view-model.ts +4 -0
  66. package/source/types/access-guards.ts +4 -0
  67. package/source/types/application.ts +1 -1
  68. package/source/types/artifact.ts +42 -1
  69. package/source/types/builder.ts +6 -1
  70. package/source/types/controller.ts +1 -1
  71. package/source/types/http-responses.ts +8 -0
  72. package/source/types/index.ts +1 -0
  73. package/source/types/responses.ts +1 -1
  74. package/source/types/router.ts +1 -1
  75. package/source/types/runtime.ts +5 -3
  76. package/source/types/scheme.ts +153 -0
  77. package/source/types/socket.ts +15 -0
  78. package/source/types/thread.ts +4 -2
  79. package/source/sdk/constants/decorators.constant.ts +0 -8
  80. package/source/sdk/decorators/index.ts +0 -6
  81. package/source/sdk/plugins/index.ts +0 -2
  82. package/source/sdk/plugins/security/cors.ts +0 -44
  83. package/source/sdk/runtime/deno/server.ts +0 -53
  84. package/source/sdk/runtime/node/reply.ts +0 -0
  85. package/source/sdk/runtime/node/request.ts +0 -0
  86. package/source/sdk/runtime/node/server.ts +0 -60
  87. package/source/sdk/runtime/web/server.ts +0 -57
  88. /package/source/{sdk → framework}/constants/index.ts +0 -0
  89. /package/source/{sdk → framework}/constants/microservices.constant.ts +0 -0
  90. /package/source/{sdk → framework}/controllers.ts +0 -0
  91. /package/source/{sdk → framework}/data-transfer-object.ts +0 -0
  92. /package/source/{sdk → framework}/decorators/access-guard.decorator.ts +0 -0
  93. /package/source/{sdk → framework}/decorators/controllable.decorator.ts +0 -0
  94. /package/source/{sdk → framework}/decorators/guard.decorator.ts +0 -0
  95. /package/source/{sdk → framework}/decorators/injection.decorator.ts +0 -0
  96. /package/source/{sdk → framework}/decorators/middleware.decorator.ts +0 -0
  97. /package/source/{sdk → framework}/decorators/routable.decorator.ts +0 -0
  98. /package/source/{sdk → framework}/enums/event.message.enum.ts +0 -0
  99. /package/source/{sdk → framework}/enums/http-method.enum.ts +0 -0
  100. /package/source/{sdk → framework}/enums/http-status.enum.ts +0 -0
  101. /package/source/{sdk → framework}/enums/index.ts +0 -0
  102. /package/source/{sdk → framework}/enums/timestamp.enum.ts +0 -0
  103. /package/source/{sdk → framework}/exceptions/index.ts +0 -0
  104. /package/source/{sdk → framework}/exceptions/throwable.ts +0 -0
  105. /package/source/{sdk → framework}/parameter-bag.ts +0 -0
  106. /package/source/{sdk → framework}/plugins/security/body-limit.ts +0 -0
  107. /package/source/{sdk → framework}/plugins/security/headers.ts +0 -0
  108. /package/source/{sdk → framework}/plugins/security/index.ts +0 -0
  109. /package/source/{sdk → framework}/plugins/security/method-guard.ts +0 -0
  110. /package/source/{sdk → framework}/plugins/security/rate-limit.ts +0 -0
  111. /package/source/{sdk → framework}/repositories.ts +0 -0
  112. /package/source/{sdk → framework}/responses/error.ts +0 -0
  113. /package/source/{sdk → framework}/responses/index.ts +0 -0
  114. /package/source/{sdk → framework}/services.ts +0 -0
  115. /package/source/{sdk → framework}/utilities/alias-path.util.ts +0 -0
  116. /package/source/{sdk → framework}/utilities/callable.util.ts +0 -0
  117. /package/source/{sdk → framework}/utilities/json.util.ts +0 -0
  118. /package/source/{sdk → framework}/utilities/path.util.ts +0 -0
  119. /package/source/{sdk → framework}/utilities/url.ts +0 -0
  120. /package/source/{sdk → framework}/utilities/utilities.util.ts +0 -0
@@ -3873,13 +3873,13 @@ var require_Reflect2 = __commonJS(() => {
3873
3873
  }
3874
3874
  return { value: undefined, done: true };
3875
3875
  };
3876
- MapIterator2.prototype.throw = function(error) {
3876
+ MapIterator2.prototype.throw = function(error2) {
3877
3877
  if (this._index >= 0) {
3878
3878
  this._index = -1;
3879
3879
  this._keys = arraySentinel;
3880
3880
  this._values = arraySentinel;
3881
3881
  }
3882
- throw error;
3882
+ throw error2;
3883
3883
  };
3884
3884
  MapIterator2.prototype.return = function(value) {
3885
3885
  if (this._index >= 0) {
@@ -4279,7 +4279,7 @@ var require_format = __commonJS((exports, module) => {
4279
4279
  // node_modules/node-gyp-build/node-gyp-build.js
4280
4280
  var require_node_gyp_build = __commonJS((exports, module) => {
4281
4281
  var fs2 = __require("fs");
4282
- var path5 = __require("path");
4282
+ var path3 = __require("path");
4283
4283
  var os = __require("os");
4284
4284
  var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
4285
4285
  var vars = process.config && process.config.variables || {};
@@ -4296,24 +4296,24 @@ var require_node_gyp_build = __commonJS((exports, module) => {
4296
4296
  return runtimeRequire(load.resolve(dir));
4297
4297
  }
4298
4298
  load.resolve = load.path = function(dir) {
4299
- dir = path5.resolve(dir || ".");
4299
+ dir = path3.resolve(dir || ".");
4300
4300
  try {
4301
- var name = runtimeRequire(path5.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
4301
+ var name = runtimeRequire(path3.join(dir, "package.json")).name.toUpperCase().replace(/-/g, "_");
4302
4302
  if (process.env[name + "_PREBUILD"])
4303
4303
  dir = process.env[name + "_PREBUILD"];
4304
4304
  } catch (err) {}
4305
4305
  if (!prebuildsOnly) {
4306
- var release = getFirst(path5.join(dir, "build/Release"), matchBuild);
4306
+ var release = getFirst(path3.join(dir, "build/Release"), matchBuild);
4307
4307
  if (release)
4308
4308
  return release;
4309
- var debug = getFirst(path5.join(dir, "build/Debug"), matchBuild);
4309
+ var debug = getFirst(path3.join(dir, "build/Debug"), matchBuild);
4310
4310
  if (debug)
4311
4311
  return debug;
4312
4312
  }
4313
4313
  var prebuild = resolve(dir);
4314
4314
  if (prebuild)
4315
4315
  return prebuild;
4316
- var nearby = resolve(path5.dirname(process.execPath));
4316
+ var nearby = resolve(path3.dirname(process.execPath));
4317
4317
  if (nearby)
4318
4318
  return nearby;
4319
4319
  var target = [
@@ -4332,16 +4332,16 @@ var require_node_gyp_build = __commonJS((exports, module) => {
4332
4332
  loaded from: ` + dir + `
4333
4333
  `);
4334
4334
  function resolve(dir2) {
4335
- var tuples = readdirSync(path5.join(dir2, "prebuilds")).map(parseTuple);
4335
+ var tuples = readdirSync(path3.join(dir2, "prebuilds")).map(parseTuple);
4336
4336
  var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0];
4337
4337
  if (!tuple)
4338
4338
  return;
4339
- var prebuilds = path5.join(dir2, "prebuilds", tuple.name);
4339
+ var prebuilds = path3.join(dir2, "prebuilds", tuple.name);
4340
4340
  var parsed = readdirSync(prebuilds).map(parseTags);
4341
4341
  var candidates = parsed.filter(matchTags(runtime2, abi));
4342
4342
  var winner = candidates.sort(compareTags(runtime2))[0];
4343
4343
  if (winner)
4344
- return path5.join(prebuilds, winner.file);
4344
+ return path3.join(prebuilds, winner.file);
4345
4345
  }
4346
4346
  };
4347
4347
  function readdirSync(dir) {
@@ -4353,7 +4353,7 @@ var require_node_gyp_build = __commonJS((exports, module) => {
4353
4353
  }
4354
4354
  function getFirst(dir, filter) {
4355
4355
  var files = readdirSync(dir).filter(filter);
4356
- return files[0] && path5.join(dir, files[0]);
4356
+ return files[0] && path3.join(dir, files[0]);
4357
4357
  }
4358
4358
  function matchBuild(name) {
4359
4359
  return /\.node$/.test(name);
@@ -4630,8 +4630,8 @@ var require_promises = __commonJS((exports, module) => {
4630
4630
  // node_modules/bcrypt/bcrypt.js
4631
4631
  var require_bcrypt = __commonJS((exports, module) => {
4632
4632
  var __dirname = "/home/runner/work/raiton/raiton/node_modules/bcrypt";
4633
- var path5 = __require("path");
4634
- var bindings = require_node_gyp_build2()(path5.resolve(__dirname));
4633
+ var path3 = __require("path");
4634
+ var bindings = require_node_gyp_build2()(path3.resolve(__dirname));
4635
4635
  var crypto2 = __require("crypto");
4636
4636
  var promises = require_promises();
4637
4637
  function genSaltSync(rounds, minor) {
@@ -4799,7 +4799,7 @@ var require_bcrypt = __commonJS((exports, module) => {
4799
4799
  });
4800
4800
 
4801
4801
  // source/bin/index.ts
4802
- var import_reflect_metadata5 = __toESM(require_Reflect(), 1);
4802
+ var import_reflect_metadata8 = __toESM(require_Reflect(), 1);
4803
4803
 
4804
4804
  // node_modules/commander/esm.mjs
4805
4805
  var import__ = __toESM(require_commander(), 1);
@@ -4817,7 +4817,7 @@ var {
4817
4817
  Help
4818
4818
  } = import__.default;
4819
4819
  // package.json
4820
- var version = "3.1.1";
4820
+ var version = "5.4.0-beta.2";
4821
4821
 
4822
4822
  // source/bin/cli.ts
4823
4823
  var CLI = new Command;
@@ -6211,7 +6211,7 @@ class RaitonConfig {
6211
6211
  }
6212
6212
  }
6213
6213
  }
6214
- // source/sdk/utilities/artifact.util.ts
6214
+ // source/framework/utilities/artifact.util.ts
6215
6215
  function isControllerArtifact(filename) {
6216
6216
  return isArtifact(filename, "controller");
6217
6217
  }
@@ -6223,7 +6223,15 @@ function isArtifact(filename, artifact) {
6223
6223
  filename.endsWith(`.${artifact}.cjs`)
6224
6224
  ].some(Boolean);
6225
6225
  }
6226
- // source/sdk/utilities/path.util.ts
6226
+ // source/framework/utilities/json.util.ts
6227
+ function tryParseJson(obj) {
6228
+ try {
6229
+ return JSON.parse(obj);
6230
+ } catch (e) {
6231
+ return null;
6232
+ }
6233
+ }
6234
+ // source/framework/utilities/path.util.ts
6227
6235
  import path2 from "node:path";
6228
6236
  import { fileURLToPath } from "node:url";
6229
6237
  function getDirname(importMetaUrl) {
@@ -6236,245 +6244,409 @@ function getPackageRoot(importMetaUrl) {
6236
6244
  }
6237
6245
  return dirname;
6238
6246
  }
6239
- // source/core/directories.ts
6240
- import path4 from "node:path";
6241
- class RaitonDirectories {
6242
- static index = `.${Raiton.identifier}`;
6243
- static bootstrapFile = "main.ts";
6244
- static caches(workdir) {
6245
- return path4.join(workdir, this.index, "caches");
6246
- }
6247
- static artifacts(workdir) {
6248
- return path4.join(workdir, this.index, "artifacts");
6249
- }
6250
- static server(workdir) {
6251
- return path4.join(workdir, this.index, "server");
6252
- }
6253
- static root(workdir) {
6254
- return path4.join(workdir, this.index);
6255
- }
6256
- static app() {
6257
- return path4.join(Raiton.thread?.builder.workdir || "", RaitonConfig.get("rootDir") || "./");
6258
- }
6259
- }
6260
- // source/sdk/constants/decorators.constant.ts
6247
+ // source/framework/constants/decorators.constant.ts
6261
6248
  var METADATA_KEYS = {
6262
6249
  CONTROLLERS: Symbol("controller:meta"),
6250
+ SOCKETS: Symbol("socket:meta"),
6251
+ SOCKET_EVENTS: Symbol("socket:event:meta"),
6263
6252
  ROUTE_PARAMETERS: Symbol("route:meta"),
6264
6253
  GRAFTS: Symbol("graft:meta"),
6265
6254
  CONTAINER: Symbol("container:meta"),
6266
6255
  INJECT_PARAMETERS: Symbol("inject:parameters"),
6267
- INJECT_PROPERTIES: Symbol("inject:properties")
6256
+ INJECT_PROPERTIES: Symbol("inject:properties"),
6257
+ API_RESPONSES: Symbol("api:responses"),
6258
+ API_REQUEST_BODY: Symbol("api:requestBody"),
6259
+ API_PARAMETERS: Symbol("api:parameters"),
6260
+ API_TAGS: Symbol("api:tags"),
6261
+ API_OPERATION: Symbol("api:operation"),
6262
+ API_SECURITY: Symbol("api:security")
6268
6263
  };
6269
- // source/sdk/decorators/routable.decorator.ts
6270
- function stabilizeRoute(meta, { path: path5, method, propertyKey }) {
6271
- return {
6272
- ...meta.routes.filter((route) => route.path === path5 && route.method === method || route.propertyKey === propertyKey)[0] || {},
6273
- method,
6274
- path: path5,
6275
- propertyKey
6276
- };
6277
- }
6278
- function createRoutableDecorator(method) {
6279
- return (path5 = "") => (target, propertyKey) => {
6280
- const meta = getControllerMetadata(target);
6281
- const route = stabilizeRoute(meta, {
6282
- method,
6283
- path: path5,
6284
- propertyKey
6264
+ // source/framework/responses/http.ts
6265
+ class HttpResponse {
6266
+ response;
6267
+ static push(response) {
6268
+ throw new ThrowableResponse({
6269
+ statusCode: response.statusCode || 400 /* BAD_REQUEST */,
6270
+ message: response.message || "No response message provided",
6271
+ data: response.data,
6272
+ error: response.error,
6273
+ errorStack: response.errorStack
6285
6274
  });
6286
- meta.routes.push(route);
6287
- };
6288
- }
6289
- var Get = createRoutableDecorator("GET" /* GET */);
6290
- var Post = createRoutableDecorator("POST" /* POST */);
6291
- var Put = createRoutableDecorator("PUT" /* PUT */);
6292
- var Patch = createRoutableDecorator("PATCH" /* PATCH */);
6293
- var Options = createRoutableDecorator("OPTIONS" /* OPTIONS */);
6294
- var Trace = createRoutableDecorator("TRACE" /* TRACE */);
6295
- var Delete = createRoutableDecorator("DELETE" /* DELETE */);
6296
- var Head = createRoutableDecorator("HEAD" /* HEAD */);
6297
- // source/sdk/decorators/parametrable.ts
6298
- var import_reflect_metadata = __toESM(require_Reflect2(), 1);
6299
- function createRouteParametrableDecorator(type, callable2) {
6300
- return (key) => {
6301
- return (target, propertyKey, index) => {
6302
- const params = Reflect.getMetadata(METADATA_KEYS.ROUTE_PARAMETERS, target.constructor) || {};
6303
- const metatypes = Reflect.getMetadata("design:paramtypes", target, propertyKey);
6304
- const metatype = metatypes ? metatypes[index] : undefined;
6305
- if (!params[propertyKey]) {
6306
- params[propertyKey] = [];
6307
- }
6308
- params[propertyKey].push({ index, type, key, callable: callable2, metatype });
6309
- Reflect.defineMetadata(METADATA_KEYS.ROUTE_PARAMETERS, params, target.constructor);
6310
- };
6311
- };
6312
- }
6313
- var Query = createRouteParametrableDecorator("query" /* QUERY */);
6314
- var Param = createRouteParametrableDecorator("param" /* PARAM */);
6315
- var Body = createRouteParametrableDecorator("body" /* BODY */);
6316
- var UploadedFile = createRouteParametrableDecorator("upload" /* UPLOAD_FILE */);
6317
- var Headers2 = createRouteParametrableDecorator("header" /* HEADER */);
6318
- var Req = createRouteParametrableDecorator("req" /* REQ */);
6319
- var Reply = createRouteParametrableDecorator("reply" /* REPLY */);
6320
- // source/sdk/decorators/injection.decorator.ts
6321
- var import_reflect_metadata3 = __toESM(require_Reflect2(), 1);
6322
-
6323
- // source/core/injection/injection.ts
6324
- var import_reflect_metadata2 = __toESM(require_Reflect2(), 1);
6325
- // source/sdk/exceptions/throwable.ts
6326
- class Throwable extends Error {
6327
- statusCode;
6328
- constructor(message, statusCode = 500, label) {
6329
- super(message);
6330
- this.statusCode = statusCode;
6331
- this.name = "Throwable";
6332
- if (label)
6333
- Logger.debug(LBadge.debug(label), message);
6334
- EventBus.dispatch(EventBusEnum.SERVER_THROW, { error: this });
6335
6275
  }
6336
- static error(message, soft = true, statusCode = 500) {
6337
- EventBus.dispatch(EventBusEnum.SERVER_ERROR, { message, soft });
6338
- if (!soft)
6339
- throw new Throwable(message, statusCode, "ERR");
6276
+ constructor(response) {
6277
+ this.response = response;
6340
6278
  }
6341
- static warning(message, soft = true, statusCode = 500) {
6342
- EventBus.dispatch(EventBusEnum.SERVER_WARNING, { message, soft });
6343
- if (!soft)
6344
- throw new Throwable(message, statusCode, "WRN");
6279
+ status(statusCode) {
6280
+ this.response.statusCode = statusCode;
6281
+ return this;
6345
6282
  }
6346
- static critical(message) {
6347
- Logger.debug(LBadge.debug("CRITICAL"), message);
6348
- EventBus.dispatch(EventBusEnum.SERVER_CRITICAL, { message });
6349
- process.exit(1);
6283
+ message(message) {
6284
+ this.response.message = message;
6285
+ return this;
6350
6286
  }
6351
- }
6352
- // source/core/injection/injection.ts
6353
- var camelCase = TextUtility.camelCase;
6354
-
6355
- class Injection {
6356
- static _classes = new Map;
6357
- static _instances = new Map;
6358
- static _resolutionStack = [];
6359
- static _dependents = new Map;
6360
- static _artifactPaths = new Map;
6361
- static get classes() {
6362
- return this._classes;
6287
+ data(data) {
6288
+ this.response.data = data;
6289
+ return this;
6363
6290
  }
6364
- static defaultScope = Symbol("default");
6365
- static get instances() {
6366
- return this._instances;
6291
+ error(error) {
6292
+ this.response.error = error;
6293
+ return this;
6367
6294
  }
6368
- static has(name) {
6369
- return this._classes.has(this.normalizeName(name));
6295
+ stack(stack) {
6296
+ this.response.errorStack = stack;
6297
+ return this;
6370
6298
  }
6371
- static clear() {
6372
- Logger.error("Clearing injection container");
6373
- this._classes.clear();
6374
- this._instances.clear();
6375
- this._dependents.clear();
6376
- this._artifactPaths.clear();
6299
+ render() {
6300
+ return new ThrowableResponse({ ...this.response }).render();
6377
6301
  }
6378
- static normalizeName(name) {
6379
- const stableName = camelCase(name);
6380
- return stableName[0].toLowerCase() + stableName.slice(1);
6302
+ }
6303
+
6304
+ // source/framework/responses/error.ts
6305
+ class HttpErrorResponse {
6306
+ stack = new Map;
6307
+ get entries() {
6308
+ return [...this.stack.values()];
6381
6309
  }
6382
- static registry(name, construct, lifetime = LifetimeEnum.SINGLETON, scope) {
6383
- if (!construct.name)
6384
- throw new Error("Le constructeur doit avoir un nom valide pour être enregistré dans le conteneur.");
6385
- this._classes.set(this.normalizeName(name), { name, construct, lifetime, scope });
6310
+ add(input) {
6311
+ this.stack.set(input.id, input);
6386
6312
  return this;
6387
6313
  }
6388
- static updateConstruct(name, construct) {
6389
- const name_ = this.normalizeName(name);
6390
- this._classes.set(name_, { ...this._classes.get(this.normalizeName(name)), construct });
6314
+ remove(id) {
6315
+ this.stack.delete(id);
6391
6316
  return this;
6392
6317
  }
6393
- static getDependents(name) {
6394
- return Array.from(this._dependents.get(this.normalizeName(name)) || []);
6318
+ get(id) {
6319
+ return this.stack.get(id);
6320
+ }
6321
+ has(id) {
6322
+ return this.stack.has(id);
6395
6323
  }
6396
- static registerArtifactPath(name, path5) {
6397
- this._artifactPaths.set(this.normalizeName(name), path5);
6324
+ clear() {
6325
+ this.stack.clear();
6398
6326
  return this;
6399
6327
  }
6400
- static getArtifactPath(name) {
6401
- return this._artifactPaths.get(this.normalizeName(name));
6328
+ get empty() {
6329
+ return this.stack.size === 0;
6402
6330
  }
6403
- static resolveArguments(definition, scope) {
6404
- try {
6405
- const parameters = Reflect.getMetadata(METADATA_KEYS.INJECT_PARAMETERS, definition.construct) || [];
6406
- const designParameters = Reflect.getMetadata("design:paramtypes", definition.construct) || [];
6407
- const effectiveScope = scope || definition.scope || this.defaultScope;
6408
- const maxLen = Math.max(parameters.length, designParameters.length);
6409
- const args = [];
6410
- for (let i = 0;i < maxLen; i++) {
6411
- const param = parameters[i];
6412
- const designParam = designParameters[i];
6413
- if (param && param !== true) {
6414
- const token = typeof param === "function" ? param.name || param : param;
6415
- if (typeof token === "string") {
6416
- this.addDependent(token, definition.name);
6417
- args.push(this.get(token, effectiveScope));
6418
- continue;
6419
- }
6420
- if (typeof param === "function") {
6421
- const metadata = Reflect.getMetadata(METADATA_KEYS.CONTAINER, param);
6422
- const token2 = metadata?.name || param.name;
6423
- this.addDependent(token2, definition.name);
6424
- args.push(this.get(token2, effectiveScope));
6425
- continue;
6426
- }
6427
- }
6428
- if (designParam && typeof designParam === "function" && designParam.name) {
6429
- const metadata = Reflect.getMetadata(METADATA_KEYS.CONTAINER, designParam);
6430
- const token = metadata?.name || designParam.name;
6431
- this.addDependent(token, definition.name);
6432
- args.push(this.get(token, effectiveScope));
6433
- continue;
6434
- }
6435
- args.push(undefined);
6436
- }
6437
- return args;
6438
- } catch (e) {
6439
- Logger.error("Resolve", e);
6440
- return [];
6441
- }
6331
+ get existence() {
6332
+ return this.stack.size;
6442
6333
  }
6443
- static addDependent(dependencyName, dependentName) {
6444
- const dep = this.normalizeName(dependencyName);
6445
- if (!this._dependents.has(dep)) {
6446
- this._dependents.set(dep, new Set);
6447
- }
6448
- this._dependents.get(dep).add(this.normalizeName(dependentName));
6334
+ push() {
6335
+ const first = this.stack.values().next().value;
6336
+ HttpResponse.push({
6337
+ statusCode: 500,
6338
+ message: first?.message || "Internal server error",
6339
+ error: true,
6340
+ errorStack: this.entries
6341
+ });
6449
6342
  }
6450
- static get(name, scope) {
6451
- const name_ = this.normalizeName(name);
6452
- const cls = this._classes.get(name_);
6453
- if (!cls)
6454
- throw new Throwable(`Dependency ${name} not registered`);
6455
- const effectiveScope = scope || cls.scope || this.defaultScope;
6456
- if (this._resolutionStack.includes(name_)) {
6457
- throw new Throwable(`Circular dependency detected: ${this._resolutionStack.join(" -> ")} -> ${name}`);
6458
- }
6459
- this._resolutionStack.push(name_);
6460
- try {
6461
- let instance;
6462
- if (cls.lifetime === LifetimeEnum.SINGLETON) {
6463
- if (!this._instances.has(name_)) {
6464
- this._instances.set(name_, new Map);
6465
- }
6466
- const scopeInstances = this._instances.get(name_);
6467
- if (!scopeInstances.has(effectiveScope)) {
6468
- instance = new cls.construct(...this.resolveArguments(cls, effectiveScope));
6469
- scopeInstances.set(effectiveScope, instance);
6470
- this.injectProperties(instance, cls, effectiveScope);
6471
- this.triggerLifecycle(instance);
6472
- }
6473
- return scopeInstances.get(effectiveScope);
6474
- }
6475
- if (cls.lifetime === LifetimeEnum.TRANSIENT) {
6476
- instance = new cls.construct(...this.resolveArguments(cls, effectiveScope));
6477
- this.injectProperties(instance, cls, effectiveScope);
6343
+ }
6344
+ // source/framework/responses/http-throwable.ts
6345
+ class ThrowableResponse extends Error {
6346
+ input;
6347
+ statusCode;
6348
+ constructor(input, statusCode = 500 /* INTERNAL_SERVER_ERROR */) {
6349
+ super(typeof input === "string" ? input : input.message);
6350
+ this.input = input;
6351
+ this.statusCode = statusCode;
6352
+ }
6353
+ render() {
6354
+ const stack = typeof this.input === "object" ? this.input.errorStack : undefined;
6355
+ return {
6356
+ message: this.message,
6357
+ statusCode: this.statusCode,
6358
+ data: typeof this.input === "object" ? this.input.data : undefined,
6359
+ error: typeof this.input === "object" ? this.input.error : false,
6360
+ stack: stack instanceof Error ? Raiton.thread?.builder?.options?.serve ? this.stack?.split(`
6361
+ `).map((e) => e.trim()) : undefined : stack
6362
+ };
6363
+ }
6364
+ }
6365
+ // source/core/controller/metadata.ts
6366
+ var import_reflect_metadata = __toESM(require_Reflect2(), 1);
6367
+ function getControllerMetadata(target) {
6368
+ let metadata = Reflect.getMetadata(METADATA_KEYS.CONTROLLERS, target);
6369
+ if (!metadata) {
6370
+ metadata = { routes: [], middlewares: {} };
6371
+ Reflect.defineMetadata(METADATA_KEYS.CONTROLLERS, metadata, target);
6372
+ }
6373
+ return metadata;
6374
+ }
6375
+ // source/core/router/route.ts
6376
+ class Route {
6377
+ method;
6378
+ path;
6379
+ version;
6380
+ handler;
6381
+ parameters = {};
6382
+ constructor(def) {
6383
+ this.method = def.method;
6384
+ this.path = def.path;
6385
+ this.version = def.version;
6386
+ this.handler = def.handler;
6387
+ }
6388
+ get params() {
6389
+ const fullPath = this.version ? `/${this.version}${this.path}` : this.path;
6390
+ const matches = fullPath.match(/:[a-zA-Z0-9_]+/g);
6391
+ return matches ? matches.map((m) => m.substring(1)) : [];
6392
+ }
6393
+ get name() {
6394
+ return this.handler.name;
6395
+ }
6396
+ extractParams(url) {
6397
+ const fullPath = (this.version ? `/${this.version}${this.path}` : this.path).replace(/\/+$/, "");
6398
+ const paramNames = this.params;
6399
+ if (paramNames.length === 0)
6400
+ return this;
6401
+ const regexPath = fullPath.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
6402
+ const regex = new RegExp(`^${regexPath || "/"}/?$`);
6403
+ const matches = url.match(regex);
6404
+ if (matches) {
6405
+ const params = {};
6406
+ paramNames.forEach((name, index) => {
6407
+ params[name] = matches[index + 1];
6408
+ });
6409
+ this.parameters = params;
6410
+ }
6411
+ return this;
6412
+ }
6413
+ match(method, url) {
6414
+ if (method !== this.method)
6415
+ return false;
6416
+ const fullPath = (this.version ? `/${this.version}${this.path}` : this.path).replace(/\/+$/, "");
6417
+ const cleanUrl = url.replace(/\/+$/, "");
6418
+ if (!fullPath.includes(":")) {
6419
+ return (fullPath || "/") === (cleanUrl || "/");
6420
+ }
6421
+ const regexPath = fullPath.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
6422
+ const regex = new RegExp(`^${regexPath || "/"}/?$`);
6423
+ return regex.test(url);
6424
+ }
6425
+ }
6426
+ // source/core/router/matcher.ts
6427
+ class RouteMatcher {
6428
+ _routes = new Map;
6429
+ getKey(route) {
6430
+ return `${route.method}:${route.path}`;
6431
+ }
6432
+ get routes() {
6433
+ return this._routes;
6434
+ }
6435
+ add(route) {
6436
+ this._routes.set(this.getKey(route), route);
6437
+ return this;
6438
+ }
6439
+ has(route) {
6440
+ return this._routes.has(this.getKey(route));
6441
+ }
6442
+ find(route) {
6443
+ return this._routes.get(this.getKey(route));
6444
+ }
6445
+ replace(route) {
6446
+ if (this.has(route)) {
6447
+ this._routes.set(this.getKey(route), route);
6448
+ }
6449
+ return this;
6450
+ }
6451
+ upsert(route) {
6452
+ this._routes.set(this.getKey(route), route);
6453
+ return this;
6454
+ }
6455
+ remove(route) {
6456
+ this._routes.delete(this.getKey(route));
6457
+ return this;
6458
+ }
6459
+ match(method, url) {
6460
+ for (const route of this._routes.values())
6461
+ if (route.match(method, url))
6462
+ return route.extractParams(url);
6463
+ return null;
6464
+ }
6465
+ clear() {
6466
+ this._routes.clear();
6467
+ return this;
6468
+ }
6469
+ }
6470
+ // source/core/router/router.ts
6471
+ class Router {
6472
+ matcher = new RouteMatcher;
6473
+ add(method, path3, handler, version2) {
6474
+ const route = new Route({
6475
+ method,
6476
+ path: path3,
6477
+ handler,
6478
+ version: version2
6479
+ });
6480
+ this.matcher.add(route);
6481
+ return route;
6482
+ }
6483
+ remove(route) {
6484
+ this.matcher.remove(route);
6485
+ }
6486
+ match(method, url) {
6487
+ return this.matcher.match(method, url);
6488
+ }
6489
+ reset() {
6490
+ this.matcher.clear();
6491
+ }
6492
+ getRoutes() {
6493
+ return Array.from(this.matcher.routes.values());
6494
+ }
6495
+ }
6496
+ // source/framework/exceptions/throwable.ts
6497
+ class Throwable extends Error {
6498
+ statusCode;
6499
+ constructor(message, statusCode = 500, label) {
6500
+ super(message);
6501
+ this.statusCode = statusCode;
6502
+ this.name = "Throwable";
6503
+ if (label)
6504
+ Logger.debug(LBadge.debug(label), message);
6505
+ EventBus.dispatch(EventBusEnum.SERVER_THROW, { error: this });
6506
+ }
6507
+ static error(message, soft = true, statusCode = 500) {
6508
+ EventBus.dispatch(EventBusEnum.SERVER_ERROR, { message, soft });
6509
+ if (!soft)
6510
+ throw new Throwable(message, statusCode, "ERR");
6511
+ }
6512
+ static warning(message, soft = true, statusCode = 500) {
6513
+ EventBus.dispatch(EventBusEnum.SERVER_WARNING, { message, soft });
6514
+ if (!soft)
6515
+ throw new Throwable(message, statusCode, "WRN");
6516
+ }
6517
+ static critical(message) {
6518
+ Logger.debug(LBadge.debug("CRITICAL"), message);
6519
+ EventBus.dispatch(EventBusEnum.SERVER_CRITICAL, { message });
6520
+ process.exit(1);
6521
+ }
6522
+ }
6523
+ // source/core/injection/injection.ts
6524
+ var import_reflect_metadata2 = __toESM(require_Reflect2(), 1);
6525
+ var camelCase = TextUtility.camelCase;
6526
+
6527
+ class Injection {
6528
+ static _classes = new Map;
6529
+ static _instances = new Map;
6530
+ static _resolutionStack = [];
6531
+ static _dependents = new Map;
6532
+ static _artifactPaths = new Map;
6533
+ static get classes() {
6534
+ return this._classes;
6535
+ }
6536
+ static defaultScope = Symbol("default");
6537
+ static get instances() {
6538
+ return this._instances;
6539
+ }
6540
+ static has(name) {
6541
+ return this._classes.has(this.normalizeName(name));
6542
+ }
6543
+ static clear() {
6544
+ Logger.error("Clearing injection container");
6545
+ this._classes.clear();
6546
+ this._instances.clear();
6547
+ this._dependents.clear();
6548
+ this._artifactPaths.clear();
6549
+ }
6550
+ static normalizeName(name) {
6551
+ const stableName = camelCase(name);
6552
+ return stableName[0].toLowerCase() + stableName.slice(1);
6553
+ }
6554
+ static registry(name, construct, lifetime = LifetimeEnum.SINGLETON, scope) {
6555
+ if (!construct.name)
6556
+ throw new Error("Le constructeur doit avoir un nom valide pour être enregistré dans le conteneur.");
6557
+ this._classes.set(this.normalizeName(name), { name, construct, lifetime, scope });
6558
+ return this;
6559
+ }
6560
+ static updateConstruct(name, construct) {
6561
+ const name_ = this.normalizeName(name);
6562
+ this._classes.set(name_, { ...this._classes.get(this.normalizeName(name)), construct });
6563
+ return this;
6564
+ }
6565
+ static getDependents(name) {
6566
+ return Array.from(this._dependents.get(this.normalizeName(name)) || []);
6567
+ }
6568
+ static registerArtifactPath(name, path3) {
6569
+ this._artifactPaths.set(this.normalizeName(name), path3);
6570
+ return this;
6571
+ }
6572
+ static getArtifactPath(name) {
6573
+ return this._artifactPaths.get(this.normalizeName(name));
6574
+ }
6575
+ static resolveArguments(definition, scope) {
6576
+ try {
6577
+ const parameters = Reflect.getMetadata(METADATA_KEYS.INJECT_PARAMETERS, definition.construct) || [];
6578
+ const designParameters = Reflect.getMetadata("design:paramtypes", definition.construct) || [];
6579
+ const effectiveScope = scope || definition.scope || this.defaultScope;
6580
+ const maxLen = Math.max(parameters.length, designParameters.length);
6581
+ const args = [];
6582
+ for (let i = 0;i < maxLen; i++) {
6583
+ const param = parameters[i];
6584
+ const designParam = designParameters[i];
6585
+ if (param && param !== true) {
6586
+ const token = typeof param === "function" ? param.name || param : param;
6587
+ if (typeof token === "string") {
6588
+ this.addDependent(token, definition.name);
6589
+ args.push(this.get(token, effectiveScope));
6590
+ continue;
6591
+ }
6592
+ if (typeof param === "function") {
6593
+ const metadata = Reflect.getMetadata(METADATA_KEYS.CONTAINER, param);
6594
+ const token2 = metadata?.name || param.name;
6595
+ this.addDependent(token2, definition.name);
6596
+ args.push(this.get(token2, effectiveScope));
6597
+ continue;
6598
+ }
6599
+ }
6600
+ if (designParam && typeof designParam === "function" && designParam.name) {
6601
+ const metadata = Reflect.getMetadata(METADATA_KEYS.CONTAINER, designParam);
6602
+ const token = metadata?.name || designParam.name;
6603
+ this.addDependent(token, definition.name);
6604
+ args.push(this.get(token, effectiveScope));
6605
+ continue;
6606
+ }
6607
+ args.push(undefined);
6608
+ }
6609
+ return args;
6610
+ } catch (e) {
6611
+ Logger.error("Resolve", e);
6612
+ return [];
6613
+ }
6614
+ }
6615
+ static addDependent(dependencyName, dependentName) {
6616
+ const dep = this.normalizeName(dependencyName);
6617
+ if (!this._dependents.has(dep)) {
6618
+ this._dependents.set(dep, new Set);
6619
+ }
6620
+ this._dependents.get(dep).add(this.normalizeName(dependentName));
6621
+ }
6622
+ static get(name, scope) {
6623
+ const name_ = this.normalizeName(name);
6624
+ const cls = this._classes.get(name_);
6625
+ if (!cls)
6626
+ throw new Throwable(`Dependency ${name_} not registered`);
6627
+ const effectiveScope = scope || cls.scope || this.defaultScope;
6628
+ if (this._resolutionStack.includes(name_)) {
6629
+ throw new Throwable(`Circular dependency detected: ${this._resolutionStack.join(" -> ")} -> ${name}`);
6630
+ }
6631
+ this._resolutionStack.push(name_);
6632
+ try {
6633
+ let instance;
6634
+ if (cls.lifetime === LifetimeEnum.SINGLETON) {
6635
+ if (!this._instances.has(name_)) {
6636
+ this._instances.set(name_, new Map);
6637
+ }
6638
+ const scopeInstances = this._instances.get(name_);
6639
+ if (!scopeInstances.has(effectiveScope)) {
6640
+ instance = new cls.construct(...this.resolveArguments(cls, effectiveScope));
6641
+ scopeInstances.set(effectiveScope, instance);
6642
+ this.injectProperties(instance, cls, effectiveScope);
6643
+ this.triggerLifecycle(instance);
6644
+ }
6645
+ return scopeInstances.get(effectiveScope);
6646
+ }
6647
+ if (cls.lifetime === LifetimeEnum.TRANSIENT) {
6648
+ instance = new cls.construct(...this.resolveArguments(cls, effectiveScope));
6649
+ this.injectProperties(instance, cls, effectiveScope);
6478
6650
  this.triggerLifecycle(instance);
6479
6651
  return instance;
6480
6652
  }
@@ -6520,154 +6692,269 @@ class Injection {
6520
6692
  }
6521
6693
  static resolve(construct) {
6522
6694
  const metadata = Reflect.getMetadata(METADATA_KEYS.CONTAINER, construct);
6523
- if (!metadata)
6524
- throw new Throwable(`Cannot resolve ${construct.name} as dependency`);
6525
- return this.get(metadata.name);
6695
+ const name = metadata?.name || ("constructor" in construct ? construct.constructor.name || false : false) || construct.name;
6696
+ if (!metadata) {
6697
+ if (typeof name === "undefined")
6698
+ Logger.debug("Cannot resolve", construct);
6699
+ throw new Throwable(`Cannot resolve ${name} as dependency`);
6700
+ }
6701
+ return this.get(name);
6526
6702
  }
6527
6703
  }
6528
- // source/core/guards.ts
6529
- class RaitonGuards {
6530
- static _map = new Map;
6531
- static set(name, guard) {
6532
- this._map.set(name, guard);
6533
- return this;
6534
- }
6535
- static get(name) {
6536
- return this._map.get(name);
6704
+ // source/framework/plugins/body-parser.plugin.ts
6705
+ function bodyParserPlugin() {
6706
+ return {
6707
+ name: "body-parser-plugin",
6708
+ setup: (scope) => {
6709
+ scope.use(async ({ context, next }) => {
6710
+ readQueryBody(context);
6711
+ const isGetOrHead = ["GET", "HEAD"].includes(context.req.method.toUpperCase());
6712
+ if (isGetOrHead) {
6713
+ context.req.body = context.req.query;
6714
+ }
6715
+ const hasBody = context.req.body !== undefined && context.req.body !== null;
6716
+ if (hasBody && !context.state.bodyParsed && !isGetOrHead) {
6717
+ try {
6718
+ const contentType = context.req.headers.get("content-type") || "";
6719
+ const rawBody = await readRawBody(context.req.body);
6720
+ const bodyString = decode(rawBody);
6721
+ await readMultipartBody(context, contentType, rawBody);
6722
+ readJsonBody(context, contentType, bodyString);
6723
+ readUrlEncodedBody(context, contentType, bodyString);
6724
+ readTextBody(context, contentType, bodyString);
6725
+ if (!context.state.bodyParsed) {
6726
+ context.req.body = rawBody;
6727
+ context.state.bodyParsed = true;
6728
+ }
6729
+ } catch (e) {
6730
+ Logger.error("Error parsing body:", e);
6731
+ }
6732
+ }
6733
+ await next();
6734
+ });
6735
+ }
6736
+ };
6737
+ }
6738
+ function readJsonBody(ctx, contentType, body) {
6739
+ if (contentType.includes("application/json")) {
6740
+ ctx.req.body = tryParseJson(body) || {};
6741
+ ctx.state.bodyParsed = true;
6537
6742
  }
6538
- static remove(name) {
6539
- this._map.delete(name);
6540
- return this;
6743
+ }
6744
+ async function readMultipartBody(ctx, contentType, rawBody) {
6745
+ if (contentType.includes("multipart/form-data")) {
6746
+ try {
6747
+ const tempRequest = new Request(ctx.req.url, {
6748
+ method: ctx.req.method,
6749
+ headers: ctx.req.headers,
6750
+ body: rawBody
6751
+ });
6752
+ const formData = await tempRequest.formData();
6753
+ const record = {};
6754
+ const files = {};
6755
+ for (const [key, value] of formData.entries()) {
6756
+ const v = value;
6757
+ if (v && v instanceof File) {
6758
+ files[key] = {
6759
+ name: v.name,
6760
+ type: v.type,
6761
+ size: v.size,
6762
+ lastModified: v.lastModified,
6763
+ buffer: Buffer.from(await v.arrayBuffer())
6764
+ };
6765
+ } else {
6766
+ record[key] = value;
6767
+ }
6768
+ }
6769
+ ctx.req.body = record;
6770
+ ctx.req.files = files;
6771
+ ctx.req.file = Object.values(files)[0] || null;
6772
+ ctx.state.bodyParsed = true;
6773
+ } catch (e) {
6774
+ Logger.error("Error parsing multipart body:", e);
6775
+ }
6541
6776
  }
6542
- static removeAll() {
6543
- Logger.error("Removing all guards");
6544
- this._map.clear();
6545
- return this;
6777
+ }
6778
+ function readUrlEncodedBody(ctx, contentType, body) {
6779
+ if (contentType.includes("application/x-www-form-urlencoded")) {
6780
+ const params = new URLSearchParams(body);
6781
+ const record = {};
6782
+ params.forEach((value, key) => {
6783
+ record[key] = value;
6784
+ });
6785
+ ctx.req.body = record;
6786
+ ctx.state.bodyParsed = true;
6546
6787
  }
6547
- static enabled(name) {
6548
- const guard = this.get(name);
6549
- return !guard ? false : guard.enabled;
6788
+ }
6789
+ function readTextBody(ctx, contentType, body) {
6790
+ if (contentType.includes("text/")) {
6791
+ ctx.req.body = body;
6792
+ ctx.state.bodyParsed = true;
6550
6793
  }
6551
- static enable(name) {
6552
- const guard = this.get(name);
6553
- if (guard)
6554
- guard.enabled = true;
6555
- return this;
6794
+ }
6795
+ function readQueryBody(ctx) {
6796
+ const searchParams = new URLSearchParams(ctx.req.url.split("?")[1] || "");
6797
+ const record = {};
6798
+ searchParams.forEach((value, key) => record[key] = value);
6799
+ ctx.req.query = record;
6800
+ }
6801
+ async function readRawBody(body) {
6802
+ if (!body)
6803
+ return new Uint8Array(0);
6804
+ if (body instanceof Uint8Array || typeof body === "string") {
6805
+ return body;
6806
+ }
6807
+ if (typeof body === "object" && !("on" in body) && !(body instanceof ReadableStream)) {
6808
+ return JSON.stringify(body);
6809
+ }
6810
+ if (body instanceof ReadableStream) {
6811
+ const reader = body.getReader();
6812
+ const chunks = [];
6813
+ while (true) {
6814
+ const { done, value } = await reader.read();
6815
+ if (done)
6816
+ break;
6817
+ chunks.push(value);
6818
+ }
6819
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
6820
+ const result = new Uint8Array(totalLength);
6821
+ let offset = 0;
6822
+ for (const chunk of chunks) {
6823
+ result.set(chunk, offset);
6824
+ offset += chunk.length;
6825
+ }
6826
+ return result;
6556
6827
  }
6557
- static disable(name) {
6558
- const guard = this.get(name);
6559
- if (guard)
6560
- guard.enabled = false;
6561
- return this;
6828
+ if (typeof body === "object" && body !== null && "on" in body && typeof body.on === "function") {
6829
+ return new Promise((resolve, reject) => {
6830
+ const chunks = [];
6831
+ body.on("data", (chunk) => chunks.push(chunk));
6832
+ body.on("end", () => {
6833
+ if (chunks.length > 0 && typeof chunks[0] === "string") {
6834
+ resolve(chunks.join(""));
6835
+ } else {
6836
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
6837
+ const result = new Uint8Array(totalLength);
6838
+ let offset = 0;
6839
+ for (const chunk of chunks) {
6840
+ result.set(new Uint8Array(chunk), offset);
6841
+ offset += chunk.length;
6842
+ }
6843
+ resolve(result);
6844
+ }
6845
+ });
6846
+ body.on("error", reject);
6847
+ });
6562
6848
  }
6849
+ return body;
6563
6850
  }
6564
- // source/sdk/responses/http.ts
6565
- class HttpResponse {
6566
- response;
6567
- static push(response) {
6568
- throw new ThrowableResponse({
6569
- statusCode: response.statusCode || 400 /* BAD_REQUEST */,
6570
- message: response.message || "No response message provided",
6571
- data: response.data,
6572
- error: response.error,
6573
- errorStack: response.errorStack
6851
+ function decode(data) {
6852
+ if (typeof data === "string")
6853
+ return data;
6854
+ return new TextDecoder().decode(data);
6855
+ }
6856
+ // source/core/socket/metadata.ts
6857
+ var import_reflect_metadata3 = __toESM(require_Reflect2(), 1);
6858
+ // source/framework/decorators/routable.decorator.ts
6859
+ function stabilizeRoute(meta, { path: path3, method, propertyKey }) {
6860
+ return {
6861
+ ...meta.routes.filter((route2) => route2.path === path3 && route2.method === method || route2.propertyKey === propertyKey)[0] || {},
6862
+ method,
6863
+ path: path3,
6864
+ propertyKey
6865
+ };
6866
+ }
6867
+ function createRoutableDecorator(method) {
6868
+ return (path3 = "") => (target, propertyKey) => {
6869
+ const meta = getControllerMetadata(target);
6870
+ const route2 = stabilizeRoute(meta, {
6871
+ method,
6872
+ path: path3,
6873
+ propertyKey
6574
6874
  });
6575
- }
6576
- constructor(response) {
6577
- this.response = response;
6578
- }
6579
- status(statusCode) {
6580
- this.response.statusCode = statusCode;
6581
- return this;
6582
- }
6583
- message(message) {
6584
- this.response.message = message;
6875
+ meta.routes.push(route2);
6876
+ };
6877
+ }
6878
+ var Get = createRoutableDecorator("GET" /* GET */);
6879
+ var Post = createRoutableDecorator("POST" /* POST */);
6880
+ var Put = createRoutableDecorator("PUT" /* PUT */);
6881
+ var Patch = createRoutableDecorator("PATCH" /* PATCH */);
6882
+ var Options = createRoutableDecorator("OPTIONS" /* OPTIONS */);
6883
+ var Trace = createRoutableDecorator("TRACE" /* TRACE */);
6884
+ var Delete = createRoutableDecorator("DELETE" /* DELETE */);
6885
+ var Head = createRoutableDecorator("HEAD" /* HEAD */);
6886
+ // source/framework/decorators/parametrable.decorator.ts
6887
+ var import_reflect_metadata4 = __toESM(require_Reflect2(), 1);
6888
+ function createRouteParametrableDecorator(type, callable) {
6889
+ return (key) => {
6890
+ return (target, propertyKey, index) => {
6891
+ const params = Reflect.getMetadata(METADATA_KEYS.ROUTE_PARAMETERS, target.constructor) || {};
6892
+ const metatypes = Reflect.getMetadata("design:paramtypes", target, propertyKey);
6893
+ const metatype = metatypes ? metatypes[index] : undefined;
6894
+ if (!params[propertyKey]) {
6895
+ params[propertyKey] = [];
6896
+ }
6897
+ params[propertyKey].push({ index, type, key, callable, metatype });
6898
+ Reflect.defineMetadata(METADATA_KEYS.ROUTE_PARAMETERS, params, target.constructor);
6899
+ };
6900
+ };
6901
+ }
6902
+ var Query = createRouteParametrableDecorator("query" /* QUERY */);
6903
+ var Param = createRouteParametrableDecorator("param" /* PARAM */);
6904
+ var Body = createRouteParametrableDecorator("body" /* BODY */);
6905
+ var UploadedFile = createRouteParametrableDecorator("upload" /* UPLOAD_FILE */);
6906
+ var Headers2 = createRouteParametrableDecorator("header" /* HEADER */);
6907
+ var Cookie = createRouteParametrableDecorator("cookie" /* COOKIE */);
6908
+ var Req = createRouteParametrableDecorator("req" /* REQ */);
6909
+ var Reply = createRouteParametrableDecorator("reply" /* REPLY */);
6910
+ // source/framework/decorators/injection.decorator.ts
6911
+ var import_reflect_metadata5 = __toESM(require_Reflect2(), 1);
6912
+ // source/core/guards.ts
6913
+ class RaitonGuards {
6914
+ static _map = new Map;
6915
+ static set(name, guard) {
6916
+ this._map.set(name, guard);
6585
6917
  return this;
6586
6918
  }
6587
- data(data) {
6588
- this.response.data = data;
6589
- return this;
6919
+ static get(name) {
6920
+ return this._map.get(name);
6590
6921
  }
6591
- error(error) {
6592
- this.response.error = error;
6922
+ static remove(name) {
6923
+ this._map.delete(name);
6593
6924
  return this;
6594
6925
  }
6595
- stack(stack) {
6596
- this.response.errorStack = stack;
6926
+ static removeAll() {
6927
+ Logger.error("Removing all guards");
6928
+ this._map.clear();
6597
6929
  return this;
6598
6930
  }
6599
- render() {
6600
- return new ThrowableResponse({ ...this.response }).render();
6601
- }
6602
- }
6603
-
6604
- // source/sdk/responses/error.ts
6605
- class HttpErrorResponse {
6606
- stack = new Map;
6607
- get entries() {
6608
- return [...this.stack.values()];
6609
- }
6610
- add(input) {
6611
- this.stack.set(input.id, input);
6612
- return this;
6931
+ static enabled(name) {
6932
+ const guard = this.get(name);
6933
+ return !guard ? false : guard.enabled;
6613
6934
  }
6614
- remove(id) {
6615
- this.stack.delete(id);
6935
+ static enable(name) {
6936
+ const guard = this.get(name);
6937
+ if (guard)
6938
+ guard.enabled = true;
6616
6939
  return this;
6617
6940
  }
6618
- get(id) {
6619
- return this.stack.get(id);
6620
- }
6621
- has(id) {
6622
- return this.stack.has(id);
6623
- }
6624
- clear() {
6625
- this.stack.clear();
6941
+ static disable(name) {
6942
+ const guard = this.get(name);
6943
+ if (guard)
6944
+ guard.enabled = false;
6626
6945
  return this;
6627
6946
  }
6628
- get empty() {
6629
- return this.stack.size === 0;
6630
- }
6631
- get existence() {
6632
- return this.stack.size;
6633
- }
6634
- push() {
6635
- const first = this.stack.values().next().value;
6636
- HttpResponse.push({
6637
- statusCode: 500,
6638
- message: first?.message || "Internal server error",
6639
- error: true,
6640
- errorStack: this.entries
6641
- });
6642
- }
6643
- }
6644
- // source/sdk/responses/http-throwable.ts
6645
- class ThrowableResponse extends Error {
6646
- input;
6647
- statusCode;
6648
- constructor(input, statusCode = 500 /* INTERNAL_SERVER_ERROR */) {
6649
- super(typeof input === "string" ? input : input.message);
6650
- this.input = input;
6651
- this.statusCode = statusCode;
6652
- }
6653
- render() {
6654
- const stack = typeof this.input === "object" ? this.input.errorStack : undefined;
6655
- return {
6656
- message: this.message,
6657
- statusCode: this.statusCode,
6658
- data: typeof this.input === "object" ? this.input.data : undefined,
6659
- error: typeof this.input === "object" ? this.input.error : false,
6660
- stack: stack instanceof Error ? Raiton.thread?.builder?.options?.development ? this.stack?.split(`
6661
- `).map((e) => e.trim()) : undefined : stack
6662
- };
6663
- }
6664
6947
  }
6948
+ // source/framework/decorators/api-response.decorator.ts
6949
+ var import_reflect_metadata6 = __toESM(require_Reflect2(), 1);
6950
+ // source/framework/decorators/api.decorator.ts
6951
+ var import_reflect_metadata7 = __toESM(require_Reflect2(), 1);
6665
6952
  // source/core/hooks.ts
6666
6953
  class HookStore {
6667
6954
  hooks = new Map;
6668
- add(name, handler) {
6955
+ add(name, handler2) {
6669
6956
  const list = this.hooks.get(name) ?? [];
6670
- list.push(handler);
6957
+ list.push(handler2);
6671
6958
  this.hooks.set(name, list);
6672
6959
  }
6673
6960
  async run(name, ctx) {
@@ -6678,13 +6965,6 @@ class HookStore {
6678
6965
  await hook(ctx);
6679
6966
  }
6680
6967
  }
6681
- clone() {
6682
- const store = new HookStore;
6683
- for (const [key, value] of this.hooks) {
6684
- store.hooks.set(key, [...value]);
6685
- }
6686
- return store;
6687
- }
6688
6968
  }
6689
6969
 
6690
6970
  // source/core/middleware/compose.ts
@@ -6729,139 +7009,21 @@ class MiddlewarePipeline {
6729
7009
  this.stack = [];
6730
7010
  return this;
6731
7011
  }
6732
- run(ctx) {
6733
- const fn = middlewareCompose(this.stack);
7012
+ run(ctx, ...extra) {
7013
+ const fn = middlewareCompose([...this.stack, ...extra]);
6734
7014
  return typeof fn == "function" ? fn(ctx) : undefined;
6735
7015
  }
6736
- clone() {
6737
- const pipeline = new MiddlewarePipeline;
6738
- pipeline.stack = [...this.stack];
6739
- return pipeline;
6740
- }
6741
- }
6742
- // source/core/router/route.ts
6743
- class Route {
6744
- method;
6745
- path;
6746
- version;
6747
- handler;
6748
- parameters = {};
6749
- constructor(def) {
6750
- this.method = def.method;
6751
- this.path = def.path;
6752
- this.version = def.version;
6753
- this.handler = def.handler;
6754
- }
6755
- get params() {
6756
- const fullPath = this.version ? `/${this.version}${this.path}` : this.path;
6757
- const matches = fullPath.match(/:[a-zA-Z0-9_]+/g);
6758
- return matches ? matches.map((m) => m.substring(1)) : [];
6759
- }
6760
- get name() {
6761
- return this.handler.name;
6762
- }
6763
- extractParams(url) {
6764
- const fullPath = (this.version ? `/${this.version}${this.path}` : this.path).replace(/\/+$/, "");
6765
- const paramNames = this.params;
6766
- if (paramNames.length === 0)
6767
- return this;
6768
- const regexPath = fullPath.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
6769
- const regex = new RegExp(`^${regexPath || "/"}/?$`);
6770
- const matches = url.match(regex);
6771
- if (matches) {
6772
- const params = {};
6773
- paramNames.forEach((name, index) => {
6774
- params[name] = matches[index + 1];
6775
- });
6776
- this.parameters = params;
6777
- }
6778
- return this;
6779
- }
6780
- match(method, url) {
6781
- if (method !== this.method)
6782
- return false;
6783
- const fullPath = (this.version ? `/${this.version}${this.path}` : this.path).replace(/\/+$/, "");
6784
- const cleanUrl = url.replace(/\/+$/, "");
6785
- if (!fullPath.includes(":")) {
6786
- return (fullPath || "/") === (cleanUrl || "/");
6787
- }
6788
- const regexPath = fullPath.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
6789
- const regex = new RegExp(`^${regexPath || "/"}/?$`);
6790
- return regex.test(url);
6791
- }
6792
- }
6793
- // source/core/router/matcher.ts
6794
- class RouteMatcher {
6795
- routes = new Map;
6796
- getKey(route) {
6797
- return `${route.method}:${route.path}`;
6798
- }
6799
- add(route) {
6800
- this.routes.set(this.getKey(route), route);
6801
- return this;
6802
- }
6803
- has(route) {
6804
- return this.routes.has(this.getKey(route));
6805
- }
6806
- find(route) {
6807
- return this.routes.get(this.getKey(route));
6808
- }
6809
- replace(route) {
6810
- if (this.has(route)) {
6811
- this.routes.set(this.getKey(route), route);
6812
- }
6813
- return this;
6814
- }
6815
- upsert(route) {
6816
- this.routes.set(this.getKey(route), route);
6817
- return this;
6818
- }
6819
- remove(route) {
6820
- this.routes.delete(this.getKey(route));
6821
- return this;
6822
- }
6823
- match(method, url) {
6824
- for (const route of this.routes.values())
6825
- if (route.match(method, url))
6826
- return route.extractParams(url);
6827
- return null;
6828
- }
6829
- clear() {
6830
- this.routes.clear();
6831
- return this;
6832
- }
6833
- }
6834
- // source/core/router/router.ts
6835
- class Router {
6836
- matcher = new RouteMatcher;
6837
- add(method, path5, handler, version2) {
6838
- const route = new Route({
6839
- method,
6840
- path: path5,
6841
- handler,
6842
- version: version2
6843
- });
6844
- this.matcher.add(route);
6845
- return route;
6846
- }
6847
- remove(route) {
6848
- this.matcher.remove(route);
6849
- }
6850
- match(method, url) {
6851
- return this.matcher.match(method, url);
6852
- }
6853
- reset() {
6854
- this.matcher.clear();
6855
- }
6856
7016
  }
6857
7017
  // source/core/plugins/scope.ts
6858
7018
  class PluginScope {
6859
7019
  hooks;
6860
7020
  middleware;
6861
7021
  router;
7022
+ parent;
6862
7023
  constructor(parent) {
6863
- this.hooks = parent ? parent.hooks.clone() : new HookStore;
6864
- this.middleware = parent ? parent.middleware.clone() : new MiddlewarePipeline;
7024
+ this.parent = parent;
7025
+ this.hooks = parent ? parent.hooks : new HookStore;
7026
+ this.middleware = parent ? parent.middleware : new MiddlewarePipeline;
6865
7027
  this.router = parent ? parent.router : new Router;
6866
7028
  }
6867
7029
  addHook(name, fn) {
@@ -6876,20 +7038,27 @@ class PluginScope {
6876
7038
  this.middleware.use(mw);
6877
7039
  return this;
6878
7040
  }
6879
- route(method, path5, handler2, version2) {
6880
- return this.router.add(method, path5, handler2, version2);
7041
+ route(method, path3, handler2, version2) {
7042
+ return this.router.add(method, path3, handler2, version2);
7043
+ }
7044
+ get(path3, handler2, version2) {
7045
+ return this.route("GET" /* GET */, path3, handler2, version2);
6881
7046
  }
6882
7047
  register(plugin) {
7048
+ if (typeof plugin === "object" && plugin !== null && "setup" in plugin && typeof plugin.setup === "function" && plugin.setup.length === 1) {
7049
+ plugin.setup(this);
7050
+ return this;
7051
+ }
6883
7052
  const child = new PluginScope(this);
6884
7053
  plugin.setup(child);
6885
- return child;
7054
+ return this;
6886
7055
  }
6887
7056
  }
6888
7057
  // source/core/plugins/plugin.ts
6889
7058
  function definePlugin(setup, name) {
6890
7059
  return { setup, name };
6891
7060
  }
6892
- // source/sdk/plugins/security/headers.ts
7061
+ // source/framework/plugins/security/headers.ts
6893
7062
  var secureHeaders = definePlugin((scope2) => {
6894
7063
  scope2.use(async ({ context, next }) => {
6895
7064
  context.reply.header("X-Content-Type-Options", "nosniff");
@@ -6899,26 +7068,143 @@ var secureHeaders = definePlugin((scope2) => {
6899
7068
  await next();
6900
7069
  });
6901
7070
  }, "security-headers");
6902
- // source/sdk/encryption.ts
7071
+
7072
+ // source/framework/plugins/security/cors.ts
7073
+ var secureCors = (opts = {}) => {
7074
+ return async ({ context, next }) => {
7075
+ const origin = context.req.headers.get("origin");
7076
+ if (origin) {
7077
+ context.reply.header("Vary", "Origin");
7078
+ }
7079
+ let allowedOrigin = null;
7080
+ if (opts.origin === undefined || opts.origin === "*") {
7081
+ allowedOrigin = "*";
7082
+ } else if (opts.origin === true) {
7083
+ allowedOrigin = origin || "*";
7084
+ } else if (typeof opts.origin === "function") {
7085
+ if (origin && await opts.origin(origin)) {
7086
+ allowedOrigin = origin;
7087
+ }
7088
+ } else if (Array.isArray(opts.origin)) {
7089
+ if (origin && opts.origin.includes(origin)) {
7090
+ allowedOrigin = origin;
7091
+ }
7092
+ } else if (typeof opts.origin === "string") {
7093
+ if (opts.origin === origin) {
7094
+ allowedOrigin = origin;
7095
+ } else if (opts.origin === "*") {
7096
+ allowedOrigin = "*";
7097
+ }
7098
+ }
7099
+ if (allowedOrigin) {
7100
+ context.reply.header("Access-Control-Allow-Origin", allowedOrigin);
7101
+ }
7102
+ if (opts.credentials) {
7103
+ context.reply.header("Access-Control-Allow-Credentials", "true");
7104
+ }
7105
+ if (opts.exposeHeaders) {
7106
+ context.reply.header("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
7107
+ }
7108
+ if (context.req.method === "OPTIONS") {
7109
+ context.reply.header("Access-Control-Allow-Methods", (opts.methods ?? ["GET", "POST", "PUT", "DELETE", "PATCH"]).join(","));
7110
+ context.reply.header("Access-Control-Allow-Headers", (opts.headers ?? ["Content-Type", "Authorization", "X-Requested-With"]).join(","));
7111
+ if (opts.maxAge) {
7112
+ context.reply.header("Access-Control-Max-Age", opts.maxAge.toString());
7113
+ }
7114
+ context.reply.status(204);
7115
+ return context.send(null);
7116
+ }
7117
+ await next();
7118
+ };
7119
+ };
7120
+
7121
+ // source/framework/plugins/security/rate-limit.ts
7122
+ var secureRateLimit = (opts = {}) => definePlugin((scope2) => {
7123
+ const hits = new Map;
7124
+ const windowMs = opts.windowMs ?? 60000;
7125
+ const max = opts.max ?? 100;
7126
+ scope2.use(async ({ context, next }) => {
7127
+ const ip = context.req.remoteAddress ?? "unknown";
7128
+ const now = Date.now();
7129
+ const entry = hits.get(ip) ?? { count: 0, ts: now };
7130
+ if (now - entry.ts > windowMs) {
7131
+ entry.count = 0;
7132
+ entry.ts = now;
7133
+ }
7134
+ entry.count++;
7135
+ hits.set(ip, entry);
7136
+ if (entry.count > max) {
7137
+ context.reply.status(429);
7138
+ return context.send({ error: "Too many requests" });
7139
+ }
7140
+ await next();
7141
+ });
7142
+ }, "rate-limit");
7143
+
7144
+ // source/framework/plugins/security/body-limit.ts
7145
+ var secureBodyLimit = (maxBytes = 1e6) => definePlugin((scope2) => {
7146
+ scope2.use(async ({ context, next }) => {
7147
+ const len = Number(context.req.headers.get("content-length") ?? 0);
7148
+ if (len > maxBytes) {
7149
+ context.reply.status(413);
7150
+ return context.send({ error: "Payload too large" });
7151
+ }
7152
+ await next();
7153
+ });
7154
+ }, "body-limit");
7155
+
7156
+ // source/framework/plugins/security/method-guard.ts
7157
+ var secureMethodGuard = (allowed) => definePlugin((scope2) => {
7158
+ scope2.use(async ({ context, next }) => {
7159
+ if (!allowed.includes(context.req.method)) {
7160
+ context.reply.status(405);
7161
+ return context.send({ error: "Method not allowed" });
7162
+ }
7163
+ await next();
7164
+ });
7165
+ }, "method-guard");
7166
+
7167
+ // source/framework/plugins/security/index.ts
7168
+ class Security {
7169
+ static headers = secureHeaders;
7170
+ static cors = secureCors;
7171
+ static rateLimit = secureRateLimit;
7172
+ static bodyLimit = secureBodyLimit;
7173
+ static methodGuard = secureMethodGuard;
7174
+ }
7175
+ // source/framework/encryption.ts
6903
7176
  var import_argon2 = __toESM(require_argon2(), 1);
6904
7177
  var import_bcrypt = __toESM(require_bcrypt(), 1);
6905
- // source/core/controller/metadata.ts
6906
- var import_reflect_metadata4 = __toESM(require_Reflect2(), 1);
6907
- function getControllerMetadata(target) {
6908
- let metadata = Reflect.getMetadata(METADATA_KEYS.CONTROLLERS, target);
6909
- if (!metadata) {
6910
- metadata = { routes: [], middlewares: {} };
6911
- Reflect.defineMetadata(METADATA_KEYS.CONTROLLERS, metadata, target);
7178
+ // source/core/directories.ts
7179
+ import path4 from "node:path";
7180
+ class RaitonDirectories {
7181
+ static index = `.${Raiton.identifier}`;
7182
+ static bootstrapFile = "main.ts";
7183
+ static caches(workdir) {
7184
+ return path4.join(workdir, this.index, "caches");
7185
+ }
7186
+ static artifacts(workdir) {
7187
+ return path4.join(workdir, this.index, "artifacts");
7188
+ }
7189
+ static server(workdir) {
7190
+ return path4.join(workdir, this.index, "server");
7191
+ }
7192
+ static root(workdir) {
7193
+ return path4.join(workdir, this.index);
7194
+ }
7195
+ static app() {
7196
+ return path4.join(Raiton.thread?.builder.workdir || "", RaitonConfig.get("rootDir") || "./");
6912
7197
  }
6913
- return metadata;
6914
7198
  }
6915
- // source/sdk/artifacts.ts
7199
+
7200
+ // source/framework/artifacts.ts
6916
7201
  class Artifacts {
6917
7202
  static types = new Set;
6918
7203
  static defaultTypes = [
6919
7204
  "service",
6920
7205
  "provider",
6921
7206
  "type",
7207
+ "interface",
6922
7208
  "repository",
6923
7209
  "database",
6924
7210
  "db",
@@ -6926,6 +7212,7 @@ class Artifacts {
6926
7212
  "utility",
6927
7213
  "source",
6928
7214
  "controller",
7215
+ "socket",
6929
7216
  "middleware",
6930
7217
  "hook",
6931
7218
  "event",
@@ -6933,7 +7220,12 @@ class Artifacts {
6933
7220
  "validator",
6934
7221
  "strategy",
6935
7222
  "strategy-provider",
6936
- "strategy-type"
7223
+ "strategy-type",
7224
+ "use-case",
7225
+ "dto",
7226
+ "entity",
7227
+ "model",
7228
+ "schema"
6937
7229
  ];
6938
7230
  static register(type) {
6939
7231
  this.types.add(type);
@@ -6948,7 +7240,7 @@ class Artifacts {
6948
7240
  return [...this.types].map((type) => isArtifact(filename, type)).some(Boolean);
6949
7241
  }
6950
7242
  static reload(modulo, filename) {
6951
- if (Raiton.thread?.builder.options.development === false)
7243
+ if (Raiton.thread?.builder.options.serve === false)
6952
7244
  return Logger.warn("Artifact reload is only available in development mode");
6953
7245
  for (const mod of Object.values(modulo)) {
6954
7246
  const name = mod && typeof mod === "object" && "name" in mod ? mod.name : typeof mod === "function" ? mod.name ?? mod.constructor.name : undefined;
@@ -7061,7 +7353,9 @@ class Application {
7061
7353
  config;
7062
7354
  root;
7063
7355
  version = RaitonConfig.get("version") || "0.0.1";
7064
- container = Injection;
7356
+ static get container() {
7357
+ return Injection;
7358
+ }
7065
7359
  constructor(config2) {
7066
7360
  this.config = config2;
7067
7361
  this.root = new PluginScope;
@@ -7074,6 +7368,8 @@ class Application {
7074
7368
  const artifacts = RaitonConfig.get("artifacts");
7075
7369
  const artifactTypes = [...artifacts?.types || [], ...Artifacts.defaultTypes];
7076
7370
  Artifacts.registerMany(...artifactTypes);
7371
+ this.register(Security.headers);
7372
+ this.register(bodyParserPlugin());
7077
7373
  return this;
7078
7374
  }
7079
7375
  get hostname() {
@@ -7131,32 +7427,34 @@ class Application {
7131
7427
  Logger.info(`Incoming request: ${req.method} ${req.url}`);
7132
7428
  }
7133
7429
  await this.root.hooks.run("onRequest", ctx);
7134
- const url = new URL(req.url, this.hostname);
7135
- let pathname = url.pathname;
7136
- if (this.config.pathname && this.config.pathname !== "/") {
7137
- const appPathname = this.config.pathname.endsWith("/") ? this.config.pathname : `${this.config.pathname}/`;
7138
- if (pathname.startsWith(appPathname)) {
7139
- pathname = pathname.substring(appPathname.length - 1) || "/";
7140
- } else if (pathname === this.config.pathname) {
7141
- pathname = "/";
7142
- } else {
7143
- if (this.config.verbose) {
7144
- Logger.warn(`Request out of application pathname: ${pathname} (expected prefix: ${this.config.pathname})`);
7430
+ const handler2 = async (param) => {
7431
+ const context = param.context ?? param;
7432
+ const req2 = context.req;
7433
+ const reply2 = context.reply;
7434
+ const url = new URL(req2.url, this.hostname);
7435
+ let pathname = url.pathname;
7436
+ if (this.config.pathname && this.config.pathname !== "/") {
7437
+ const appPathname = this.config.pathname.endsWith("/") ? this.config.pathname : `${this.config.pathname}/`;
7438
+ if (pathname.startsWith(appPathname)) {
7439
+ pathname = pathname.substring(appPathname.length - 1) || "/";
7440
+ } else if (pathname === this.config.pathname) {
7441
+ pathname = "/";
7442
+ } else {
7443
+ if (this.config.verbose) {
7444
+ Logger.warn(`Request out of application pathname: ${pathname} (expected prefix: ${this.config.pathname})`);
7445
+ }
7446
+ reply2.status(404);
7447
+ return reply2.send({ error: false, statusCode: 404 });
7145
7448
  }
7146
- reply.status(404);
7147
- return reply.send({ error: false, statusCode: 404 });
7148
7449
  }
7149
- }
7150
- const route2 = this.root.router.match(req.method, pathname);
7151
- if (!route2) {
7152
- if (this.config.verbose) {
7153
- Logger.warn(`Route not found: ${req.method} ${pathname}`);
7450
+ const route2 = this.root.router.match(req2.method, pathname);
7451
+ if (!route2) {
7452
+ if (this.config.verbose) {
7453
+ Logger.warn(`Route not found: ${req2.method} ${pathname}`);
7454
+ }
7455
+ reply2.status(404);
7456
+ return reply2.send({ error: false, statusCode: 404 });
7154
7457
  }
7155
- reply.status(404);
7156
- return reply.send({ error: false, statusCode: 404 });
7157
- }
7158
- const pipeline2 = this.root.middleware.clone();
7159
- pipeline2.use(async ({ context }) => {
7160
7458
  try {
7161
7459
  context.params = route2.parameters;
7162
7460
  let responses2 = await route2.handler(context);
@@ -7167,8 +7465,8 @@ class Application {
7167
7465
  console.error(e);
7168
7466
  }
7169
7467
  }
7170
- });
7171
- await pipeline2.run(ctx);
7468
+ };
7469
+ await this.root.middleware.run(ctx, handler2);
7172
7470
  await this.root.hooks.run("onResponse", ctx);
7173
7471
  }
7174
7472
  }