@forinda/kickjs 0.1.3 → 0.1.6

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.
package/dist/index.js CHANGED
@@ -6,6 +6,9 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
9
12
  var __export = (target, all) => {
10
13
  for (var name in all)
11
14
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -28,337 +31,427 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
31
  ));
29
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
33
 
34
+ // src/cli/utils/config-loader.ts
35
+ async function loadKickConfig(cwd) {
36
+ const workingDir = cwd || process.cwd();
37
+ for (const configFileName of CONFIG_FILE_NAMES) {
38
+ const configPath = import_node_path.default.resolve(workingDir, configFileName);
39
+ if ((0, import_node_fs.existsSync)(configPath)) {
40
+ try {
41
+ const configModule = await import(configPath);
42
+ const config = configModule.default || configModule;
43
+ return {
44
+ ...config,
45
+ configPath
46
+ };
47
+ } catch (error) {
48
+ console.warn(`\u26A0\uFE0F Failed to load config from ${configPath}:`, error);
49
+ }
50
+ }
51
+ }
52
+ return getDefaultConfig();
53
+ }
54
+ function getDefaultConfig() {
55
+ return {
56
+ app: {
57
+ name: "KickJS App",
58
+ port: 3e3,
59
+ host: "localhost",
60
+ prefix: "",
61
+ env: "development"
62
+ },
63
+ dev: {
64
+ port: 3e3,
65
+ host: "localhost",
66
+ entry: "src/index.ts",
67
+ watch: true,
68
+ env: {
69
+ NODE_ENV: "development"
70
+ }
71
+ },
72
+ start: {
73
+ port: 3e3,
74
+ host: "0.0.0.0",
75
+ entry: "dist/index.js",
76
+ env: {
77
+ NODE_ENV: "production"
78
+ }
79
+ },
80
+ structure: {
81
+ domainRoot: "src/domains",
82
+ domainFolders: [
83
+ "controllers",
84
+ "services",
85
+ "domain"
86
+ ],
87
+ defaultDomain: "app"
88
+ },
89
+ generators: {
90
+ controllerRoot: "src/domains/app/controllers"
91
+ }
92
+ };
93
+ }
94
+ function getAppConfig(config, overrides = {}) {
95
+ return {
96
+ ...getDefaultConfig().app,
97
+ ...config.app,
98
+ ...overrides
99
+ };
100
+ }
101
+ var import_node_fs, import_node_path, CONFIG_FILE_NAMES;
102
+ var init_config_loader = __esm({
103
+ "src/cli/utils/config-loader.ts"() {
104
+ "use strict";
105
+ import_node_fs = require("fs");
106
+ import_node_path = __toESM(require("path"));
107
+ CONFIG_FILE_NAMES = [
108
+ "kick.config.ts",
109
+ "kick.config.js",
110
+ "kick.config.mjs",
111
+ "kickjs.config.ts",
112
+ "kickjs.config.js",
113
+ "kickjs.config.mjs"
114
+ ];
115
+ __name(loadKickConfig, "loadKickConfig");
116
+ __name(getDefaultConfig, "getDefaultConfig");
117
+ __name(getAppConfig, "getAppConfig");
118
+ }
119
+ });
120
+
121
+ // src/core/utils/app-config.ts
122
+ var app_config_exports = {};
123
+ __export(app_config_exports, {
124
+ getConfigFromEnv: () => getConfigFromEnv,
125
+ loadAppConfig: () => loadAppConfig
126
+ });
127
+ async function loadAppConfig(overrides = {}) {
128
+ const kickConfig = await loadKickConfig();
129
+ return getAppConfig(kickConfig, overrides);
130
+ }
131
+ function getConfigFromEnv() {
132
+ return {
133
+ port: process.env.PORT ? parseInt(process.env.PORT) : void 0,
134
+ host: process.env.HOST || void 0,
135
+ env: process.env.NODE_ENV || void 0
136
+ };
137
+ }
138
+ var init_app_config = __esm({
139
+ "src/core/utils/app-config.ts"() {
140
+ "use strict";
141
+ init_config_loader();
142
+ __name(loadAppConfig, "loadAppConfig");
143
+ __name(getConfigFromEnv, "getConfigFromEnv");
144
+ }
145
+ });
146
+
31
147
  // src/index.ts
32
148
  var index_exports = {};
33
149
  __export(index_exports, {
34
- AppDiagnostics: () => AppDiagnostics,
35
- AppError: () => AppError,
36
- BaseController: () => BaseController,
37
- Controller: () => Controller,
38
- Delete: () => Delete,
39
- DeleteController: () => DeleteController,
40
- Get: () => Get,
41
- GetController: () => GetController,
42
- HttpVerbController: () => HttpVerbController,
43
- Inject: () => Inject,
44
- Injectable: () => Injectable,
45
- MultiInject: () => MultiInject,
46
- Named: () => Named,
47
- Optional: () => Optional,
48
- Patch: () => Patch,
49
- PatchController: () => PatchController,
50
- Post: () => Post,
51
- PostController: () => PostController,
52
- Put: () => Put,
53
- PutController: () => PutController,
54
- RequestTracker: () => RequestTracker,
55
- TYPES: () => TYPES,
56
- Tagged: () => Tagged,
57
- Unmanaged: () => Unmanaged,
58
- bootstrap: () => bootstrap,
59
- configureApp: () => configureApp,
60
- createApp: () => createApp,
61
- createError: () => createError,
150
+ AutoBind: () => AutoBind,
151
+ BaseKickMiddleware: () => BaseKickMiddleware,
152
+ BaseKickPlugin: () => BaseKickPlugin,
153
+ KICK_CONTROLLER_METADATA_KEYS: () => KICK_CONTROLLER_METADATA_KEYS,
154
+ KICK_MODULE_KEYS: () => KICK_MODULE_KEYS,
155
+ KickApp: () => KickApp,
156
+ KickController: () => KickController,
157
+ KickDelete: () => KickDelete,
158
+ KickGet: () => KickGet,
159
+ KickInject: () => KickInject,
160
+ KickInjectable: () => KickInjectable,
161
+ KickMiddleware: () => KickMiddleware,
162
+ KickPatch: () => KickPatch,
163
+ KickPost: () => KickPost,
164
+ KickPut: () => KickPut,
165
+ RouteMapper: () => RouteMapper,
166
+ bindClassMethods: () => bindClassMethods,
167
+ combineRoutePaths: () => combineRoutePaths,
168
+ createKickApp: () => createKickApp,
169
+ createKickAppWithConfig: () => createKickAppWithConfig,
62
170
  createKickConfig: () => createKickConfig,
63
- discoverControllersFromFilesystem: () => discoverControllersFromFilesystem,
64
- getAppConfig: () => getAppConfig,
65
- isAppError: () => isAppError,
66
- listRegisteredControllers: () => listRegisteredControllers,
67
- registerController: () => registerController,
68
- resetAppConfig: () => resetAppConfig,
69
- resetControllerRegistry: () => resetControllerRegistry,
70
- resolveConfig: () => resolveConfig
171
+ createModule: () => createModule,
172
+ defineAppConfig: () => defineAppConfig,
173
+ defineDevConfig: () => defineDevConfig,
174
+ defineStartConfig: () => defineStartConfig,
175
+ getConfigFromEnv: () => getConfigFromEnv,
176
+ getMiddlewareMetadata: () => getMiddlewareMetadata,
177
+ isKickMiddleware: () => isKickMiddleware,
178
+ loadAppConfig: () => loadAppConfig,
179
+ mapController: () => mapController,
180
+ normalizeRoutePath: () => normalizeRoutePath
71
181
  });
72
182
  module.exports = __toCommonJS(index_exports);
73
183
 
74
- // src/decorators/http.ts
184
+ // src/core/index.ts
75
185
  var import_reflect_metadata = require("reflect-metadata");
76
- var CONTROLLER_KEY = Symbol("core:controller");
77
- var ROUTES_KEY = Symbol("core:routes");
78
- var controllerRegistry = /* @__PURE__ */ new Set();
79
- function Controller(pathOrOptions = "/") {
80
- const options = normalizeControllerOptions(pathOrOptions);
81
- return function(target) {
82
- Reflect.defineMetadata(CONTROLLER_KEY, {
83
- basePath: options.path,
84
- tags: options.tags
85
- }, target);
86
- if (!Reflect.hasMetadata(ROUTES_KEY, target)) {
87
- Reflect.defineMetadata(ROUTES_KEY, [], target);
88
- }
89
- if (options.autoRegister !== false) {
90
- controllerRegistry.add(target);
91
- }
92
- };
93
- }
94
- __name(Controller, "Controller");
95
- function Get(path3, ...middlewares) {
96
- return createRouteDecorator("get")(path3, ...middlewares);
97
- }
98
- __name(Get, "Get");
99
- function Post(path3, ...middlewares) {
100
- return createRouteDecorator("post")(path3, ...middlewares);
101
- }
102
- __name(Post, "Post");
103
- function Put(path3, ...middlewares) {
104
- return createRouteDecorator("put")(path3, ...middlewares);
105
- }
106
- __name(Put, "Put");
107
- function Patch(path3, ...middlewares) {
108
- return createRouteDecorator("patch")(path3, ...middlewares);
109
- }
110
- __name(Patch, "Patch");
111
- function Delete(path3, ...middlewares) {
112
- return createRouteDecorator("delete")(path3, ...middlewares);
113
- }
114
- __name(Delete, "Delete");
115
- function listRegisteredControllers() {
116
- return Array.from(controllerRegistry);
117
- }
118
- __name(listRegisteredControllers, "listRegisteredControllers");
119
- function registerController(controller) {
120
- controllerRegistry.add(controller);
121
- }
122
- __name(registerController, "registerController");
123
- function resetControllerRegistry() {
124
- controllerRegistry.clear();
125
- }
126
- __name(resetControllerRegistry, "resetControllerRegistry");
127
- var DecoratorMetadata = {
128
- CONTROLLER_KEY,
129
- ROUTES_KEY
186
+
187
+ // src/core/constants/di-keys.ts
188
+ var KICK_MODULE_KEYS = {
189
+ KickControllerType: Symbol.for("Kick:ControllerType"),
190
+ KickMiddlewareType: Symbol.for("Kick:MiddlewareType")
130
191
  };
131
- function createRouteDecorator(method) {
132
- return (pathOrOptions, ...middlewares) => function(target, propertyKey) {
133
- const controller = target.constructor;
134
- const routes = Reflect.getMetadata(ROUTES_KEY, controller) ?? [];
135
- const normalized = normalizeRouteOptions(pathOrOptions, middlewares);
136
- routes.push({
137
- method,
138
- path: normalized.path,
139
- propertyKey,
140
- middlewares: normalized.middlewares,
141
- validation: normalized.validation
142
- });
143
- Reflect.defineMetadata(ROUTES_KEY, routes, controller);
144
- };
145
- }
146
- __name(createRouteDecorator, "createRouteDecorator");
147
- function normalizeControllerOptions(pathOrOptions) {
148
- if (typeof pathOrOptions === "string") {
149
- return {
150
- path: normalizePath(pathOrOptions),
151
- autoRegister: true,
152
- tags: []
192
+ var KICK_CONTROLLER_METADATA_KEYS = {
193
+ path: Symbol.for("Kick:controller:path"),
194
+ options: Symbol.for("Kick:controller:options"),
195
+ routes: Symbol.for("Kick:controller:routes"),
196
+ middlewares: Symbol.for("Kick:controller:middlewares"),
197
+ middlewareOptions: Symbol.for("Kick:middleware:options"),
198
+ isMiddleware: Symbol.for("Kick:middleware:isMiddleware")
199
+ };
200
+
201
+ // src/core/decorators/route.ts
202
+ function createKickRoute(createOptions) {
203
+ return function(path2, options = {}) {
204
+ return function(target, propertyKey, descriptor) {
205
+ if (typeof descriptor.value !== "function") {
206
+ throw new Error("[KickRoute] Decorator can only be applied to methods.");
207
+ }
208
+ const routeMetadata = {
209
+ path: path2,
210
+ method: createOptions.method,
211
+ handlerName: propertyKey,
212
+ handler: descriptor.value,
213
+ middlewares: options.middlewares ?? []
214
+ };
215
+ const existingRoutes = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.routes, target.constructor) || [];
216
+ existingRoutes.push(routeMetadata);
217
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.routes, existingRoutes, target.constructor);
153
218
  };
154
- }
155
- return {
156
- path: normalizePath(pathOrOptions.path ?? "/"),
157
- autoRegister: pathOrOptions.autoRegister ?? true,
158
- tags: pathOrOptions.tags ?? []
159
219
  };
160
220
  }
161
- __name(normalizeControllerOptions, "normalizeControllerOptions");
162
- function normalizeRouteOptions(pathOrOptions, extraMiddlewares) {
163
- const base = normalizeRouteOptionObject(pathOrOptions);
164
- const middlewares = [
165
- ...base.middlewares ?? [],
166
- ...extraMiddlewares
167
- ];
168
- return {
169
- path: normalizeRoutePath(base.path ?? "/"),
170
- middlewares,
171
- validation: base.validate
221
+ __name(createKickRoute, "createKickRoute");
222
+ function KickGet(path2, options) {
223
+ return createKickRoute({
224
+ method: "GET"
225
+ })(path2, options);
226
+ }
227
+ __name(KickGet, "KickGet");
228
+ function KickPost(path2, options) {
229
+ return createKickRoute({
230
+ method: "POST"
231
+ })(path2, options);
232
+ }
233
+ __name(KickPost, "KickPost");
234
+ function KickPut(path2, options) {
235
+ return createKickRoute({
236
+ method: "PUT"
237
+ })(path2, options);
238
+ }
239
+ __name(KickPut, "KickPut");
240
+ function KickPatch(path2, options) {
241
+ return createKickRoute({
242
+ method: "PATCH"
243
+ })(path2, options);
244
+ }
245
+ __name(KickPatch, "KickPatch");
246
+ function KickDelete(path2, options) {
247
+ return createKickRoute({
248
+ method: "DELETE"
249
+ })(path2, options);
250
+ }
251
+ __name(KickDelete, "KickDelete");
252
+
253
+ // src/core/decorators/controller.ts
254
+ var import_inversify = require("inversify");
255
+
256
+ // src/core/utils/bind-class-methods.ts
257
+ function bindClassMethods(instance) {
258
+ const proto = Object.getPrototypeOf(instance);
259
+ const methods = Object.getOwnPropertyNames(proto).filter((prop) => typeof instance[prop] === "function" && prop !== "constructor");
260
+ methods.forEach((method) => {
261
+ instance[method] = instance[method].bind(instance);
262
+ });
263
+ }
264
+ __name(bindClassMethods, "bindClassMethods");
265
+
266
+ // src/core/decorators/controller.ts
267
+ function KickController(path2, options) {
268
+ return function(target) {
269
+ (0, import_inversify.decorate)((0, import_inversify.injectable)("Request"), target);
270
+ bindClassMethods(target.prototype);
271
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.path, path2, target);
272
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.options, options || {}, target);
172
273
  };
173
274
  }
174
- __name(normalizeRouteOptions, "normalizeRouteOptions");
175
- function normalizeRouteOptionObject(pathOrOptions) {
176
- if (typeof pathOrOptions === "string") {
177
- return {
178
- path: pathOrOptions
179
- };
180
- }
181
- if (typeof pathOrOptions === "object" && pathOrOptions !== null) {
182
- return {
183
- ...pathOrOptions
275
+ __name(KickController, "KickController");
276
+
277
+ // src/core/decorators/auto-bind.ts
278
+ function AutoBind(target) {
279
+ bindClassMethods(target.prototype);
280
+ }
281
+ __name(AutoBind, "AutoBind");
282
+
283
+ // src/core/decorators/middleware.ts
284
+ var import_inversify2 = require("inversify");
285
+ function KickMiddleware(options = {}) {
286
+ return function(target) {
287
+ AutoBind(target);
288
+ (0, import_inversify2.decorate)((0, import_inversify2.injectable)(), target);
289
+ const middlewareMetadata = {
290
+ name: options.name || target.name,
291
+ priority: options.priority || 0,
292
+ global: options.global || false,
293
+ tags: options.tags || [],
294
+ className: target.name
184
295
  };
185
- }
186
- return {};
296
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, middlewareMetadata, target);
297
+ Reflect.defineMetadata(KICK_CONTROLLER_METADATA_KEYS.isMiddleware, true, target);
298
+ };
187
299
  }
188
- __name(normalizeRouteOptionObject, "normalizeRouteOptionObject");
189
- function normalizePath(path3) {
190
- if (!path3 || path3 === "/") {
191
- return "/";
192
- }
193
- const withLeading = path3.startsWith("/") ? path3 : `/${path3}`;
194
- return withLeading.endsWith("/") && withLeading !== "/" ? withLeading.slice(0, -1) : withLeading;
300
+ __name(KickMiddleware, "KickMiddleware");
301
+ function isKickMiddleware(target) {
302
+ return Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.isMiddleware, target) === true;
195
303
  }
196
- __name(normalizePath, "normalizePath");
197
- function normalizeRoutePath(path3) {
198
- if (!path3 || path3 === "/") {
199
- return "";
200
- }
201
- const cleaned = path3.startsWith("/") ? path3.slice(1) : path3;
202
- return cleaned.endsWith("/") ? cleaned.slice(0, -1) : cleaned;
304
+ __name(isKickMiddleware, "isKickMiddleware");
305
+ function getMiddlewareMetadata(target) {
306
+ return Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, target);
203
307
  }
204
- __name(normalizeRoutePath, "normalizeRoutePath");
308
+ __name(getMiddlewareMetadata, "getMiddlewareMetadata");
205
309
 
206
- // src/utils/errors.ts
207
- var AppError = class extends Error {
208
- static {
209
- __name(this, "AppError");
310
+ // src/core/utils/normalize-route-path.ts
311
+ function normalizeRoutePath(path2) {
312
+ if (typeof path2 !== "string") {
313
+ throw new Error("Invalid path type");
210
314
  }
211
- code;
212
- status;
213
- details;
214
- constructor(code, message, options = {}) {
215
- super(message);
216
- this.code = code;
217
- this.status = options.status;
218
- this.details = options.details;
219
- if (options.cause) {
220
- this.cause = options.cause;
221
- }
222
- this.name = "AppError";
315
+ if (!path2.startsWith("/")) {
316
+ path2 = `/${path2}`;
223
317
  }
224
- };
225
- function createError(code, message, options = {}) {
226
- return new AppError(code, message, options);
318
+ if (path2.endsWith("/")) {
319
+ path2 = path2.slice(0, -1);
320
+ }
321
+ return path2;
227
322
  }
228
- __name(createError, "createError");
229
- function isAppError(error) {
230
- return error instanceof AppError;
323
+ __name(normalizeRoutePath, "normalizeRoutePath");
324
+ function combineRoutePaths(basePath, routePath) {
325
+ const base = basePath === "" ? "" : basePath.replace(/\/$/, "");
326
+ const route = routePath === "" ? "" : routePath;
327
+ const full = `${base}${route}`;
328
+ return normalizeRoutePath(full === "" ? "/" : full);
231
329
  }
232
- __name(isAppError, "isAppError");
330
+ __name(combineRoutePaths, "combineRoutePaths");
233
331
 
234
- // src/core/request-tracker.ts
235
- var import_node_crypto2 = require("crypto");
332
+ // src/core/utils/controller-mapper.ts
333
+ function mapController(controller) {
334
+ const basePath = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.path, controller.constructor) || "";
335
+ const routes = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.routes, controller.constructor) || [];
336
+ const baseOptions = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.options, controller.constructor) || {};
337
+ return routes.map((route) => ({
338
+ ...route,
339
+ path: combineRoutePaths(basePath, route.path),
340
+ middlewares: [
341
+ ...baseOptions.middlewares || [],
342
+ ...route.middlewares || []
343
+ ]
344
+ }));
345
+ }
346
+ __name(mapController, "mapController");
236
347
 
237
- // src/utils/injection.ts
238
- var import_inversify = require("inversify");
239
- function Injectable() {
240
- return (0, import_inversify.injectable)();
241
- }
242
- __name(Injectable, "Injectable");
243
- function Inject(identifier) {
244
- return (0, import_inversify.inject)(identifier);
245
- }
246
- __name(Inject, "Inject");
247
- function Optional() {
248
- return (0, import_inversify.optional)();
249
- }
250
- __name(Optional, "Optional");
251
- function MultiInject(identifier) {
252
- return (0, import_inversify.multiInject)(identifier);
253
- }
254
- __name(MultiInject, "MultiInject");
255
- function Named(name) {
256
- return (0, import_inversify.named)(name);
257
- }
258
- __name(Named, "Named");
259
- function Tagged(metadataKey, metadataValue) {
260
- return (0, import_inversify.tagged)(metadataKey, metadataValue);
261
- }
262
- __name(Tagged, "Tagged");
263
- function Unmanaged() {
264
- return (0, import_inversify.unmanaged)();
265
- }
266
- __name(Unmanaged, "Unmanaged");
348
+ // src/core/utils/di.ts
349
+ var import_inversify3 = require("inversify");
350
+ var KickInject = import_inversify3.inject;
351
+ var KickInjectable = import_inversify3.injectable;
267
352
 
268
- // src/utils/reactive.ts
269
- var import_node_crypto = require("crypto");
270
- var ReactiveRegistry2 = class {
353
+ // src/core/utils/route-mapper.ts
354
+ var RouteMapper = class _RouteMapper {
271
355
  static {
272
- __name(this, "ReactiveRegistry");
273
- }
274
- stores = /* @__PURE__ */ new Map();
275
- register(store) {
276
- this.stores.set(store.id, store);
356
+ __name(this, "RouteMapper");
277
357
  }
278
- unregister(id) {
279
- this.stores.delete(id);
358
+ /**
359
+ * Creates a contextual handler that injects request context into controller methods
360
+ * @param controller - The controller instance
361
+ * @param route - The route metadata
362
+ * @param prefix - Optional prefix to prepend to route paths
363
+ * @returns Express-compatible handler function
364
+ */
365
+ static createContextualHandler(controller, route, prefix = "") {
366
+ return (req, res, next) => {
367
+ const requestId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
368
+ const requestContext = {
369
+ req,
370
+ res,
371
+ next,
372
+ meta: {
373
+ routePath: _RouteMapper.buildRoutePath(prefix, route.path),
374
+ method: route.method,
375
+ controllerName: controller.constructor.name,
376
+ handlerName: route.handlerName,
377
+ startTime: Date.now(),
378
+ requestId
379
+ }
380
+ };
381
+ try {
382
+ const result = route.handler.call(controller, requestContext);
383
+ if (result instanceof Promise) {
384
+ result.catch((error) => {
385
+ console.error(`[${controller.constructor.name}:${route.handlerName}] Error:`, error);
386
+ if (!res.headersSent) {
387
+ res.status(500).json({
388
+ error: "Internal Server Error",
389
+ requestId: requestContext.meta.requestId
390
+ });
391
+ }
392
+ });
393
+ }
394
+ return result;
395
+ } catch (error) {
396
+ console.error(`[${controller.constructor.name}:${route.handlerName}] Error:`, error);
397
+ if (!res.headersSent) {
398
+ res.status(500).json({
399
+ error: "Internal Server Error",
400
+ requestId: requestContext.meta.requestId
401
+ });
402
+ }
403
+ }
404
+ };
280
405
  }
281
- get(id) {
282
- return this.stores.get(id);
406
+ /**
407
+ * Builds the full route path by combining prefix and route path
408
+ * @param prefix - The prefix to prepend
409
+ * @param routePath - The route path
410
+ * @returns Combined route path
411
+ */
412
+ static buildRoutePath(prefix, routePath) {
413
+ const normalizedPrefix = prefix.replace(/\/+$/, "");
414
+ const normalizedRoutePath = routePath.startsWith("/") ? routePath : `/${routePath}`;
415
+ if (!normalizedPrefix) {
416
+ return normalizedRoutePath;
417
+ }
418
+ return combineRoutePaths(normalizedPrefix, normalizedRoutePath);
283
419
  }
284
- list() {
285
- return Array.from(this.stores.values()).map((store) => ({
286
- id: store.id,
287
- label: store.label,
288
- snapshot: store.snapshot(),
289
- history: store.history()
420
+ /**
421
+ * Maps a controller to its routes with optional prefix
422
+ * @param controller - The controller instance
423
+ * @param routes - The route metadata array
424
+ * @param prefix - Optional prefix to prepend to all routes
425
+ * @returns Array of mapped route information
426
+ */
427
+ static mapControllerRoutes(controller, routes, prefix = "") {
428
+ return routes.map((route) => ({
429
+ ...route,
430
+ fullPath: _RouteMapper.buildRoutePath(prefix, route.path),
431
+ handler: _RouteMapper.createContextualHandler(controller, route, prefix),
432
+ controllerName: controller.constructor.name
290
433
  }));
291
434
  }
435
+ /**
436
+ * Logs route registration information
437
+ * @param method - HTTP method
438
+ * @param path - Route path
439
+ * @param handlerName - Handler method name
440
+ * @param controllerName - Controller class name
441
+ * @param prefix - Optional prefix used
442
+ */
443
+ static logRouteRegistration(method, path2, handlerName, controllerName, prefix) {
444
+ const _prefixInfo = prefix ? ` [prefix: ${prefix}]` : "";
445
+ }
292
446
  };
293
- function createReactive(initial, options = {}) {
294
- const listeners = /* @__PURE__ */ new Set();
295
- const target = {
296
- ...initial
297
- };
298
- const history = [];
299
- const historyEnabled = options.trackHistory ?? true;
300
- const maxHistory = options.maxHistory ?? 100;
301
- const reactiveId = options.id ?? (0, import_node_crypto.randomUUID)();
302
- const proxy = new Proxy(target, {
303
- set(current, prop, value) {
304
- if (typeof prop === "symbol") {
305
- return Reflect.set(current, prop, value);
306
- }
307
- const typedProp = prop;
308
- const previous = current[typedProp];
309
- const didChange = previous !== value;
310
- const result = Reflect.set(current, typedProp, value);
311
- if (didChange) {
312
- const change = {
313
- property: typedProp,
314
- value,
315
- previous,
316
- timestamp: Date.now()
317
- };
318
- if (historyEnabled) {
319
- history.push(change);
320
- if (history.length > maxHistory) {
321
- history.shift();
322
- }
323
- }
324
- listeners.forEach((listener) => listener(proxy, change));
325
- }
326
- return result;
327
- }
328
- });
329
- const store = {
330
- id: reactiveId,
331
- label: options.label,
332
- state: proxy,
333
- watch(watcher) {
334
- listeners.add(watcher);
335
- return () => listeners.delete(watcher);
336
- },
337
- snapshot() {
338
- return structuredClone(target);
339
- },
340
- history() {
341
- return historyEnabled ? [
342
- ...history
343
- ] : [];
344
- }
345
- };
346
- options.registry?.register(store);
347
- return store;
348
- }
349
- __name(createReactive, "createReactive");
350
447
 
351
- // src/shared/types.ts
352
- var TYPES = {
353
- AppState: Symbol.for("kick:AppState"),
354
- Config: Symbol.for("kick:Config"),
355
- Diagnostics: Symbol.for("kick:Diagnostics"),
356
- Logger: Symbol.for("kick:Logger"),
357
- StateRegistry: Symbol.for("kick:StateRegistry"),
358
- RequestTracker: Symbol.for("kick:RequestTracker")
359
- };
448
+ // src/core/utils/index.ts
449
+ init_app_config();
360
450
 
361
- // src/core/request-tracker.ts
451
+ // src/core/app/index.ts
452
+ var import_http = require("http");
453
+ var import_events = require("events");
454
+ var import_inversify4 = require("inversify");
362
455
  function _ts_decorate(decorators, target, key, desc) {
363
456
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
364
457
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -370,1459 +463,420 @@ function _ts_metadata(k, v) {
370
463
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
371
464
  }
372
465
  __name(_ts_metadata, "_ts_metadata");
373
- function _ts_param(paramIndex, decorator) {
374
- return function(target, key) {
375
- decorator(target, key, paramIndex);
376
- };
377
- }
378
- __name(_ts_param, "_ts_param");
379
- var RequestTracker = class {
466
+ var KickApp = class extends import_events.EventEmitter {
380
467
  static {
381
- __name(this, "RequestTracker");
468
+ __name(this, "KickApp");
382
469
  }
383
- registry;
470
+ context;
471
+ name;
472
+ prefix;
384
473
  config;
385
- logger;
386
- constructor(registry, config, logger) {
387
- this.registry = registry;
474
+ container;
475
+ _isInitialized = false;
476
+ _state = {};
477
+ constructor(context, name = "KickApp", prefix = "", config) {
478
+ super();
479
+ this.context = context;
480
+ this.name = name;
481
+ this.prefix = prefix;
388
482
  this.config = config;
389
- this.logger = logger;
390
- }
391
- middleware() {
392
- return (req, res, next) => {
393
- const id = (0, import_node_crypto2.randomUUID)();
394
- const requestState = createReactive({
395
- id,
396
- method: req.method,
397
- path: req.originalUrl ?? req.url,
398
- startedAt: Date.now(),
399
- logs: [],
400
- metadata: {}
401
- }, {
402
- id,
403
- label: `request:${req.method} ${req.originalUrl ?? req.url}`,
404
- registry: this.registry,
405
- trackHistory: this.config.telemetry.trackReactiveHistory,
406
- maxHistory: this.config.telemetry.requestHistoryLimit
407
- });
408
- res.locals.requestState = requestState;
409
- req.on("error", (error) => {
410
- this.recordError(res, error);
411
- });
412
- res.on("finish", () => {
413
- this.finalise(res);
414
- });
415
- res.on("close", () => {
416
- this.finalise(res);
417
- });
418
- res.on("error", (error) => {
419
- this.recordError(res, error);
420
- });
421
- next();
422
- };
423
- }
424
- get(res) {
425
- return res.locals.requestState;
426
- }
427
- log(res, message, level = "info", metadata) {
428
- const store = this.get(res);
429
- if (!store) {
430
- return;
431
- }
432
- const entry = {
433
- timestamp: Date.now(),
434
- level,
435
- message,
436
- metadata
437
- };
438
- store.state.logs = [
439
- ...store.state.logs,
440
- entry
441
- ];
442
- this.dispatchLog(level, `[${store.state.method} ${store.state.path}] ${message}`, {
443
- requestId: store.state.id,
444
- ...metadata
483
+ this.container = new import_inversify4.Container({
484
+ autobind: true
445
485
  });
446
- }
447
- mergeMetadata(res, patch) {
448
- const store = this.get(res);
449
- if (!store) {
450
- return;
451
- }
452
- store.state.metadata = {
453
- ...store.state.metadata,
454
- ...patch
455
- };
456
- }
457
- recordResponse(res, status, payload) {
458
- const store = this.get(res);
459
- if (!store) {
460
- return;
461
- }
462
- store.state.status = status;
463
- store.state.response = payload;
464
- }
465
- recordError(res, error) {
466
- const store = this.get(res);
467
- if (!store) {
468
- return;
469
- }
470
- const errorMessage = error instanceof Error ? error.message : String(error);
471
- store.state.error = errorMessage;
472
- if (isAppError(error)) {
473
- store.state.errorCode = error.code;
474
- this.mergeMetadata(res, {
475
- errorCode: error.code,
476
- errorDetails: error.details
477
- });
478
- }
479
- this.log(res, errorMessage, "error", {
480
- errorCode: isAppError(error) ? error.code : void 0
486
+ this.emit("created", {
487
+ name: this.name,
488
+ prefix: this.prefix,
489
+ config: this.config
481
490
  });
482
491
  }
483
- finalise(res) {
484
- const store = this.get(res);
485
- if (!store) {
486
- return;
487
- }
488
- store.state.status = res.statusCode;
489
- store.state.endedAt = Date.now();
490
- store.state.durationMs = store.state.endedAt - store.state.startedAt;
491
- this.dispatchLog("debug", `Request completed with ${res.statusCode}`, {
492
- requestId: store.state.id,
493
- durationMs: store.state.durationMs
494
- });
495
- }
496
- dispatchLog(level, message, metadata) {
497
- switch (level) {
498
- case "debug":
499
- this.logger.debug(message, metadata);
500
- break;
501
- case "info":
502
- this.logger.info(message, metadata);
503
- break;
504
- case "warn":
505
- this.logger.warn(message, metadata);
506
- break;
507
- case "error":
508
- this.logger.error(message, metadata);
509
- break;
510
- }
492
+ get isInitialized() {
493
+ return this._isInitialized;
511
494
  }
512
- };
513
- RequestTracker = _ts_decorate([
514
- Injectable(),
515
- _ts_param(0, Inject(TYPES.StateRegistry)),
516
- _ts_param(1, Inject(TYPES.Config)),
517
- _ts_param(2, Inject(TYPES.Logger)),
518
- _ts_metadata("design:type", Function),
519
- _ts_metadata("design:paramtypes", [
520
- typeof ReactiveRegistry === "undefined" ? Object : ReactiveRegistry,
521
- typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig,
522
- typeof AppLogger === "undefined" ? Object : AppLogger
523
- ])
524
- ], RequestTracker);
525
-
526
- // src/core/base-controller.ts
527
- function _ts_decorate2(decorators, target, key, desc) {
528
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
529
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
530
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
531
- return c > 3 && r && Object.defineProperty(target, key, r), r;
532
- }
533
- __name(_ts_decorate2, "_ts_decorate");
534
- function _ts_metadata2(k, v) {
535
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
536
- }
537
- __name(_ts_metadata2, "_ts_metadata");
538
- var BaseController = class {
539
- static {
540
- __name(this, "BaseController");
541
- }
542
- injectedTracker;
543
- runtimeTracker;
544
- ok(res, payload) {
545
- return this.respond(res, 200, payload);
546
- }
547
- created(res, payload) {
548
- return this.respond(res, 201, payload);
549
- }
550
- accepted(res, payload) {
551
- return this.respond(res, 202, payload);
552
- }
553
- noContent(res) {
554
- return this.respond(res, 204);
555
- }
556
- respond(res, status, payload) {
557
- const tracker = this.ensureTracker();
558
- tracker.recordResponse(res, status, payload);
559
- if (payload === void 0) {
560
- res.status(status).end();
561
- } else {
562
- res.status(status).json(payload);
495
+ get controllers() {
496
+ try {
497
+ return this.container.getAll(KICK_MODULE_KEYS.KickControllerType);
498
+ } catch {
499
+ return [];
563
500
  }
564
- return res;
565
501
  }
566
- logDebug(res, message, metadata) {
567
- const tracker = this.ensureTracker();
568
- tracker.log(res, `[${this.controllerId()}] ${message}`, "debug", metadata);
569
- }
570
- logInfo(res, message, metadata) {
571
- const tracker = this.ensureTracker();
572
- tracker.log(res, `[${this.controllerId()}] ${message}`, "info", metadata);
573
- }
574
- logWarn(res, message, metadata) {
575
- const tracker = this.ensureTracker();
576
- tracker.log(res, `[${this.controllerId()}] ${message}`, "warn", metadata);
577
- }
578
- logError(res, message, metadata) {
579
- const tracker = this.ensureTracker();
580
- tracker.log(res, `[${this.controllerId()}] ${message}`, "error", metadata);
581
- }
582
- mergeRequestMetadata(res, patch) {
583
- const tracker = this.ensureTracker();
584
- const current = tracker.get(res)?.state.metadata[this.controllerId()];
585
- const currentRecord = typeof current === "object" && current !== null ? current : {};
586
- const namespacedPatch = {
587
- [this.controllerId()]: {
588
- ...currentRecord,
589
- ...patch
590
- }
502
+ get state() {
503
+ return {
504
+ ...this._state
591
505
  };
592
- tracker.mergeMetadata(res, namespacedPatch);
593
506
  }
594
- getRequestState(res) {
595
- return this.ensureTracker().get(res)?.state;
596
- }
597
- fail(code, message, options) {
598
- throw createError(code, message, options);
507
+ setState(key, value) {
508
+ const oldValue = this._state[key];
509
+ this._state[key] = value;
510
+ this.emit("state:changed", {
511
+ key,
512
+ value,
513
+ oldValue
514
+ });
515
+ this.emit(`state:${key}`, {
516
+ value,
517
+ oldValue
518
+ });
599
519
  }
600
- attachRequestTracker(tracker) {
601
- this.runtimeTracker = tracker;
520
+ getState(key) {
521
+ return this._state[key];
602
522
  }
603
- ensureTracker() {
604
- if (this.runtimeTracker) {
605
- return this.runtimeTracker;
606
- }
607
- if (this.injectedTracker) {
608
- this.runtimeTracker = this.injectedTracker;
609
- return this.runtimeTracker;
610
- }
611
- throw createError("TRACKER_MISSING", "RequestTracker is not available on this controller");
523
+ onStateChange(key, listener) {
524
+ this.on(`state:${key}`, listener);
612
525
  }
613
- };
614
- _ts_decorate2([
615
- Inject(TYPES.RequestTracker),
616
- _ts_metadata2("design:type", typeof RequestTracker === "undefined" ? Object : RequestTracker)
617
- ], BaseController.prototype, "injectedTracker", void 0);
618
- BaseController = _ts_decorate2([
619
- Injectable()
620
- ], BaseController);
621
-
622
- // src/core/http-controllers.ts
623
- var VERB_CONTROLLER_SYMBOL = Symbol.for("kick:core:verb-controller");
624
- var HttpVerbController = class extends BaseController {
625
- static {
626
- __name(this, "HttpVerbController");
526
+ offStateChange(key, listener) {
527
+ this.off(`state:${key}`, listener);
627
528
  }
628
529
  /**
629
- * Return the HTTP method associated with this controller. Static so discovery can consume it
630
- * without instantiating the controller (which would require container dependencies).
631
- */
632
- static method() {
633
- throw new Error("HttpVerbController.method() must be implemented by subclasses");
530
+ * Get a configuration value by key path (supports nested access like 'database.host')
531
+ */
532
+ getConfig(key) {
533
+ if (!this.config) return void 0;
534
+ if (!key) return this.config;
535
+ return key.split(".").reduce((obj, k) => obj?.[k], this.config);
634
536
  }
635
- /** HTTP method instance mirror for convenience in handlers/tests. */
636
- httpMethod = this.constructor.method();
637
537
  /**
638
- * Optional static override for the route path. When provided, discovery will use this value
639
- * instead of deriving the path from the file-system location.
640
- */
641
- static route;
642
- /**
643
- * Optional static tags collection. These map to the controller metadata and can be used by
644
- * diagnostics tooling.
645
- */
646
- static tags;
647
- controllerId() {
648
- return this.constructor.name;
649
- }
650
- };
651
- Object.defineProperty(HttpVerbController, VERB_CONTROLLER_SYMBOL, {
652
- value: true,
653
- enumerable: false,
654
- configurable: false,
655
- writable: false
656
- });
657
- var GetController = class extends HttpVerbController {
658
- static {
659
- __name(this, "GetController");
660
- }
661
- static method() {
662
- return "get";
663
- }
664
- };
665
- var PostController = class extends HttpVerbController {
666
- static {
667
- __name(this, "PostController");
668
- }
669
- static method() {
670
- return "post";
671
- }
672
- };
673
- var PutController = class extends HttpVerbController {
674
- static {
675
- __name(this, "PutController");
676
- }
677
- static method() {
678
- return "put";
538
+ * Check if a configuration key exists
539
+ */
540
+ hasConfig(key) {
541
+ return this.getConfig(key) !== void 0;
679
542
  }
680
- };
681
- var PatchController = class extends HttpVerbController {
682
- static {
683
- __name(this, "PatchController");
684
- }
685
- static method() {
686
- return "patch";
687
- }
688
- };
689
- var DeleteController = class extends HttpVerbController {
690
- static {
691
- __name(this, "DeleteController");
692
- }
693
- static method() {
694
- return "delete";
695
- }
696
- };
697
- function isVerbController(constructor) {
698
- if (typeof constructor !== "function") {
699
- return false;
700
- }
701
- return Boolean(constructor[VERB_CONTROLLER_SYMBOL]);
702
- }
703
- __name(isVerbController, "isVerbController");
704
-
705
- // src/core/controller-discovery.ts
706
- var import_node_fs = require("fs");
707
- var import_node_path = __toESM(require("path"));
708
- var import_reflect_metadata2 = require("reflect-metadata");
709
- var HTTP_METHODS = [
710
- "get",
711
- "post",
712
- "put",
713
- "patch",
714
- "delete"
715
- ];
716
- var tsNodeRegistered = false;
717
- function discoverControllersFromFilesystem(config) {
718
- if (!config.enabled) {
719
- return [];
720
- }
721
- const discovered = [];
722
- const seen = /* @__PURE__ */ new Map();
723
- const resolvedRoots = config.roots.map((root) => import_node_path.default.isAbsolute(root) ? root : import_node_path.default.join(process.cwd(), root));
724
- resolvedRoots.forEach((root) => {
725
- if (!safeExistsSync(root)) {
726
- return;
727
- }
728
- traverseDirectory(root, root, [], config, (filePath, dirSegments) => {
729
- const discovery = interpretControllerFile(root, filePath, dirSegments, config);
730
- if (!discovery) {
731
- return;
732
- }
733
- const key = `${discovery.method}:${discovery.route}`;
734
- if (seen.has(key)) {
735
- throw createError("ROUTE_CONFLICT", `Duplicate discovered route for [${discovery.method.toUpperCase()}] ${discovery.route}`, {
736
- details: {
737
- existing: seen.get(key),
738
- duplicate: filePath
739
- }
740
- });
741
- }
742
- seen.set(key, filePath);
743
- annotateController(discovery.controller, discovery.route, discovery.method, discovery.tags);
744
- if (config.registerGlobally) {
745
- registerController(discovery.controller);
746
- }
747
- discovered.push(discovery);
748
- });
749
- });
750
- return discovered;
751
- }
752
- __name(discoverControllersFromFilesystem, "discoverControllersFromFilesystem");
753
- function traverseDirectory(root, directory, segments, config, onFile) {
754
- const entries = (0, import_node_fs.readdirSync)(directory, {
755
- withFileTypes: true
756
- });
757
- entries.forEach((entry) => {
758
- if (shouldIgnore(entry.name, config)) {
759
- return;
760
- }
761
- const entryPath = import_node_path.default.join(directory, entry.name);
762
- if (entry.isDirectory()) {
763
- traverseDirectory(root, entryPath, [
764
- ...segments,
765
- entry.name
766
- ], config, onFile);
767
- return;
768
- }
769
- if (!entry.isFile()) {
770
- return;
771
- }
772
- onFile(entryPath, segments);
773
- });
774
- }
775
- __name(traverseDirectory, "traverseDirectory");
776
- function interpretControllerFile(root, filePath, dirSegments, config) {
777
- const ext = import_node_path.default.extname(filePath);
778
- if (!config.extensions.includes(ext)) {
779
- return void 0;
780
- }
781
- const relative = import_node_path.default.relative(root, filePath);
782
- const fileName = import_node_path.default.basename(relative, ext);
783
- const normalized = stripSuffix(fileName, config.suffix);
784
- const { slug, method } = extractSlugAndMethod(normalized, config);
785
- if (!slug || !method) {
786
- if (config.enforceStructure) {
787
- throw createError("INVALID_CONTROLLER_STRUCTURE", `Controller file ${relative} must follow <name>.<verb>${config.suffix}${ext}`);
543
+ /**
544
+ * Get config value with fallback
545
+ */
546
+ getConfigOrDefault(key, defaultValue) {
547
+ const value = this.getConfig(key);
548
+ return value !== void 0 ? value : defaultValue;
549
+ }
550
+ loadPlugin(plugins) {
551
+ if (!Array.isArray(plugins)) {
552
+ plugins = [
553
+ plugins
554
+ ];
788
555
  }
789
- return void 0;
790
- }
791
- const controllerConstructor = loadController(filePath);
792
- if (!controllerConstructor) {
793
- return void 0;
794
- }
795
- if (!isVerbController(controllerConstructor)) {
796
- throw createError("INVALID_VERB_CONTROLLER", `Discovered controller ${controllerConstructor.name || filePath} must extend HttpVerbController.`);
797
- }
798
- const VerbController = controllerConstructor;
799
- const methodFromClass = VerbController.method();
800
- if (methodFromClass !== method) {
801
- throw createError("VERB_MISMATCH", `Controller ${VerbController.name} declares ${methodFromClass.toUpperCase()} but file name enforces ${method.toUpperCase()}.`, {
802
- details: {
803
- filePath
804
- }
556
+ plugins.forEach((plugin) => {
557
+ plugin.install(this.context);
558
+ this.emit("plugin:loaded", {
559
+ plugin
560
+ });
805
561
  });
562
+ return this;
806
563
  }
807
- const derivedSegments = buildRouteSegments(dirSegments, slug, config);
808
- const baseSegments = toSegments(config.baseRoute);
809
- const override = config.allowStaticRoutes ? extractStaticRoute(VerbController) : void 0;
810
- const overrideSegments = override ? toSegments(override.startsWith("/") ? override : joinSegments([
811
- ...baseSegments,
812
- override
813
- ])) : void 0;
814
- const finalSegments = overrideSegments ?? [
815
- ...baseSegments,
816
- ...derivedSegments
817
- ];
818
- const route = normalizeRoute(finalSegments);
819
- const tags = buildTags(VerbController, dirSegments, config);
820
- return {
821
- controller: controllerConstructor,
822
- filePath,
823
- route,
824
- method,
825
- tags
826
- };
827
- }
828
- __name(interpretControllerFile, "interpretControllerFile");
829
- function buildTags(controller, dirSegments, config) {
830
- const staticTags = Array.isArray(controller.tags) ? controller.tags : [];
831
- if (!config.tagsFromDirectories) {
832
- return [
833
- ...new Set(staticTags)
834
- ];
835
- }
836
- const derived = dirSegments.filter(Boolean).map((segment) => segment.replace(/[^A-Za-z0-9]/g, "-").toLowerCase());
837
- return [
838
- .../* @__PURE__ */ new Set([
839
- ...staticTags,
840
- ...derived
841
- ])
842
- ];
843
- }
844
- __name(buildTags, "buildTags");
845
- function extractStaticRoute(controller) {
846
- const route = controller.route;
847
- if (!route) {
848
- return void 0;
849
- }
850
- return route;
851
- }
852
- __name(extractStaticRoute, "extractStaticRoute");
853
- function buildRouteSegments(dirSegments, slugSegments, config) {
854
- const directoryParts = dirSegments.flatMap((segment) => interpretSegment(segment, false));
855
- const slugParts = slugSegments.flatMap((segment, index) => interpretSegment(segment, true, index === slugSegments.length - 1));
856
- const segments = [
857
- ...directoryParts,
858
- ...slugParts
859
- ];
860
- if (segments.length === 0) {
861
- return [
862
- "/"
863
- ];
864
- }
865
- return segments;
866
- }
867
- __name(buildRouteSegments, "buildRouteSegments");
868
- function interpretSegment(segment, fromFile, isLastFilePart = false) {
869
- if (!segment) {
870
- return [];
871
- }
872
- if (segment === "index" && fromFile && isLastFilePart) {
873
- return [];
874
- }
875
- const dynamic = segment.match(/^\[(\.\.\.)?(.+)]$/);
876
- if (dynamic) {
877
- const [, spread, name] = dynamic;
878
- if (spread) {
879
- return [
880
- `:${name}*`
564
+ registerMiddleware(middleware) {
565
+ if (!Array.isArray(middleware)) {
566
+ middleware = [
567
+ middleware
881
568
  ];
882
569
  }
883
- return [
884
- `:${name}`
885
- ];
886
- }
887
- return [
888
- segment
889
- ];
890
- }
891
- __name(interpretSegment, "interpretSegment");
892
- function normalizeRoute(segments) {
893
- const filtered = segments.flat().map((segment) => segment.trim()).filter((segment) => segment && segment !== "/");
894
- if (filtered.length === 0) {
895
- return "/";
896
- }
897
- return `/${filtered.join("/")}`.replace(/\/+/g, "/");
898
- }
899
- __name(normalizeRoute, "normalizeRoute");
900
- function stripSuffix(fileName, suffix) {
901
- if (!suffix) {
902
- return fileName;
903
- }
904
- return fileName.endsWith(suffix) ? fileName.slice(0, -suffix.length) : fileName;
905
- }
906
- __name(stripSuffix, "stripSuffix");
907
- function extractSlugAndMethod(fileName, config) {
908
- const parts = fileName.split(".").filter(Boolean);
909
- if (parts.length === 0) {
910
- return {
911
- slug: void 0,
912
- method: void 0
913
- };
914
- }
915
- const potentialMethod = parts[parts.length - 1].toLowerCase();
916
- if (!HTTP_METHODS.includes(potentialMethod)) {
917
- return {
918
- slug: void 0,
919
- method: void 0
920
- };
921
- }
922
- const slugString = fileName.slice(0, fileName.length - potentialMethod.length - 1);
923
- const slugSegments = slugString ? slugString.split(config.segmentSeparator).filter(Boolean) : [
924
- "index"
925
- ];
926
- return {
927
- slug: slugSegments,
928
- method: potentialMethod
929
- };
930
- }
931
- __name(extractSlugAndMethod, "extractSlugAndMethod");
932
- function loadController(filePath) {
933
- const ext = import_node_path.default.extname(filePath);
934
- if (ext === ".ts" || ext === ".tsx") {
935
- ensureTsNode();
936
- }
937
- const required = require(filePath);
938
- const exported = required?.default ?? required?.Controller ?? pickFirstConstructor(required);
939
- if (typeof exported !== "function") {
940
- return void 0;
941
- }
942
- return exported;
943
- }
944
- __name(loadController, "loadController");
945
- function pickFirstConstructor(exportsObject) {
946
- if (!exportsObject || typeof exportsObject !== "object") {
947
- return void 0;
948
- }
949
- return Object.values(exportsObject).find((value) => typeof value === "function");
950
- }
951
- __name(pickFirstConstructor, "pickFirstConstructor");
952
- function ensureTsNode() {
953
- if (tsNodeRegistered) {
954
- return;
955
- }
956
- try {
957
- require("ts-node/register");
958
- tsNodeRegistered = true;
959
- } catch (error) {
960
- throw createError("TS_NODE_REQUIRED", "Unable to load TypeScript controllers. Install ts-node or run with a TS-aware runner.");
961
- }
962
- }
963
- __name(ensureTsNode, "ensureTsNode");
964
- function shouldIgnore(name, config) {
965
- if (!name) {
966
- return true;
967
- }
968
- if (name.startsWith(".")) {
969
- return true;
970
- }
971
- return config.ignore.includes(name);
972
- }
973
- __name(shouldIgnore, "shouldIgnore");
974
- function safeExistsSync(target) {
975
- try {
976
- const stats = (0, import_node_fs.statSync)(target);
977
- return stats.isDirectory();
978
- } catch (error) {
979
- return false;
980
- }
981
- }
982
- __name(safeExistsSync, "safeExistsSync");
983
- function toSegments(value) {
984
- if (!value || value === "/") {
985
- return [];
986
- }
987
- return value.split("/").map((segment) => segment.trim()).filter(Boolean);
988
- }
989
- __name(toSegments, "toSegments");
990
- function joinSegments(segments) {
991
- return segments.filter(Boolean).join("/");
992
- }
993
- __name(joinSegments, "joinSegments");
994
- function annotateController(controller, route, method, tags) {
995
- const basePath = route === "/" ? "/" : route;
996
- Reflect.defineMetadata(DecoratorMetadata.CONTROLLER_KEY, {
997
- basePath,
998
- tags
999
- }, controller);
1000
- const handleKey = "handle";
1001
- const descriptor = controller.prototype?.[handleKey];
1002
- if (typeof descriptor !== "function") {
1003
- throw createError("INVALID_CONTROLLER_HANDLER", `Controller ${controller.name || "[anonymous]"} must implement a handle method.`);
1004
- }
1005
- const routes = [
1006
- {
1007
- method,
1008
- path: "",
1009
- propertyKey: handleKey,
1010
- middlewares: []
1011
- }
1012
- ];
1013
- Reflect.defineMetadata(DecoratorMetadata.ROUTES_KEY, routes, controller);
1014
- }
1015
- __name(annotateController, "annotateController");
1016
-
1017
- // src/core/diagnostics.ts
1018
- function _ts_decorate3(decorators, target, key, desc) {
1019
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1020
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1021
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1022
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1023
- }
1024
- __name(_ts_decorate3, "_ts_decorate");
1025
- function _ts_metadata3(k, v) {
1026
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1027
- }
1028
- __name(_ts_metadata3, "_ts_metadata");
1029
- function _ts_param2(paramIndex, decorator) {
1030
- return function(target, key) {
1031
- decorator(target, key, paramIndex);
1032
- };
1033
- }
1034
- __name(_ts_param2, "_ts_param");
1035
- var AppDiagnostics = class {
1036
- static {
1037
- __name(this, "AppDiagnostics");
1038
- }
1039
- registry;
1040
- config;
1041
- constructor(registry, config) {
1042
- this.registry = registry;
1043
- this.config = config;
1044
- }
1045
- settings() {
1046
- return this.config;
1047
- }
1048
- stores() {
1049
- return this.registry.list().map((entry) => ({
1050
- id: entry.id,
1051
- label: entry.label,
1052
- snapshot: entry.snapshot,
1053
- history: entry.history
1054
- }));
1055
- }
1056
- requests() {
1057
- return this.registry.list().filter((entry) => entry.label?.startsWith("request:")).map((entry) => entry.snapshot);
1058
- }
1059
- };
1060
- AppDiagnostics = _ts_decorate3([
1061
- Injectable(),
1062
- _ts_param2(0, Inject(TYPES.StateRegistry)),
1063
- _ts_param2(1, Inject(TYPES.Config)),
1064
- _ts_metadata3("design:type", Function),
1065
- _ts_metadata3("design:paramtypes", [
1066
- typeof ReactiveRegistry2 === "undefined" ? Object : ReactiveRegistry2,
1067
- typeof ResolvedAppConfig === "undefined" ? Object : ResolvedAppConfig
1068
- ])
1069
- ], AppDiagnostics);
1070
-
1071
- // src/core/application.ts
1072
- var import_reflect_metadata4 = require("reflect-metadata");
1073
- var import_express = __toESM(require("express"));
1074
-
1075
- // src/core/server.ts
1076
- var import_node_crypto3 = require("crypto");
1077
- var import_reflect_metadata3 = require("reflect-metadata");
1078
- var appRouteRegistry = /* @__PURE__ */ new WeakMap();
1079
- function registerControllers(app, container, options = {}) {
1080
- const controllers = options.controllers ?? listRegisteredControllers();
1081
- const prefix = options.prefix ?? "";
1082
- const requestTracker = container.get(TYPES.RequestTracker);
1083
- controllers.forEach((ControllerClass) => {
1084
- ensureInjectable(ControllerClass);
1085
- const controllerMetadata = Reflect.getMetadata(DecoratorMetadata.CONTROLLER_KEY, ControllerClass);
1086
- if (!controllerMetadata) {
1087
- return;
1088
- }
1089
- if (!container.isBound(ControllerClass)) {
1090
- container.bind(ControllerClass).toSelf().inSingletonScope();
1091
- }
1092
- const instance = container.get(ControllerClass);
1093
- attachRequestTracker(instance, requestTracker);
1094
- const routes = Reflect.getMetadata(DecoratorMetadata.ROUTES_KEY, ControllerClass) ?? [];
1095
- routes.forEach((route) => {
1096
- const handler = instance[route.propertyKey];
1097
- if (typeof handler !== "function") {
1098
- throw new Error(`Route handler ${String(route.propertyKey)} on ${ControllerClass.name} is not a function`);
1099
- }
1100
- const fullPath = buildRoutePath(prefix, controllerMetadata.basePath, route.path);
1101
- const routeHash = registerRouteSignature(app, route.method, fullPath, ControllerClass.name, route.propertyKey);
1102
- const boundHandler = handler.bind(instance);
1103
- const validationMiddleware = buildValidationMiddleware(route.validation);
1104
- const routeMetadataMiddleware = /* @__PURE__ */ __name((_req, res, next) => {
1105
- requestTracker.mergeMetadata(res, {
1106
- route: fullPath,
1107
- method: route.method.toUpperCase(),
1108
- routeHash
1109
- });
1110
- next();
1111
- }, "routeMetadataMiddleware");
1112
- const pipeline = [
1113
- routeMetadataMiddleware,
1114
- ...validationMiddleware,
1115
- ...route.middlewares
1116
- ];
1117
- app[route.method](fullPath, ...pipeline, async (req, res, next) => {
1118
- try {
1119
- const result = await Promise.resolve(boundHandler(req, res, next));
1120
- if (result !== void 0 && !res.headersSent) {
1121
- res.json(result);
1122
- }
1123
- } catch (error) {
1124
- next(error);
1125
- }
1126
- });
570
+ const sortedMiddleware = middleware.sort((a, b) => {
571
+ const metadataA = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, a.constructor) || {
572
+ priority: 0
573
+ };
574
+ const metadataB = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, b.constructor) || {
575
+ priority: 0
576
+ };
577
+ return metadataA.priority - metadataB.priority;
1127
578
  });
1128
- });
1129
- }
1130
- __name(registerControllers, "registerControllers");
1131
- function ensureInjectable(constructor) {
1132
- if (!Reflect.hasOwnMetadata("inversify:paramtypes", constructor)) {
1133
- Injectable()(constructor);
1134
- }
1135
- }
1136
- __name(ensureInjectable, "ensureInjectable");
1137
- function attachRequestTracker(instance, tracker) {
1138
- const attach = instance.attachRequestTracker;
1139
- if (typeof attach !== "function") {
1140
- return;
1141
- }
1142
- attach.call(instance, tracker);
1143
- }
1144
- __name(attachRequestTracker, "attachRequestTracker");
1145
- function buildRoutePath(prefix, basePath, routePath) {
1146
- const segments = [
1147
- ...toSegments2(prefix),
1148
- ...toSegments2(basePath),
1149
- ...toSegments2(routePath)
1150
- ];
1151
- if (segments.length === 0) {
1152
- return "/";
1153
- }
1154
- return `/${segments.join("/")}`;
1155
- }
1156
- __name(buildRoutePath, "buildRoutePath");
1157
- function toSegments2(segment) {
1158
- if (!segment || segment === "/") {
1159
- return [];
1160
- }
1161
- const trimmed = segment.replace(/^\/+|\/+$/g, "");
1162
- return trimmed ? [
1163
- trimmed
1164
- ] : [];
1165
- }
1166
- __name(toSegments2, "toSegments");
1167
- function registerRouteSignature(app, method, path3, controllerName, propertyKey) {
1168
- let registry = appRouteRegistry.get(app);
1169
- if (!registry) {
1170
- registry = /* @__PURE__ */ new Set();
1171
- appRouteRegistry.set(app, registry);
1172
- }
1173
- const normalized = `${method.toLowerCase()}:${path3.toLowerCase()}`;
1174
- const hash = (0, import_node_crypto3.createHash)("sha256").update(normalized).digest("hex");
1175
- if (registry.has(hash)) {
1176
- throw createError("ROUTE_CONFLICT", `Duplicate route detected for [${method.toUpperCase()}] ${path3}`, {
1177
- details: {
1178
- controller: controllerName,
1179
- handler: String(propertyKey)
579
+ this.context.middlewares.push(...sortedMiddleware);
580
+ sortedMiddleware.forEach((mw) => {
581
+ const metadata = Reflect.getMetadata(KICK_CONTROLLER_METADATA_KEYS.middlewareOptions, mw.constructor);
582
+ if (metadata) {
583
+ this.emit("middleware:registered:detailed", {
584
+ middleware: mw,
585
+ metadata,
586
+ className: mw.constructor.name
587
+ });
588
+ } else {
589
+ console.log(`[KickApp]: Registered global middleware: ${mw.constructor.name}`);
1180
590
  }
1181
591
  });
592
+ this.emit("middleware:registered", {
593
+ count: sortedMiddleware.length
594
+ });
595
+ return this;
1182
596
  }
1183
- registry.add(hash);
1184
- return hash;
1185
- }
1186
- __name(registerRouteSignature, "registerRouteSignature");
1187
- function buildValidationMiddleware(validation) {
1188
- if (!validation) {
1189
- return [];
597
+ mountMiddlewares() {
598
+ this.context.middlewares.forEach((middleware) => {
599
+ this.context.app.use(middleware.use);
600
+ });
601
+ this.emit("middlewares:mounted", {
602
+ count: this.context.middlewares.length
603
+ });
604
+ return this;
1190
605
  }
1191
- const middleware = /* @__PURE__ */ __name((req, _res, next) => {
606
+ loadModules(modules) {
607
+ modules.forEach((module2) => {
608
+ module2.install(this.container);
609
+ this.emit("module:loaded", {
610
+ module: module2.name
611
+ });
612
+ });
613
+ this.extractMiddlewaresFromContainer();
614
+ this.mapControllers();
615
+ this._isInitialized = true;
616
+ this.setState("isInitialized", true);
617
+ this.setState("modulesCount", modules.length);
618
+ this.emit("initialized", this.getStats());
619
+ return this;
620
+ }
621
+ extractMiddlewaresFromContainer() {
1192
622
  try {
1193
- if (validation.params) {
1194
- req.params = runSchema(validation.params, req.params, "params");
1195
- }
1196
- if (validation.query) {
1197
- req.query = runSchema(validation.query, req.query, "query");
623
+ const middlewares = this.container.getAll(KICK_MODULE_KEYS.KickMiddlewareType);
624
+ if (middlewares.length > 0) {
625
+ this.registerMiddleware(middlewares);
1198
626
  }
1199
- if (validation.body) {
1200
- req.body = runSchema(validation.body, req.body, "body");
1201
- }
1202
- next();
1203
- } catch (error) {
1204
- next(error);
1205
- }
1206
- }, "middleware");
1207
- return [
1208
- middleware
1209
- ];
1210
- }
1211
- __name(buildValidationMiddleware, "buildValidationMiddleware");
1212
- function runSchema(schema, value, target) {
1213
- if (isZodSchema(schema)) {
1214
- if (typeof schema.safeParse === "function") {
1215
- const result = schema.safeParse(value);
1216
- if (!result.success) {
1217
- const issues = Array.isArray(result.error?.issues) ? result.error.issues.map((issue) => issue.message) : [
1218
- result.error.message
1219
- ].filter(Boolean);
1220
- throw validationError(target, issues);
1221
- }
1222
- return result.data;
627
+ } catch {
628
+ console.warn("[KickApp]: No middlewares found in DI container");
1223
629
  }
630
+ }
631
+ mapControllers() {
1224
632
  try {
1225
- return schema.parse(value);
633
+ const controllers = this.container.getAll(KICK_MODULE_KEYS.KickControllerType);
634
+ let routeCount = 0;
635
+ controllers.forEach((controller) => {
636
+ const routes = mapController(controller);
637
+ const mappedRoutes = RouteMapper.mapControllerRoutes(controller, routes, this.prefix);
638
+ mappedRoutes.forEach((mappedRoute) => {
639
+ const expressMethod = mappedRoute.method.toLowerCase();
640
+ if (typeof this.context.app[expressMethod] === "function") {
641
+ RouteMapper.logRouteRegistration(mappedRoute.method, mappedRoute.fullPath, mappedRoute.handlerName, mappedRoute.controllerName, this.prefix || void 0);
642
+ this.context.app[expressMethod](mappedRoute.fullPath, mappedRoute.handler);
643
+ this.context.requestHandlers[`${mappedRoute.method}:${mappedRoute.fullPath}`] = {
644
+ ...mappedRoute,
645
+ path: mappedRoute.fullPath
646
+ };
647
+ this.emit("route:registered", {
648
+ method: mappedRoute.method,
649
+ path: mappedRoute.fullPath,
650
+ handler: mappedRoute.handlerName,
651
+ controller: mappedRoute.controllerName,
652
+ prefix: this.prefix
653
+ });
654
+ routeCount++;
655
+ }
656
+ });
657
+ this.emit("controller:mapped", {
658
+ controller: controller.constructor.name,
659
+ routeCount: mappedRoutes.length,
660
+ prefix: this.prefix
661
+ });
662
+ });
663
+ this.setState("controllersCount", controllers.length);
664
+ this.setState("routesCount", routeCount);
665
+ this.setState("routePrefix", this.prefix);
1226
666
  } catch (error) {
1227
- const issues = extractErrorMessages(error);
1228
- throw validationError(target, issues);
1229
- }
1230
- }
1231
- if (isJoiSchema(schema)) {
1232
- const { error, value: validated } = schema.validate(value, {
1233
- abortEarly: false,
1234
- stripUnknown: true
1235
- });
1236
- if (error) {
1237
- throw validationError(target, error.details?.map((detail) => detail.message));
1238
- }
1239
- return validated;
1240
- }
1241
- throw createError("VALIDATION_UNSUPPORTED", "Unsupported validation schema provided", {
1242
- details: {
1243
- target
1244
- }
1245
- });
1246
- }
1247
- __name(runSchema, "runSchema");
1248
- function isZodSchema(schema) {
1249
- if (typeof schema !== "object" || schema === null) {
1250
- return false;
1251
- }
1252
- return typeof schema.safeParse === "function" || typeof schema.parse === "function";
1253
- }
1254
- __name(isZodSchema, "isZodSchema");
1255
- function isJoiSchema(schema) {
1256
- if (typeof schema !== "object" || schema === null) {
1257
- return false;
1258
- }
1259
- return typeof schema.validate === "function";
1260
- }
1261
- __name(isJoiSchema, "isJoiSchema");
1262
- function validationError(target, issues) {
1263
- return createError("VALIDATION_ERROR", `Invalid ${target}`, {
1264
- status: 400,
1265
- details: {
1266
- target,
1267
- issues: issues?.filter((issue) => Boolean(issue))
667
+ this.emit("error", {
668
+ type: "controller-mapping",
669
+ error
670
+ });
1268
671
  }
1269
- });
1270
- }
1271
- __name(validationError, "validationError");
1272
- function extractErrorMessages(error) {
1273
- if (!error) {
1274
- return [];
1275
672
  }
1276
- if (Array.isArray(error.issues)) {
1277
- return error.issues.map((issue) => issue.message);
673
+ getContainer() {
674
+ return this.container;
1278
675
  }
1279
- if (error instanceof Error && error.message) {
1280
- return [
1281
- error.message
1282
- ];
1283
- }
1284
- return [
1285
- String(error)
1286
- ];
1287
- }
1288
- __name(extractErrorMessages, "extractErrorMessages");
1289
-
1290
- // src/infrastructure/container.ts
1291
- var import_inversify2 = require("inversify");
1292
-
1293
- // src/utils/logger.ts
1294
- var LEVEL_WEIGHT = {
1295
- debug: 10,
1296
- info: 20,
1297
- warn: 30,
1298
- error: 40
1299
- };
1300
- var ConsoleLogger = class {
1301
- static {
1302
- __name(this, "ConsoleLogger");
1303
- }
1304
- level;
1305
- constructor(level = "info") {
1306
- this.level = level;
1307
- }
1308
- debug(message, metadata) {
1309
- this.log("debug", message, metadata);
1310
- }
1311
- info(message, metadata) {
1312
- this.log("info", message, metadata);
1313
- }
1314
- warn(message, metadata) {
1315
- this.log("warn", message, metadata);
676
+ getStats() {
677
+ return {
678
+ name: this.name,
679
+ isInitialized: this._isInitialized,
680
+ controllersCount: this.controllers.length,
681
+ middlewaresCount: this.context.middlewares.length,
682
+ routes: Object.keys(this.context.requestHandlers),
683
+ routesCount: Object.keys(this.context.requestHandlers).length,
684
+ state: this.state
685
+ };
1316
686
  }
1317
- error(message, metadata) {
1318
- this.log("error", message, metadata);
687
+ addErrorHandler(handler) {
688
+ this.on("error", handler);
1319
689
  }
1320
- log(level, message, metadata) {
1321
- if (!this.shouldLog(level)) {
1322
- return;
1323
- }
1324
- const payload = metadata ? [
1325
- message,
1326
- metadata
1327
- ] : [
1328
- message
1329
- ];
1330
- switch (level) {
1331
- case "debug":
1332
- console.debug(...payload);
1333
- break;
1334
- case "info":
1335
- console.info(...payload);
1336
- break;
1337
- case "warn":
1338
- console.warn(...payload);
1339
- break;
1340
- case "error":
1341
- console.error(...payload);
1342
- break;
1343
- }
690
+ handleError(error, context) {
691
+ this.emit("error", {
692
+ error,
693
+ context,
694
+ timestamp: Date.now()
695
+ });
1344
696
  }
1345
- shouldLog(level) {
1346
- return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.level];
697
+ addRequestInterceptor(interceptor) {
698
+ this.context.app.use((req, res, next) => {
699
+ try {
700
+ interceptor(req, res, next);
701
+ } catch (error) {
702
+ this.handleError(error, {
703
+ req: req.url,
704
+ method: req.method
705
+ });
706
+ next(error);
707
+ }
708
+ });
1347
709
  }
1348
710
  };
1349
- function createLogger(config = {}) {
1350
- return new ConsoleLogger(config.level);
1351
- }
1352
- __name(createLogger, "createLogger");
1353
-
1354
- // src/infrastructure/container.ts
1355
- function buildContainer(resolvedConfig) {
1356
- const container = new import_inversify2.Container({
1357
- defaultScope: "Singleton"
711
+ KickApp = _ts_decorate([
712
+ AutoBind,
713
+ _ts_metadata("design:type", Function),
714
+ _ts_metadata("design:paramtypes", [
715
+ typeof KickApplicationContext === "undefined" ? Object : KickApplicationContext,
716
+ String,
717
+ String,
718
+ typeof KickAppConfig === "undefined" ? Object : KickAppConfig
719
+ ])
720
+ ], KickApp);
721
+ function createKickApp(options) {
722
+ const appContext = {
723
+ requestHandlers: {},
724
+ middlewares: [],
725
+ app: options.app
726
+ };
727
+ const kickApp = new KickApp(appContext, options.name || "KickApp", options.prefix || "", options.config);
728
+ if (kickApp.config) {
729
+ }
730
+ if (options.plugins) {
731
+ kickApp.loadPlugin(options.plugins);
732
+ }
733
+ if (options.globalMiddlewares) {
734
+ kickApp.registerMiddleware(options.globalMiddlewares);
735
+ }
736
+ kickApp.loadModules(options.modules);
737
+ kickApp.mountMiddlewares();
738
+ const server = (0, import_http.createServer)(kickApp.context.app);
739
+ const kickServer = {
740
+ // Server methods
741
+ listen: server.listen.bind(server),
742
+ close: server.close.bind(server),
743
+ address: server.address.bind(server),
744
+ getConnections: server.getConnections.bind(server),
745
+ on: server.on.bind(server),
746
+ off: server.off.bind(server),
747
+ emit: server.emit.bind(server),
748
+ // KickApp instance and methods
749
+ kickApp,
750
+ app: kickApp.context.app,
751
+ // Convenience methods
752
+ getStats: /* @__PURE__ */ __name(() => kickApp.getStats(), "getStats"),
753
+ getState: /* @__PURE__ */ __name(() => kickApp.state, "getState"),
754
+ setState: /* @__PURE__ */ __name((key, value) => kickApp.setState(key, value), "setState"),
755
+ onStateChange: /* @__PURE__ */ __name((key, listener) => kickApp.onStateChange(key, listener), "onStateChange"),
756
+ onKickEvent: /* @__PURE__ */ __name((event, listener) => kickApp.on(event, listener), "onKickEvent"),
757
+ offKickEvent: /* @__PURE__ */ __name((event, listener) => kickApp.off(event, listener), "offKickEvent"),
758
+ emitKickEvent: /* @__PURE__ */ __name((event, data) => kickApp.emit(event, data), "emitKickEvent"),
759
+ addErrorHandler: /* @__PURE__ */ __name((handler) => kickApp.addErrorHandler(handler), "addErrorHandler"),
760
+ handleError: /* @__PURE__ */ __name((error, context) => kickApp.handleError(error, context), "handleError")
761
+ };
762
+ kickServer.addErrorHandler((errorData) => {
763
+ console.error(`[Server:${kickApp.name}] Unhandled error:`, errorData);
1358
764
  });
1359
- const registry = new ReactiveRegistry2();
1360
- container.bind(TYPES.StateRegistry).toConstantValue(registry);
1361
- container.bind(TYPES.Config).toConstantValue(resolvedConfig);
1362
- container.bind(TYPES.Logger).toConstantValue(createLogger(resolvedConfig.logging));
1363
- const appState = createReactive({
1364
- bootedAt: Date.now(),
1365
- metadata: {}
1366
- }, {
1367
- id: "app:state",
1368
- label: "application:state",
1369
- registry,
1370
- trackHistory: resolvedConfig.telemetry.trackReactiveHistory,
1371
- maxHistory: resolvedConfig.telemetry.requestHistoryLimit
765
+ return kickServer;
766
+ }
767
+ __name(createKickApp, "createKickApp");
768
+ async function createKickAppWithConfig(options) {
769
+ const { loadAppConfig: loadAppConfig2, getConfigFromEnv: getConfigFromEnv2 } = await Promise.resolve().then(() => (init_app_config(), app_config_exports));
770
+ const envConfig = getConfigFromEnv2();
771
+ const appConfig = await loadAppConfig2({
772
+ ...envConfig,
773
+ ...options.configOverrides
1372
774
  });
1373
- container.bind(TYPES.AppState).toConstantValue(appState);
1374
- container.bind(TYPES.RequestTracker).to(RequestTracker).inSingletonScope();
1375
- container.bind(TYPES.Diagnostics).to(AppDiagnostics).inSingletonScope();
1376
- return container;
775
+ const appOptions = {
776
+ ...options,
777
+ name: options.name || appConfig.name,
778
+ prefix: options.prefix || appConfig.prefix,
779
+ config: appConfig
780
+ };
781
+ return createKickApp(appOptions);
1377
782
  }
1378
- __name(buildContainer, "buildContainer");
783
+ __name(createKickAppWithConfig, "createKickAppWithConfig");
1379
784
 
1380
- // src/utils/env.ts
1381
- var import_node_fs2 = require("fs");
1382
- var import_node_path2 = __toESM(require("path"));
1383
- function parseEnv(content) {
1384
- const result = {};
1385
- const lines = content.split(/\r?\n/);
1386
- for (const line of lines) {
1387
- if (!line || line.trim().startsWith("#")) {
1388
- continue;
1389
- }
1390
- const match = line.match(/^(\w[\w\d_\.]*)\s*=\s*(.*)$/);
1391
- if (!match) {
1392
- continue;
1393
- }
1394
- const [, key, rawValue] = match;
1395
- const value = rawValue.trim().replace(/^['"]|['"]$/g, "");
1396
- result[key] = value;
1397
- }
1398
- return result;
1399
- }
1400
- __name(parseEnv, "parseEnv");
1401
- function loadEnvFiles(files) {
1402
- for (const file of files) {
1403
- if (!file) {
1404
- continue;
1405
- }
1406
- const filePath = import_node_path2.default.isAbsolute(file) ? file : import_node_path2.default.join(process.cwd(), file);
1407
- try {
1408
- const content = (0, import_node_fs2.readFileSync)(filePath, "utf8");
1409
- const parsed = parseEnv(content);
1410
- for (const [key, value] of Object.entries(parsed)) {
1411
- if (process.env[key] === void 0) {
1412
- process.env[key] = value;
1413
- }
1414
- }
1415
- } catch (error) {
1416
- }
785
+ // src/core/base/base-plugin.ts
786
+ var BaseKickPlugin = class {
787
+ static {
788
+ __name(this, "BaseKickPlugin");
1417
789
  }
1418
- }
1419
- __name(loadEnvFiles, "loadEnvFiles");
1420
-
1421
- // src/shared/config.ts
1422
- var DEFAULT_DISCOVERY_CONFIG = {
1423
- enabled: true,
1424
- roots: [
1425
- "src/domains",
1426
- "src/http"
1427
- ],
1428
- suffix: ".controller",
1429
- extensions: [
1430
- ".ts",
1431
- ".js",
1432
- ".mjs",
1433
- ".cjs"
1434
- ],
1435
- baseRoute: "/",
1436
- segmentSeparator: ".",
1437
- enforceStructure: true,
1438
- registerGlobally: true,
1439
- ignore: [
1440
- "__tests__",
1441
- "__mocks__",
1442
- ".DS_Store"
1443
- ],
1444
- tagsFromDirectories: true,
1445
- allowStaticRoutes: true
1446
790
  };
1447
- var DEFAULT_CONFIG = {
1448
- prefix: "",
1449
- healthEndpoint: "/health",
1450
- logging: {
1451
- level: "info"
1452
- },
1453
- telemetry: {
1454
- trackReactiveHistory: true,
1455
- requestHistoryLimit: 250
1456
- },
1457
- api: {
1458
- discovery: DEFAULT_DISCOVERY_CONFIG
791
+
792
+ // src/core/base/base-middleware.ts
793
+ var BaseKickMiddleware = class {
794
+ static {
795
+ __name(this, "BaseKickMiddleware");
1459
796
  }
1460
797
  };
1461
- var currentConfig = cloneResolvedConfig(DEFAULT_CONFIG);
1462
- function createKickConfig(options = {}) {
1463
- if (options.envFiles !== false) {
1464
- const defaultFiles = [
1465
- ".env"
1466
- ];
1467
- const nodeEnv = process.env.NODE_ENV;
1468
- if (nodeEnv) {
1469
- defaultFiles.push(`.env.${nodeEnv}`);
1470
- }
1471
- defaultFiles.push(".env.local");
1472
- const envFiles = Array.isArray(options.envFiles) ? options.envFiles : defaultFiles;
1473
- loadEnvFiles(envFiles);
1474
- }
1475
- let config = {
1476
- ...options.defaults ?? {}
1477
- };
1478
- if (options.env) {
1479
- for (const [envKey, binding] of Object.entries(options.env)) {
1480
- const rawValue = process.env[envKey];
1481
- if (rawValue === void 0) {
1482
- continue;
1483
- }
1484
- if (typeof binding === "function") {
1485
- const partial = binding(rawValue, process.env);
1486
- config = mergeAppConfigs(config, partial);
1487
- continue;
1488
- }
1489
- if (typeof binding === "string") {
1490
- config = setConfigValue(config, binding, autoCast(rawValue));
1491
- continue;
1492
- }
1493
- const value = binding.transform ? binding.transform(rawValue, process.env) : autoCast(rawValue);
1494
- config = setConfigValue(config, binding.path, value);
1495
- }
1496
- }
1497
- if (options.overrides) {
1498
- const overrides = typeof options.overrides === "function" ? options.overrides(config) : options.overrides;
1499
- config = mergeAppConfigs(config, overrides);
1500
- }
1501
- return config;
1502
- }
1503
- __name(createKickConfig, "createKickConfig");
1504
- function configureApp(config) {
1505
- currentConfig = mergeConfig(currentConfig, config);
1506
- }
1507
- __name(configureApp, "configureApp");
1508
- function getAppConfig() {
1509
- return currentConfig;
1510
- }
1511
- __name(getAppConfig, "getAppConfig");
1512
- function resolveConfig(overrides) {
1513
- if (!overrides) {
1514
- return currentConfig;
1515
- }
1516
- return mergeConfig(currentConfig, overrides);
1517
- }
1518
- __name(resolveConfig, "resolveConfig");
1519
- function resetAppConfig() {
1520
- currentConfig = cloneResolvedConfig(DEFAULT_CONFIG);
1521
- }
1522
- __name(resetAppConfig, "resetAppConfig");
1523
- function mergeConfig(base, overrides) {
1524
- return {
1525
- prefix: overrides.prefix ?? base.prefix,
1526
- healthEndpoint: overrides.healthEndpoint ?? base.healthEndpoint,
1527
- logging: {
1528
- level: overrides.logging?.level ?? base.logging.level
1529
- },
1530
- telemetry: {
1531
- trackReactiveHistory: overrides.telemetry?.trackReactiveHistory ?? base.telemetry.trackReactiveHistory,
1532
- requestHistoryLimit: overrides.telemetry?.requestHistoryLimit ?? base.telemetry.requestHistoryLimit
1533
- },
1534
- api: {
1535
- discovery: mergeDiscoveryConfig(base.api.discovery, overrides.api?.discovery)
1536
- }
1537
- };
1538
- }
1539
- __name(mergeConfig, "mergeConfig");
1540
- function cloneResolvedConfig(config) {
1541
- return {
1542
- prefix: config.prefix,
1543
- healthEndpoint: config.healthEndpoint,
1544
- logging: {
1545
- ...config.logging
1546
- },
1547
- telemetry: {
1548
- ...config.telemetry
1549
- },
1550
- api: {
1551
- discovery: {
1552
- enabled: config.api.discovery.enabled,
1553
- roots: [
1554
- ...config.api.discovery.roots
1555
- ],
1556
- suffix: config.api.discovery.suffix,
1557
- extensions: [
1558
- ...config.api.discovery.extensions
1559
- ],
1560
- baseRoute: config.api.discovery.baseRoute,
1561
- segmentSeparator: config.api.discovery.segmentSeparator,
1562
- enforceStructure: config.api.discovery.enforceStructure,
1563
- registerGlobally: config.api.discovery.registerGlobally,
1564
- ignore: [
1565
- ...config.api.discovery.ignore
1566
- ],
1567
- tagsFromDirectories: config.api.discovery.tagsFromDirectories,
1568
- allowStaticRoutes: config.api.discovery.allowStaticRoutes
1569
- }
1570
- }
1571
- };
1572
- }
1573
- __name(cloneResolvedConfig, "cloneResolvedConfig");
1574
- function mergeDiscoveryConfig(base, overrides) {
1575
- if (!overrides) {
1576
- return {
1577
- ...base,
1578
- roots: [
1579
- ...base.roots
1580
- ],
1581
- extensions: [
1582
- ...base.extensions
1583
- ],
1584
- ignore: [
1585
- ...base.ignore
1586
- ]
1587
- };
1588
- }
1589
- return {
1590
- enabled: overrides.enabled ?? base.enabled,
1591
- roots: overrides.roots ? [
1592
- ...overrides.roots
1593
- ] : [
1594
- ...base.roots
1595
- ],
1596
- suffix: overrides.suffix ?? base.suffix,
1597
- extensions: overrides.extensions ? [
1598
- ...overrides.extensions
1599
- ] : [
1600
- ...base.extensions
1601
- ],
1602
- baseRoute: overrides.baseRoute ?? base.baseRoute,
1603
- segmentSeparator: overrides.segmentSeparator ?? base.segmentSeparator,
1604
- enforceStructure: overrides.enforceStructure ?? base.enforceStructure,
1605
- registerGlobally: overrides.registerGlobally ?? base.registerGlobally,
1606
- ignore: overrides.ignore ? [
1607
- ...overrides.ignore
1608
- ] : [
1609
- ...base.ignore
1610
- ],
1611
- tagsFromDirectories: overrides.tagsFromDirectories ?? base.tagsFromDirectories,
1612
- allowStaticRoutes: overrides.allowStaticRoutes ?? base.allowStaticRoutes
1613
- };
1614
- }
1615
- __name(mergeDiscoveryConfig, "mergeDiscoveryConfig");
1616
- function mergeAppConfigs(base, patch) {
1617
- if (!patch) {
1618
- return base;
1619
- }
1620
- const merged = {
1621
- ...base
1622
- };
1623
- if (patch.prefix !== void 0) {
1624
- merged.prefix = patch.prefix;
1625
- }
1626
- if (patch.healthEndpoint !== void 0) {
1627
- merged.healthEndpoint = patch.healthEndpoint;
1628
- }
1629
- if (patch.logging) {
1630
- merged.logging = {
1631
- ...merged.logging,
1632
- ...patch.logging
1633
- };
1634
- }
1635
- if (patch.telemetry) {
1636
- merged.telemetry = {
1637
- ...merged.telemetry,
1638
- ...patch.telemetry
1639
- };
1640
- }
1641
- if (patch.api?.discovery) {
1642
- merged.api = merged.api ?? {};
1643
- merged.api.discovery = {
1644
- ...merged.api.discovery,
1645
- ...patch.api.discovery
1646
- };
1647
- }
1648
- return merged;
1649
- }
1650
- __name(mergeAppConfigs, "mergeAppConfigs");
1651
- function setConfigValue(config, path3, value) {
1652
- const patch = buildConfigFromPath(path3, value);
1653
- return mergeAppConfigs(config, patch);
1654
- }
1655
- __name(setConfigValue, "setConfigValue");
1656
- function buildConfigFromPath(path3, value) {
1657
- const segments = path3.split(".");
1658
- const result = {};
1659
- let cursor = result;
1660
- segments.forEach((segment, index) => {
1661
- if (index === segments.length - 1) {
1662
- cursor[segment] = value;
1663
- return;
1664
- }
1665
- cursor[segment] = cursor[segment] ? {
1666
- ...cursor[segment]
1667
- } : {};
1668
- cursor = cursor[segment];
1669
- });
1670
- return result;
1671
- }
1672
- __name(buildConfigFromPath, "buildConfigFromPath");
1673
- function autoCast(value) {
1674
- const lower = value.toLowerCase();
1675
- if (lower === "true") {
1676
- return true;
1677
- }
1678
- if (lower === "false") {
1679
- return false;
1680
- }
1681
- const num = Number(value);
1682
- if (!Number.isNaN(num) && `${num}` === value.trim()) {
1683
- return num;
1684
- }
1685
- try {
1686
- if (value.startsWith("{") && value.endsWith("}") || value.startsWith("[") && value.endsWith("]")) {
1687
- return JSON.parse(value);
1688
- }
1689
- } catch (error) {
1690
- }
1691
- return value;
1692
- }
1693
- __name(autoCast, "autoCast");
1694
798
 
1695
- // src/core/application.ts
1696
- function createApp(options = {}) {
1697
- const config = resolveConfig(options.config);
1698
- const container = options.container ?? buildContainer(config);
1699
- options.configureContainer?.(container);
1700
- const app = (0, import_express.default)();
1701
- const requestTracker = container.get(TYPES.RequestTracker);
1702
- const diagnostics = container.get(TYPES.Diagnostics);
1703
- const discoveredControllers = discoverControllersFromFilesystem(config.api.discovery);
1704
- const manualControllers = options.controllers ?? [];
1705
- const controllers = /* @__PURE__ */ new Set();
1706
- manualControllers.forEach((ControllerClass) => controllers.add(ControllerClass));
1707
- discoveredControllers.forEach((entry) => controllers.add(entry.controller));
1708
- const controllersToRegister = controllers.size > 0 ? Array.from(controllers) : void 0;
1709
- app.use(import_express.default.json());
1710
- options.additionalMiddleware?.forEach((middleware) => {
1711
- app.use(middleware);
1712
- });
1713
- app.use(requestTracker.middleware());
1714
- registerControllers(app, container, {
1715
- controllers: controllersToRegister,
1716
- prefix: config.prefix
1717
- });
1718
- if (config.healthEndpoint !== false) {
1719
- app.get(config.healthEndpoint, (_req, res) => {
1720
- res.json({
1721
- status: "ok"
1722
- });
799
+ // src/core/module.ts
800
+ var import_inversify5 = require("inversify");
801
+ var createModule = /* @__PURE__ */ __name((name, options) => {
802
+ const { controllers = [], middlewares = [] } = options;
803
+ const uniqueControllers = new Set(controllers);
804
+ const uniqueMiddlewares = new Set(middlewares);
805
+ const module2 = new import_inversify5.ContainerModule(({ bind }) => {
806
+ uniqueControllers.forEach((controller) => {
807
+ const bindingKey = KICK_MODULE_KEYS.KickControllerType;
808
+ bind(bindingKey).to(controller);
809
+ bind(controller).toSelf();
1723
810
  });
1724
- }
1725
- app.use((err, _req, res, _next) => {
1726
- const appError = isAppError(err) ? err : createError("INTERNAL_ERROR", err instanceof Error ? err.message : "Unexpected error", {
1727
- cause: err,
1728
- status: 500
811
+ uniqueMiddlewares.forEach((middleware) => {
812
+ const bindingKey = KICK_MODULE_KEYS.KickMiddlewareType;
813
+ bind(bindingKey).to(middleware);
814
+ bind(middleware).toSelf();
1729
815
  });
1730
- if (err instanceof Error && err.stack) {
1731
- requestTracker.mergeMetadata(res, {
1732
- errorStack: err.stack
1733
- });
1734
- }
1735
- requestTracker.recordError(res, appError);
1736
- const status = Number.isFinite(appError.status) ? Number(appError.status) : 500;
1737
- const payload = {
1738
- error: {
1739
- code: appError.code,
1740
- message: appError.message
1741
- }
1742
- };
1743
- if (appError.details) {
1744
- payload.error.details = appError.details;
1745
- }
1746
- requestTracker.recordResponse(res, status, payload);
1747
- if (!res.headersSent) {
1748
- res.status(status).json(payload);
1749
- }
1750
816
  });
1751
817
  return {
1752
- app,
1753
- container,
1754
- requestTracker,
1755
- diagnostics,
1756
- config,
1757
- discovery: {
1758
- controllers: discoveredControllers
1759
- }
818
+ /**
819
+ * Installs the module into the provided Inversify container.
820
+ */
821
+ install: /* @__PURE__ */ __name((container) => {
822
+ container.load(module2);
823
+ }, "install"),
824
+ name
1760
825
  };
826
+ }, "createModule");
827
+
828
+ // src/cli/utils/config-helpers.ts
829
+ function createKickConfig(config) {
830
+ return config;
1761
831
  }
1762
- __name(createApp, "createApp");
1763
- async function bootstrap(options = {}) {
1764
- const { app, container, requestTracker, diagnostics, config, discovery } = createApp(options);
1765
- const port = Number(options.port ?? process.env.PORT ?? 3e3);
1766
- const server = app.listen(port, () => {
1767
- console.log(`\u{1F680} Server listening on http://localhost:${port}`);
1768
- });
1769
- const shutdown = /* @__PURE__ */ __name(() => {
1770
- server.close(() => {
1771
- console.log("HTTP server closed");
1772
- });
1773
- }, "shutdown");
1774
- process.once("SIGINT", shutdown);
1775
- process.once("SIGTERM", shutdown);
1776
- return {
1777
- app,
1778
- server,
1779
- container,
1780
- requestTracker,
1781
- diagnostics,
1782
- config,
1783
- discovery,
1784
- shutdown
1785
- };
832
+ __name(createKickConfig, "createKickConfig");
833
+ function defineAppConfig(config) {
834
+ return config;
835
+ }
836
+ __name(defineAppConfig, "defineAppConfig");
837
+ function defineDevConfig(config) {
838
+ return config;
1786
839
  }
1787
- __name(bootstrap, "bootstrap");
840
+ __name(defineDevConfig, "defineDevConfig");
841
+ function defineStartConfig(config) {
842
+ return config;
843
+ }
844
+ __name(defineStartConfig, "defineStartConfig");
845
+
846
+ // src/index.ts
847
+ init_app_config();
1788
848
  // Annotate the CommonJS export names for ESM import in node:
1789
849
  0 && (module.exports = {
1790
- AppDiagnostics,
1791
- AppError,
1792
- BaseController,
1793
- Controller,
1794
- Delete,
1795
- DeleteController,
1796
- Get,
1797
- GetController,
1798
- HttpVerbController,
1799
- Inject,
1800
- Injectable,
1801
- MultiInject,
1802
- Named,
1803
- Optional,
1804
- Patch,
1805
- PatchController,
1806
- Post,
1807
- PostController,
1808
- Put,
1809
- PutController,
1810
- RequestTracker,
1811
- TYPES,
1812
- Tagged,
1813
- Unmanaged,
1814
- bootstrap,
1815
- configureApp,
1816
- createApp,
1817
- createError,
850
+ AutoBind,
851
+ BaseKickMiddleware,
852
+ BaseKickPlugin,
853
+ KICK_CONTROLLER_METADATA_KEYS,
854
+ KICK_MODULE_KEYS,
855
+ KickApp,
856
+ KickController,
857
+ KickDelete,
858
+ KickGet,
859
+ KickInject,
860
+ KickInjectable,
861
+ KickMiddleware,
862
+ KickPatch,
863
+ KickPost,
864
+ KickPut,
865
+ RouteMapper,
866
+ bindClassMethods,
867
+ combineRoutePaths,
868
+ createKickApp,
869
+ createKickAppWithConfig,
1818
870
  createKickConfig,
1819
- discoverControllersFromFilesystem,
1820
- getAppConfig,
1821
- isAppError,
1822
- listRegisteredControllers,
1823
- registerController,
1824
- resetAppConfig,
1825
- resetControllerRegistry,
1826
- resolveConfig
871
+ createModule,
872
+ defineAppConfig,
873
+ defineDevConfig,
874
+ defineStartConfig,
875
+ getConfigFromEnv,
876
+ getMiddlewareMetadata,
877
+ isKickMiddleware,
878
+ loadAppConfig,
879
+ mapController,
880
+ normalizeRoutePath
1827
881
  });
1828
882
  //# sourceMappingURL=index.js.map