@noxfly/noxus 2.4.0 → 3.0.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +403 -341
  2. package/dist/app-injector-Bz3Upc0y.d.mts +125 -0
  3. package/dist/app-injector-Bz3Upc0y.d.ts +125 -0
  4. package/dist/child.d.mts +48 -22
  5. package/dist/child.d.ts +48 -22
  6. package/dist/child.js +1114 -1239
  7. package/dist/child.mjs +1090 -1193
  8. package/dist/main.d.mts +304 -261
  9. package/dist/main.d.ts +304 -261
  10. package/dist/main.js +1473 -1873
  11. package/dist/main.mjs +1423 -1791
  12. package/dist/renderer.d.mts +113 -2
  13. package/dist/renderer.d.ts +113 -2
  14. package/dist/renderer.js +144 -132
  15. package/dist/renderer.mjs +143 -132
  16. package/dist/request-BlTtiHbi.d.ts +112 -0
  17. package/dist/request-qJ9EiDZc.d.mts +112 -0
  18. package/package.json +7 -7
  19. package/src/DI/app-injector.ts +95 -106
  20. package/src/DI/injector-explorer.ts +100 -81
  21. package/src/DI/token.ts +53 -0
  22. package/src/app.ts +141 -131
  23. package/src/bootstrap.ts +79 -40
  24. package/src/decorators/controller.decorator.ts +38 -27
  25. package/src/decorators/guards.decorator.ts +5 -64
  26. package/src/decorators/injectable.decorator.ts +68 -15
  27. package/src/decorators/method.decorator.ts +40 -81
  28. package/src/decorators/middleware.decorator.ts +5 -72
  29. package/src/index.ts +3 -0
  30. package/src/main.ts +4 -11
  31. package/src/non-electron-process.ts +0 -1
  32. package/src/preload-bridge.ts +1 -1
  33. package/src/renderer-client.ts +2 -2
  34. package/src/renderer-events.ts +1 -1
  35. package/src/request.ts +3 -3
  36. package/src/router.ts +221 -369
  37. package/src/routes.ts +78 -0
  38. package/src/socket.ts +4 -4
  39. package/src/window/window-manager.ts +255 -0
  40. package/tsconfig.json +5 -10
  41. package/tsup.config.ts +2 -2
  42. package/dist/app-injector-B3MvgV3k.d.mts +0 -95
  43. package/dist/app-injector-B3MvgV3k.d.ts +0 -95
  44. package/dist/index-BxWQVi6C.d.ts +0 -253
  45. package/dist/index-DQBQQfMw.d.mts +0 -253
  46. package/src/decorators/inject.decorator.ts +0 -24
  47. package/src/decorators/injectable.metadata.ts +0 -15
  48. package/src/decorators/module.decorator.ts +0 -75
package/dist/child.mjs CHANGED
@@ -4,448 +4,389 @@
4
4
  * @author NoxFly
5
5
  */
6
6
  var __defProp = Object.defineProperty;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
10
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
-
11
- // src/DI/app-injector.ts
12
- import "reflect-metadata";
13
-
14
- // src/decorators/inject.decorator.ts
15
- import "reflect-metadata";
16
- var INJECT_METADATA_KEY = "custom:inject";
17
- function Inject(token) {
18
- return (target, propertyKey, parameterIndex) => {
19
- const existingParameters = Reflect.getOwnMetadata(INJECT_METADATA_KEY, target) || [];
20
- existingParameters[parameterIndex] = token;
21
- Reflect.defineMetadata(INJECT_METADATA_KEY, existingParameters, target);
22
- };
23
- }
24
- __name(Inject, "Inject");
25
-
26
- // src/exceptions.ts
27
- var _ResponseException = class _ResponseException extends Error {
28
- constructor(statusOrMessage, message) {
29
- let statusCode;
30
- if (typeof statusOrMessage === "number") {
31
- statusCode = statusOrMessage;
32
- } else if (typeof statusOrMessage === "string") {
33
- message = statusOrMessage;
34
- }
35
- super(message ?? "");
36
- __publicField(this, "status", 0);
37
- if (statusCode !== void 0) {
38
- this.status = statusCode;
39
- }
40
- this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
41
- }
11
+ var __esm = (fn, res) => function __init() {
12
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
42
13
  };
43
- __name(_ResponseException, "ResponseException");
44
- var ResponseException = _ResponseException;
45
- var _BadRequestException = class _BadRequestException extends ResponseException {
46
- constructor() {
47
- super(...arguments);
48
- __publicField(this, "status", 400);
49
- }
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
50
17
  };
51
- __name(_BadRequestException, "BadRequestException");
52
- var BadRequestException = _BadRequestException;
53
- var _UnauthorizedException = class _UnauthorizedException extends ResponseException {
54
- constructor() {
55
- super(...arguments);
56
- __publicField(this, "status", 401);
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
57
23
  }
24
+ return to;
58
25
  };
59
- __name(_UnauthorizedException, "UnauthorizedException");
60
- var UnauthorizedException = _UnauthorizedException;
61
- var _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
62
- constructor() {
63
- super(...arguments);
64
- __publicField(this, "status", 402);
65
- }
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var __decorateClass = (decorators, target, key, kind) => {
28
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
29
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
30
+ if (decorator = decorators[i])
31
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
32
+ if (kind && result) __defProp(target, key, result);
33
+ return result;
66
34
  };
67
- __name(_PaymentRequiredException, "PaymentRequiredException");
68
- var PaymentRequiredException = _PaymentRequiredException;
69
- var _ForbiddenException = class _ForbiddenException extends ResponseException {
70
- constructor() {
71
- super(...arguments);
72
- __publicField(this, "status", 403);
73
- }
74
- };
75
- __name(_ForbiddenException, "ForbiddenException");
76
- var ForbiddenException = _ForbiddenException;
77
- var _NotFoundException = class _NotFoundException extends ResponseException {
78
- constructor() {
79
- super(...arguments);
80
- __publicField(this, "status", 404);
81
- }
82
- };
83
- __name(_NotFoundException, "NotFoundException");
84
- var NotFoundException = _NotFoundException;
85
- var _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
86
- constructor() {
87
- super(...arguments);
88
- __publicField(this, "status", 405);
89
- }
90
- };
91
- __name(_MethodNotAllowedException, "MethodNotAllowedException");
92
- var MethodNotAllowedException = _MethodNotAllowedException;
93
- var _NotAcceptableException = class _NotAcceptableException extends ResponseException {
94
- constructor() {
95
- super(...arguments);
96
- __publicField(this, "status", 406);
97
- }
98
- };
99
- __name(_NotAcceptableException, "NotAcceptableException");
100
- var NotAcceptableException = _NotAcceptableException;
101
- var _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
102
- constructor() {
103
- super(...arguments);
104
- __publicField(this, "status", 408);
105
- }
106
- };
107
- __name(_RequestTimeoutException, "RequestTimeoutException");
108
- var RequestTimeoutException = _RequestTimeoutException;
109
- var _ConflictException = class _ConflictException extends ResponseException {
110
- constructor() {
111
- super(...arguments);
112
- __publicField(this, "status", 409);
113
- }
114
- };
115
- __name(_ConflictException, "ConflictException");
116
- var ConflictException = _ConflictException;
117
- var _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
118
- constructor() {
119
- super(...arguments);
120
- __publicField(this, "status", 426);
121
- }
122
- };
123
- __name(_UpgradeRequiredException, "UpgradeRequiredException");
124
- var UpgradeRequiredException = _UpgradeRequiredException;
125
- var _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
126
- constructor() {
127
- super(...arguments);
128
- __publicField(this, "status", 429);
129
- }
130
- };
131
- __name(_TooManyRequestsException, "TooManyRequestsException");
132
- var TooManyRequestsException = _TooManyRequestsException;
133
- var _InternalServerException = class _InternalServerException extends ResponseException {
134
- constructor() {
135
- super(...arguments);
136
- __publicField(this, "status", 500);
137
- }
138
- };
139
- __name(_InternalServerException, "InternalServerException");
140
- var InternalServerException = _InternalServerException;
141
- var _NotImplementedException = class _NotImplementedException extends ResponseException {
142
- constructor() {
143
- super(...arguments);
144
- __publicField(this, "status", 501);
145
- }
146
- };
147
- __name(_NotImplementedException, "NotImplementedException");
148
- var NotImplementedException = _NotImplementedException;
149
- var _BadGatewayException = class _BadGatewayException extends ResponseException {
150
- constructor() {
151
- super(...arguments);
152
- __publicField(this, "status", 502);
153
- }
154
- };
155
- __name(_BadGatewayException, "BadGatewayException");
156
- var BadGatewayException = _BadGatewayException;
157
- var _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
158
- constructor() {
159
- super(...arguments);
160
- __publicField(this, "status", 503);
161
- }
162
- };
163
- __name(_ServiceUnavailableException, "ServiceUnavailableException");
164
- var ServiceUnavailableException = _ServiceUnavailableException;
165
- var _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
166
- constructor() {
167
- super(...arguments);
168
- __publicField(this, "status", 504);
169
- }
170
- };
171
- __name(_GatewayTimeoutException, "GatewayTimeoutException");
172
- var GatewayTimeoutException = _GatewayTimeoutException;
173
- var _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
174
- constructor() {
175
- super(...arguments);
176
- __publicField(this, "status", 505);
177
- }
178
- };
179
- __name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
180
- var HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
181
- var _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
182
- constructor() {
183
- super(...arguments);
184
- __publicField(this, "status", 506);
185
- }
186
- };
187
- __name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
188
- var VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
189
- var _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
190
- constructor() {
191
- super(...arguments);
192
- __publicField(this, "status", 507);
193
- }
194
- };
195
- __name(_InsufficientStorageException, "InsufficientStorageException");
196
- var InsufficientStorageException = _InsufficientStorageException;
197
- var _LoopDetectedException = class _LoopDetectedException extends ResponseException {
198
- constructor() {
199
- super(...arguments);
200
- __publicField(this, "status", 508);
201
- }
202
- };
203
- __name(_LoopDetectedException, "LoopDetectedException");
204
- var LoopDetectedException = _LoopDetectedException;
205
- var _NotExtendedException = class _NotExtendedException extends ResponseException {
206
- constructor() {
207
- super(...arguments);
208
- __publicField(this, "status", 510);
209
- }
210
- };
211
- __name(_NotExtendedException, "NotExtendedException");
212
- var NotExtendedException = _NotExtendedException;
213
- var _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
214
- constructor() {
215
- super(...arguments);
216
- __publicField(this, "status", 511);
217
- }
218
- };
219
- __name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
220
- var NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
221
- var _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
222
- constructor() {
223
- super(...arguments);
224
- __publicField(this, "status", 599);
225
- }
226
- };
227
- __name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
228
- var NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
229
35
 
230
36
  // src/utils/forward-ref.ts
231
- var _ForwardReference = class _ForwardReference {
232
- constructor(forwardRefFn) {
233
- __publicField(this, "forwardRefFn");
234
- this.forwardRefFn = forwardRefFn;
235
- }
236
- };
237
- __name(_ForwardReference, "ForwardReference");
238
- var ForwardReference = _ForwardReference;
239
37
  function forwardRef(fn) {
240
38
  return new ForwardReference(fn);
241
39
  }
242
- __name(forwardRef, "forwardRef");
243
-
244
- // src/DI/app-injector.ts
245
- var _AppInjector = class _AppInjector {
246
- constructor(name = null) {
247
- __publicField(this, "name");
248
- __publicField(this, "bindings", /* @__PURE__ */ new Map());
249
- __publicField(this, "singletons", /* @__PURE__ */ new Map());
250
- __publicField(this, "scoped", /* @__PURE__ */ new Map());
251
- this.name = name;
252
- }
253
- /**
254
- * Typically used to create a dependency injection scope
255
- * at the "scope" level (i.e., per-request lifetime).
256
- *
257
- * SHOULD NOT BE USED by anything else than the framework itself.
258
- */
259
- createScope() {
260
- const scope = new _AppInjector();
261
- scope.bindings = this.bindings;
262
- scope.singletons = this.singletons;
263
- return scope;
264
- }
265
- /**
266
- * Called when resolving a dependency,
267
- * i.e., retrieving the instance of a given class.
268
- */
269
- resolve(target) {
270
- if (target instanceof ForwardReference) {
271
- return new Proxy({}, {
272
- get: /* @__PURE__ */ __name((obj, prop, receiver) => {
273
- const realType = target.forwardRefFn();
274
- const instance = this.resolve(realType);
275
- const value = Reflect.get(instance, prop, receiver);
276
- return typeof value === "function" ? value.bind(instance) : value;
277
- }, "get"),
278
- set: /* @__PURE__ */ __name((obj, prop, value, receiver) => {
279
- const realType = target.forwardRefFn();
280
- const instance = this.resolve(realType);
281
- return Reflect.set(instance, prop, value, receiver);
282
- }, "set"),
283
- getPrototypeOf: /* @__PURE__ */ __name(() => {
284
- const realType = target.forwardRefFn();
285
- return realType.prototype;
286
- }, "getPrototypeOf")
287
- });
288
- }
289
- const binding = this.bindings.get(target);
290
- if (!binding) {
291
- if (target === void 0) {
292
- throw new InternalServerException("Failed to resolve a dependency injection : Undefined target type.\nThis might be caused by a circular dependency.");
293
- }
294
- const name = target.name || "unknown";
295
- throw new InternalServerException(`Failed to resolve a dependency injection : No binding for type ${name}.
296
- Did you forget to use @Injectable() decorator ?`);
297
- }
298
- switch (binding.lifetime) {
299
- case "transient":
300
- return this.instantiate(binding.implementation);
301
- case "scope": {
302
- if (this.scoped.has(target)) {
303
- return this.scoped.get(target);
304
- }
305
- const instance = this.instantiate(binding.implementation);
306
- this.scoped.set(target, instance);
307
- return instance;
308
- }
309
- case "singleton": {
310
- if (binding.instance === void 0 && this.name === "root") {
311
- binding.instance = this.instantiate(binding.implementation);
312
- this.singletons.set(target, binding.instance);
313
- }
314
- return binding.instance;
40
+ var _ForwardReference, ForwardReference;
41
+ var init_forward_ref = __esm({
42
+ "src/utils/forward-ref.ts"() {
43
+ "use strict";
44
+ _ForwardReference = class _ForwardReference {
45
+ constructor(forwardRefFn) {
46
+ this.forwardRefFn = forwardRefFn;
315
47
  }
316
- }
317
- }
318
- /**
319
- * Instantiates a class, resolving its dependencies.
320
- */
321
- instantiate(target) {
322
- const paramTypes = Reflect.getMetadata("design:paramtypes", target) || [];
323
- const injectParams = Reflect.getMetadata(INJECT_METADATA_KEY, target) || [];
324
- const params = paramTypes.map((paramType, index) => {
325
- const overrideToken = injectParams[index];
326
- const actualToken = overrideToken !== void 0 ? overrideToken : paramType;
327
- return this.resolve(actualToken);
328
- });
329
- return new target(...params);
48
+ };
49
+ __name(_ForwardReference, "ForwardReference");
50
+ ForwardReference = _ForwardReference;
51
+ __name(forwardRef, "forwardRef");
330
52
  }
331
- };
332
- __name(_AppInjector, "AppInjector");
333
- var AppInjector = _AppInjector;
334
- function inject(t) {
335
- return RootInjector.resolve(t);
336
- }
337
- __name(inject, "inject");
338
- var RootInjector = new AppInjector("root");
339
-
340
- // src/decorators/guards.decorator.ts
341
- function getGuardForController(controllerName) {
342
- const key = `${controllerName}`;
343
- return authorizations.get(key) ?? [];
344
- }
345
- __name(getGuardForController, "getGuardForController");
346
- function getGuardForControllerAction(controllerName, actionName) {
347
- const key = `${controllerName}.${actionName}`;
348
- return authorizations.get(key) ?? [];
349
- }
350
- __name(getGuardForControllerAction, "getGuardForControllerAction");
351
- var authorizations = /* @__PURE__ */ new Map();
352
-
353
- // src/decorators/controller.decorator.ts
354
- function getControllerMetadata(target) {
355
- return Reflect.getMetadata(CONTROLLER_METADATA_KEY, target);
356
- }
357
- __name(getControllerMetadata, "getControllerMetadata");
358
- var CONTROLLER_METADATA_KEY = Symbol("CONTROLLER_METADATA_KEY");
53
+ });
359
54
 
360
- // src/decorators/injectable.metadata.ts
361
- var INJECTABLE_METADATA_KEY = Symbol("INJECTABLE_METADATA_KEY");
362
- function defineInjectableMetadata(target, lifetime) {
363
- Reflect.defineMetadata(INJECTABLE_METADATA_KEY, lifetime, target);
364
- }
365
- __name(defineInjectableMetadata, "defineInjectableMetadata");
366
- function getInjectableMetadata(target) {
367
- return Reflect.getMetadata(INJECTABLE_METADATA_KEY, target);
368
- }
369
- __name(getInjectableMetadata, "getInjectableMetadata");
370
- function hasInjectableMetadata(target) {
371
- return Reflect.hasMetadata(INJECTABLE_METADATA_KEY, target);
372
- }
373
- __name(hasInjectableMetadata, "hasInjectableMetadata");
374
-
375
- // src/decorators/method.decorator.ts
376
- function createRouteDecorator(verb) {
377
- return (path2) => {
378
- return (target, propertyKey) => {
379
- const existingRoutes = Reflect.getMetadata(ROUTE_METADATA_KEY, target.constructor) || [];
380
- const metadata = {
381
- method: verb,
382
- path: path2.trim().replace(/^\/|\/$/g, ""),
383
- handler: propertyKey,
384
- guards: getGuardForControllerAction(target.constructor.__controllerName, propertyKey)
385
- };
386
- existingRoutes.push(metadata);
387
- Reflect.defineMetadata(ROUTE_METADATA_KEY, existingRoutes, target.constructor);
55
+ // src/DI/token.ts
56
+ var _Token, Token;
57
+ var init_token = __esm({
58
+ "src/DI/token.ts"() {
59
+ "use strict";
60
+ _Token = class _Token {
61
+ constructor(target) {
62
+ this.target = target;
63
+ this.description = typeof target === "string" ? target : target.name;
64
+ }
65
+ toString() {
66
+ return `Token(${this.description})`;
67
+ }
388
68
  };
389
- };
390
- }
391
- __name(createRouteDecorator, "createRouteDecorator");
392
- function getRouteMetadata(target) {
393
- return Reflect.getMetadata(ROUTE_METADATA_KEY, target) || [];
394
- }
395
- __name(getRouteMetadata, "getRouteMetadata");
396
- var Get = createRouteDecorator("GET");
397
- var Post = createRouteDecorator("POST");
398
- var Put = createRouteDecorator("PUT");
399
- var Patch = createRouteDecorator("PATCH");
400
- var Delete = createRouteDecorator("DELETE");
401
- var ROUTE_METADATA_KEY = Symbol("ROUTE_METADATA_KEY");
402
-
403
- // src/decorators/module.decorator.ts
404
- function getModuleMetadata(target) {
405
- return Reflect.getMetadata(MODULE_METADATA_KEY, target);
406
- }
407
- __name(getModuleMetadata, "getModuleMetadata");
408
- var MODULE_METADATA_KEY = Symbol("MODULE_METADATA_KEY");
409
-
410
- // src/router.ts
411
- import "reflect-metadata";
69
+ __name(_Token, "Token");
70
+ Token = _Token;
71
+ }
72
+ });
412
73
 
413
- // src/decorators/middleware.decorator.ts
414
- function getMiddlewaresForController(controllerName) {
415
- const key = `${controllerName}`;
416
- return middlewares.get(key) ?? [];
74
+ // src/DI/app-injector.ts
75
+ function keyOf(k) {
76
+ return k;
417
77
  }
418
- __name(getMiddlewaresForController, "getMiddlewaresForController");
419
- function getMiddlewaresForControllerAction(controllerName, actionName) {
420
- const key = `${controllerName}.${actionName}`;
421
- return middlewares.get(key) ?? [];
78
+ function inject(t) {
79
+ return RootInjector.resolve(t);
422
80
  }
423
- __name(getMiddlewaresForControllerAction, "getMiddlewaresForControllerAction");
424
- var middlewares = /* @__PURE__ */ new Map();
81
+ var _AppInjector, AppInjector, RootInjector;
82
+ var init_app_injector = __esm({
83
+ "src/DI/app-injector.ts"() {
84
+ "use strict";
85
+ init_forward_ref();
86
+ init_token();
87
+ __name(keyOf, "keyOf");
88
+ _AppInjector = class _AppInjector {
89
+ constructor(name = null) {
90
+ this.name = name;
91
+ this.bindings = /* @__PURE__ */ new Map();
92
+ this.singletons = /* @__PURE__ */ new Map();
93
+ this.scoped = /* @__PURE__ */ new Map();
94
+ }
95
+ /**
96
+ * Creates a child scope for per-request lifetime resolution.
97
+ */
98
+ createScope() {
99
+ const scope = new _AppInjector();
100
+ scope.bindings = this.bindings;
101
+ scope.singletons = this.singletons;
102
+ return scope;
103
+ }
104
+ /**
105
+ * Registers a binding explicitly.
106
+ */
107
+ register(key, implementation, lifetime, deps = []) {
108
+ const k = keyOf(key);
109
+ if (!this.bindings.has(k)) {
110
+ this.bindings.set(k, { lifetime, implementation, deps });
111
+ }
112
+ }
113
+ /**
114
+ * Resolves a dependency by token or class reference.
115
+ */
116
+ resolve(target) {
117
+ if (target instanceof ForwardReference) {
118
+ return this._resolveForwardRef(target);
119
+ }
120
+ const k = keyOf(target);
121
+ const binding = this.bindings.get(k);
122
+ if (!binding) {
123
+ const name = target instanceof Token ? target.description : target.name ?? "unknown";
124
+ throw new Error(
125
+ `[Noxus DI] No binding found for "${name}".
126
+ Did you forget to declare it in @Injectable({ deps }) or in bootstrapApplication({ singletons })?`
127
+ );
128
+ }
129
+ switch (binding.lifetime) {
130
+ case "transient":
131
+ return this._instantiate(binding);
132
+ case "scope": {
133
+ if (this.scoped.has(k)) return this.scoped.get(k);
134
+ const inst = this._instantiate(binding);
135
+ this.scoped.set(k, inst);
136
+ return inst;
137
+ }
138
+ case "singleton": {
139
+ if (this.singletons.has(k)) return this.singletons.get(k);
140
+ const inst = this._instantiate(binding);
141
+ this.singletons.set(k, inst);
142
+ if (binding.instance === void 0) {
143
+ binding.instance = inst;
144
+ }
145
+ return inst;
146
+ }
147
+ }
148
+ }
149
+ // -------------------------------------------------------------------------
150
+ _resolveForwardRef(ref) {
151
+ return new Proxy({}, {
152
+ get: /* @__PURE__ */ __name((_obj, prop, receiver) => {
153
+ const realType = ref.forwardRefFn();
154
+ const instance = this.resolve(realType);
155
+ const value = Reflect.get(instance, prop, receiver);
156
+ return typeof value === "function" ? value.bind(instance) : value;
157
+ }, "get"),
158
+ set: /* @__PURE__ */ __name((_obj, prop, value, receiver) => {
159
+ const realType = ref.forwardRefFn();
160
+ const instance = this.resolve(realType);
161
+ return Reflect.set(instance, prop, value, receiver);
162
+ }, "set"),
163
+ getPrototypeOf: /* @__PURE__ */ __name(() => {
164
+ const realType = ref.forwardRefFn();
165
+ return realType.prototype;
166
+ }, "getPrototypeOf")
167
+ });
168
+ }
169
+ _instantiate(binding) {
170
+ const resolvedDeps = binding.deps.map((dep) => this.resolve(dep));
171
+ return new binding.implementation(...resolvedDeps);
172
+ }
173
+ };
174
+ __name(_AppInjector, "AppInjector");
175
+ AppInjector = _AppInjector;
176
+ RootInjector = new AppInjector("root");
177
+ __name(inject, "inject");
178
+ }
179
+ });
425
180
 
426
- // src/request.ts
427
- import "reflect-metadata";
428
- var _Request = class _Request {
429
- constructor(event, senderId, id, method, path2, body) {
430
- __publicField(this, "event");
431
- __publicField(this, "senderId");
432
- __publicField(this, "id");
433
- __publicField(this, "method");
434
- __publicField(this, "path");
435
- __publicField(this, "body");
436
- __publicField(this, "context", RootInjector.createScope());
437
- __publicField(this, "params", {});
438
- this.event = event;
439
- this.senderId = senderId;
440
- this.id = id;
441
- this.method = method;
442
- this.path = path2;
443
- this.body = body;
444
- this.path = path2.replace(/^\/|\/$/g, "");
181
+ // src/exceptions.ts
182
+ var _ResponseException, ResponseException, _BadRequestException, BadRequestException, _UnauthorizedException, UnauthorizedException, _PaymentRequiredException, PaymentRequiredException, _ForbiddenException, ForbiddenException, _NotFoundException, NotFoundException, _MethodNotAllowedException, MethodNotAllowedException, _NotAcceptableException, NotAcceptableException, _RequestTimeoutException, RequestTimeoutException, _ConflictException, ConflictException, _UpgradeRequiredException, UpgradeRequiredException, _TooManyRequestsException, TooManyRequestsException, _InternalServerException, InternalServerException, _NotImplementedException, NotImplementedException, _BadGatewayException, BadGatewayException, _ServiceUnavailableException, ServiceUnavailableException, _GatewayTimeoutException, GatewayTimeoutException, _HttpVersionNotSupportedException, HttpVersionNotSupportedException, _VariantAlsoNegotiatesException, VariantAlsoNegotiatesException, _InsufficientStorageException, InsufficientStorageException, _LoopDetectedException, LoopDetectedException, _NotExtendedException, NotExtendedException, _NetworkAuthenticationRequiredException, NetworkAuthenticationRequiredException, _NetworkConnectTimeoutException, NetworkConnectTimeoutException;
183
+ var init_exceptions = __esm({
184
+ "src/exceptions.ts"() {
185
+ "use strict";
186
+ _ResponseException = class _ResponseException extends Error {
187
+ constructor(statusOrMessage, message) {
188
+ let statusCode;
189
+ if (typeof statusOrMessage === "number") {
190
+ statusCode = statusOrMessage;
191
+ } else if (typeof statusOrMessage === "string") {
192
+ message = statusOrMessage;
193
+ }
194
+ super(message ?? "");
195
+ this.status = 0;
196
+ if (statusCode !== void 0) {
197
+ this.status = statusCode;
198
+ }
199
+ this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
200
+ }
201
+ };
202
+ __name(_ResponseException, "ResponseException");
203
+ ResponseException = _ResponseException;
204
+ _BadRequestException = class _BadRequestException extends ResponseException {
205
+ constructor() {
206
+ super(...arguments);
207
+ this.status = 400;
208
+ }
209
+ };
210
+ __name(_BadRequestException, "BadRequestException");
211
+ BadRequestException = _BadRequestException;
212
+ _UnauthorizedException = class _UnauthorizedException extends ResponseException {
213
+ constructor() {
214
+ super(...arguments);
215
+ this.status = 401;
216
+ }
217
+ };
218
+ __name(_UnauthorizedException, "UnauthorizedException");
219
+ UnauthorizedException = _UnauthorizedException;
220
+ _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
221
+ constructor() {
222
+ super(...arguments);
223
+ this.status = 402;
224
+ }
225
+ };
226
+ __name(_PaymentRequiredException, "PaymentRequiredException");
227
+ PaymentRequiredException = _PaymentRequiredException;
228
+ _ForbiddenException = class _ForbiddenException extends ResponseException {
229
+ constructor() {
230
+ super(...arguments);
231
+ this.status = 403;
232
+ }
233
+ };
234
+ __name(_ForbiddenException, "ForbiddenException");
235
+ ForbiddenException = _ForbiddenException;
236
+ _NotFoundException = class _NotFoundException extends ResponseException {
237
+ constructor() {
238
+ super(...arguments);
239
+ this.status = 404;
240
+ }
241
+ };
242
+ __name(_NotFoundException, "NotFoundException");
243
+ NotFoundException = _NotFoundException;
244
+ _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
245
+ constructor() {
246
+ super(...arguments);
247
+ this.status = 405;
248
+ }
249
+ };
250
+ __name(_MethodNotAllowedException, "MethodNotAllowedException");
251
+ MethodNotAllowedException = _MethodNotAllowedException;
252
+ _NotAcceptableException = class _NotAcceptableException extends ResponseException {
253
+ constructor() {
254
+ super(...arguments);
255
+ this.status = 406;
256
+ }
257
+ };
258
+ __name(_NotAcceptableException, "NotAcceptableException");
259
+ NotAcceptableException = _NotAcceptableException;
260
+ _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
261
+ constructor() {
262
+ super(...arguments);
263
+ this.status = 408;
264
+ }
265
+ };
266
+ __name(_RequestTimeoutException, "RequestTimeoutException");
267
+ RequestTimeoutException = _RequestTimeoutException;
268
+ _ConflictException = class _ConflictException extends ResponseException {
269
+ constructor() {
270
+ super(...arguments);
271
+ this.status = 409;
272
+ }
273
+ };
274
+ __name(_ConflictException, "ConflictException");
275
+ ConflictException = _ConflictException;
276
+ _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
277
+ constructor() {
278
+ super(...arguments);
279
+ this.status = 426;
280
+ }
281
+ };
282
+ __name(_UpgradeRequiredException, "UpgradeRequiredException");
283
+ UpgradeRequiredException = _UpgradeRequiredException;
284
+ _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
285
+ constructor() {
286
+ super(...arguments);
287
+ this.status = 429;
288
+ }
289
+ };
290
+ __name(_TooManyRequestsException, "TooManyRequestsException");
291
+ TooManyRequestsException = _TooManyRequestsException;
292
+ _InternalServerException = class _InternalServerException extends ResponseException {
293
+ constructor() {
294
+ super(...arguments);
295
+ this.status = 500;
296
+ }
297
+ };
298
+ __name(_InternalServerException, "InternalServerException");
299
+ InternalServerException = _InternalServerException;
300
+ _NotImplementedException = class _NotImplementedException extends ResponseException {
301
+ constructor() {
302
+ super(...arguments);
303
+ this.status = 501;
304
+ }
305
+ };
306
+ __name(_NotImplementedException, "NotImplementedException");
307
+ NotImplementedException = _NotImplementedException;
308
+ _BadGatewayException = class _BadGatewayException extends ResponseException {
309
+ constructor() {
310
+ super(...arguments);
311
+ this.status = 502;
312
+ }
313
+ };
314
+ __name(_BadGatewayException, "BadGatewayException");
315
+ BadGatewayException = _BadGatewayException;
316
+ _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
317
+ constructor() {
318
+ super(...arguments);
319
+ this.status = 503;
320
+ }
321
+ };
322
+ __name(_ServiceUnavailableException, "ServiceUnavailableException");
323
+ ServiceUnavailableException = _ServiceUnavailableException;
324
+ _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
325
+ constructor() {
326
+ super(...arguments);
327
+ this.status = 504;
328
+ }
329
+ };
330
+ __name(_GatewayTimeoutException, "GatewayTimeoutException");
331
+ GatewayTimeoutException = _GatewayTimeoutException;
332
+ _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
333
+ constructor() {
334
+ super(...arguments);
335
+ this.status = 505;
336
+ }
337
+ };
338
+ __name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
339
+ HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
340
+ _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
341
+ constructor() {
342
+ super(...arguments);
343
+ this.status = 506;
344
+ }
345
+ };
346
+ __name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
347
+ VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
348
+ _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
349
+ constructor() {
350
+ super(...arguments);
351
+ this.status = 507;
352
+ }
353
+ };
354
+ __name(_InsufficientStorageException, "InsufficientStorageException");
355
+ InsufficientStorageException = _InsufficientStorageException;
356
+ _LoopDetectedException = class _LoopDetectedException extends ResponseException {
357
+ constructor() {
358
+ super(...arguments);
359
+ this.status = 508;
360
+ }
361
+ };
362
+ __name(_LoopDetectedException, "LoopDetectedException");
363
+ LoopDetectedException = _LoopDetectedException;
364
+ _NotExtendedException = class _NotExtendedException extends ResponseException {
365
+ constructor() {
366
+ super(...arguments);
367
+ this.status = 510;
368
+ }
369
+ };
370
+ __name(_NotExtendedException, "NotExtendedException");
371
+ NotExtendedException = _NotExtendedException;
372
+ _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
373
+ constructor() {
374
+ super(...arguments);
375
+ this.status = 511;
376
+ }
377
+ };
378
+ __name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
379
+ NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
380
+ _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
381
+ constructor() {
382
+ super(...arguments);
383
+ this.status = 599;
384
+ }
385
+ };
386
+ __name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
387
+ NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
445
388
  }
446
- };
447
- __name(_Request, "Request");
448
- var Request = _Request;
389
+ });
449
390
 
450
391
  // src/utils/logger.ts
451
392
  import * as fs from "fs";
@@ -454,7 +395,6 @@ function getPrettyTimestamp() {
454
395
  const now = /* @__PURE__ */ new Date();
455
396
  return `${now.getDate().toString().padStart(2, "0")}/${(now.getMonth() + 1).toString().padStart(2, "0")}/${now.getFullYear()} ${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
456
397
  }
457
- __name(getPrettyTimestamp, "getPrettyTimestamp");
458
398
  function getLogPrefix(callee, messageType, color) {
459
399
  const timestamp = getPrettyTimestamp();
460
400
  const spaces = " ".repeat(10 - messageType.length);
@@ -467,7 +407,6 @@ function getLogPrefix(callee, messageType, color) {
467
407
  }
468
408
  return `${color}[APP] ${process.pid} - ${colReset}${timestamp}${spaces}${color}${messageType.toUpperCase()}${colReset} ${colCallee}[${callee}]${colReset}`;
469
409
  }
470
- __name(getLogPrefix, "getLogPrefix");
471
410
  function formatObject(prefix, arg, enableColor = true) {
472
411
  const json = JSON.stringify(arg, null, 2);
473
412
  let colStart = "";
@@ -481,7 +420,6 @@ function formatObject(prefix, arg, enableColor = true) {
481
420
  const prefixedJson = json.split("\n").map((line, idx) => idx === 0 ? `${colStart}${line}` : `${prefix} ${colLine}${line}`).join("\n") + colReset;
482
421
  return prefixedJson;
483
422
  }
484
- __name(formatObject, "formatObject");
485
423
  function formattedArgs(prefix, args, color) {
486
424
  let colReset = Logger.colors.initial;
487
425
  if (color === void 0) {
@@ -497,17 +435,14 @@ function formattedArgs(prefix, args, color) {
497
435
  return arg;
498
436
  });
499
437
  }
500
- __name(formattedArgs, "formattedArgs");
501
438
  function getCallee() {
502
439
  const stack = new Error().stack?.split("\n") ?? [];
503
440
  const caller = stack[3]?.trim().match(/at (.+?)(?:\..+)? .+$/)?.[1]?.replace("Object", "").replace(/^_/, "") || "App";
504
441
  return caller;
505
442
  }
506
- __name(getCallee, "getCallee");
507
443
  function canLog(level) {
508
444
  return logLevels.has(level);
509
445
  }
510
- __name(canLog, "canLog");
511
446
  function processLogQueue(filepath) {
512
447
  const state = fileStates.get(filepath);
513
448
  if (!state || state.isWriting || state.queue.length === 0) {
@@ -517,17 +452,13 @@ function processLogQueue(filepath) {
517
452
  const messagesToWrite = state.queue.join("\n") + "\n";
518
453
  state.queue = [];
519
454
  const dir = path.dirname(filepath);
520
- fs.mkdir(dir, {
521
- recursive: true
522
- }, (err) => {
455
+ fs.mkdir(dir, { recursive: true }, (err) => {
523
456
  if (err) {
524
457
  console.error(`[Logger] Failed to create directory ${dir}`, err);
525
458
  state.isWriting = false;
526
459
  return;
527
460
  }
528
- fs.appendFile(filepath, messagesToWrite, {
529
- encoding: "utf-8"
530
- }, (err2) => {
461
+ fs.appendFile(filepath, messagesToWrite, { encoding: "utf-8" }, (err2) => {
531
462
  state.isWriting = false;
532
463
  if (err2) {
533
464
  console.error(`[Logger] Failed to write log to ${filepath}`, err2);
@@ -538,19 +469,14 @@ function processLogQueue(filepath) {
538
469
  });
539
470
  });
540
471
  }
541
- __name(processLogQueue, "processLogQueue");
542
472
  function enqueue(filepath, message) {
543
473
  if (!fileStates.has(filepath)) {
544
- fileStates.set(filepath, {
545
- queue: [],
546
- isWriting: false
547
- });
474
+ fileStates.set(filepath, { queue: [], isWriting: false });
548
475
  }
549
476
  const state = fileStates.get(filepath);
550
477
  state.queue.push(message);
551
478
  processLogQueue(filepath);
552
479
  }
553
- __name(enqueue, "enqueue");
554
480
  function output(level, args) {
555
481
  if (!canLog(level)) {
556
482
  return;
@@ -571,793 +497,768 @@ function output(level, args) {
571
497
  }
572
498
  }
573
499
  }
574
- __name(output, "output");
575
- (function(Logger2) {
576
- function setLogLevel(level) {
577
- logLevels.clear();
578
- if (Array.isArray(level)) {
579
- for (const lvl of level) {
580
- logLevels.add(lvl);
581
- }
582
- } else {
583
- const targetRank = logLevelRank[level];
584
- for (const [lvl, rank] of Object.entries(logLevelRank)) {
585
- if (rank >= targetRank) {
586
- logLevels.add(lvl);
500
+ var Logger, fileSettings, fileStates, logLevels, logLevelRank, logLevelColors, logLevelChannel;
501
+ var init_logger = __esm({
502
+ "src/utils/logger.ts"() {
503
+ "use strict";
504
+ __name(getPrettyTimestamp, "getPrettyTimestamp");
505
+ __name(getLogPrefix, "getLogPrefix");
506
+ __name(formatObject, "formatObject");
507
+ __name(formattedArgs, "formattedArgs");
508
+ __name(getCallee, "getCallee");
509
+ __name(canLog, "canLog");
510
+ __name(processLogQueue, "processLogQueue");
511
+ __name(enqueue, "enqueue");
512
+ __name(output, "output");
513
+ ((Logger2) => {
514
+ function setLogLevel(level) {
515
+ logLevels.clear();
516
+ if (Array.isArray(level)) {
517
+ for (const lvl of level) {
518
+ logLevels.add(lvl);
519
+ }
520
+ } else {
521
+ const targetRank = logLevelRank[level];
522
+ for (const [lvl, rank] of Object.entries(logLevelRank)) {
523
+ if (rank >= targetRank) {
524
+ logLevels.add(lvl);
525
+ }
526
+ }
587
527
  }
588
528
  }
589
- }
590
- }
591
- __name(setLogLevel, "setLogLevel");
592
- Logger2.setLogLevel = setLogLevel;
593
- function log(...args) {
594
- output("log", args);
595
- }
596
- __name(log, "log");
597
- Logger2.log = log;
598
- function info(...args) {
599
- output("info", args);
600
- }
601
- __name(info, "info");
602
- Logger2.info = info;
603
- function warn(...args) {
604
- output("warn", args);
605
- }
606
- __name(warn, "warn");
607
- Logger2.warn = warn;
608
- function error(...args) {
609
- output("error", args);
610
- }
611
- __name(error, "error");
612
- Logger2.error = error;
613
- function errorStack(...args) {
614
- output("error", args);
615
- }
616
- __name(errorStack, "errorStack");
617
- Logger2.errorStack = errorStack;
618
- function debug(...args) {
619
- output("debug", args);
620
- }
621
- __name(debug, "debug");
622
- Logger2.debug = debug;
623
- function comment(...args) {
624
- output("comment", args);
625
- }
626
- __name(comment, "comment");
627
- Logger2.comment = comment;
628
- function critical(...args) {
629
- output("critical", args);
529
+ Logger2.setLogLevel = setLogLevel;
530
+ __name(setLogLevel, "setLogLevel");
531
+ function log(...args) {
532
+ output("log", args);
533
+ }
534
+ Logger2.log = log;
535
+ __name(log, "log");
536
+ function info(...args) {
537
+ output("info", args);
538
+ }
539
+ Logger2.info = info;
540
+ __name(info, "info");
541
+ function warn(...args) {
542
+ output("warn", args);
543
+ }
544
+ Logger2.warn = warn;
545
+ __name(warn, "warn");
546
+ function error(...args) {
547
+ output("error", args);
548
+ }
549
+ Logger2.error = error;
550
+ __name(error, "error");
551
+ function errorStack(...args) {
552
+ output("error", args);
553
+ }
554
+ Logger2.errorStack = errorStack;
555
+ __name(errorStack, "errorStack");
556
+ function debug(...args) {
557
+ output("debug", args);
558
+ }
559
+ Logger2.debug = debug;
560
+ __name(debug, "debug");
561
+ function comment(...args) {
562
+ output("comment", args);
563
+ }
564
+ Logger2.comment = comment;
565
+ __name(comment, "comment");
566
+ function critical(...args) {
567
+ output("critical", args);
568
+ }
569
+ Logger2.critical = critical;
570
+ __name(critical, "critical");
571
+ function enableFileLogging(filepath, levels = ["debug", "comment", "log", "info", "warn", "error", "critical"]) {
572
+ for (const level of levels) {
573
+ fileSettings.set(level, { filepath });
574
+ }
575
+ }
576
+ Logger2.enableFileLogging = enableFileLogging;
577
+ __name(enableFileLogging, "enableFileLogging");
578
+ function disableFileLogging(levels = ["debug", "comment", "log", "info", "warn", "error", "critical"]) {
579
+ for (const level of levels) {
580
+ fileSettings.delete(level);
581
+ }
582
+ }
583
+ Logger2.disableFileLogging = disableFileLogging;
584
+ __name(disableFileLogging, "disableFileLogging");
585
+ Logger2.colors = {
586
+ black: "\x1B[0;30m",
587
+ grey: "\x1B[0;37m",
588
+ red: "\x1B[0;31m",
589
+ green: "\x1B[0;32m",
590
+ brown: "\x1B[0;33m",
591
+ blue: "\x1B[0;34m",
592
+ purple: "\x1B[0;35m",
593
+ darkGrey: "\x1B[1;30m",
594
+ lightRed: "\x1B[1;31m",
595
+ lightGreen: "\x1B[1;32m",
596
+ yellow: "\x1B[1;33m",
597
+ lightBlue: "\x1B[1;34m",
598
+ magenta: "\x1B[1;35m",
599
+ cyan: "\x1B[1;36m",
600
+ white: "\x1B[1;37m",
601
+ initial: "\x1B[0m"
602
+ };
603
+ })(Logger || (Logger = {}));
604
+ fileSettings = /* @__PURE__ */ new Map();
605
+ fileStates = /* @__PURE__ */ new Map();
606
+ logLevels = /* @__PURE__ */ new Set();
607
+ logLevelRank = {
608
+ debug: 0,
609
+ comment: 1,
610
+ log: 2,
611
+ info: 3,
612
+ warn: 4,
613
+ error: 5,
614
+ critical: 6
615
+ };
616
+ logLevelColors = {
617
+ debug: Logger.colors.purple,
618
+ comment: Logger.colors.grey,
619
+ log: Logger.colors.green,
620
+ info: Logger.colors.blue,
621
+ warn: Logger.colors.brown,
622
+ error: Logger.colors.red,
623
+ critical: Logger.colors.lightRed
624
+ };
625
+ logLevelChannel = {
626
+ debug: console.debug,
627
+ comment: console.debug,
628
+ log: console.log,
629
+ info: console.info,
630
+ warn: console.warn,
631
+ error: console.error,
632
+ critical: console.error
633
+ };
634
+ Logger.setLogLevel("debug");
630
635
  }
631
- __name(critical, "critical");
632
- Logger2.critical = critical;
633
- function enableFileLogging(filepath, levels = [
634
- "debug",
635
- "comment",
636
- "log",
637
- "info",
638
- "warn",
639
- "error",
640
- "critical"
641
- ]) {
642
- for (const level of levels) {
643
- fileSettings.set(level, {
644
- filepath
636
+ });
637
+
638
+ // src/decorators/controller.decorator.ts
639
+ function getControllerMetadata(target) {
640
+ return controllerMetaMap.get(target);
641
+ }
642
+ var controllerMetaMap;
643
+ var init_controller_decorator = __esm({
644
+ "src/decorators/controller.decorator.ts"() {
645
+ "use strict";
646
+ init_injector_explorer();
647
+ controllerMetaMap = /* @__PURE__ */ new WeakMap();
648
+ __name(getControllerMetadata, "getControllerMetadata");
649
+ }
650
+ });
651
+
652
+ // src/decorators/method.decorator.ts
653
+ function isAtomicHttpMethod(m) {
654
+ return typeof m === "string" && ATOMIC_METHODS.has(m);
655
+ }
656
+ function createRouteDecorator(verb) {
657
+ return (path2, options = {}) => {
658
+ return (target, propertyKey) => {
659
+ const ctor = target.constructor;
660
+ const existing = routeMetaMap.get(ctor) ?? [];
661
+ existing.push({
662
+ method: verb,
663
+ path: (path2 ?? "").trim().replace(/^\/|\/$/g, ""),
664
+ handler: propertyKey,
665
+ guards: options.guards ?? [],
666
+ middlewares: options.middlewares ?? []
645
667
  });
646
- }
647
- }
648
- __name(enableFileLogging, "enableFileLogging");
649
- Logger2.enableFileLogging = enableFileLogging;
650
- function disableFileLogging(levels = [
651
- "debug",
652
- "comment",
653
- "log",
654
- "info",
655
- "warn",
656
- "error",
657
- "critical"
658
- ]) {
659
- for (const level of levels) {
660
- fileSettings.delete(level);
661
- }
662
- }
663
- __name(disableFileLogging, "disableFileLogging");
664
- Logger2.disableFileLogging = disableFileLogging;
665
- Logger2.colors = {
666
- black: "\x1B[0;30m",
667
- grey: "\x1B[0;37m",
668
- red: "\x1B[0;31m",
669
- green: "\x1B[0;32m",
670
- brown: "\x1B[0;33m",
671
- blue: "\x1B[0;34m",
672
- purple: "\x1B[0;35m",
673
- darkGrey: "\x1B[1;30m",
674
- lightRed: "\x1B[1;31m",
675
- lightGreen: "\x1B[1;32m",
676
- yellow: "\x1B[1;33m",
677
- lightBlue: "\x1B[1;34m",
678
- magenta: "\x1B[1;35m",
679
- cyan: "\x1B[1;36m",
680
- white: "\x1B[1;37m",
681
- initial: "\x1B[0m"
668
+ routeMetaMap.set(ctor, existing);
669
+ };
682
670
  };
683
- })(Logger || (Logger = {}));
684
- var fileSettings = /* @__PURE__ */ new Map();
685
- var fileStates = /* @__PURE__ */ new Map();
686
- var logLevels = /* @__PURE__ */ new Set();
687
- var logLevelRank = {
688
- debug: 0,
689
- comment: 1,
690
- log: 2,
691
- info: 3,
692
- warn: 4,
693
- error: 5,
694
- critical: 6
695
- };
696
- var logLevelColors = {
697
- debug: Logger.colors.purple,
698
- comment: Logger.colors.grey,
699
- log: Logger.colors.green,
700
- info: Logger.colors.blue,
701
- warn: Logger.colors.brown,
702
- error: Logger.colors.red,
703
- critical: Logger.colors.lightRed
704
- };
705
- var logLevelChannel = {
706
- debug: console.debug,
707
- comment: console.debug,
708
- log: console.log,
709
- info: console.info,
710
- warn: console.warn,
711
- error: console.error,
712
- critical: console.error
713
- };
714
- Logger.setLogLevel("debug");
715
- var Logger;
671
+ }
672
+ function getRouteMetadata(target) {
673
+ return routeMetaMap.get(target) ?? [];
674
+ }
675
+ var ATOMIC_METHODS, routeMetaMap, Get, Post, Put, Patch, Delete;
676
+ var init_method_decorator = __esm({
677
+ "src/decorators/method.decorator.ts"() {
678
+ "use strict";
679
+ ATOMIC_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
680
+ __name(isAtomicHttpMethod, "isAtomicHttpMethod");
681
+ routeMetaMap = /* @__PURE__ */ new WeakMap();
682
+ __name(createRouteDecorator, "createRouteDecorator");
683
+ __name(getRouteMetadata, "getRouteMetadata");
684
+ Get = createRouteDecorator("GET");
685
+ Post = createRouteDecorator("POST");
686
+ Put = createRouteDecorator("PUT");
687
+ Patch = createRouteDecorator("PATCH");
688
+ Delete = createRouteDecorator("DELETE");
689
+ }
690
+ });
716
691
 
717
- // src/utils/radix-tree.ts
718
- var _a;
719
- var RadixNode = (_a = class {
720
- /**
721
- * Creates a new RadixNode.
722
- * @param segment - The segment of the path this node represents.
723
- */
724
- constructor(segment) {
725
- __publicField(this, "segment");
726
- __publicField(this, "children", []);
727
- __publicField(this, "value");
728
- __publicField(this, "isParam");
729
- __publicField(this, "paramName");
730
- this.segment = segment;
731
- this.isParam = segment.startsWith(":");
732
- if (this.isParam) {
733
- this.paramName = segment.slice(1);
734
- }
735
- }
736
- /**
737
- * Matches a child node against a given segment.
738
- * This method checks if the segment matches any of the children nodes.
739
- * @param segment - The segment to match against the children of this node.
740
- * @returns A child node that matches the segment, or undefined if no match is found.
741
- */
742
- matchChild(segment) {
743
- for (const child of this.children) {
744
- if (child.isParam || segment.startsWith(child.segment)) return child;
745
- }
746
- return void 0;
747
- }
748
- /**
749
- * Finds a child node that matches the segment exactly.
750
- * This method checks if there is a child node that matches the segment exactly.
751
- * @param segment - The segment to find an exact match for among the children of this node.
752
- * @returns A child node that matches the segment exactly, or undefined if no match is found.
753
- */
754
- findExactChild(segment) {
755
- return this.children.find((c) => c.segment === segment);
756
- }
757
- /**
758
- * Adds a child node to this node's children.
759
- * This method adds a new child node to the list of children for this node.
760
- * @param node - The child node to add to this node's children.
761
- */
762
- addChild(node) {
763
- this.children.push(node);
764
- }
765
- }, __name(_a, "RadixNode"), _a);
766
- var _RadixTree = class _RadixTree {
767
- constructor() {
768
- __publicField(this, "root", new RadixNode(""));
769
- }
770
- /**
771
- * Inserts a path and its associated value into the Radix Tree.
772
- * This method normalizes the path and inserts it into the tree, associating it with
773
- * @param path - The path to insert into the tree.
774
- * @param value - The value to associate with the path.
775
- */
776
- insert(path2, value) {
777
- const segments = this.normalize(path2);
778
- this.insertRecursive(this.root, segments, value);
779
- }
780
- /**
781
- * Recursively inserts a path into the Radix Tree.
782
- * This method traverses the tree and inserts the segments of the path, creating new nodes
783
- * @param node - The node to start inserting from.
784
- * @param segments - The segments of the path to insert.
785
- * @param value - The value to associate with the path.
786
- */
787
- insertRecursive(node, segments, value) {
788
- if (segments.length === 0) {
789
- node.value = value;
790
- return;
791
- }
792
- const segment = segments[0] ?? "";
793
- let child = node.children.find((c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment));
794
- if (!child) {
795
- child = new RadixNode(segment);
796
- node.addChild(child);
797
- }
798
- this.insertRecursive(child, segments.slice(1), value);
799
- }
800
- /**
801
- * Searches for a path in the Radix Tree.
802
- * This method normalizes the path and searches for it in the tree, returning the node
803
- * @param path - The path to search for in the Radix Tree.
804
- * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
805
- */
806
- search(path2) {
807
- const segments = this.normalize(path2);
808
- return this.searchRecursive(this.root, segments, {});
692
+ // src/request.ts
693
+ var _Request, Request;
694
+ var init_request = __esm({
695
+ "src/request.ts"() {
696
+ "use strict";
697
+ init_app_injector();
698
+ _Request = class _Request {
699
+ constructor(event, senderId, id, method, path2, body) {
700
+ this.event = event;
701
+ this.senderId = senderId;
702
+ this.id = id;
703
+ this.method = method;
704
+ this.path = path2;
705
+ this.body = body;
706
+ this.context = RootInjector.createScope();
707
+ this.params = {};
708
+ this.path = path2.replace(/^\/|\/$/g, "");
709
+ }
710
+ };
711
+ __name(_Request, "Request");
712
+ Request = _Request;
809
713
  }
810
- /**
811
- * Recursively searches for a path in the Radix Tree.
812
- * This method traverses the tree and searches for the segments of the path, collecting parameters
813
- * @param node - The node to start searching from.
814
- * @param segments - The segments of the path to search for.
815
- * @param params - The parameters collected during the search.
816
- * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
817
- */
818
- searchRecursive(node, segments, params) {
819
- if (segments.length === 0) {
820
- if (node.value !== void 0) {
821
- return {
822
- node,
823
- params
824
- };
714
+ });
715
+
716
+ // src/utils/radix-tree.ts
717
+ var _RadixNode, RadixNode, _RadixTree, RadixTree;
718
+ var init_radix_tree = __esm({
719
+ "src/utils/radix-tree.ts"() {
720
+ "use strict";
721
+ _RadixNode = class _RadixNode {
722
+ /**
723
+ * Creates a new RadixNode.
724
+ * @param segment - The segment of the path this node represents.
725
+ */
726
+ constructor(segment) {
727
+ this.children = [];
728
+ this.segment = segment;
729
+ this.isParam = segment.startsWith(":");
730
+ if (this.isParam) {
731
+ this.paramName = segment.slice(1);
732
+ }
825
733
  }
826
- return void 0;
827
- }
828
- const [segment, ...rest] = segments;
829
- for (const child of node.children) {
830
- if (child.isParam) {
831
- const paramName = child.paramName;
832
- const childParams = {
833
- ...params,
834
- [paramName]: segment ?? ""
835
- };
836
- if (rest.length === 0) {
837
- return {
838
- node: child,
839
- params: childParams
840
- };
734
+ /**
735
+ * Matches a child node against a given segment.
736
+ * This method checks if the segment matches any of the children nodes.
737
+ * @param segment - The segment to match against the children of this node.
738
+ * @returns A child node that matches the segment, or undefined if no match is found.
739
+ */
740
+ matchChild(segment) {
741
+ for (const child of this.children) {
742
+ if (child.isParam || segment.startsWith(child.segment))
743
+ return child;
841
744
  }
842
- const result = this.searchRecursive(child, rest, childParams);
843
- if (result) return result;
844
- } else if (segment === child.segment) {
845
- if (rest.length === 0) {
846
- return {
847
- node: child,
848
- params
849
- };
745
+ return void 0;
746
+ }
747
+ /**
748
+ * Finds a child node that matches the segment exactly.
749
+ * This method checks if there is a child node that matches the segment exactly.
750
+ * @param segment - The segment to find an exact match for among the children of this node.
751
+ * @returns A child node that matches the segment exactly, or undefined if no match is found.
752
+ */
753
+ findExactChild(segment) {
754
+ return this.children.find((c) => c.segment === segment);
755
+ }
756
+ /**
757
+ * Adds a child node to this node's children.
758
+ * This method adds a new child node to the list of children for this node.
759
+ * @param node - The child node to add to this node's children.
760
+ */
761
+ addChild(node) {
762
+ this.children.push(node);
763
+ }
764
+ };
765
+ __name(_RadixNode, "RadixNode");
766
+ RadixNode = _RadixNode;
767
+ _RadixTree = class _RadixTree {
768
+ constructor() {
769
+ this.root = new RadixNode("");
770
+ }
771
+ /**
772
+ * Inserts a path and its associated value into the Radix Tree.
773
+ * This method normalizes the path and inserts it into the tree, associating it with
774
+ * @param path - The path to insert into the tree.
775
+ * @param value - The value to associate with the path.
776
+ */
777
+ insert(path2, value) {
778
+ const segments = this.normalize(path2);
779
+ this.insertRecursive(this.root, segments, value);
780
+ }
781
+ /**
782
+ * Recursively inserts a path into the Radix Tree.
783
+ * This method traverses the tree and inserts the segments of the path, creating new nodes
784
+ * @param node - The node to start inserting from.
785
+ * @param segments - The segments of the path to insert.
786
+ * @param value - The value to associate with the path.
787
+ */
788
+ insertRecursive(node, segments, value) {
789
+ if (segments.length === 0) {
790
+ node.value = value;
791
+ return;
850
792
  }
851
- const result = this.searchRecursive(child, rest, params);
852
- if (result) return result;
793
+ const segment = segments[0] ?? "";
794
+ let child = node.children.find(
795
+ (c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment)
796
+ );
797
+ if (!child) {
798
+ child = new RadixNode(segment);
799
+ node.addChild(child);
800
+ }
801
+ this.insertRecursive(child, segments.slice(1), value);
853
802
  }
854
- }
855
- return void 0;
856
- }
857
- /**
858
- * Normalizes a path into an array of segments.
859
- * This method removes leading and trailing slashes, splits the path by slashes, and
860
- * @param path - The path to normalize.
861
- * @returns An array of normalized path segments.
862
- */
863
- normalize(path2) {
864
- const segments = path2.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
865
- return [
866
- "",
867
- ...segments
868
- ];
803
+ /**
804
+ * Searches for a path in the Radix Tree.
805
+ * This method normalizes the path and searches for it in the tree, returning the node
806
+ * @param path - The path to search for in the Radix Tree.
807
+ * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
808
+ */
809
+ search(path2) {
810
+ const segments = this.normalize(path2);
811
+ return this.searchRecursive(this.root, segments, {});
812
+ }
813
+ /**
814
+ * Recursively searches for a path in the Radix Tree.
815
+ * This method traverses the tree and searches for the segments of the path, collecting parameters
816
+ * @param node - The node to start searching from.
817
+ * @param segments - The segments of the path to search for.
818
+ * @param params - The parameters collected during the search.
819
+ * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
820
+ */
821
+ searchRecursive(node, segments, params) {
822
+ if (segments.length === 0) {
823
+ if (node.value !== void 0) {
824
+ return {
825
+ node,
826
+ params
827
+ };
828
+ }
829
+ return void 0;
830
+ }
831
+ const [segment, ...rest] = segments;
832
+ for (const child of node.children) {
833
+ if (child.isParam) {
834
+ const paramName = child.paramName;
835
+ const childParams = {
836
+ ...params,
837
+ [paramName]: segment ?? ""
838
+ };
839
+ if (rest.length === 0) {
840
+ return {
841
+ node: child,
842
+ params: childParams
843
+ };
844
+ }
845
+ const result = this.searchRecursive(child, rest, childParams);
846
+ if (result)
847
+ return result;
848
+ } else if (segment === child.segment) {
849
+ if (rest.length === 0) {
850
+ return {
851
+ node: child,
852
+ params
853
+ };
854
+ }
855
+ const result = this.searchRecursive(child, rest, params);
856
+ if (result)
857
+ return result;
858
+ }
859
+ }
860
+ return void 0;
861
+ }
862
+ /**
863
+ * Normalizes a path into an array of segments.
864
+ * This method removes leading and trailing slashes, splits the path by slashes, and
865
+ * @param path - The path to normalize.
866
+ * @returns An array of normalized path segments.
867
+ */
868
+ normalize(path2) {
869
+ const segments = path2.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
870
+ return ["", ...segments];
871
+ }
872
+ };
873
+ __name(_RadixTree, "RadixTree");
874
+ RadixTree = _RadixTree;
869
875
  }
870
- };
871
- __name(_RadixTree, "RadixTree");
872
- var RadixTree = _RadixTree;
876
+ });
873
877
 
874
878
  // src/router.ts
875
- function _ts_decorate(decorators, target, key, desc) {
876
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
877
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
878
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
879
- return c > 3 && r && Object.defineProperty(target, key, r), r;
880
- }
881
- __name(_ts_decorate, "_ts_decorate");
882
- var ATOMIC_HTTP_METHODS = /* @__PURE__ */ new Set([
883
- "GET",
884
- "POST",
885
- "PUT",
886
- "PATCH",
887
- "DELETE"
888
- ]);
889
- function isAtomicHttpMethod(method) {
890
- return typeof method === "string" && ATOMIC_HTTP_METHODS.has(method);
891
- }
892
- __name(isAtomicHttpMethod, "isAtomicHttpMethod");
893
- var _Router = class _Router {
894
- constructor() {
895
- __publicField(this, "routes", new RadixTree());
896
- __publicField(this, "rootMiddlewares", []);
897
- }
898
- /**
899
- * Registers a controller class with the router.
900
- * This method extracts the route metadata from the controller class and registers it in the routing tree.
901
- * It also handles the guards and middlewares associated with the controller.
902
- * @param controllerClass - The controller class to register.
903
- */
904
- registerController(controllerClass) {
905
- const controllerMeta = getControllerMetadata(controllerClass);
906
- const controllerGuards = getGuardForController(controllerClass.name);
907
- const controllerMiddlewares = getMiddlewaresForController(controllerClass.name);
908
- if (!controllerMeta) throw new Error(`Missing @Controller decorator on ${controllerClass.name}`);
909
- const routeMetadata = getRouteMetadata(controllerClass);
910
- for (const def of routeMetadata) {
911
- const fullPath = `${controllerMeta.path}/${def.path}`.replace(/\/+/g, "/");
912
- const routeGuards = getGuardForControllerAction(controllerClass.name, def.handler);
913
- const routeMiddlewares = getMiddlewaresForControllerAction(controllerClass.name, def.handler);
914
- const guards = /* @__PURE__ */ new Set([
915
- ...controllerGuards,
916
- ...routeGuards
917
- ]);
918
- const middlewares2 = /* @__PURE__ */ new Set([
919
- ...controllerMiddlewares,
920
- ...routeMiddlewares
921
- ]);
922
- const routeDef = {
923
- method: def.method,
924
- path: fullPath,
925
- controller: controllerClass,
926
- handler: def.handler,
927
- guards: [
928
- ...guards
929
- ],
930
- middlewares: [
931
- ...middlewares2
932
- ]
933
- };
934
- this.routes.insert(fullPath + "/" + def.method, routeDef);
935
- const hasActionGuards = routeDef.guards.length > 0;
936
- const actionGuardsInfo = hasActionGuards ? "<" + routeDef.guards.map((g) => g.name).join("|") + ">" : "";
937
- Logger.log(`Mapped {${routeDef.method} /${fullPath}}${actionGuardsInfo} route`);
938
- }
939
- const hasCtrlGuards = controllerMeta.guards.length > 0;
940
- const controllerGuardsInfo = hasCtrlGuards ? "<" + controllerMeta.guards.map((g) => g.name).join("|") + ">" : "";
941
- Logger.log(`Mapped ${controllerClass.name}${controllerGuardsInfo} controller's routes`);
942
- return this;
943
- }
944
- /**
945
- * Defines a middleware for the root of the application.
946
- * This method allows you to register a middleware that will be applied to all requests
947
- * to the application, regardless of the controller or action.
948
- * @param middleware - The middleware class to register.
949
- */
950
- defineRootMiddleware(middleware) {
951
- this.rootMiddlewares.push(middleware);
952
- return this;
953
- }
954
- /**
955
- * Shuts down the message channel for a specific sender ID.
956
- * This method closes the IPC channel for the specified sender ID and
957
- * removes it from the messagePorts map.
958
- * @param channelSenderId - The ID of the sender channel to shut down.
959
- */
960
- async handle(request) {
961
- if (request.method === "BATCH") {
962
- return this.handleBatch(request);
963
- }
964
- return this.handleAtomic(request);
965
- }
966
- async handleAtomic(request) {
967
- Logger.comment(`> ${request.method} /${request.path}`);
968
- const t0 = performance.now();
969
- const response = {
970
- requestId: request.id,
971
- status: 200,
972
- body: null
973
- };
974
- let isCritical = false;
975
- try {
976
- const routeDef = this.findRoute(request);
977
- await this.resolveController(request, response, routeDef);
978
- if (response.status > 400) {
979
- throw new ResponseException(response.status, response.error);
980
- }
981
- } catch (error) {
982
- response.body = void 0;
983
- if (error instanceof ResponseException) {
984
- response.status = error.status;
985
- response.error = error.message;
986
- response.stack = error.stack;
987
- } else if (error instanceof Error) {
988
- isCritical = true;
989
- response.status = 500;
990
- response.error = error.message || "Internal Server Error";
991
- response.stack = error.stack || "No stack trace available";
992
- } else {
993
- isCritical = true;
994
- response.status = 500;
995
- response.error = "Unknown error occurred";
996
- response.stack = "No stack trace available";
997
- }
998
- } finally {
999
- const t1 = performance.now();
1000
- const message = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(t1 - t0)}ms${Logger.colors.initial}`;
1001
- if (response.status < 400) {
1002
- Logger.log(message);
1003
- } else if (response.status < 500) {
1004
- Logger.warn(message);
1005
- } else {
1006
- if (isCritical) {
1007
- Logger.critical(message);
1008
- } else {
1009
- Logger.error(message);
879
+ var router_exports = {};
880
+ __export(router_exports, {
881
+ Router: () => Router
882
+ });
883
+ var Router;
884
+ var init_router = __esm({
885
+ "src/router.ts"() {
886
+ "use strict";
887
+ init_controller_decorator();
888
+ init_injectable_decorator();
889
+ init_method_decorator();
890
+ init_injector_explorer();
891
+ init_exceptions();
892
+ init_request();
893
+ init_logger();
894
+ init_radix_tree();
895
+ Router = class {
896
+ constructor() {
897
+ this.routes = new RadixTree();
898
+ this.rootMiddlewares = [];
899
+ this.lazyRoutes = /* @__PURE__ */ new Map();
900
+ }
901
+ // -------------------------------------------------------------------------
902
+ // Registration
903
+ // -------------------------------------------------------------------------
904
+ registerController(controllerClass, pathPrefix, routeGuards = [], routeMiddlewares = []) {
905
+ const meta = getControllerMetadata(controllerClass);
906
+ if (!meta) {
907
+ throw new Error(`[Noxus] Missing @Controller decorator on ${controllerClass.name}`);
1010
908
  }
909
+ const routeMeta = getRouteMetadata(controllerClass);
910
+ for (const def of routeMeta) {
911
+ const fullPath = `${pathPrefix}/${def.path}`.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
912
+ const guards = [.../* @__PURE__ */ new Set([...routeGuards, ...def.guards])];
913
+ const middlewares = [.../* @__PURE__ */ new Set([...routeMiddlewares, ...def.middlewares])];
914
+ const routeDef = {
915
+ method: def.method,
916
+ path: fullPath,
917
+ controller: controllerClass,
918
+ handler: def.handler,
919
+ guards,
920
+ middlewares
921
+ };
922
+ this.routes.insert(fullPath + "/" + def.method, routeDef);
923
+ const guardInfo = guards.length ? `<${guards.map((g) => g.name).join("|")}>` : "";
924
+ Logger.log(`Mapped {${def.method} /${fullPath}}${guardInfo} route`);
925
+ }
926
+ const ctrlGuardInfo = routeGuards.length ? `<${routeGuards.map((g) => g.name).join("|")}>` : "";
927
+ Logger.log(`Mapped ${controllerClass.name}${ctrlGuardInfo} controller's routes`);
928
+ return this;
1011
929
  }
1012
- if (response.error !== void 0) {
1013
- if (isCritical) {
1014
- Logger.critical(response.error);
1015
- } else {
1016
- Logger.error(response.error);
930
+ registerLazyRoute(pathPrefix, load, guards = [], middlewares = []) {
931
+ const normalized = pathPrefix.replace(/^\/+|\/+$/g, "");
932
+ this.lazyRoutes.set(normalized, { load, guards, middlewares, loading: null, loaded: false });
933
+ Logger.log(`Registered lazy route prefix {${normalized}}`);
934
+ return this;
935
+ }
936
+ defineRootMiddleware(middleware) {
937
+ this.rootMiddlewares.push(middleware);
938
+ return this;
939
+ }
940
+ // -------------------------------------------------------------------------
941
+ // Request handling
942
+ // -------------------------------------------------------------------------
943
+ async handle(request) {
944
+ return request.method === "BATCH" ? this.handleBatch(request) : this.handleAtomic(request);
945
+ }
946
+ async handleAtomic(request) {
947
+ Logger.comment(`> ${request.method} /${request.path}`);
948
+ const t0 = performance.now();
949
+ const response = { requestId: request.id, status: 200, body: null };
950
+ let isCritical = false;
951
+ try {
952
+ const routeDef = await this.findRoute(request);
953
+ await this.resolveController(request, response, routeDef);
954
+ if (response.status >= 400) throw new ResponseException(response.status, response.error);
955
+ } catch (error) {
956
+ this.fillErrorResponse(response, error, (c) => {
957
+ isCritical = c;
958
+ });
959
+ } finally {
960
+ this.logResponse(request, response, performance.now() - t0, isCritical);
961
+ return response;
1017
962
  }
1018
- if (response.stack !== void 0) {
1019
- Logger.errorStack(response.stack);
963
+ }
964
+ async handleBatch(request) {
965
+ Logger.comment(`> ${request.method} /${request.path}`);
966
+ const t0 = performance.now();
967
+ const response = {
968
+ requestId: request.id,
969
+ status: 200,
970
+ body: { responses: [] }
971
+ };
972
+ let isCritical = false;
973
+ try {
974
+ const payload = this.normalizeBatchPayload(request.body);
975
+ response.body.responses = await Promise.all(
976
+ payload.requests.map((item, i) => {
977
+ const id = item.requestId ?? `${request.id}:${i}`;
978
+ return this.handleAtomic(new Request(request.event, request.senderId, id, item.method, item.path, item.body));
979
+ })
980
+ );
981
+ } catch (error) {
982
+ this.fillErrorResponse(response, error, (c) => {
983
+ isCritical = c;
984
+ });
985
+ } finally {
986
+ this.logResponse(request, response, performance.now() - t0, isCritical);
987
+ return response;
1020
988
  }
1021
989
  }
1022
- return response;
1023
- }
1024
- }
1025
- async handleBatch(request) {
1026
- Logger.comment(`> ${request.method} /${request.path}`);
1027
- const t0 = performance.now();
1028
- const response = {
1029
- requestId: request.id,
1030
- status: 200,
1031
- body: {
1032
- responses: []
990
+ // -------------------------------------------------------------------------
991
+ // Route resolution
992
+ // -------------------------------------------------------------------------
993
+ tryFindRoute(request) {
994
+ const matched = this.routes.search(request.path);
995
+ if (!matched?.node || matched.node.children.length === 0) return void 0;
996
+ return matched.node.findExactChild(request.method)?.value;
1033
997
  }
1034
- };
1035
- let isCritical = false;
1036
- try {
1037
- const payload = this.normalizeBatchPayload(request.body);
1038
- const batchPromises = payload.requests.map((item, index) => {
1039
- const subRequestId = item.requestId ?? `${request.id}:${index}`;
1040
- const atomicRequest = new Request(request.event, request.senderId, subRequestId, item.method, item.path, item.body);
1041
- return this.handleAtomic(atomicRequest);
1042
- });
1043
- response.body.responses = await Promise.all(batchPromises);
1044
- } catch (error) {
1045
- response.body = void 0;
1046
- if (error instanceof ResponseException) {
1047
- response.status = error.status;
1048
- response.error = error.message;
1049
- response.stack = error.stack;
1050
- } else if (error instanceof Error) {
1051
- isCritical = true;
1052
- response.status = 500;
1053
- response.error = error.message || "Internal Server Error";
1054
- response.stack = error.stack || "No stack trace available";
1055
- } else {
1056
- isCritical = true;
1057
- response.status = 500;
1058
- response.error = "Unknown error occurred";
1059
- response.stack = "No stack trace available";
1060
- }
1061
- } finally {
1062
- const t1 = performance.now();
1063
- const message = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(t1 - t0)}ms${Logger.colors.initial}`;
1064
- if (response.status < 400) {
1065
- Logger.log(message);
1066
- } else if (response.status < 500) {
1067
- Logger.warn(message);
1068
- } else {
1069
- if (isCritical) {
1070
- Logger.critical(message);
1071
- } else {
1072
- Logger.error(message);
998
+ async findRoute(request) {
999
+ const direct = this.tryFindRoute(request);
1000
+ if (direct) return direct;
1001
+ await this.tryLoadLazyRoute(request.path);
1002
+ const afterLazy = this.tryFindRoute(request);
1003
+ if (afterLazy) return afterLazy;
1004
+ throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
1005
+ }
1006
+ async tryLoadLazyRoute(requestPath) {
1007
+ const firstSegment = requestPath.replace(/^\/+/, "").split("/")[0] ?? "";
1008
+ for (const [prefix, entry] of this.lazyRoutes) {
1009
+ if (entry.loaded) continue;
1010
+ const normalized = requestPath.replace(/^\/+/, "");
1011
+ if (normalized === prefix || normalized.startsWith(prefix + "/") || firstSegment === prefix) {
1012
+ if (!entry.loading) entry.loading = this.loadLazyModule(prefix, entry);
1013
+ await entry.loading;
1014
+ return;
1015
+ }
1073
1016
  }
1074
1017
  }
1075
- if (response.error !== void 0) {
1076
- if (isCritical) {
1077
- Logger.critical(response.error);
1078
- } else {
1079
- Logger.error(response.error);
1018
+ async loadLazyModule(prefix, entry) {
1019
+ const t0 = performance.now();
1020
+ InjectorExplorer.beginAccumulate();
1021
+ await entry.load?.();
1022
+ entry.loading = null;
1023
+ entry.load = null;
1024
+ InjectorExplorer.flushAccumulated(entry.guards, entry.middlewares, prefix);
1025
+ entry.loaded = true;
1026
+ Logger.info(`Lazy-loaded module for prefix {${prefix}} in ${Math.round(performance.now() - t0)}ms`);
1027
+ }
1028
+ // -------------------------------------------------------------------------
1029
+ // Pipeline
1030
+ // -------------------------------------------------------------------------
1031
+ async resolveController(request, response, routeDef) {
1032
+ const instance = request.context.resolve(routeDef.controller);
1033
+ Object.assign(request.params, this.extractParams(request.path, routeDef.path));
1034
+ await this.runPipeline(request, response, routeDef, instance);
1035
+ }
1036
+ async runPipeline(request, response, routeDef, controllerInstance) {
1037
+ const middlewares = [.../* @__PURE__ */ new Set([...this.rootMiddlewares, ...routeDef.middlewares])];
1038
+ const mwMax = middlewares.length - 1;
1039
+ const guardMax = mwMax + routeDef.guards.length;
1040
+ let index = -1;
1041
+ const dispatch = /* @__PURE__ */ __name(async (i) => {
1042
+ if (i <= index) throw new Error("next() called multiple times");
1043
+ index = i;
1044
+ if (i <= mwMax) {
1045
+ await this.runMiddleware(request, response, dispatch.bind(null, i + 1), middlewares[i]);
1046
+ if (response.status >= 400) throw new ResponseException(response.status, response.error);
1047
+ return;
1048
+ }
1049
+ if (i <= guardMax) {
1050
+ await this.runGuard(request, routeDef.guards[i - middlewares.length]);
1051
+ await dispatch(i + 1);
1052
+ return;
1053
+ }
1054
+ const action = controllerInstance[routeDef.handler];
1055
+ response.body = await action.call(controllerInstance, request, response);
1056
+ if (response.body === void 0) response.body = {};
1057
+ }, "dispatch");
1058
+ await dispatch(0);
1059
+ }
1060
+ async runMiddleware(request, response, next, middleware) {
1061
+ await middleware(request, response, next);
1062
+ }
1063
+ async runGuard(request, guard) {
1064
+ if (!await guard(request)) {
1065
+ throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
1080
1066
  }
1081
- if (response.stack !== void 0) {
1082
- Logger.errorStack(response.stack);
1067
+ }
1068
+ // -------------------------------------------------------------------------
1069
+ // Utilities
1070
+ // -------------------------------------------------------------------------
1071
+ extractParams(actual, template) {
1072
+ const aParts = actual.split("/");
1073
+ const tParts = template.split("/");
1074
+ const params = {};
1075
+ tParts.forEach((part, i) => {
1076
+ if (part.startsWith(":")) params[part.slice(1)] = aParts[i] ?? "";
1077
+ });
1078
+ return params;
1079
+ }
1080
+ normalizeBatchPayload(body) {
1081
+ if (body === null || typeof body !== "object") {
1082
+ throw new BadRequestException("Batch payload must be an object containing a requests array.");
1083
1083
  }
1084
+ const { requests } = body;
1085
+ if (!Array.isArray(requests)) throw new BadRequestException("Batch payload must define a requests array.");
1086
+ return { requests: requests.map((e, i) => this.normalizeBatchItem(e, i)) };
1084
1087
  }
1085
- return response;
1086
- }
1087
- }
1088
- normalizeBatchPayload(body) {
1089
- if (body === null || typeof body !== "object") {
1090
- throw new BadRequestException("Batch payload must be an object containing a requests array.");
1091
- }
1092
- const possiblePayload = body;
1093
- const { requests } = possiblePayload;
1094
- if (!Array.isArray(requests)) {
1095
- throw new BadRequestException("Batch payload must define a requests array.");
1096
- }
1097
- const normalizedRequests = requests.map((entry, index) => this.normalizeBatchItem(entry, index));
1098
- return {
1099
- requests: normalizedRequests
1100
- };
1101
- }
1102
- normalizeBatchItem(entry, index) {
1103
- if (entry === null || typeof entry !== "object") {
1104
- throw new BadRequestException(`Batch request at index ${index} must be an object.`);
1105
- }
1106
- const { requestId, path: path2, method, body } = entry;
1107
- if (requestId !== void 0 && typeof requestId !== "string") {
1108
- throw new BadRequestException(`Batch request at index ${index} has an invalid requestId.`);
1109
- }
1110
- if (typeof path2 !== "string" || path2.length === 0) {
1111
- throw new BadRequestException(`Batch request at index ${index} must define a non-empty path.`);
1112
- }
1113
- if (typeof method !== "string") {
1114
- throw new BadRequestException(`Batch request at index ${index} must define an HTTP method.`);
1115
- }
1116
- const normalizedMethod = method.toUpperCase();
1117
- if (!isAtomicHttpMethod(normalizedMethod)) {
1118
- throw new BadRequestException(`Batch request at index ${index} uses the unsupported method ${method}.`);
1119
- }
1120
- return {
1121
- requestId,
1122
- path: path2,
1123
- method: normalizedMethod,
1124
- body
1125
- };
1126
- }
1127
- /**
1128
- * Finds the route definition for a given request.
1129
- * This method searches the routing tree for a matching route based on the request's path and method.
1130
- * If no matching route is found, it throws a NotFoundException.
1131
- * @param request - The Request object containing the method and path to search for.
1132
- * @returns The IRouteDefinition for the matched route.
1133
- */
1134
- findRoute(request) {
1135
- const matchedRoutes = this.routes.search(request.path);
1136
- if (matchedRoutes?.node === void 0 || matchedRoutes.node.children.length === 0) {
1137
- throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
1138
- }
1139
- const routeDef = matchedRoutes.node.findExactChild(request.method);
1140
- if (routeDef?.value === void 0) {
1141
- throw new MethodNotAllowedException(`Method Not Allowed for ${request.method} ${request.path}`);
1142
- }
1143
- return routeDef.value;
1144
- }
1145
- /**
1146
- * Resolves the controller for a given route definition.
1147
- * This method creates an instance of the controller class and prepares the request parameters.
1148
- * It also runs the request pipeline, which includes executing middlewares and guards.
1149
- * @param request - The Request object containing the request data.
1150
- * @param response - The IResponse object to populate with the response data.
1151
- * @param routeDef - The IRouteDefinition for the matched route.
1152
- * @return A Promise that resolves when the controller action has been executed.
1153
- * @throws UnauthorizedException if the request is not authorized by the guards.
1154
- */
1155
- async resolveController(request, response, routeDef) {
1156
- const controllerInstance = request.context.resolve(routeDef.controller);
1157
- Object.assign(request.params, this.extractParams(request.path, routeDef.path));
1158
- await this.runRequestPipeline(request, response, routeDef, controllerInstance);
1159
- }
1160
- /**
1161
- * Runs the request pipeline for a given request.
1162
- * This method executes the middlewares and guards associated with the route,
1163
- * and finally calls the controller action.
1164
- * @param request - The Request object containing the request data.
1165
- * @param response - The IResponse object to populate with the response data.
1166
- * @param routeDef - The IRouteDefinition for the matched route.
1167
- * @param controllerInstance - The instance of the controller class.
1168
- * @return A Promise that resolves when the request pipeline has been executed.
1169
- * @throws ResponseException if the response status is not successful.
1170
- */
1171
- async runRequestPipeline(request, response, routeDef, controllerInstance) {
1172
- const middlewares2 = [
1173
- .../* @__PURE__ */ new Set([
1174
- ...this.rootMiddlewares,
1175
- ...routeDef.middlewares
1176
- ])
1177
- ];
1178
- const middlewareMaxIndex = middlewares2.length - 1;
1179
- const guardsMaxIndex = middlewareMaxIndex + routeDef.guards.length;
1180
- let index = -1;
1181
- const dispatch = /* @__PURE__ */ __name(async (i) => {
1182
- if (i <= index) throw new Error("next() called multiple times");
1183
- index = i;
1184
- if (i <= middlewareMaxIndex) {
1185
- const nextFn = dispatch.bind(null, i + 1);
1186
- await this.runMiddleware(request, response, nextFn, middlewares2[i]);
1187
- if (response.status >= 400) {
1188
- throw new ResponseException(response.status, response.error);
1088
+ normalizeBatchItem(entry, index) {
1089
+ if (entry === null || typeof entry !== "object") throw new BadRequestException(`Batch request at index ${index} must be an object.`);
1090
+ const { requestId, path: path2, method, body } = entry;
1091
+ if (requestId !== void 0 && typeof requestId !== "string") throw new BadRequestException(`Batch request at index ${index} has an invalid requestId.`);
1092
+ if (typeof path2 !== "string" || !path2.length) throw new BadRequestException(`Batch request at index ${index} must define a non-empty path.`);
1093
+ if (typeof method !== "string") throw new BadRequestException(`Batch request at index ${index} must define an HTTP method.`);
1094
+ const normalized = method.toUpperCase();
1095
+ if (!isAtomicHttpMethod(normalized)) throw new BadRequestException(`Batch request at index ${index} uses unsupported method ${method}.`);
1096
+ return { requestId, path: path2, method: normalized, body };
1097
+ }
1098
+ fillErrorResponse(response, error, setCritical) {
1099
+ response.body = void 0;
1100
+ if (error instanceof ResponseException) {
1101
+ response.status = error.status;
1102
+ response.error = error.message;
1103
+ response.stack = error.stack;
1104
+ } else if (error instanceof Error) {
1105
+ setCritical(true);
1106
+ response.status = 500;
1107
+ response.error = error.message || "Internal Server Error";
1108
+ response.stack = error.stack;
1109
+ } else {
1110
+ setCritical(true);
1111
+ response.status = 500;
1112
+ response.error = "Unknown error occurred";
1189
1113
  }
1190
- return;
1191
- }
1192
- if (i <= guardsMaxIndex) {
1193
- const guardIndex = i - middlewares2.length;
1194
- const guardType = routeDef.guards[guardIndex];
1195
- await this.runGuard(request, guardType);
1196
- await dispatch(i + 1);
1197
- return;
1198
- }
1199
- const action = controllerInstance[routeDef.handler];
1200
- response.body = await action.call(controllerInstance, request, response);
1201
- if (response.body === void 0) {
1202
- response.body = {};
1203
- }
1204
- }, "dispatch");
1205
- await dispatch(0);
1206
- }
1207
- /**
1208
- * Runs a middleware function in the request pipeline.
1209
- * This method creates an instance of the middleware and invokes its `invoke` method,
1210
- * passing the request, response, and next function.
1211
- * @param request - The Request object containing the request data.
1212
- * @param response - The IResponse object to populate with the response data.
1213
- * @param next - The NextFunction to call to continue the middleware chain.
1214
- * @param middlewareType - The type of the middleware to run.
1215
- * @return A Promise that resolves when the middleware has been executed.
1216
- */
1217
- async runMiddleware(request, response, next, middlewareType) {
1218
- const middleware = request.context.resolve(middlewareType);
1219
- await middleware.invoke(request, response, next);
1220
- }
1221
- /**
1222
- * Runs a guard to check if the request is authorized.
1223
- * This method creates an instance of the guard and calls its `canActivate` method.
1224
- * If the guard returns false, it throws an UnauthorizedException.
1225
- * @param request - The Request object containing the request data.
1226
- * @param guardType - The type of the guard to run.
1227
- * @return A Promise that resolves if the guard allows the request, or throws an UnauthorizedException if not.
1228
- * @throws UnauthorizedException if the guard denies access to the request.
1229
- */
1230
- async runGuard(request, guardType) {
1231
- const guard = request.context.resolve(guardType);
1232
- const allowed = await guard.canActivate(request);
1233
- if (!allowed) throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
1234
- }
1235
- /**
1236
- * Extracts parameters from the actual request path based on the template path.
1237
- * This method splits the actual path and the template path into segments,
1238
- * then maps the segments to parameters based on the template.
1239
- * @param actual - The actual request path.
1240
- * @param template - The template path to extract parameters from.
1241
- * @returns An object containing the extracted parameters.
1242
- */
1243
- extractParams(actual, template) {
1244
- const aParts = actual.split("/");
1245
- const tParts = template.split("/");
1246
- const params = {};
1247
- tParts.forEach((part, i) => {
1248
- if (part.startsWith(":")) {
1249
- params[part.slice(1)] = aParts[i] ?? "";
1250
1114
  }
1251
- });
1252
- return params;
1115
+ logResponse(request, response, ms, isCritical) {
1116
+ const msg = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(ms)}ms${Logger.colors.initial}`;
1117
+ if (response.status < 400) Logger.log(msg);
1118
+ else if (response.status < 500) Logger.warn(msg);
1119
+ else isCritical ? Logger.critical(msg) : Logger.error(msg);
1120
+ if (response.error) {
1121
+ isCritical ? Logger.critical(response.error) : Logger.error(response.error);
1122
+ if (response.stack) Logger.errorStack(response.stack);
1123
+ }
1124
+ }
1125
+ };
1126
+ __name(Router, "Router");
1127
+ Router = __decorateClass([
1128
+ Injectable({ lifetime: "singleton" })
1129
+ ], Router);
1253
1130
  }
1254
- };
1255
- __name(_Router, "Router");
1256
- var Router = _Router;
1257
- Router = _ts_decorate([
1258
- Injectable("singleton")
1259
- ], Router);
1131
+ });
1260
1132
 
1261
1133
  // src/DI/injector-explorer.ts
1262
- var _InjectorExplorer = class _InjectorExplorer {
1263
- /**
1264
- * Enqueues a class for deferred registration.
1265
- * Called by the @Injectable decorator at import time.
1266
- *
1267
- * If {@link processPending} has already been called (i.e. after bootstrap),
1268
- * the class is registered immediately so that late dynamic imports
1269
- * (e.g. middlewares loaded after bootstrap) work correctly.
1270
- */
1271
- static enqueue(target, lifetime) {
1272
- if (_InjectorExplorer.processed) {
1273
- _InjectorExplorer.registerImmediate(target, lifetime);
1274
- return;
1275
- }
1276
- _InjectorExplorer.pending.push({
1277
- target,
1278
- lifetime
1279
- });
1280
- }
1281
- /**
1282
- * Processes all pending registrations in two phases:
1283
- * 1. Register all bindings (no instantiation) so every dependency is known.
1284
- * 2. Resolve singletons, register controllers and log module readiness.
1285
- *
1286
- * This two-phase approach makes the system resilient to import ordering:
1287
- * all bindings exist before any singleton is instantiated.
1288
- */
1289
- static processPending() {
1290
- const queue = _InjectorExplorer.pending;
1291
- for (const { target, lifetime } of queue) {
1292
- if (!RootInjector.bindings.has(target)) {
1293
- RootInjector.bindings.set(target, {
1294
- implementation: target,
1295
- lifetime
1296
- });
1134
+ var _InjectorExplorer, InjectorExplorer;
1135
+ var init_injector_explorer = __esm({
1136
+ "src/DI/injector-explorer.ts"() {
1137
+ "use strict";
1138
+ init_app_injector();
1139
+ init_logger();
1140
+ _InjectorExplorer = class _InjectorExplorer {
1141
+ // -------------------------------------------------------------------------
1142
+ // Public API
1143
+ // -------------------------------------------------------------------------
1144
+ static enqueue(reg) {
1145
+ if (_InjectorExplorer.processed && !_InjectorExplorer.accumulating) {
1146
+ _InjectorExplorer._registerImmediate(reg);
1147
+ return;
1148
+ }
1149
+ _InjectorExplorer.pending.push(reg);
1297
1150
  }
1298
- }
1299
- for (const { target, lifetime } of queue) {
1300
- _InjectorExplorer.processRegistration(target, lifetime);
1301
- }
1302
- queue.length = 0;
1303
- _InjectorExplorer.processed = true;
1304
- }
1305
- /**
1306
- * Registers a single class immediately (post-bootstrap path).
1307
- * Used for classes discovered via late dynamic imports.
1308
- */
1309
- static registerImmediate(target, lifetime) {
1310
- if (RootInjector.bindings.has(target)) {
1311
- return;
1312
- }
1313
- RootInjector.bindings.set(target, {
1314
- implementation: target,
1315
- lifetime
1316
- });
1317
- _InjectorExplorer.processRegistration(target, lifetime);
1318
- }
1319
- /**
1320
- * Performs phase-2 work for a single registration: resolve singletons,
1321
- * register controllers, and log module readiness.
1322
- */
1323
- static processRegistration(target, lifetime) {
1324
- if (lifetime === "singleton") {
1325
- RootInjector.resolve(target);
1326
- }
1327
- if (getModuleMetadata(target)) {
1328
- Logger.log(`${target.name} dependencies initialized`);
1329
- return;
1330
- }
1331
- const controllerMeta = getControllerMetadata(target);
1332
- if (controllerMeta) {
1333
- const router = RootInjector.resolve(Router);
1334
- router?.registerController(target);
1335
- return;
1336
- }
1337
- if (getRouteMetadata(target).length > 0) {
1338
- return;
1339
- }
1340
- if (getInjectableMetadata(target)) {
1341
- Logger.log(`Registered ${target.name} as ${lifetime}`);
1342
- }
1151
+ /**
1152
+ * Two-phase flush of all pending registrations collected at startup.
1153
+ * Called by bootstrapApplication after app.whenReady().
1154
+ */
1155
+ static processPending(singletonOverrides) {
1156
+ const queue = [..._InjectorExplorer.pending];
1157
+ _InjectorExplorer.pending.length = 0;
1158
+ _InjectorExplorer._phaseOne(queue);
1159
+ _InjectorExplorer._phaseTwo(queue, singletonOverrides);
1160
+ _InjectorExplorer.processed = true;
1161
+ }
1162
+ /** Enters accumulation mode for lazy-loaded batches. */
1163
+ static beginAccumulate() {
1164
+ _InjectorExplorer.accumulating = true;
1165
+ }
1166
+ /**
1167
+ * Exits accumulation mode and flushes queued registrations
1168
+ * with the same two-phase guarantee as processPending.
1169
+ */
1170
+ static flushAccumulated(routeGuards = [], routeMiddlewares = [], pathPrefix = "") {
1171
+ _InjectorExplorer.accumulating = false;
1172
+ const queue = [..._InjectorExplorer.pending];
1173
+ _InjectorExplorer.pending.length = 0;
1174
+ _InjectorExplorer._phaseOne(queue);
1175
+ for (const reg of queue) {
1176
+ if (reg.isController) reg.pathPrefix = pathPrefix;
1177
+ }
1178
+ _InjectorExplorer._phaseTwo(queue, void 0, routeGuards, routeMiddlewares);
1179
+ }
1180
+ // -------------------------------------------------------------------------
1181
+ // Private helpers
1182
+ // -------------------------------------------------------------------------
1183
+ /** Phase 1: register all bindings without instantiating anything. */
1184
+ static _phaseOne(queue) {
1185
+ for (const reg of queue) {
1186
+ RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
1187
+ }
1188
+ }
1189
+ /** Phase 2: resolve singletons and register controllers in the router. */
1190
+ static _phaseTwo(queue, overrides, routeGuards = [], routeMiddlewares = []) {
1191
+ for (const reg of queue) {
1192
+ if (overrides?.has(reg.key)) {
1193
+ const override = overrides.get(reg.key);
1194
+ RootInjector.singletons.set(reg.key, override);
1195
+ Logger.log(`Registered ${reg.implementation.name} as singleton (overridden)`);
1196
+ continue;
1197
+ }
1198
+ if (reg.lifetime === "singleton") {
1199
+ RootInjector.resolve(reg.key);
1200
+ }
1201
+ if (reg.isController) {
1202
+ const { Router: Router2 } = (init_router(), __toCommonJS(router_exports));
1203
+ const router = RootInjector.resolve(Router2);
1204
+ router.registerController(reg.implementation, reg.pathPrefix ?? "", routeGuards, routeMiddlewares);
1205
+ } else if (reg.lifetime !== "singleton") {
1206
+ Logger.log(`Registered ${reg.implementation.name} as ${reg.lifetime}`);
1207
+ }
1208
+ }
1209
+ }
1210
+ static _registerImmediate(reg) {
1211
+ RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
1212
+ if (reg.lifetime === "singleton") {
1213
+ RootInjector.resolve(reg.key);
1214
+ }
1215
+ if (reg.isController) {
1216
+ const { Router: Router2 } = (init_router(), __toCommonJS(router_exports));
1217
+ const router = RootInjector.resolve(Router2);
1218
+ router.registerController(reg.implementation);
1219
+ }
1220
+ }
1221
+ };
1222
+ __name(_InjectorExplorer, "InjectorExplorer");
1223
+ _InjectorExplorer.pending = [];
1224
+ _InjectorExplorer.processed = false;
1225
+ _InjectorExplorer.accumulating = false;
1226
+ InjectorExplorer = _InjectorExplorer;
1343
1227
  }
1344
- };
1345
- __name(_InjectorExplorer, "InjectorExplorer");
1346
- __publicField(_InjectorExplorer, "pending", []);
1347
- __publicField(_InjectorExplorer, "processed", false);
1348
- var InjectorExplorer = _InjectorExplorer;
1228
+ });
1349
1229
 
1350
1230
  // src/decorators/injectable.decorator.ts
1351
- function Injectable(lifetime = "scope") {
1231
+ function Injectable(options = {}) {
1232
+ const { lifetime = "scope", deps = [] } = options;
1352
1233
  return (target) => {
1353
1234
  if (typeof target !== "function" || !target.prototype) {
1354
- throw new Error(`@Injectable can only be used on classes, not on ${typeof target}`);
1235
+ throw new Error(`@Injectable can only be applied to classes, not ${typeof target}`);
1355
1236
  }
1356
- defineInjectableMetadata(target, lifetime);
1357
- InjectorExplorer.enqueue(target, lifetime);
1237
+ const key = target;
1238
+ InjectorExplorer.enqueue({
1239
+ key,
1240
+ implementation: key,
1241
+ lifetime,
1242
+ deps,
1243
+ isController: false
1244
+ });
1358
1245
  };
1359
1246
  }
1360
- __name(Injectable, "Injectable");
1247
+ var init_injectable_decorator = __esm({
1248
+ "src/decorators/injectable.decorator.ts"() {
1249
+ "use strict";
1250
+ init_injector_explorer();
1251
+ init_token();
1252
+ __name(Injectable, "Injectable");
1253
+ }
1254
+ });
1255
+
1256
+ // src/non-electron-process.ts
1257
+ init_app_injector();
1258
+ init_exceptions();
1259
+ init_injectable_decorator();
1260
+ init_logger();
1261
+ init_forward_ref();
1361
1262
  export {
1362
1263
  AppInjector,
1363
1264
  BadGatewayException,
@@ -1367,9 +1268,6 @@ export {
1367
1268
  ForwardReference,
1368
1269
  GatewayTimeoutException,
1369
1270
  HttpVersionNotSupportedException,
1370
- INJECTABLE_METADATA_KEY,
1371
- INJECT_METADATA_KEY,
1372
- Inject,
1373
1271
  Injectable,
1374
1272
  InsufficientStorageException,
1375
1273
  InternalServerException,
@@ -1387,13 +1285,12 @@ export {
1387
1285
  ResponseException,
1388
1286
  RootInjector,
1389
1287
  ServiceUnavailableException,
1288
+ Token,
1390
1289
  TooManyRequestsException,
1391
1290
  UnauthorizedException,
1392
1291
  UpgradeRequiredException,
1393
1292
  VariantAlsoNegotiatesException,
1394
1293
  forwardRef,
1395
- getInjectableMetadata,
1396
- hasInjectableMetadata,
1397
1294
  inject
1398
1295
  };
1399
1296
  /**