@noxfly/noxus 3.0.0-dev.1 → 3.0.0-dev.11

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 (57) hide show
  1. package/README.md +121 -8
  2. package/dist/child.d.mts +8 -2
  3. package/dist/child.d.ts +8 -2
  4. package/dist/child.js +405 -862
  5. package/dist/child.js.map +1 -0
  6. package/dist/child.mjs +396 -854
  7. package/dist/child.mjs.map +1 -0
  8. package/dist/main.d.mts +180 -132
  9. package/dist/main.d.ts +180 -132
  10. package/dist/main.js +1087 -926
  11. package/dist/main.js.map +1 -0
  12. package/dist/main.mjs +1038 -877
  13. package/dist/main.mjs.map +1 -0
  14. package/dist/preload.js.map +1 -0
  15. package/dist/preload.mjs.map +1 -0
  16. package/dist/renderer.d.mts +30 -4
  17. package/dist/renderer.d.ts +30 -4
  18. package/dist/renderer.js +191 -128
  19. package/dist/renderer.js.map +1 -0
  20. package/dist/renderer.mjs +180 -116
  21. package/dist/renderer.mjs.map +1 -0
  22. package/package.json +18 -9
  23. package/.editorconfig +0 -16
  24. package/.github/copilot-instructions.md +0 -32
  25. package/.vscode/settings.json +0 -3
  26. package/eslint.config.js +0 -109
  27. package/scripts/postbuild.js +0 -31
  28. package/src/DI/app-injector.ts +0 -151
  29. package/src/DI/injector-explorer.ts +0 -143
  30. package/src/DI/token.ts +0 -53
  31. package/src/decorators/controller.decorator.ts +0 -58
  32. package/src/decorators/guards.decorator.ts +0 -15
  33. package/src/decorators/injectable.decorator.ts +0 -81
  34. package/src/decorators/method.decorator.ts +0 -66
  35. package/src/decorators/middleware.decorator.ts +0 -15
  36. package/src/index.ts +0 -10
  37. package/src/internal/app.ts +0 -217
  38. package/src/internal/bootstrap.ts +0 -108
  39. package/src/internal/exceptions.ts +0 -57
  40. package/src/internal/preload-bridge.ts +0 -75
  41. package/src/internal/renderer-client.ts +0 -338
  42. package/src/internal/renderer-events.ts +0 -110
  43. package/src/internal/request.ts +0 -97
  44. package/src/internal/router.ts +0 -353
  45. package/src/internal/routes.ts +0 -78
  46. package/src/internal/socket.ts +0 -73
  47. package/src/main.ts +0 -26
  48. package/src/non-electron-process.ts +0 -22
  49. package/src/preload.ts +0 -10
  50. package/src/renderer.ts +0 -13
  51. package/src/utils/forward-ref.ts +0 -31
  52. package/src/utils/logger.ts +0 -430
  53. package/src/utils/radix-tree.ts +0 -210
  54. package/src/utils/types.ts +0 -21
  55. package/src/window/window-manager.ts +0 -255
  56. package/tsconfig.json +0 -29
  57. package/tsup.config.ts +0 -50
package/dist/main.mjs CHANGED
@@ -3,10 +3,16 @@
3
3
  * @license MIT
4
4
  * @author NoxFly
5
5
  */
6
+ var __create = Object.create;
6
7
  var __defProp = Object.defineProperty;
7
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
9
  var __getOwnPropNames = Object.getOwnPropertyNames;
9
10
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
12
+ var __typeError = (msg) => {
13
+ throw TypeError(msg);
14
+ };
15
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
16
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
17
  var __esm = (fn, res) => function __init() {
12
18
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
@@ -24,14 +30,45 @@ var __copyProps = (to, from, except, desc) => {
24
30
  return to;
25
31
  };
26
32
  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;
33
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
34
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
35
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
36
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
37
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
38
+ var __runInitializers = (array, flags, self, value) => {
39
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
40
+ return value;
41
+ };
42
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
43
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
44
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
45
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
46
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
47
+ return __privateGet(this, extra);
48
+ }, set [name](x) {
49
+ return __privateSet(this, extra, x);
50
+ } }, name));
51
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
52
+ for (var i = decorators.length - 1; i >= 0; i--) {
53
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
54
+ if (k) {
55
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
56
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
57
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
58
+ }
59
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
60
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
61
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
62
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
63
+ }
64
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
34
65
  };
66
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
67
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
68
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
69
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
70
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
71
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
35
72
 
36
73
  // src/utils/forward-ref.ts
37
74
  function forwardRef(fn) {
@@ -63,6 +100,7 @@ var init_token = __esm({
63
100
  _Token = class _Token {
64
101
  constructor(target) {
65
102
  this.target = target;
103
+ __publicField(this, "description");
66
104
  this.description = typeof target === "string" ? target : target.name;
67
105
  }
68
106
  toString() {
@@ -75,113 +113,6 @@ var init_token = __esm({
75
113
  }
76
114
  });
77
115
 
78
- // src/DI/app-injector.ts
79
- function keyOf(k) {
80
- return k;
81
- }
82
- function inject(t) {
83
- return RootInjector.resolve(t);
84
- }
85
- var _AppInjector, AppInjector, RootInjector;
86
- var init_app_injector = __esm({
87
- "src/DI/app-injector.ts"() {
88
- "use strict";
89
- init_forward_ref();
90
- init_token();
91
- __name(keyOf, "keyOf");
92
- _AppInjector = class _AppInjector {
93
- constructor(name = null) {
94
- this.name = name;
95
- this.bindings = /* @__PURE__ */ new Map();
96
- this.singletons = /* @__PURE__ */ new Map();
97
- this.scoped = /* @__PURE__ */ new Map();
98
- }
99
- /**
100
- * Creates a child scope for per-request lifetime resolution.
101
- */
102
- createScope() {
103
- const scope = new _AppInjector();
104
- scope.bindings = this.bindings;
105
- scope.singletons = this.singletons;
106
- return scope;
107
- }
108
- /**
109
- * Registers a binding explicitly.
110
- */
111
- register(key, implementation, lifetime, deps = []) {
112
- const k = keyOf(key);
113
- if (!this.bindings.has(k)) {
114
- this.bindings.set(k, { lifetime, implementation, deps });
115
- }
116
- }
117
- /**
118
- * Resolves a dependency by token or class reference.
119
- */
120
- resolve(target) {
121
- if (target instanceof ForwardReference) {
122
- return this._resolveForwardRef(target);
123
- }
124
- const k = keyOf(target);
125
- const binding = this.bindings.get(k);
126
- if (!binding) {
127
- const name = target instanceof Token ? target.description : target.name ?? "unknown";
128
- throw new Error(
129
- `[Noxus DI] No binding found for "${name}".
130
- Did you forget to declare it in @Injectable({ deps }) or in bootstrapApplication({ singletons })?`
131
- );
132
- }
133
- switch (binding.lifetime) {
134
- case "transient":
135
- return this._instantiate(binding);
136
- case "scope": {
137
- if (this.scoped.has(k)) return this.scoped.get(k);
138
- const inst = this._instantiate(binding);
139
- this.scoped.set(k, inst);
140
- return inst;
141
- }
142
- case "singleton": {
143
- if (this.singletons.has(k)) return this.singletons.get(k);
144
- const inst = this._instantiate(binding);
145
- this.singletons.set(k, inst);
146
- if (binding.instance === void 0) {
147
- binding.instance = inst;
148
- }
149
- return inst;
150
- }
151
- }
152
- }
153
- // -------------------------------------------------------------------------
154
- _resolveForwardRef(ref) {
155
- return new Proxy({}, {
156
- get: /* @__PURE__ */ __name((_obj, prop, receiver) => {
157
- const realType = ref.forwardRefFn();
158
- const instance = this.resolve(realType);
159
- const value = Reflect.get(instance, prop, receiver);
160
- return typeof value === "function" ? value.bind(instance) : value;
161
- }, "get"),
162
- set: /* @__PURE__ */ __name((_obj, prop, value, receiver) => {
163
- const realType = ref.forwardRefFn();
164
- const instance = this.resolve(realType);
165
- return Reflect.set(instance, prop, value, receiver);
166
- }, "set"),
167
- getPrototypeOf: /* @__PURE__ */ __name(() => {
168
- const realType = ref.forwardRefFn();
169
- return realType.prototype;
170
- }, "getPrototypeOf")
171
- });
172
- }
173
- _instantiate(binding) {
174
- const resolvedDeps = binding.deps.map((dep) => this.resolve(dep));
175
- return new binding.implementation(...resolvedDeps);
176
- }
177
- };
178
- __name(_AppInjector, "AppInjector");
179
- AppInjector = _AppInjector;
180
- RootInjector = new AppInjector("root");
181
- __name(inject, "inject");
182
- }
183
- });
184
-
185
116
  // src/utils/logger.ts
186
117
  import * as fs from "fs";
187
118
  import * as path from "path";
@@ -430,6 +361,10 @@ var init_logger = __esm({
430
361
  });
431
362
 
432
363
  // src/DI/injector-explorer.ts
364
+ var injector_explorer_exports = {};
365
+ __export(injector_explorer_exports, {
366
+ InjectorExplorer: () => InjectorExplorer
367
+ });
433
368
  var _InjectorExplorer, InjectorExplorer;
434
369
  var init_injector_explorer = __esm({
435
370
  "src/DI/injector-explorer.ts"() {
@@ -440,6 +375,13 @@ var init_injector_explorer = __esm({
440
375
  // -------------------------------------------------------------------------
441
376
  // Public API
442
377
  // -------------------------------------------------------------------------
378
+ /**
379
+ * Sets the callback used to register controllers.
380
+ * Must be called once before processPending (typically by bootstrapApplication).
381
+ */
382
+ static setControllerRegistrar(registrar) {
383
+ _InjectorExplorer.controllerRegistrar = registrar;
384
+ }
443
385
  static enqueue(reg) {
444
386
  if (_InjectorExplorer.processed && !_InjectorExplorer.accumulating) {
445
387
  _InjectorExplorer._registerImmediate(reg);
@@ -465,16 +407,37 @@ var init_injector_explorer = __esm({
465
407
  /**
466
408
  * Exits accumulation mode and flushes queued registrations
467
409
  * with the same two-phase guarantee as processPending.
410
+ * Serialised through a lock to prevent concurrent lazy loads from corrupting the queue.
468
411
  */
469
412
  static flushAccumulated(routeGuards = [], routeMiddlewares = [], pathPrefix = "") {
470
- _InjectorExplorer.accumulating = false;
471
- const queue = [..._InjectorExplorer.pending];
413
+ _InjectorExplorer.loadingLock = _InjectorExplorer.loadingLock.then(() => {
414
+ _InjectorExplorer.accumulating = false;
415
+ const queue = [..._InjectorExplorer.pending];
416
+ _InjectorExplorer.pending.length = 0;
417
+ _InjectorExplorer._phaseOne(queue);
418
+ for (const reg of queue) {
419
+ if (reg.isController) reg.pathPrefix = pathPrefix;
420
+ }
421
+ _InjectorExplorer._phaseTwo(queue, void 0, routeGuards, routeMiddlewares);
422
+ });
423
+ return _InjectorExplorer.loadingLock;
424
+ }
425
+ /**
426
+ * Returns a Promise that resolves once all pending flushAccumulated calls
427
+ * have completed. Useful for awaiting lazy-load serialisation.
428
+ */
429
+ static waitForFlush() {
430
+ return _InjectorExplorer.loadingLock;
431
+ }
432
+ /**
433
+ * Resets the explorer state. Intended for tests only.
434
+ */
435
+ static reset() {
472
436
  _InjectorExplorer.pending.length = 0;
473
- _InjectorExplorer._phaseOne(queue);
474
- for (const reg of queue) {
475
- if (reg.isController) reg.pathPrefix = pathPrefix;
476
- }
477
- _InjectorExplorer._phaseTwo(queue, void 0, routeGuards, routeMiddlewares);
437
+ _InjectorExplorer.processed = false;
438
+ _InjectorExplorer.accumulating = false;
439
+ _InjectorExplorer.loadingLock = Promise.resolve();
440
+ _InjectorExplorer.controllerRegistrar = null;
478
441
  }
479
442
  // -------------------------------------------------------------------------
480
443
  // Private helpers
@@ -485,8 +448,15 @@ var init_injector_explorer = __esm({
485
448
  RootInjector.register(reg.key, reg.implementation, reg.lifetime, reg.deps);
486
449
  }
487
450
  }
488
- /** Phase 2: resolve singletons and register controllers in the router. */
451
+ /** Phase 2: validate deps, resolve singletons and register controllers via the registrar callback. */
489
452
  static _phaseTwo(queue, overrides, routeGuards = [], routeMiddlewares = []) {
453
+ for (const reg of queue) {
454
+ for (const dep of reg.deps) {
455
+ if (!RootInjector.bindings.has(dep) && !RootInjector.singletons.has(dep)) {
456
+ Logger.warn(`[Noxus DI] "${reg.implementation.name}" declares dep "${dep.name ?? dep}" which has no binding`);
457
+ }
458
+ }
459
+ }
490
460
  for (const reg of queue) {
491
461
  if (overrides?.has(reg.key)) {
492
462
  const override = overrides.get(reg.key);
@@ -498,9 +468,15 @@ var init_injector_explorer = __esm({
498
468
  RootInjector.resolve(reg.key);
499
469
  }
500
470
  if (reg.isController) {
501
- const { Router: Router2 } = (init_router(), __toCommonJS(router_exports));
502
- const router = RootInjector.resolve(Router2);
503
- router.registerController(reg.implementation, reg.pathPrefix ?? "", routeGuards, routeMiddlewares);
471
+ if (!_InjectorExplorer.controllerRegistrar) {
472
+ throw new Error("[Noxus DI] No controller registrar set. Call InjectorExplorer.setControllerRegistrar() before processing.");
473
+ }
474
+ _InjectorExplorer.controllerRegistrar(
475
+ reg.implementation,
476
+ reg.pathPrefix ?? "",
477
+ routeGuards,
478
+ routeMiddlewares
479
+ );
504
480
  } else if (reg.lifetime !== "singleton") {
505
481
  Logger.log(`Registered ${reg.implementation.name} as ${reg.lifetime}`);
506
482
  }
@@ -511,24 +487,147 @@ var init_injector_explorer = __esm({
511
487
  if (reg.lifetime === "singleton") {
512
488
  RootInjector.resolve(reg.key);
513
489
  }
514
- if (reg.isController) {
515
- const { Router: Router2 } = (init_router(), __toCommonJS(router_exports));
516
- const router = RootInjector.resolve(Router2);
517
- router.registerController(reg.implementation);
490
+ if (reg.isController && _InjectorExplorer.controllerRegistrar) {
491
+ _InjectorExplorer.controllerRegistrar(reg.implementation, "", [], []);
518
492
  }
519
493
  }
520
494
  };
521
495
  __name(_InjectorExplorer, "InjectorExplorer");
522
- _InjectorExplorer.pending = [];
523
- _InjectorExplorer.processed = false;
524
- _InjectorExplorer.accumulating = false;
496
+ __publicField(_InjectorExplorer, "pending", []);
497
+ __publicField(_InjectorExplorer, "processed", false);
498
+ __publicField(_InjectorExplorer, "accumulating", false);
499
+ __publicField(_InjectorExplorer, "loadingLock", Promise.resolve());
500
+ __publicField(_InjectorExplorer, "controllerRegistrar", null);
525
501
  InjectorExplorer = _InjectorExplorer;
526
502
  }
527
503
  });
528
504
 
505
+ // src/DI/app-injector.ts
506
+ function keyOf(k) {
507
+ return k;
508
+ }
509
+ function resetRootInjector() {
510
+ RootInjector.bindings.clear();
511
+ RootInjector.singletons.clear();
512
+ RootInjector.scoped.clear();
513
+ const { InjectorExplorer: InjectorExplorer2 } = (init_injector_explorer(), __toCommonJS(injector_explorer_exports));
514
+ InjectorExplorer2.reset();
515
+ }
516
+ function inject(t) {
517
+ return RootInjector.resolve(t);
518
+ }
519
+ var _AppInjector, AppInjector, RootInjector;
520
+ var init_app_injector = __esm({
521
+ "src/DI/app-injector.ts"() {
522
+ "use strict";
523
+ init_forward_ref();
524
+ init_token();
525
+ __name(keyOf, "keyOf");
526
+ _AppInjector = class _AppInjector {
527
+ constructor(name = null) {
528
+ this.name = name;
529
+ __publicField(this, "bindings", /* @__PURE__ */ new Map());
530
+ __publicField(this, "singletons", /* @__PURE__ */ new Map());
531
+ __publicField(this, "scoped", /* @__PURE__ */ new Map());
532
+ }
533
+ /**
534
+ * Creates a child scope for per-request lifetime resolution.
535
+ */
536
+ createScope() {
537
+ const scope = new _AppInjector();
538
+ scope.bindings = this.bindings;
539
+ scope.singletons = this.singletons;
540
+ return scope;
541
+ }
542
+ /**
543
+ * Registers a binding explicitly.
544
+ */
545
+ register(key, implementation, lifetime, deps = []) {
546
+ const k = keyOf(key);
547
+ if (!this.bindings.has(k)) {
548
+ this.bindings.set(k, { lifetime, implementation, deps });
549
+ }
550
+ }
551
+ /**
552
+ * Resolves a dependency by token or class reference.
553
+ */
554
+ resolve(target) {
555
+ if (target instanceof ForwardReference) {
556
+ return this._resolveForwardRef(target);
557
+ }
558
+ const k = keyOf(target);
559
+ if (this.singletons.has(k)) {
560
+ return this.singletons.get(k);
561
+ }
562
+ const binding = this.bindings.get(k);
563
+ if (!binding) {
564
+ const name = target instanceof Token ? target.description : target.name ?? "unknown";
565
+ throw new Error(
566
+ `[Noxus DI] No binding found for "${name}".
567
+ Did you forget to declare it in @Injectable({ deps }) or in bootstrapApplication({ singletons })?`
568
+ );
569
+ }
570
+ switch (binding.lifetime) {
571
+ case "transient":
572
+ return this._instantiate(binding);
573
+ case "scope": {
574
+ if (this.scoped.has(k)) return this.scoped.get(k);
575
+ const inst = this._instantiate(binding);
576
+ this.scoped.set(k, inst);
577
+ return inst;
578
+ }
579
+ case "singleton": {
580
+ if (this.singletons.has(k)) return this.singletons.get(k);
581
+ const inst = this._instantiate(binding);
582
+ this.singletons.set(k, inst);
583
+ if (binding.instance === void 0) {
584
+ binding.instance = inst;
585
+ }
586
+ return inst;
587
+ }
588
+ }
589
+ }
590
+ // -------------------------------------------------------------------------
591
+ _resolveForwardRef(ref) {
592
+ let resolved;
593
+ return new Proxy({}, {
594
+ get: /* @__PURE__ */ __name((_obj, prop, receiver) => {
595
+ resolved ?? (resolved = this.resolve(ref.forwardRefFn()));
596
+ const value = Reflect.get(resolved, prop, receiver);
597
+ return typeof value === "function" ? value.bind(resolved) : value;
598
+ }, "get"),
599
+ set: /* @__PURE__ */ __name((_obj, prop, value, receiver) => {
600
+ resolved ?? (resolved = this.resolve(ref.forwardRefFn()));
601
+ return Reflect.set(resolved, prop, value, receiver);
602
+ }, "set"),
603
+ getPrototypeOf: /* @__PURE__ */ __name(() => {
604
+ resolved ?? (resolved = this.resolve(ref.forwardRefFn()));
605
+ return Object.getPrototypeOf(resolved);
606
+ }, "getPrototypeOf")
607
+ });
608
+ }
609
+ _instantiate(binding) {
610
+ const resolvedDeps = binding.deps.map((dep) => this.resolve(dep));
611
+ return new binding.implementation(...resolvedDeps);
612
+ }
613
+ };
614
+ __name(_AppInjector, "AppInjector");
615
+ AppInjector = _AppInjector;
616
+ RootInjector = new AppInjector("root");
617
+ __name(resetRootInjector, "resetRootInjector");
618
+ __name(inject, "inject");
619
+ }
620
+ });
621
+
622
+ // src/main.ts
623
+ init_app_injector();
624
+ init_token();
625
+
529
626
  // src/decorators/controller.decorator.ts
627
+ init_injector_explorer();
628
+ var controllerMetaMap = /* @__PURE__ */ new WeakMap();
530
629
  function Controller(options = {}) {
531
- return (target) => {
630
+ return (target, _context) => {
532
631
  const meta = {
533
632
  deps: options.deps ?? []
534
633
  };
@@ -542,27 +641,18 @@ function Controller(options = {}) {
542
641
  });
543
642
  };
544
643
  }
644
+ __name(Controller, "Controller");
545
645
  function getControllerMetadata(target) {
546
646
  return controllerMetaMap.get(target);
547
647
  }
548
- var controllerMetaMap;
549
- var init_controller_decorator = __esm({
550
- "src/decorators/controller.decorator.ts"() {
551
- "use strict";
552
- init_injector_explorer();
553
- controllerMetaMap = /* @__PURE__ */ new WeakMap();
554
- __name(Controller, "Controller");
555
- __name(getControllerMetadata, "getControllerMetadata");
556
- }
557
- });
648
+ __name(getControllerMetadata, "getControllerMetadata");
558
649
 
559
650
  // src/decorators/injectable.decorator.ts
651
+ init_injector_explorer();
652
+ init_token();
560
653
  function Injectable(options = {}) {
561
654
  const { lifetime = "scope", deps = [] } = options;
562
- return (target) => {
563
- if (typeof target !== "function" || !target.prototype) {
564
- throw new Error(`@Injectable can only be applied to classes, not ${typeof target}`);
565
- }
655
+ return (target, _context) => {
566
656
  const key = target;
567
657
  InjectorExplorer.enqueue({
568
658
  key,
@@ -573,428 +663,454 @@ function Injectable(options = {}) {
573
663
  });
574
664
  };
575
665
  }
576
- var init_injectable_decorator = __esm({
577
- "src/decorators/injectable.decorator.ts"() {
578
- "use strict";
579
- init_injector_explorer();
580
- init_token();
581
- __name(Injectable, "Injectable");
582
- }
583
- });
666
+ __name(Injectable, "Injectable");
584
667
 
585
668
  // src/decorators/method.decorator.ts
669
+ var ATOMIC_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
586
670
  function isAtomicHttpMethod(m) {
587
671
  return typeof m === "string" && ATOMIC_METHODS.has(m);
588
672
  }
673
+ __name(isAtomicHttpMethod, "isAtomicHttpMethod");
674
+ var methodMeta = /* @__PURE__ */ new WeakMap();
589
675
  function createRouteDecorator(verb) {
590
676
  return (path2, options = {}) => {
591
- return (target, propertyKey) => {
592
- const ctor = target.constructor;
593
- const existing = routeMetaMap.get(ctor) ?? [];
594
- existing.push({
677
+ return (value, context) => {
678
+ methodMeta.set(value, {
595
679
  method: verb,
596
680
  path: (path2 ?? "").trim().replace(/^\/|\/$/g, ""),
597
- handler: propertyKey,
681
+ handler: context.name,
598
682
  guards: options.guards ?? [],
599
683
  middlewares: options.middlewares ?? []
600
684
  });
601
- routeMetaMap.set(ctor, existing);
602
685
  };
603
686
  };
604
687
  }
688
+ __name(createRouteDecorator, "createRouteDecorator");
605
689
  function getRouteMetadata(target) {
606
- return routeMetaMap.get(target) ?? [];
607
- }
608
- var ATOMIC_METHODS, routeMetaMap, Get, Post, Put, Patch, Delete;
609
- var init_method_decorator = __esm({
610
- "src/decorators/method.decorator.ts"() {
611
- "use strict";
612
- ATOMIC_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
613
- __name(isAtomicHttpMethod, "isAtomicHttpMethod");
614
- routeMetaMap = /* @__PURE__ */ new WeakMap();
615
- __name(createRouteDecorator, "createRouteDecorator");
616
- __name(getRouteMetadata, "getRouteMetadata");
617
- Get = createRouteDecorator("GET");
618
- Post = createRouteDecorator("POST");
619
- Put = createRouteDecorator("PUT");
620
- Patch = createRouteDecorator("PATCH");
621
- Delete = createRouteDecorator("DELETE");
690
+ const routes = [];
691
+ const proto = target.prototype;
692
+ for (const key of Object.getOwnPropertyNames(proto)) {
693
+ const fn = proto[key];
694
+ if (typeof fn === "function" && methodMeta.has(fn)) {
695
+ const meta = methodMeta.get(fn);
696
+ if (meta) {
697
+ routes.push(meta);
698
+ }
699
+ }
622
700
  }
623
- });
701
+ return routes;
702
+ }
703
+ __name(getRouteMetadata, "getRouteMetadata");
704
+ var Get = createRouteDecorator("GET");
705
+ var Post = createRouteDecorator("POST");
706
+ var Put = createRouteDecorator("PUT");
707
+ var Patch = createRouteDecorator("PATCH");
708
+ var Delete = createRouteDecorator("DELETE");
709
+
710
+ // src/internal/router.ts
711
+ init_injector_explorer();
712
+ init_logger();
624
713
 
625
714
  // src/utils/radix-tree.ts
626
- var _RadixNode, RadixNode, _RadixTree, RadixTree;
627
- var init_radix_tree = __esm({
628
- "src/utils/radix-tree.ts"() {
629
- "use strict";
630
- _RadixNode = class _RadixNode {
631
- /**
632
- * Creates a new RadixNode.
633
- * @param segment - The segment of the path this node represents.
634
- */
635
- constructor(segment) {
636
- this.children = [];
637
- this.segment = segment;
638
- this.isParam = segment.startsWith(":");
639
- if (this.isParam) {
640
- this.paramName = segment.slice(1);
641
- }
642
- }
643
- /**
644
- * Matches a child node against a given segment.
645
- * This method checks if the segment matches any of the children nodes.
646
- * @param segment - The segment to match against the children of this node.
647
- * @returns A child node that matches the segment, or undefined if no match is found.
648
- */
649
- matchChild(segment) {
650
- for (const child of this.children) {
651
- if (child.isParam || segment.startsWith(child.segment))
652
- return child;
653
- }
654
- return void 0;
655
- }
656
- /**
657
- * Finds a child node that matches the segment exactly.
658
- * This method checks if there is a child node that matches the segment exactly.
659
- * @param segment - The segment to find an exact match for among the children of this node.
660
- * @returns A child node that matches the segment exactly, or undefined if no match is found.
661
- */
662
- findExactChild(segment) {
663
- return this.children.find((c) => c.segment === segment);
664
- }
665
- /**
666
- * Adds a child node to this node's children.
667
- * This method adds a new child node to the list of children for this node.
668
- * @param node - The child node to add to this node's children.
669
- */
670
- addChild(node) {
671
- this.children.push(node);
672
- }
673
- };
674
- __name(_RadixNode, "RadixNode");
675
- RadixNode = _RadixNode;
676
- _RadixTree = class _RadixTree {
677
- constructor() {
678
- this.root = new RadixNode("");
715
+ var _RadixNode = class _RadixNode {
716
+ /**
717
+ * Creates a new RadixNode.
718
+ * @param segment - The segment of the path this node represents.
719
+ */
720
+ constructor(segment) {
721
+ __publicField(this, "segment");
722
+ __publicField(this, "children", []);
723
+ __publicField(this, "value");
724
+ __publicField(this, "isParam");
725
+ __publicField(this, "paramName");
726
+ this.segment = segment;
727
+ this.isParam = segment.startsWith(":");
728
+ if (this.isParam) {
729
+ this.paramName = segment.slice(1);
730
+ }
731
+ }
732
+ /**
733
+ * Matches a child node against a given segment.
734
+ * This method checks if the segment matches any of the children nodes.
735
+ * @param segment - The segment to match against the children of this node.
736
+ * @returns A child node that matches the segment, or undefined if no match is found.
737
+ */
738
+ matchChild(segment) {
739
+ for (const child of this.children) {
740
+ if (child.isParam || segment.startsWith(child.segment))
741
+ return child;
742
+ }
743
+ return void 0;
744
+ }
745
+ /**
746
+ * Finds a child node that matches the segment exactly.
747
+ * This method checks if there is a child node that matches the segment exactly.
748
+ * @param segment - The segment to find an exact match for among the children of this node.
749
+ * @returns A child node that matches the segment exactly, or undefined if no match is found.
750
+ */
751
+ findExactChild(segment) {
752
+ return this.children.find((c) => c.segment === segment);
753
+ }
754
+ /**
755
+ * Adds a child node to this node's children.
756
+ * This method adds a new child node to the list of children for this node.
757
+ * @param node - The child node to add to this node's children.
758
+ */
759
+ addChild(node) {
760
+ this.children.push(node);
761
+ }
762
+ };
763
+ __name(_RadixNode, "RadixNode");
764
+ var RadixNode = _RadixNode;
765
+ var _RadixTree = class _RadixTree {
766
+ constructor() {
767
+ __publicField(this, "root", new RadixNode(""));
768
+ }
769
+ /**
770
+ * Inserts a path and its associated value into the Radix Tree.
771
+ * This method normalizes the path and inserts it into the tree, associating it with
772
+ * @param path - The path to insert into the tree.
773
+ * @param value - The value to associate with the path.
774
+ */
775
+ insert(path2, value) {
776
+ const segments = this.normalize(path2);
777
+ this.insertRecursive(this.root, segments, value);
778
+ }
779
+ /**
780
+ * Recursively inserts a path into the Radix Tree.
781
+ * This method traverses the tree and inserts the segments of the path, creating new nodes
782
+ * @param node - The node to start inserting from.
783
+ * @param segments - The segments of the path to insert.
784
+ * @param value - The value to associate with the path.
785
+ */
786
+ insertRecursive(node, segments, value) {
787
+ if (segments.length === 0) {
788
+ node.value = value;
789
+ return;
790
+ }
791
+ const segment = segments[0] ?? "";
792
+ let child = node.children.find(
793
+ (c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment)
794
+ );
795
+ if (!child) {
796
+ child = new RadixNode(segment);
797
+ node.addChild(child);
798
+ }
799
+ this.insertRecursive(child, segments.slice(1), value);
800
+ }
801
+ /**
802
+ * Searches for a path in the Radix Tree.
803
+ * This method normalizes the path and searches for it in the tree, returning the node
804
+ * @param path - The path to search for in the Radix Tree.
805
+ * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
806
+ */
807
+ search(path2) {
808
+ const segments = this.normalize(path2);
809
+ return this.searchRecursive(this.root, segments, {});
810
+ }
811
+ collectValues(node, values = []) {
812
+ if (!node) {
813
+ node = this.root;
814
+ }
815
+ if (node.value !== void 0) {
816
+ values.push(node.value);
817
+ }
818
+ for (const child of node.children) {
819
+ this.collectValues(child, values);
820
+ }
821
+ return values;
822
+ }
823
+ /**
824
+ * Recursively searches for a path in the Radix Tree.
825
+ * This method traverses the tree and searches for the segments of the path, collecting parameters
826
+ * @param node - The node to start searching from.
827
+ * @param segments - The segments of the path to search for.
828
+ * @param params - The parameters collected during the search.
829
+ * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
830
+ */
831
+ searchRecursive(node, segments, params) {
832
+ if (segments.length === 0) {
833
+ if (node.value !== void 0) {
834
+ return {
835
+ node,
836
+ params
837
+ };
679
838
  }
680
- /**
681
- * Inserts a path and its associated value into the Radix Tree.
682
- * This method normalizes the path and inserts it into the tree, associating it with
683
- * @param path - The path to insert into the tree.
684
- * @param value - The value to associate with the path.
685
- */
686
- insert(path2, value) {
687
- const segments = this.normalize(path2);
688
- this.insertRecursive(this.root, segments, value);
839
+ return void 0;
840
+ }
841
+ const [segment, ...rest] = segments;
842
+ const staticChildren = [];
843
+ const paramChildren = [];
844
+ for (const child of node.children) {
845
+ if (child.isParam) {
846
+ paramChildren.push(child);
847
+ } else if (segment === child.segment) {
848
+ staticChildren.push(child);
689
849
  }
690
- /**
691
- * Recursively inserts a path into the Radix Tree.
692
- * This method traverses the tree and inserts the segments of the path, creating new nodes
693
- * @param node - The node to start inserting from.
694
- * @param segments - The segments of the path to insert.
695
- * @param value - The value to associate with the path.
696
- */
697
- insertRecursive(node, segments, value) {
698
- if (segments.length === 0) {
699
- node.value = value;
700
- return;
701
- }
702
- const segment = segments[0] ?? "";
703
- let child = node.children.find(
704
- (c) => c.isParam === segment.startsWith(":") && (c.isParam || c.segment === segment)
705
- );
706
- if (!child) {
707
- child = new RadixNode(segment);
708
- node.addChild(child);
850
+ }
851
+ for (const child of staticChildren) {
852
+ if (rest.length === 0) {
853
+ if (child.value !== void 0 || child.children.length > 0) {
854
+ return { node: child, params };
709
855
  }
710
- this.insertRecursive(child, segments.slice(1), value);
711
856
  }
712
- /**
713
- * Searches for a path in the Radix Tree.
714
- * This method normalizes the path and searches for it in the tree, returning the node
715
- * @param path - The path to search for in the Radix Tree.
716
- * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
717
- */
718
- search(path2) {
719
- const segments = this.normalize(path2);
720
- return this.searchRecursive(this.root, segments, {});
721
- }
722
- /**
723
- * Recursively searches for a path in the Radix Tree.
724
- * This method traverses the tree and searches for the segments of the path, collecting parameters
725
- * @param node - The node to start searching from.
726
- * @param segments - The segments of the path to search for.
727
- * @param params - The parameters collected during the search.
728
- * @returns An ISearchResult containing the node and parameters if a match is found, otherwise undefined.
729
- */
730
- searchRecursive(node, segments, params) {
731
- if (segments.length === 0) {
732
- if (node.value !== void 0) {
733
- return {
734
- node,
735
- params
736
- };
737
- }
738
- return void 0;
739
- }
740
- const [segment, ...rest] = segments;
741
- for (const child of node.children) {
742
- if (child.isParam) {
743
- const paramName = child.paramName;
744
- const childParams = {
745
- ...params,
746
- [paramName]: segment ?? ""
747
- };
748
- if (rest.length === 0) {
749
- return {
750
- node: child,
751
- params: childParams
752
- };
753
- }
754
- const result = this.searchRecursive(child, rest, childParams);
755
- if (result)
756
- return result;
757
- } else if (segment === child.segment) {
758
- if (rest.length === 0) {
759
- return {
760
- node: child,
761
- params
762
- };
763
- }
764
- const result = this.searchRecursive(child, rest, params);
765
- if (result)
766
- return result;
767
- }
857
+ const result = this.searchRecursive(child, rest, params);
858
+ if (result) return result;
859
+ }
860
+ for (const child of paramChildren) {
861
+ const paramName = child.paramName;
862
+ const childParams = {
863
+ ...params,
864
+ [paramName]: segment ?? ""
865
+ };
866
+ if (rest.length === 0) {
867
+ if (child.value !== void 0 || child.children.length > 0) {
868
+ return { node: child, params: childParams };
768
869
  }
769
- return void 0;
770
- }
771
- /**
772
- * Normalizes a path into an array of segments.
773
- * This method removes leading and trailing slashes, splits the path by slashes, and
774
- * @param path - The path to normalize.
775
- * @returns An array of normalized path segments.
776
- */
777
- normalize(path2) {
778
- const segments = path2.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
779
- return ["", ...segments];
780
870
  }
781
- };
782
- __name(_RadixTree, "RadixTree");
783
- RadixTree = _RadixTree;
871
+ const result = this.searchRecursive(child, rest, childParams);
872
+ if (result) return result;
873
+ }
874
+ return void 0;
784
875
  }
785
- });
876
+ /**
877
+ * Normalizes a path into an array of segments.
878
+ * This method removes leading and trailing slashes, splits the path by slashes, and
879
+ * @param path - The path to normalize.
880
+ * @returns An array of normalized path segments.
881
+ */
882
+ normalize(path2) {
883
+ const segments = path2.replace(/^\/+|\/+$/g, "").split("/").filter(Boolean);
884
+ return ["", ...segments];
885
+ }
886
+ };
887
+ __name(_RadixTree, "RadixTree");
888
+ var RadixTree = _RadixTree;
786
889
 
787
890
  // src/internal/exceptions.ts
788
- 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;
789
- var init_exceptions = __esm({
790
- "src/internal/exceptions.ts"() {
791
- "use strict";
792
- _ResponseException = class _ResponseException extends Error {
793
- constructor(statusOrMessage, message) {
794
- let statusCode;
795
- if (typeof statusOrMessage === "number") {
796
- statusCode = statusOrMessage;
797
- } else if (typeof statusOrMessage === "string") {
798
- message = statusOrMessage;
799
- }
800
- super(message ?? "");
801
- this.status = 0;
802
- if (statusCode !== void 0) {
803
- this.status = statusCode;
804
- }
805
- this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
806
- }
807
- };
808
- __name(_ResponseException, "ResponseException");
809
- ResponseException = _ResponseException;
810
- _BadRequestException = class _BadRequestException extends ResponseException {
811
- constructor() {
812
- super(...arguments);
813
- this.status = 400;
814
- }
815
- };
816
- __name(_BadRequestException, "BadRequestException");
817
- BadRequestException = _BadRequestException;
818
- _UnauthorizedException = class _UnauthorizedException extends ResponseException {
819
- constructor() {
820
- super(...arguments);
821
- this.status = 401;
822
- }
823
- };
824
- __name(_UnauthorizedException, "UnauthorizedException");
825
- UnauthorizedException = _UnauthorizedException;
826
- _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
827
- constructor() {
828
- super(...arguments);
829
- this.status = 402;
830
- }
831
- };
832
- __name(_PaymentRequiredException, "PaymentRequiredException");
833
- PaymentRequiredException = _PaymentRequiredException;
834
- _ForbiddenException = class _ForbiddenException extends ResponseException {
835
- constructor() {
836
- super(...arguments);
837
- this.status = 403;
838
- }
839
- };
840
- __name(_ForbiddenException, "ForbiddenException");
841
- ForbiddenException = _ForbiddenException;
842
- _NotFoundException = class _NotFoundException extends ResponseException {
843
- constructor() {
844
- super(...arguments);
845
- this.status = 404;
846
- }
847
- };
848
- __name(_NotFoundException, "NotFoundException");
849
- NotFoundException = _NotFoundException;
850
- _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
851
- constructor() {
852
- super(...arguments);
853
- this.status = 405;
854
- }
855
- };
856
- __name(_MethodNotAllowedException, "MethodNotAllowedException");
857
- MethodNotAllowedException = _MethodNotAllowedException;
858
- _NotAcceptableException = class _NotAcceptableException extends ResponseException {
859
- constructor() {
860
- super(...arguments);
861
- this.status = 406;
862
- }
863
- };
864
- __name(_NotAcceptableException, "NotAcceptableException");
865
- NotAcceptableException = _NotAcceptableException;
866
- _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
867
- constructor() {
868
- super(...arguments);
869
- this.status = 408;
870
- }
871
- };
872
- __name(_RequestTimeoutException, "RequestTimeoutException");
873
- RequestTimeoutException = _RequestTimeoutException;
874
- _ConflictException = class _ConflictException extends ResponseException {
875
- constructor() {
876
- super(...arguments);
877
- this.status = 409;
878
- }
879
- };
880
- __name(_ConflictException, "ConflictException");
881
- ConflictException = _ConflictException;
882
- _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
883
- constructor() {
884
- super(...arguments);
885
- this.status = 426;
886
- }
887
- };
888
- __name(_UpgradeRequiredException, "UpgradeRequiredException");
889
- UpgradeRequiredException = _UpgradeRequiredException;
890
- _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
891
- constructor() {
892
- super(...arguments);
893
- this.status = 429;
894
- }
895
- };
896
- __name(_TooManyRequestsException, "TooManyRequestsException");
897
- TooManyRequestsException = _TooManyRequestsException;
898
- _InternalServerException = class _InternalServerException extends ResponseException {
899
- constructor() {
900
- super(...arguments);
901
- this.status = 500;
902
- }
903
- };
904
- __name(_InternalServerException, "InternalServerException");
905
- InternalServerException = _InternalServerException;
906
- _NotImplementedException = class _NotImplementedException extends ResponseException {
907
- constructor() {
908
- super(...arguments);
909
- this.status = 501;
910
- }
911
- };
912
- __name(_NotImplementedException, "NotImplementedException");
913
- NotImplementedException = _NotImplementedException;
914
- _BadGatewayException = class _BadGatewayException extends ResponseException {
915
- constructor() {
916
- super(...arguments);
917
- this.status = 502;
918
- }
919
- };
920
- __name(_BadGatewayException, "BadGatewayException");
921
- BadGatewayException = _BadGatewayException;
922
- _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
923
- constructor() {
924
- super(...arguments);
925
- this.status = 503;
926
- }
927
- };
928
- __name(_ServiceUnavailableException, "ServiceUnavailableException");
929
- ServiceUnavailableException = _ServiceUnavailableException;
930
- _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
931
- constructor() {
932
- super(...arguments);
933
- this.status = 504;
934
- }
935
- };
936
- __name(_GatewayTimeoutException, "GatewayTimeoutException");
937
- GatewayTimeoutException = _GatewayTimeoutException;
938
- _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
939
- constructor() {
940
- super(...arguments);
941
- this.status = 505;
942
- }
943
- };
944
- __name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
945
- HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
946
- _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
947
- constructor() {
948
- super(...arguments);
949
- this.status = 506;
950
- }
951
- };
952
- __name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
953
- VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
954
- _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
955
- constructor() {
956
- super(...arguments);
957
- this.status = 507;
958
- }
959
- };
960
- __name(_InsufficientStorageException, "InsufficientStorageException");
961
- InsufficientStorageException = _InsufficientStorageException;
962
- _LoopDetectedException = class _LoopDetectedException extends ResponseException {
963
- constructor() {
964
- super(...arguments);
965
- this.status = 508;
966
- }
967
- };
968
- __name(_LoopDetectedException, "LoopDetectedException");
969
- LoopDetectedException = _LoopDetectedException;
970
- _NotExtendedException = class _NotExtendedException extends ResponseException {
971
- constructor() {
972
- super(...arguments);
973
- this.status = 510;
974
- }
975
- };
976
- __name(_NotExtendedException, "NotExtendedException");
977
- NotExtendedException = _NotExtendedException;
978
- _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
979
- constructor() {
980
- super(...arguments);
981
- this.status = 511;
982
- }
983
- };
984
- __name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
985
- NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
986
- _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
987
- constructor() {
988
- super(...arguments);
989
- this.status = 599;
990
- }
991
- };
992
- __name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
993
- NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
891
+ var _ResponseException = class _ResponseException extends Error {
892
+ constructor(statusOrMessage, message) {
893
+ let statusCode;
894
+ if (typeof statusOrMessage === "number") {
895
+ statusCode = statusOrMessage;
896
+ } else if (typeof statusOrMessage === "string") {
897
+ message = statusOrMessage;
898
+ }
899
+ super(message ?? "");
900
+ __publicField(this, "status", 0);
901
+ if (statusCode !== void 0) {
902
+ this.status = statusCode;
903
+ }
904
+ this.name = this.constructor.name.replace(/([A-Z])/g, " $1");
994
905
  }
995
- });
906
+ };
907
+ __name(_ResponseException, "ResponseException");
908
+ var ResponseException = _ResponseException;
909
+ var _BadRequestException = class _BadRequestException extends ResponseException {
910
+ constructor() {
911
+ super(...arguments);
912
+ __publicField(this, "status", 400);
913
+ }
914
+ };
915
+ __name(_BadRequestException, "BadRequestException");
916
+ var BadRequestException = _BadRequestException;
917
+ var _UnauthorizedException = class _UnauthorizedException extends ResponseException {
918
+ constructor() {
919
+ super(...arguments);
920
+ __publicField(this, "status", 401);
921
+ }
922
+ };
923
+ __name(_UnauthorizedException, "UnauthorizedException");
924
+ var UnauthorizedException = _UnauthorizedException;
925
+ var _PaymentRequiredException = class _PaymentRequiredException extends ResponseException {
926
+ constructor() {
927
+ super(...arguments);
928
+ __publicField(this, "status", 402);
929
+ }
930
+ };
931
+ __name(_PaymentRequiredException, "PaymentRequiredException");
932
+ var PaymentRequiredException = _PaymentRequiredException;
933
+ var _ForbiddenException = class _ForbiddenException extends ResponseException {
934
+ constructor() {
935
+ super(...arguments);
936
+ __publicField(this, "status", 403);
937
+ }
938
+ };
939
+ __name(_ForbiddenException, "ForbiddenException");
940
+ var ForbiddenException = _ForbiddenException;
941
+ var _NotFoundException = class _NotFoundException extends ResponseException {
942
+ constructor() {
943
+ super(...arguments);
944
+ __publicField(this, "status", 404);
945
+ }
946
+ };
947
+ __name(_NotFoundException, "NotFoundException");
948
+ var NotFoundException = _NotFoundException;
949
+ var _MethodNotAllowedException = class _MethodNotAllowedException extends ResponseException {
950
+ constructor() {
951
+ super(...arguments);
952
+ __publicField(this, "status", 405);
953
+ }
954
+ };
955
+ __name(_MethodNotAllowedException, "MethodNotAllowedException");
956
+ var MethodNotAllowedException = _MethodNotAllowedException;
957
+ var _NotAcceptableException = class _NotAcceptableException extends ResponseException {
958
+ constructor() {
959
+ super(...arguments);
960
+ __publicField(this, "status", 406);
961
+ }
962
+ };
963
+ __name(_NotAcceptableException, "NotAcceptableException");
964
+ var NotAcceptableException = _NotAcceptableException;
965
+ var _RequestTimeoutException = class _RequestTimeoutException extends ResponseException {
966
+ constructor() {
967
+ super(...arguments);
968
+ __publicField(this, "status", 408);
969
+ }
970
+ };
971
+ __name(_RequestTimeoutException, "RequestTimeoutException");
972
+ var RequestTimeoutException = _RequestTimeoutException;
973
+ var _ConflictException = class _ConflictException extends ResponseException {
974
+ constructor() {
975
+ super(...arguments);
976
+ __publicField(this, "status", 409);
977
+ }
978
+ };
979
+ __name(_ConflictException, "ConflictException");
980
+ var ConflictException = _ConflictException;
981
+ var _UpgradeRequiredException = class _UpgradeRequiredException extends ResponseException {
982
+ constructor() {
983
+ super(...arguments);
984
+ __publicField(this, "status", 426);
985
+ }
986
+ };
987
+ __name(_UpgradeRequiredException, "UpgradeRequiredException");
988
+ var UpgradeRequiredException = _UpgradeRequiredException;
989
+ var _TooManyRequestsException = class _TooManyRequestsException extends ResponseException {
990
+ constructor() {
991
+ super(...arguments);
992
+ __publicField(this, "status", 429);
993
+ }
994
+ };
995
+ __name(_TooManyRequestsException, "TooManyRequestsException");
996
+ var TooManyRequestsException = _TooManyRequestsException;
997
+ var _InternalServerException = class _InternalServerException extends ResponseException {
998
+ constructor() {
999
+ super(...arguments);
1000
+ __publicField(this, "status", 500);
1001
+ }
1002
+ };
1003
+ __name(_InternalServerException, "InternalServerException");
1004
+ var InternalServerException = _InternalServerException;
1005
+ var _NotImplementedException = class _NotImplementedException extends ResponseException {
1006
+ constructor() {
1007
+ super(...arguments);
1008
+ __publicField(this, "status", 501);
1009
+ }
1010
+ };
1011
+ __name(_NotImplementedException, "NotImplementedException");
1012
+ var NotImplementedException = _NotImplementedException;
1013
+ var _BadGatewayException = class _BadGatewayException extends ResponseException {
1014
+ constructor() {
1015
+ super(...arguments);
1016
+ __publicField(this, "status", 502);
1017
+ }
1018
+ };
1019
+ __name(_BadGatewayException, "BadGatewayException");
1020
+ var BadGatewayException = _BadGatewayException;
1021
+ var _ServiceUnavailableException = class _ServiceUnavailableException extends ResponseException {
1022
+ constructor() {
1023
+ super(...arguments);
1024
+ __publicField(this, "status", 503);
1025
+ }
1026
+ };
1027
+ __name(_ServiceUnavailableException, "ServiceUnavailableException");
1028
+ var ServiceUnavailableException = _ServiceUnavailableException;
1029
+ var _GatewayTimeoutException = class _GatewayTimeoutException extends ResponseException {
1030
+ constructor() {
1031
+ super(...arguments);
1032
+ __publicField(this, "status", 504);
1033
+ }
1034
+ };
1035
+ __name(_GatewayTimeoutException, "GatewayTimeoutException");
1036
+ var GatewayTimeoutException = _GatewayTimeoutException;
1037
+ var _HttpVersionNotSupportedException = class _HttpVersionNotSupportedException extends ResponseException {
1038
+ constructor() {
1039
+ super(...arguments);
1040
+ __publicField(this, "status", 505);
1041
+ }
1042
+ };
1043
+ __name(_HttpVersionNotSupportedException, "HttpVersionNotSupportedException");
1044
+ var HttpVersionNotSupportedException = _HttpVersionNotSupportedException;
1045
+ var _VariantAlsoNegotiatesException = class _VariantAlsoNegotiatesException extends ResponseException {
1046
+ constructor() {
1047
+ super(...arguments);
1048
+ __publicField(this, "status", 506);
1049
+ }
1050
+ };
1051
+ __name(_VariantAlsoNegotiatesException, "VariantAlsoNegotiatesException");
1052
+ var VariantAlsoNegotiatesException = _VariantAlsoNegotiatesException;
1053
+ var _InsufficientStorageException = class _InsufficientStorageException extends ResponseException {
1054
+ constructor() {
1055
+ super(...arguments);
1056
+ __publicField(this, "status", 507);
1057
+ }
1058
+ };
1059
+ __name(_InsufficientStorageException, "InsufficientStorageException");
1060
+ var InsufficientStorageException = _InsufficientStorageException;
1061
+ var _LoopDetectedException = class _LoopDetectedException extends ResponseException {
1062
+ constructor() {
1063
+ super(...arguments);
1064
+ __publicField(this, "status", 508);
1065
+ }
1066
+ };
1067
+ __name(_LoopDetectedException, "LoopDetectedException");
1068
+ var LoopDetectedException = _LoopDetectedException;
1069
+ var _NotExtendedException = class _NotExtendedException extends ResponseException {
1070
+ constructor() {
1071
+ super(...arguments);
1072
+ __publicField(this, "status", 510);
1073
+ }
1074
+ };
1075
+ __name(_NotExtendedException, "NotExtendedException");
1076
+ var NotExtendedException = _NotExtendedException;
1077
+ var _NetworkAuthenticationRequiredException = class _NetworkAuthenticationRequiredException extends ResponseException {
1078
+ constructor() {
1079
+ super(...arguments);
1080
+ __publicField(this, "status", 511);
1081
+ }
1082
+ };
1083
+ __name(_NetworkAuthenticationRequiredException, "NetworkAuthenticationRequiredException");
1084
+ var NetworkAuthenticationRequiredException = _NetworkAuthenticationRequiredException;
1085
+ var _NetworkConnectTimeoutException = class _NetworkConnectTimeoutException extends ResponseException {
1086
+ constructor() {
1087
+ super(...arguments);
1088
+ __publicField(this, "status", 599);
1089
+ }
1090
+ };
1091
+ __name(_NetworkConnectTimeoutException, "NetworkConnectTimeoutException");
1092
+ var NetworkConnectTimeoutException = _NetworkConnectTimeoutException;
996
1093
 
997
1094
  // src/internal/request.ts
1095
+ init_app_injector();
1096
+ var _Request = class _Request {
1097
+ constructor(event, senderId, id, method, path2, body, query) {
1098
+ this.event = event;
1099
+ this.senderId = senderId;
1100
+ this.id = id;
1101
+ this.method = method;
1102
+ this.path = path2;
1103
+ this.body = body;
1104
+ __publicField(this, "context", RootInjector.createScope());
1105
+ __publicField(this, "params", {});
1106
+ __publicField(this, "query");
1107
+ this.path = path2.replace(/^\/|\/$/g, "");
1108
+ this.query = query ?? {};
1109
+ }
1110
+ };
1111
+ __name(_Request, "Request");
1112
+ var Request = _Request;
1113
+ var RENDERER_EVENT_TYPE = "noxus:event";
998
1114
  function createRendererEventMessage(event, payload) {
999
1115
  return {
1000
1116
  type: RENDERER_EVENT_TYPE,
@@ -1002,6 +1118,7 @@ function createRendererEventMessage(event, payload) {
1002
1118
  payload
1003
1119
  };
1004
1120
  }
1121
+ __name(createRendererEventMessage, "createRendererEventMessage");
1005
1122
  function isRendererEventMessage(value) {
1006
1123
  if (value === null || typeof value !== "object") {
1007
1124
  return false;
@@ -1009,306 +1126,279 @@ function isRendererEventMessage(value) {
1009
1126
  const possibleMessage = value;
1010
1127
  return possibleMessage.type === RENDERER_EVENT_TYPE && typeof possibleMessage.event === "string";
1011
1128
  }
1012
- var _Request, Request, RENDERER_EVENT_TYPE;
1013
- var init_request = __esm({
1014
- "src/internal/request.ts"() {
1015
- "use strict";
1016
- init_app_injector();
1017
- _Request = class _Request {
1018
- constructor(event, senderId, id, method, path2, body) {
1019
- this.event = event;
1020
- this.senderId = senderId;
1021
- this.id = id;
1022
- this.method = method;
1023
- this.path = path2;
1024
- this.body = body;
1025
- this.context = RootInjector.createScope();
1026
- this.params = {};
1027
- this.path = path2.replace(/^\/|\/$/g, "");
1028
- }
1029
- };
1030
- __name(_Request, "Request");
1031
- Request = _Request;
1032
- RENDERER_EVENT_TYPE = "noxus:event";
1033
- __name(createRendererEventMessage, "createRendererEventMessage");
1034
- __name(isRendererEventMessage, "isRendererEventMessage");
1035
- }
1036
- });
1129
+ __name(isRendererEventMessage, "isRendererEventMessage");
1037
1130
 
1038
1131
  // src/internal/router.ts
1039
- var router_exports = {};
1040
- __export(router_exports, {
1041
- Router: () => Router
1042
- });
1043
- var Router;
1044
- var init_router = __esm({
1045
- "src/internal/router.ts"() {
1046
- "use strict";
1047
- init_controller_decorator();
1048
- init_injectable_decorator();
1049
- init_method_decorator();
1050
- init_injector_explorer();
1051
- init_logger();
1052
- init_radix_tree();
1053
- init_exceptions();
1054
- init_request();
1055
- Router = class {
1056
- constructor() {
1057
- this.routes = new RadixTree();
1058
- this.rootMiddlewares = [];
1059
- this.lazyRoutes = /* @__PURE__ */ new Map();
1060
- }
1061
- // -------------------------------------------------------------------------
1062
- // Registration
1063
- // -------------------------------------------------------------------------
1064
- registerController(controllerClass, pathPrefix, routeGuards = [], routeMiddlewares = []) {
1065
- const meta = getControllerMetadata(controllerClass);
1066
- if (!meta) {
1067
- throw new Error(`[Noxus] Missing @Controller decorator on ${controllerClass.name}`);
1068
- }
1069
- const routeMeta = getRouteMetadata(controllerClass);
1070
- for (const def of routeMeta) {
1071
- const fullPath = `${pathPrefix}/${def.path}`.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
1072
- const guards = [.../* @__PURE__ */ new Set([...routeGuards, ...def.guards])];
1073
- const middlewares = [.../* @__PURE__ */ new Set([...routeMiddlewares, ...def.middlewares])];
1074
- const routeDef = {
1075
- method: def.method,
1076
- path: fullPath,
1077
- controller: controllerClass,
1078
- handler: def.handler,
1079
- guards,
1080
- middlewares
1081
- };
1082
- this.routes.insert(fullPath + "/" + def.method, routeDef);
1083
- const guardInfo = guards.length ? `<${guards.map((g) => g.name).join("|")}>` : "";
1084
- Logger.log(`Mapped {${def.method} /${fullPath}}${guardInfo} route`);
1085
- }
1086
- const ctrlGuardInfo = routeGuards.length ? `<${routeGuards.map((g) => g.name).join("|")}>` : "";
1087
- Logger.log(`Mapped ${controllerClass.name}${ctrlGuardInfo} controller's routes`);
1088
- return this;
1089
- }
1090
- registerLazyRoute(pathPrefix, load, guards = [], middlewares = []) {
1091
- const normalized = pathPrefix.replace(/^\/+|\/+$/g, "");
1092
- this.lazyRoutes.set(normalized, { load, guards, middlewares, loading: null, loaded: false });
1093
- Logger.log(`Registered lazy route prefix {${normalized}}`);
1094
- return this;
1095
- }
1096
- defineRootMiddleware(middleware) {
1097
- this.rootMiddlewares.push(middleware);
1098
- return this;
1099
- }
1100
- // -------------------------------------------------------------------------
1101
- // Request handling
1102
- // -------------------------------------------------------------------------
1103
- async handle(request) {
1104
- return request.method === "BATCH" ? this.handleBatch(request) : this.handleAtomic(request);
1105
- }
1106
- async handleAtomic(request) {
1107
- Logger.comment(`> ${request.method} /${request.path}`);
1108
- const t0 = performance.now();
1109
- const response = { requestId: request.id, status: 200, body: null };
1110
- let isCritical = false;
1111
- try {
1112
- const routeDef = await this.findRoute(request);
1113
- await this.resolveController(request, response, routeDef);
1114
- if (response.status >= 400) throw new ResponseException(response.status, response.error);
1115
- } catch (error) {
1116
- this.fillErrorResponse(response, error, (c) => {
1117
- isCritical = c;
1118
- });
1119
- } finally {
1120
- this.logResponse(request, response, performance.now() - t0, isCritical);
1121
- return response;
1122
- }
1123
- }
1124
- async handleBatch(request) {
1125
- Logger.comment(`> ${request.method} /${request.path}`);
1126
- const t0 = performance.now();
1127
- const response = {
1128
- requestId: request.id,
1129
- status: 200,
1130
- body: { responses: [] }
1131
- };
1132
- let isCritical = false;
1133
- try {
1134
- const payload = this.normalizeBatchPayload(request.body);
1135
- response.body.responses = await Promise.all(
1136
- payload.requests.map((item, i) => {
1137
- const id = item.requestId ?? `${request.id}:${i}`;
1138
- return this.handleAtomic(new Request(request.event, request.senderId, id, item.method, item.path, item.body));
1139
- })
1140
- );
1141
- } catch (error) {
1142
- this.fillErrorResponse(response, error, (c) => {
1143
- isCritical = c;
1144
- });
1145
- } finally {
1146
- this.logResponse(request, response, performance.now() - t0, isCritical);
1147
- return response;
1148
- }
1149
- }
1150
- // -------------------------------------------------------------------------
1151
- // Route resolution
1152
- // -------------------------------------------------------------------------
1153
- tryFindRoute(request) {
1154
- const matched = this.routes.search(request.path);
1155
- if (!matched?.node || matched.node.children.length === 0) return void 0;
1156
- return matched.node.findExactChild(request.method)?.value;
1157
- }
1158
- async findRoute(request) {
1159
- const direct = this.tryFindRoute(request);
1160
- if (direct) return direct;
1161
- await this.tryLoadLazyRoute(request.path);
1162
- const afterLazy = this.tryFindRoute(request);
1163
- if (afterLazy) return afterLazy;
1164
- throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
1165
- }
1166
- async tryLoadLazyRoute(requestPath) {
1167
- const firstSegment = requestPath.replace(/^\/+/, "").split("/")[0] ?? "";
1168
- for (const [prefix, entry] of this.lazyRoutes) {
1169
- if (entry.loaded) continue;
1170
- const normalized = requestPath.replace(/^\/+/, "");
1171
- if (normalized === prefix || normalized.startsWith(prefix + "/") || firstSegment === prefix) {
1172
- if (!entry.loading) entry.loading = this.loadLazyModule(prefix, entry);
1173
- await entry.loading;
1174
- return;
1175
- }
1176
- }
1177
- }
1178
- async loadLazyModule(prefix, entry) {
1179
- const t0 = performance.now();
1180
- InjectorExplorer.beginAccumulate();
1181
- await entry.load?.();
1182
- entry.loading = null;
1183
- entry.load = null;
1184
- InjectorExplorer.flushAccumulated(entry.guards, entry.middlewares, prefix);
1185
- entry.loaded = true;
1186
- Logger.info(`Lazy-loaded module for prefix {${prefix}} in ${Math.round(performance.now() - t0)}ms`);
1187
- }
1188
- // -------------------------------------------------------------------------
1189
- // Pipeline
1190
- // -------------------------------------------------------------------------
1191
- async resolveController(request, response, routeDef) {
1192
- const instance = request.context.resolve(routeDef.controller);
1193
- Object.assign(request.params, this.extractParams(request.path, routeDef.path));
1194
- await this.runPipeline(request, response, routeDef, instance);
1195
- }
1196
- async runPipeline(request, response, routeDef, controllerInstance) {
1197
- const middlewares = [.../* @__PURE__ */ new Set([...this.rootMiddlewares, ...routeDef.middlewares])];
1198
- const mwMax = middlewares.length - 1;
1199
- const guardMax = mwMax + routeDef.guards.length;
1200
- let index = -1;
1201
- const dispatch = /* @__PURE__ */ __name(async (i) => {
1202
- if (i <= index) throw new Error("next() called multiple times");
1203
- index = i;
1204
- if (i <= mwMax) {
1205
- await this.runMiddleware(request, response, dispatch.bind(null, i + 1), middlewares[i]);
1206
- if (response.status >= 400) throw new ResponseException(response.status, response.error);
1207
- return;
1208
- }
1209
- if (i <= guardMax) {
1210
- await this.runGuard(request, routeDef.guards[i - middlewares.length]);
1211
- await dispatch(i + 1);
1212
- return;
1213
- }
1214
- const action = controllerInstance[routeDef.handler];
1215
- response.body = await action.call(controllerInstance, request, response);
1216
- if (response.body === void 0) response.body = {};
1217
- }, "dispatch");
1218
- await dispatch(0);
1219
- }
1220
- async runMiddleware(request, response, next, middleware) {
1221
- await middleware(request, response, next);
1222
- }
1223
- async runGuard(request, guard) {
1224
- if (!await guard(request)) {
1225
- throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
1226
- }
1227
- }
1228
- // -------------------------------------------------------------------------
1229
- // Utilities
1230
- // -------------------------------------------------------------------------
1231
- extractParams(actual, template) {
1232
- const aParts = actual.split("/");
1233
- const tParts = template.split("/");
1234
- const params = {};
1235
- tParts.forEach((part, i) => {
1236
- if (part.startsWith(":")) params[part.slice(1)] = aParts[i] ?? "";
1237
- });
1238
- return params;
1239
- }
1240
- normalizeBatchPayload(body) {
1241
- if (body === null || typeof body !== "object") {
1242
- throw new BadRequestException("Batch payload must be an object containing a requests array.");
1243
- }
1244
- const { requests } = body;
1245
- if (!Array.isArray(requests)) throw new BadRequestException("Batch payload must define a requests array.");
1246
- return { requests: requests.map((e, i) => this.normalizeBatchItem(e, i)) };
1247
- }
1248
- normalizeBatchItem(entry, index) {
1249
- if (entry === null || typeof entry !== "object") throw new BadRequestException(`Batch request at index ${index} must be an object.`);
1250
- const { requestId, path: path2, method, body } = entry;
1251
- if (requestId !== void 0 && typeof requestId !== "string") throw new BadRequestException(`Batch request at index ${index} has an invalid requestId.`);
1252
- if (typeof path2 !== "string" || !path2.length) throw new BadRequestException(`Batch request at index ${index} must define a non-empty path.`);
1253
- if (typeof method !== "string") throw new BadRequestException(`Batch request at index ${index} must define an HTTP method.`);
1254
- const normalized = method.toUpperCase();
1255
- if (!isAtomicHttpMethod(normalized)) throw new BadRequestException(`Batch request at index ${index} uses unsupported method ${method}.`);
1256
- return { requestId, path: path2, method: normalized, body };
1132
+ var _Router_decorators, _init;
1133
+ _Router_decorators = [Injectable({ lifetime: "singleton" })];
1134
+ var _Router = class _Router {
1135
+ constructor() {
1136
+ __publicField(this, "routes", new RadixTree());
1137
+ __publicField(this, "rootMiddlewares", []);
1138
+ __publicField(this, "lazyRoutes", /* @__PURE__ */ new Map());
1139
+ __publicField(this, "lazyLoadLock", Promise.resolve());
1140
+ }
1141
+ // -------------------------------------------------------------------------
1142
+ // Registration
1143
+ // -------------------------------------------------------------------------
1144
+ registerController(controllerClass, pathPrefix, routeGuards = [], routeMiddlewares = []) {
1145
+ const meta = getControllerMetadata(controllerClass);
1146
+ if (!meta) {
1147
+ throw new Error(`[Noxus] Missing @Controller decorator on ${controllerClass.name}`);
1148
+ }
1149
+ const routeMeta = getRouteMetadata(controllerClass);
1150
+ for (const def of routeMeta) {
1151
+ const fullPath = `${pathPrefix}/${def.path}`.replace(/\/+/g, "/").replace(/\/$/, "") || "/";
1152
+ const guards = [.../* @__PURE__ */ new Set([...routeGuards, ...def.guards])];
1153
+ const middlewares = [.../* @__PURE__ */ new Set([...routeMiddlewares, ...def.middlewares])];
1154
+ const routeDef = {
1155
+ method: def.method,
1156
+ path: fullPath,
1157
+ controller: controllerClass,
1158
+ handler: def.handler,
1159
+ guards,
1160
+ middlewares
1161
+ };
1162
+ this.routes.insert(fullPath + "/" + def.method, routeDef);
1163
+ const guardInfo = guards.length ? `<${guards.map((g) => g.name).join("|")}>` : "";
1164
+ Logger.log(`Mapped {${def.method} /${fullPath}}${guardInfo} route`);
1165
+ }
1166
+ const ctrlGuardInfo = routeGuards.length ? `<${routeGuards.map((g) => g.name).join("|")}>` : "";
1167
+ Logger.log(`Mapped ${controllerClass.name}${ctrlGuardInfo} controller's routes`);
1168
+ return this;
1169
+ }
1170
+ registerLazyRoute(pathPrefix, load, guards = [], middlewares = []) {
1171
+ const normalized = pathPrefix.replace(/^\/+|\/+$/g, "");
1172
+ this.lazyRoutes.set(normalized, { load, guards, middlewares, loading: null, loaded: false });
1173
+ Logger.log(`Registered lazy route prefix {${normalized}}`);
1174
+ return this;
1175
+ }
1176
+ defineRootMiddleware(middleware) {
1177
+ this.rootMiddlewares.push(middleware);
1178
+ return this;
1179
+ }
1180
+ getRegisteredRoutes() {
1181
+ const allRoutes = this.routes.collectValues();
1182
+ return allRoutes.map((r) => ({ method: r.method, path: r.path }));
1183
+ }
1184
+ getLazyRoutes() {
1185
+ return [...this.lazyRoutes.entries()].map(([prefix, entry]) => ({
1186
+ prefix,
1187
+ loaded: entry.loaded
1188
+ }));
1189
+ }
1190
+ // -------------------------------------------------------------------------
1191
+ // Request handling
1192
+ // -------------------------------------------------------------------------
1193
+ async handle(request) {
1194
+ return request.method === "BATCH" ? this.handleBatch(request) : this.handleAtomic(request);
1195
+ }
1196
+ async handleAtomic(request) {
1197
+ Logger.comment(`> ${request.method} /${request.path}`);
1198
+ const t0 = performance.now();
1199
+ const response = { requestId: request.id, status: 200, body: null };
1200
+ let isCritical = false;
1201
+ try {
1202
+ const routeDef = await this.findRoute(request);
1203
+ await this.resolveController(request, response, routeDef);
1204
+ if (response.status >= 400) throw new ResponseException(response.status, response.error);
1205
+ } catch (error) {
1206
+ this.fillErrorResponse(response, error, (c) => {
1207
+ isCritical = c;
1208
+ });
1209
+ } finally {
1210
+ this.logResponse(request, response, performance.now() - t0, isCritical);
1211
+ return response;
1212
+ }
1213
+ }
1214
+ async handleBatch(request) {
1215
+ Logger.comment(`> ${request.method} /${request.path}`);
1216
+ const t0 = performance.now();
1217
+ const response = {
1218
+ requestId: request.id,
1219
+ status: 200,
1220
+ body: { responses: [] }
1221
+ };
1222
+ let isCritical = false;
1223
+ try {
1224
+ const payload = this.normalizeBatchPayload(request.body);
1225
+ response.body.responses = await Promise.all(
1226
+ payload.requests.map((item, i) => {
1227
+ const id = item.requestId ?? `${request.id}:${i}`;
1228
+ return this.handleAtomic(new Request(request.event, request.senderId, id, item.method, item.path, item.body, item.query));
1229
+ })
1230
+ );
1231
+ } catch (error) {
1232
+ this.fillErrorResponse(response, error, (c) => {
1233
+ isCritical = c;
1234
+ });
1235
+ } finally {
1236
+ this.logResponse(request, response, performance.now() - t0, isCritical);
1237
+ return response;
1238
+ }
1239
+ }
1240
+ // -------------------------------------------------------------------------
1241
+ // Route resolution
1242
+ // -------------------------------------------------------------------------
1243
+ tryFindRoute(request) {
1244
+ const matched = this.routes.search(request.path);
1245
+ if (!matched?.node || matched.node.children.length === 0) return void 0;
1246
+ return matched.node.findExactChild(request.method)?.value;
1247
+ }
1248
+ async findRoute(request) {
1249
+ const direct = this.tryFindRoute(request);
1250
+ if (direct) return direct;
1251
+ await this.tryLoadLazyRoute(request.path);
1252
+ const afterLazy = this.tryFindRoute(request);
1253
+ if (afterLazy) return afterLazy;
1254
+ throw new NotFoundException(`No route matches ${request.method} ${request.path}`);
1255
+ }
1256
+ async tryLoadLazyRoute(requestPath) {
1257
+ const firstSegment = requestPath.replace(/^\/+/, "").split("/")[0] ?? "";
1258
+ for (const [prefix, entry] of this.lazyRoutes) {
1259
+ if (entry.loaded) continue;
1260
+ const normalized = requestPath.replace(/^\/+/, "");
1261
+ if (normalized === prefix || normalized.startsWith(prefix + "/") || firstSegment === prefix) {
1262
+ if (!entry.loading) entry.loading = this.loadLazyModule(prefix, entry);
1263
+ await entry.loading;
1264
+ return;
1257
1265
  }
1258
- fillErrorResponse(response, error, setCritical) {
1259
- response.body = void 0;
1260
- if (error instanceof ResponseException) {
1261
- response.status = error.status;
1262
- response.error = error.message;
1263
- response.stack = error.stack;
1264
- } else if (error instanceof Error) {
1265
- setCritical(true);
1266
- response.status = 500;
1267
- response.error = error.message || "Internal Server Error";
1268
- response.stack = error.stack;
1269
- } else {
1270
- setCritical(true);
1271
- response.status = 500;
1272
- response.error = "Unknown error occurred";
1273
- }
1266
+ }
1267
+ }
1268
+ loadLazyModule(prefix, entry) {
1269
+ const task = this.lazyLoadLock.then(async () => {
1270
+ const t0 = performance.now();
1271
+ InjectorExplorer.beginAccumulate();
1272
+ await entry.load?.();
1273
+ entry.load = null;
1274
+ await InjectorExplorer.flushAccumulated(entry.guards, entry.middlewares, prefix);
1275
+ entry.loaded = true;
1276
+ entry.loading = null;
1277
+ Logger.info(`Lazy-loaded module for prefix {${prefix}} in ${Math.round(performance.now() - t0)}ms`);
1278
+ });
1279
+ this.lazyLoadLock = task;
1280
+ return task;
1281
+ }
1282
+ // -------------------------------------------------------------------------
1283
+ // Pipeline
1284
+ // -------------------------------------------------------------------------
1285
+ async resolveController(request, response, routeDef) {
1286
+ const instance = request.context.resolve(routeDef.controller);
1287
+ Object.assign(request.params, this.extractParams(request.path, routeDef.path));
1288
+ await this.runPipeline(request, response, routeDef, instance);
1289
+ }
1290
+ async runPipeline(request, response, routeDef, controllerInstance) {
1291
+ const middlewares = [.../* @__PURE__ */ new Set([...this.rootMiddlewares, ...routeDef.middlewares])];
1292
+ const mwMax = middlewares.length - 1;
1293
+ const guardMax = mwMax + routeDef.guards.length;
1294
+ let index = -1;
1295
+ const dispatch = /* @__PURE__ */ __name(async (i) => {
1296
+ if (i <= index) throw new Error("next() called multiple times");
1297
+ index = i;
1298
+ if (i <= mwMax) {
1299
+ await this.runMiddleware(request, response, dispatch.bind(null, i + 1), middlewares[i]);
1300
+ if (response.status >= 400) throw new ResponseException(response.status, response.error);
1301
+ return;
1274
1302
  }
1275
- logResponse(request, response, ms, isCritical) {
1276
- const msg = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(ms)}ms${Logger.colors.initial}`;
1277
- if (response.status < 400) Logger.log(msg);
1278
- else if (response.status < 500) Logger.warn(msg);
1279
- else isCritical ? Logger.critical(msg) : Logger.error(msg);
1280
- if (response.error) {
1281
- isCritical ? Logger.critical(response.error) : Logger.error(response.error);
1282
- if (response.stack) Logger.errorStack(response.stack);
1283
- }
1303
+ if (i <= guardMax) {
1304
+ await this.runGuard(request, routeDef.guards[i - middlewares.length]);
1305
+ await dispatch(i + 1);
1306
+ return;
1284
1307
  }
1285
- };
1286
- __name(Router, "Router");
1287
- Router = __decorateClass([
1288
- Injectable({ lifetime: "singleton" })
1289
- ], Router);
1308
+ const action = controllerInstance[routeDef.handler];
1309
+ response.body = await action.call(controllerInstance, request, response);
1310
+ if (response.body === void 0) response.body = {};
1311
+ }, "dispatch");
1312
+ await dispatch(0);
1290
1313
  }
1291
- });
1292
-
1293
- // src/main.ts
1294
- init_app_injector();
1295
- init_token();
1296
- init_router();
1314
+ async runMiddleware(request, response, next, middleware) {
1315
+ await middleware(request, response, next);
1316
+ }
1317
+ async runGuard(request, guard) {
1318
+ if (!await guard(request)) {
1319
+ throw new UnauthorizedException(`Unauthorized for ${request.method} ${request.path}`);
1320
+ }
1321
+ }
1322
+ // -------------------------------------------------------------------------
1323
+ // Utilities
1324
+ // -------------------------------------------------------------------------
1325
+ extractParams(actual, template) {
1326
+ const aParts = actual.split("/");
1327
+ const tParts = template.split("/");
1328
+ const params = {};
1329
+ tParts.forEach((part, i) => {
1330
+ if (part.startsWith(":")) params[part.slice(1)] = aParts[i] ?? "";
1331
+ });
1332
+ return params;
1333
+ }
1334
+ normalizeBatchPayload(body) {
1335
+ if (body === null || typeof body !== "object") {
1336
+ throw new BadRequestException("Batch payload must be an object containing a requests array.");
1337
+ }
1338
+ const { requests } = body;
1339
+ if (!Array.isArray(requests)) throw new BadRequestException("Batch payload must define a requests array.");
1340
+ return { requests: requests.map((e, i) => this.normalizeBatchItem(e, i)) };
1341
+ }
1342
+ normalizeBatchItem(entry, index) {
1343
+ if (entry === null || typeof entry !== "object") throw new BadRequestException(`Batch request at index ${index} must be an object.`);
1344
+ const { requestId, path: path2, method, body, query } = entry;
1345
+ if (requestId !== void 0 && typeof requestId !== "string") throw new BadRequestException(`Batch request at index ${index} has an invalid requestId.`);
1346
+ if (typeof path2 !== "string" || !path2.length) throw new BadRequestException(`Batch request at index ${index} must define a non-empty path.`);
1347
+ if (typeof method !== "string") throw new BadRequestException(`Batch request at index ${index} must define an HTTP method.`);
1348
+ const normalized = method.toUpperCase();
1349
+ if (!isAtomicHttpMethod(normalized)) throw new BadRequestException(`Batch request at index ${index} uses unsupported method ${method}.`);
1350
+ return { requestId, path: path2, method: normalized, body, query };
1351
+ }
1352
+ fillErrorResponse(response, error, setCritical) {
1353
+ response.body = void 0;
1354
+ if (error instanceof ResponseException) {
1355
+ response.status = error.status;
1356
+ response.error = error.message;
1357
+ response.stack = error.stack;
1358
+ } else if (error instanceof Error) {
1359
+ setCritical(true);
1360
+ response.status = 500;
1361
+ response.error = error.message || "Internal Server Error";
1362
+ response.stack = error.stack;
1363
+ } else {
1364
+ setCritical(true);
1365
+ response.status = 500;
1366
+ response.error = "Unknown error occurred";
1367
+ }
1368
+ }
1369
+ logResponse(request, response, ms, isCritical) {
1370
+ const msg = `< ${response.status} ${request.method} /${request.path} ${Logger.colors.yellow}${Math.round(ms)}ms${Logger.colors.initial}`;
1371
+ if (response.status < 400) Logger.log(msg);
1372
+ else if (response.status < 500) Logger.warn(msg);
1373
+ else isCritical ? Logger.critical(msg) : Logger.error(msg);
1374
+ if (response.error) {
1375
+ isCritical ? Logger.critical(response.error) : Logger.error(response.error);
1376
+ if (response.stack) Logger.errorStack(response.stack);
1377
+ }
1378
+ }
1379
+ };
1380
+ _init = __decoratorStart(null);
1381
+ _Router = __decorateElement(_init, 0, "Router", _Router_decorators, _Router);
1382
+ __name(_Router, "Router");
1383
+ __runInitializers(_init, 1, _Router);
1384
+ var Router = _Router;
1297
1385
 
1298
1386
  // src/internal/app.ts
1299
- init_injectable_decorator();
1387
+ import { app, BrowserWindow as BrowserWindow2, ipcMain, MessageChannelMain } from "electron/main";
1300
1388
  init_app_injector();
1301
1389
  init_injector_explorer();
1302
1390
  init_logger();
1303
- import { app, BrowserWindow as BrowserWindow2, ipcMain, MessageChannelMain } from "electron/main";
1304
1391
 
1305
1392
  // src/window/window-manager.ts
1306
- init_injectable_decorator();
1393
+ import { BrowserWindow } from "electron/main";
1307
1394
  init_logger();
1308
- import { BrowserWindow, screen } from "electron/main";
1309
- var WindowManager = class {
1395
+ var _WindowManager_decorators, _init2;
1396
+ _WindowManager_decorators = [Injectable({ lifetime: "singleton" })];
1397
+ var _WindowManager = class _WindowManager {
1310
1398
  constructor() {
1311
- this._windows = /* @__PURE__ */ new Map();
1399
+ __publicField(this, "_windows", /* @__PURE__ */ new Map());
1400
+ __publicField(this, "listeners", /* @__PURE__ */ new Map());
1401
+ __publicField(this, "_mainWindowId");
1312
1402
  }
1313
1403
  // -------------------------------------------------------------------------
1314
1404
  // Creation
@@ -1358,18 +1448,24 @@ var WindowManager = class {
1358
1448
  * win.loadFile('index.html');
1359
1449
  */
1360
1450
  async createSplash(options = {}) {
1361
- const { animationDuration = 600, ...bwOptions } = options;
1451
+ const {
1452
+ animationDuration = 10,
1453
+ expandToWorkArea = true,
1454
+ ...bwOptions
1455
+ } = options;
1362
1456
  const win = new BrowserWindow({
1363
1457
  width: 600,
1364
1458
  height: 600,
1365
1459
  center: true,
1366
- frame: false,
1367
1460
  show: true,
1368
1461
  ...bwOptions
1369
1462
  });
1370
1463
  this._register(win, true);
1371
1464
  Logger.log(`[WindowManager] Splash window #${win.id} created`);
1372
- await this._expandToWorkArea(win, animationDuration);
1465
+ if (expandToWorkArea) {
1466
+ await (() => new Promise((r) => setTimeout(r, 500)))();
1467
+ await this._expandToWorkArea(win, animationDuration);
1468
+ }
1373
1469
  return win;
1374
1470
  }
1375
1471
  // -------------------------------------------------------------------------
@@ -1428,10 +1524,24 @@ var WindowManager = class {
1428
1524
  */
1429
1525
  broadcast(channel, ...args) {
1430
1526
  for (const win of this._windows.values()) {
1431
- if (!win.isDestroyed()) win.webContents.send(channel, ...args);
1527
+ if (!win.isDestroyed()) {
1528
+ win.webContents.send(channel, ...args);
1529
+ }
1432
1530
  }
1433
1531
  }
1434
1532
  // -------------------------------------------------------------------------
1533
+ // Events
1534
+ // -------------------------------------------------------------------------
1535
+ on(event, handler) {
1536
+ const set = this.listeners.get(event) ?? /* @__PURE__ */ new Set();
1537
+ set.add(handler);
1538
+ this.listeners.set(event, set);
1539
+ return () => set.delete(handler);
1540
+ }
1541
+ _emit(event, win) {
1542
+ this.listeners.get(event)?.forEach((h) => h(win));
1543
+ }
1544
+ // -------------------------------------------------------------------------
1435
1545
  // Private
1436
1546
  // -------------------------------------------------------------------------
1437
1547
  _register(win, isMain) {
@@ -1439,10 +1549,16 @@ var WindowManager = class {
1439
1549
  if (isMain && this._mainWindowId === void 0) {
1440
1550
  this._mainWindowId = win.id;
1441
1551
  }
1552
+ this._emit("created", win);
1553
+ win.on("focus", () => this._emit("focused", win));
1554
+ win.on("blur", () => this._emit("blurred", win));
1442
1555
  win.once("closed", () => {
1443
1556
  this._windows.delete(win.id);
1444
- if (this._mainWindowId === win.id) this._mainWindowId = void 0;
1557
+ if (this._mainWindowId === win.id) {
1558
+ this._mainWindowId = void 0;
1559
+ }
1445
1560
  Logger.log(`[WindowManager] Window #${win.id} closed`);
1561
+ this._emit("closed", win);
1446
1562
  });
1447
1563
  }
1448
1564
  /**
@@ -1452,36 +1568,34 @@ var WindowManager = class {
1452
1568
  */
1453
1569
  _expandToWorkArea(win, animationDuration) {
1454
1570
  return new Promise((resolve) => {
1455
- const { x, y, width, height } = screen.getPrimaryDisplay().workArea;
1456
- win.setBounds({ x, y, width, height }, true);
1571
+ win.maximize();
1457
1572
  let resolved = false;
1458
1573
  const done = /* @__PURE__ */ __name(() => {
1459
- if (resolved) return;
1574
+ if (resolved) {
1575
+ return;
1576
+ }
1460
1577
  resolved = true;
1461
1578
  win.removeListener("resize", done);
1462
1579
  resolve();
1463
1580
  }, "done");
1464
1581
  win.once("resize", done);
1465
- setTimeout(done, animationDuration + 100);
1582
+ setTimeout(done, animationDuration);
1466
1583
  });
1467
1584
  }
1468
1585
  };
1469
- __name(WindowManager, "WindowManager");
1470
- WindowManager = __decorateClass([
1471
- Injectable({ lifetime: "singleton" })
1472
- ], WindowManager);
1473
-
1474
- // src/internal/app.ts
1475
- init_request();
1476
- init_router();
1586
+ _init2 = __decoratorStart(null);
1587
+ _WindowManager = __decorateElement(_init2, 0, "WindowManager", _WindowManager_decorators, _WindowManager);
1588
+ __name(_WindowManager, "WindowManager");
1589
+ __runInitializers(_init2, 1, _WindowManager);
1590
+ var WindowManager = _WindowManager;
1477
1591
 
1478
1592
  // src/internal/socket.ts
1479
- init_injectable_decorator();
1480
1593
  init_logger();
1481
- init_request();
1482
- var NoxSocket = class {
1594
+ var _NoxSocket_decorators, _init3;
1595
+ _NoxSocket_decorators = [Injectable({ lifetime: "singleton" })];
1596
+ var _NoxSocket = class _NoxSocket {
1483
1597
  constructor() {
1484
- this.channels = /* @__PURE__ */ new Map();
1598
+ __publicField(this, "channels", /* @__PURE__ */ new Map());
1485
1599
  }
1486
1600
  register(senderId, requestChannel, socketChannel) {
1487
1601
  this.channels.set(senderId, { request: requestChannel, socket: socketChannel });
@@ -1501,7 +1615,6 @@ var NoxSocket = class {
1501
1615
  throw new Error("Renderer event name must be a non-empty string.");
1502
1616
  }
1503
1617
  const recipients = targetSenderIds ?? this.getSenderIds();
1504
- let delivered = 0;
1505
1618
  for (const senderId of recipients) {
1506
1619
  const channel = this.channels.get(senderId);
1507
1620
  if (!channel) {
@@ -1510,40 +1623,46 @@ var NoxSocket = class {
1510
1623
  }
1511
1624
  try {
1512
1625
  channel.socket.port1.postMessage(createRendererEventMessage(normalizedEvent, payload));
1513
- delivered++;
1514
1626
  } catch (error) {
1515
1627
  Logger.error(`[Noxus] Failed to emit "${normalizedEvent}" to sender ${senderId}.`, error);
1516
1628
  }
1517
1629
  }
1518
- return delivered;
1519
1630
  }
1520
1631
  emitToRenderer(senderId, eventName, payload) {
1521
- return this.emit(eventName, payload, [senderId]) > 0;
1632
+ if (!this.channels.has(senderId)) {
1633
+ return false;
1634
+ }
1635
+ this.emit(eventName, payload, [senderId]);
1636
+ return true;
1522
1637
  }
1523
1638
  };
1524
- __name(NoxSocket, "NoxSocket");
1525
- NoxSocket = __decorateClass([
1526
- Injectable({ lifetime: "singleton" })
1527
- ], NoxSocket);
1639
+ _init3 = __decoratorStart(null);
1640
+ _NoxSocket = __decorateElement(_init3, 0, "NoxSocket", _NoxSocket_decorators, _NoxSocket);
1641
+ __name(_NoxSocket, "NoxSocket");
1642
+ __runInitializers(_init3, 1, _NoxSocket);
1643
+ var NoxSocket = _NoxSocket;
1528
1644
 
1529
1645
  // src/internal/app.ts
1530
- var NoxApp = class {
1531
- constructor() {
1532
- this.router = inject(Router);
1533
- this.socket = inject(NoxSocket);
1534
- this.windowManager = inject(WindowManager);
1646
+ var _NoxApp_decorators, _init4;
1647
+ _NoxApp_decorators = [Injectable({ lifetime: "singleton", deps: [Router, NoxSocket, WindowManager] })];
1648
+ var _NoxApp = class _NoxApp {
1649
+ constructor(router, socket, windowManager) {
1650
+ this.router = router;
1651
+ this.socket = socket;
1652
+ this.windowManager = windowManager;
1653
+ __publicField(this, "appService");
1535
1654
  // -------------------------------------------------------------------------
1536
1655
  // IPC
1537
1656
  // -------------------------------------------------------------------------
1538
- this.onRendererMessage = /* @__PURE__ */ __name(async (event) => {
1539
- const { senderId, requestId, path: path2, method, body } = event.data;
1657
+ __publicField(this, "onRendererMessage", /* @__PURE__ */ __name(async (event) => {
1658
+ const { senderId, requestId, path: path2, method, body, query } = event.data;
1540
1659
  const channels = this.socket.get(senderId);
1541
1660
  if (!channels) {
1542
1661
  Logger.error(`No message channel found for sender ID: ${senderId}`);
1543
1662
  return;
1544
1663
  }
1545
1664
  try {
1546
- const request = new Request(event, senderId, requestId, method, path2, body);
1665
+ const request = new Request(event, senderId, requestId, method, path2, body, query);
1547
1666
  const response = await this.router.handle(request);
1548
1667
  channels.request.port1.postMessage(response);
1549
1668
  } catch (err) {
@@ -1555,7 +1674,7 @@ var NoxApp = class {
1555
1674
  };
1556
1675
  channels.request.port1.postMessage(response);
1557
1676
  }
1558
- }, "onRendererMessage");
1677
+ }, "onRendererMessage"));
1559
1678
  }
1560
1679
  // -------------------------------------------------------------------------
1561
1680
  // Initialisation
@@ -1594,7 +1713,7 @@ var NoxApp = class {
1594
1713
  async load(importFns) {
1595
1714
  InjectorExplorer.beginAccumulate();
1596
1715
  await Promise.all(importFns.map((fn) => fn()));
1597
- InjectorExplorer.flushAccumulated();
1716
+ await InjectorExplorer.flushAccumulated();
1598
1717
  return this;
1599
1718
  }
1600
1719
  /**
@@ -1663,27 +1782,44 @@ var NoxApp = class {
1663
1782
  this.socket.unregister(channelSenderId);
1664
1783
  }
1665
1784
  };
1666
- __name(NoxApp, "NoxApp");
1667
- NoxApp = __decorateClass([
1668
- Injectable({ lifetime: "singleton", deps: [Router, NoxSocket, WindowManager] })
1669
- ], NoxApp);
1785
+ _init4 = __decoratorStart(null);
1786
+ _NoxApp = __decorateElement(_init4, 0, "NoxApp", _NoxApp_decorators, _NoxApp);
1787
+ __name(_NoxApp, "NoxApp");
1788
+ __runInitializers(_init4, 1, _NoxApp);
1789
+ var NoxApp = _NoxApp;
1670
1790
 
1671
1791
  // src/internal/bootstrap.ts
1672
1792
  init_app_injector();
1673
1793
  init_injector_explorer();
1794
+ init_logger();
1674
1795
  import { app as app2 } from "electron/main";
1675
1796
  async function bootstrapApplication(config = {}) {
1676
1797
  await app2.whenReady();
1798
+ if (config.logLevel !== void 0) {
1799
+ if (config.logLevel === "none") {
1800
+ Logger.setLogLevel([]);
1801
+ } else if (Array.isArray(config.logLevel)) {
1802
+ Logger.setLogLevel(config.logLevel);
1803
+ } else {
1804
+ Logger.setLogLevel(config.logLevel);
1805
+ }
1806
+ }
1677
1807
  const overrides = /* @__PURE__ */ new Map();
1678
1808
  for (const { token: token2, useValue } of config.singletons ?? []) {
1679
1809
  overrides.set(token2, useValue);
1680
1810
  RootInjector.singletons.set(token2, useValue);
1681
1811
  }
1812
+ InjectorExplorer.setControllerRegistrar((controllerClass, pathPrefix, routeGuards, routeMiddlewares) => {
1813
+ const router = inject(Router);
1814
+ router.registerController(controllerClass, pathPrefix, routeGuards, routeMiddlewares);
1815
+ });
1682
1816
  InjectorExplorer.processPending(overrides);
1683
1817
  const noxApp = inject(NoxApp);
1684
1818
  if (config.routes?.length) {
1685
1819
  for (const route of config.routes) {
1686
- noxApp.lazy(route.path, route.load, route.guards, route.middlewares);
1820
+ if (route.load) {
1821
+ noxApp.lazy(route.path, route.load, route.guards, route.middlewares);
1822
+ }
1687
1823
  }
1688
1824
  }
1689
1825
  if (config.eagerLoad?.length) {
@@ -1695,29 +1831,53 @@ async function bootstrapApplication(config = {}) {
1695
1831
  __name(bootstrapApplication, "bootstrapApplication");
1696
1832
 
1697
1833
  // src/main.ts
1698
- init_exceptions();
1699
- init_controller_decorator();
1700
- init_injectable_decorator();
1701
- init_method_decorator();
1702
1834
  init_logger();
1703
1835
  init_forward_ref();
1704
- init_request();
1705
1836
 
1706
1837
  // src/internal/routes.ts
1707
1838
  function defineRoutes(routes) {
1708
- const paths = routes.map((r) => r.path.replace(/^\/+|\/+$/g, ""));
1839
+ const flat = flattenRoutes(routes);
1840
+ const paths = flat.map((r) => r.path);
1709
1841
  const duplicates = paths.filter((p, i) => paths.indexOf(p) !== i);
1710
1842
  if (duplicates.length > 0) {
1711
1843
  throw new Error(
1712
1844
  `[Noxus] Duplicate route prefixes detected: ${[...new Set(duplicates)].map((d) => `"${d}"`).join(", ")}`
1713
1845
  );
1714
1846
  }
1715
- return routes.map((r) => ({
1716
- ...r,
1717
- path: r.path.replace(/^\/+|\/+$/g, "")
1718
- }));
1847
+ const sorted = [...paths].sort();
1848
+ for (let i = 0; i < sorted.length - 1; i++) {
1849
+ const a = sorted[i];
1850
+ const b = sorted[i + 1];
1851
+ if (b.startsWith(a + "/")) {
1852
+ throw new Error(
1853
+ `[Noxus] Overlapping route prefixes detected: "${a}" and "${b}". Use nested children under "${a}" instead of declaring both as top-level routes.`
1854
+ );
1855
+ }
1856
+ }
1857
+ return flat;
1719
1858
  }
1720
1859
  __name(defineRoutes, "defineRoutes");
1860
+ function flattenRoutes(routes, parentPath = "", parentGuards = [], parentMiddlewares = []) {
1861
+ const result = [];
1862
+ for (const route of routes) {
1863
+ const path2 = [parentPath, route.path.replace(/^\/+|\/+$/g, "")].filter(Boolean).join("/");
1864
+ const guards = [.../* @__PURE__ */ new Set([...parentGuards, ...route.guards ?? []])];
1865
+ const middlewares = [.../* @__PURE__ */ new Set([...parentMiddlewares, ...route.middlewares ?? []])];
1866
+ if (route.load) {
1867
+ result.push({ ...route, path: path2, guards, middlewares });
1868
+ }
1869
+ if (route.children?.length) {
1870
+ result.push(...flattenRoutes(route.children, path2, guards, middlewares));
1871
+ }
1872
+ if (!route.load && !route.children?.length) {
1873
+ throw new Error(
1874
+ `[Noxus] Route "${path2}" has neither a load function nor children. It must have at least one of them.`
1875
+ );
1876
+ }
1877
+ }
1878
+ return result;
1879
+ }
1880
+ __name(flattenRoutes, "flattenRoutes");
1721
1881
  export {
1722
1882
  AppInjector,
1723
1883
  BadGatewayException,
@@ -1770,6 +1930,7 @@ export {
1770
1930
  inject,
1771
1931
  isAtomicHttpMethod,
1772
1932
  isRendererEventMessage,
1933
+ resetRootInjector,
1773
1934
  token
1774
1935
  };
1775
1936
  /**