@vercube/core 0.0.2 → 0.0.4

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 (76) hide show
  1. package/dist/index.d.mts +1193 -0
  2. package/dist/index.mjs +196 -191
  3. package/package.json +8 -23
  4. package/dist/Common/App.d.ts +0 -65
  5. package/dist/Common/Container.d.ts +0 -8
  6. package/dist/Common/CreateApp.d.ts +0 -8
  7. package/dist/Config/Config.d.ts +0 -7
  8. package/dist/Config/DefaultConfig.d.ts +0 -6
  9. package/dist/Config/Loader.d.ts +0 -7
  10. package/dist/Decorators/Hooks/Listen.d.ts +0 -9
  11. package/dist/Decorators/Http/Body.d.ts +0 -15
  12. package/dist/Decorators/Http/Connect.d.ts +0 -10
  13. package/dist/Decorators/Http/Controller.d.ts +0 -10
  14. package/dist/Decorators/Http/Delete.d.ts +0 -10
  15. package/dist/Decorators/Http/Get.d.ts +0 -10
  16. package/dist/Decorators/Http/Head.d.ts +0 -10
  17. package/dist/Decorators/Http/Header.d.ts +0 -11
  18. package/dist/Decorators/Http/Headers.d.ts +0 -9
  19. package/dist/Decorators/Http/Middleware.d.ts +0 -27
  20. package/dist/Decorators/Http/MultipartFormData.d.ts +0 -15
  21. package/dist/Decorators/Http/Options.d.ts +0 -10
  22. package/dist/Decorators/Http/Param.d.ts +0 -12
  23. package/dist/Decorators/Http/Patch.d.ts +0 -10
  24. package/dist/Decorators/Http/Post.d.ts +0 -10
  25. package/dist/Decorators/Http/Put.d.ts +0 -10
  26. package/dist/Decorators/Http/QueryParam.d.ts +0 -16
  27. package/dist/Decorators/Http/QueryParams.d.ts +0 -15
  28. package/dist/Decorators/Http/Redirect.d.ts +0 -13
  29. package/dist/Decorators/Http/Request.d.ts +0 -9
  30. package/dist/Decorators/Http/Response.d.ts +0 -9
  31. package/dist/Decorators/Http/Session.d.ts +0 -9
  32. package/dist/Decorators/Http/SetHeader.d.ts +0 -7
  33. package/dist/Decorators/Http/Status.d.ts +0 -11
  34. package/dist/Decorators/Http/Trace.d.ts +0 -10
  35. package/dist/Errors/Http/BadRequestError.d.ts +0 -17
  36. package/dist/Errors/Http/ForbiddenError.d.ts +0 -17
  37. package/dist/Errors/Http/InternalServerError.d.ts +0 -17
  38. package/dist/Errors/Http/MethodNotAllowedError.d.ts +0 -17
  39. package/dist/Errors/Http/NotAcceptableError.d.ts +0 -17
  40. package/dist/Errors/Http/NotFoundError.d.ts +0 -17
  41. package/dist/Errors/Http/UnauthorizedError.d.ts +0 -17
  42. package/dist/Errors/HttpError.d.ts +0 -17
  43. package/dist/Hooks/Router/RouterAfterInitHook.d.ts +0 -1
  44. package/dist/Hooks/Router/RouterBeforeInitHook.d.ts +0 -1
  45. package/dist/Middleware/ValidationMiddleware.d.ts +0 -23
  46. package/dist/Resolvers/Body.d.ts +0 -22
  47. package/dist/Resolvers/Headers.d.ts +0 -14
  48. package/dist/Resolvers/Query.d.ts +0 -14
  49. package/dist/Resolvers/RouterParam.d.ts +0 -13
  50. package/dist/Services/Config/RuntimeConfig.d.ts +0 -22
  51. package/dist/Services/ErrorHandler/DefaultErrorHandlerProvider.d.ts +0 -16
  52. package/dist/Services/ErrorHandler/ErrorHandlerProvider.d.ts +0 -16
  53. package/dist/Services/Hooks/HooksService.d.ts +0 -76
  54. package/dist/Services/HttpServer/HttpServer.d.ts +0 -57
  55. package/dist/Services/Metadata/MetadataResolver.d.ts +0 -42
  56. package/dist/Services/Middleware/BaseMiddleware.d.ts +0 -31
  57. package/dist/Services/Middleware/GlobalMiddlewareRegistry.d.ts +0 -31
  58. package/dist/Services/Plugins/BasePlugin.d.ts +0 -16
  59. package/dist/Services/Plugins/PluginsRegistry.d.ts +0 -26
  60. package/dist/Services/Router/RequestHandler.d.ts +0 -63
  61. package/dist/Services/Router/Router.d.ts +0 -40
  62. package/dist/Services/Router/StaticRequestHandler.d.ts +0 -38
  63. package/dist/Services/Validation/StandardSchemaValidationProvider.d.ts +0 -17
  64. package/dist/Services/Validation/ValidationProvider.d.ts +0 -17
  65. package/dist/Types/CommonTypes.d.ts +0 -6
  66. package/dist/Types/ConfigTypes.d.ts +0 -124
  67. package/dist/Types/HooksTypes.d.ts +0 -17
  68. package/dist/Types/HttpTypes.d.ts +0 -63
  69. package/dist/Types/MetadataTypes.d.ts +0 -56
  70. package/dist/Types/RouterTypes.d.ts +0 -37
  71. package/dist/Types/ValidationTypes.d.ts +0 -6
  72. package/dist/Utils/InternalUtils.d.ts +0 -5
  73. package/dist/Utils/Mine.d.ts +0 -3
  74. package/dist/Utils/Utils.d.ts +0 -22
  75. package/dist/index.cjs +0 -2693
  76. package/dist/index.d.ts +0 -51
package/dist/index.cjs DELETED
@@ -1,2693 +0,0 @@
1
- //#region rolldown:runtime
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
- key = keys[i];
14
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
15
- get: ((k) => from[k]).bind(null, key),
16
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
- });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
22
- value: mod,
23
- enumerable: true
24
- }) : target, mod));
25
-
26
- //#endregion
27
- const __vercube_di = __toESM(require("@vercube/di"));
28
- const srvx = __toESM(require("srvx"));
29
- const rou3 = __toESM(require("rou3"));
30
- const node_fs = __toESM(require("node:fs"));
31
- const node_path = __toESM(require("node:path"));
32
- const node_fs_promises = __toESM(require("node:fs/promises"));
33
- const __vercube_logger = __toESM(require("@vercube/logger"));
34
- const c12 = __toESM(require("c12"));
35
- const defu = __toESM(require("defu"));
36
-
37
- //#region node_modules/.pnpm/@oxc-project+runtime@0.65.0/node_modules/@oxc-project/runtime/src/helpers/decorate.js
38
- var require_decorate = __commonJS({ "node_modules/.pnpm/@oxc-project+runtime@0.65.0/node_modules/@oxc-project/runtime/src/helpers/decorate.js"(exports, module) {
39
- function __decorate(decorators, target, key, desc) {
40
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
41
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
42
- 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;
43
- return c > 3 && r && Object.defineProperty(target, key, r), r;
44
- }
45
- module.exports = __decorate, module.exports.__esModule = true, module.exports["default"] = module.exports;
46
- } });
47
- var import_decorate = __toESM(require_decorate(), 1);
48
-
49
- //#endregion
50
- //#region packages/core/src/Services/Plugins/PluginsRegistry.ts
51
- var PluginsRegistry = class {
52
- gContainer;
53
- /** Holds the list of plugins */
54
- fPlugins = new Map();
55
- /**
56
- * Registers a plugin.
57
- *
58
- * @param {Plugin} plugin - The plugin to register.
59
- * @param {unknown} options - The options to pass to the plugin.
60
- */
61
- register(plugin, options) {
62
- const instance = this.gContainer.resolve(plugin);
63
- this.fPlugins.set(instance.name, {
64
- instance,
65
- options
66
- });
67
- }
68
- /**
69
- * Gets the list of registered plugins.
70
- *
71
- * @returns {Plugin[]} The list of registered plugins.
72
- */
73
- get plugins() {
74
- return [...this.fPlugins.values()].map((plugin) => plugin.instance);
75
- }
76
- /**
77
- * Resolves the plugins.
78
- *
79
- * @param {App} app - The application instance.
80
- */
81
- async init(app) {
82
- for (const { instance, options } of this.fPlugins.values()) await instance.use(app, options);
83
- }
84
- };
85
- (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_di.Container)], PluginsRegistry.prototype, "gContainer", void 0);
86
-
87
- //#endregion
88
- //#region packages/core/src/Services/Hooks/HooksService.ts
89
- /**
90
- * This class is responsible for managing events.
91
- */
92
- var HooksService = class {
93
- fLastId = 0;
94
- fHandlers = new Map();
95
- /**
96
- * Registers listener for event of particular type. Everytime event is called, the listener
97
- * will be executed.
98
- *
99
- * @param type type of event, simple class
100
- * @param callback callback fired when event is triggered
101
- * @returns unique ID for event listener, can be used to disable this listener
102
- */
103
- on(type, callback) {
104
- let handlersOfType = this.fHandlers.get(type);
105
- if (!handlersOfType) {
106
- handlersOfType = [];
107
- this.fHandlers.set(type, handlersOfType);
108
- }
109
- const genId = this.fLastId++;
110
- const handler = {
111
- callback,
112
- id: genId
113
- };
114
- handlersOfType.push(handler);
115
- return {
116
- __id: genId,
117
- __type: type
118
- };
119
- }
120
- /**
121
- * Waits for single event execution and removes the listener immediately after.
122
- *
123
- * @example
124
- * this.gCart.addItem(product);
125
- * await this.gEvents.waitFor(CartUpdatedEvent);
126
- * console.log('here cart updated event is already called');
127
- *
128
- * @param type type of event to wait for
129
- * @param timeout timeout param in ms - if event is not thrown until this time, it'll reject. passing null disables the timeout
130
- * @returns promise with event data that resolves when event is finally called
131
- */
132
- waitFor(type, timeout = 10 * 1e3) {
133
- return new Promise((resolve, reject) => {
134
- let waitTimeout;
135
- const eventId = this.on(type, (data) => {
136
- this.off(eventId);
137
- resolve(data);
138
- if (waitTimeout) clearTimeout(waitTimeout);
139
- });
140
- if (timeout !== null) waitTimeout = setTimeout(() => {
141
- this.off(eventId);
142
- reject(new Error(`Waiting for event timeout - ${type.name}`));
143
- }, timeout);
144
- });
145
- }
146
- /**
147
- * Removes listener from particular event.
148
- * @param eventId eventId returned from .on() method.
149
- * @throws Error if event was not registered
150
- */
151
- off(eventId) {
152
- const type = eventId.__type;
153
- const handlersOfType = this.fHandlers.get(type);
154
- if (!handlersOfType) throw new Error("Trying to unbind event that was not bound.");
155
- const index = handlersOfType.findIndex((handler) => handler.id === eventId.__id);
156
- if (index === -1) throw new Error("Trying to unbind event that was not bound.");
157
- handlersOfType.splice(index, 1);
158
- }
159
- /**
160
- * Triggers event, calling all listener callbacks. Will return Promise of number,
161
- * that is resolved when all asynchronous listeners are called.
162
- * @param type type of trigger, simple class
163
- * @param data data which will be passed to listeners, based on event class
164
- * @return number of listeners that were notified
165
- */
166
- async trigger(type, data) {
167
- const handlersOfType = this.fHandlers.get(type);
168
- if (!handlersOfType) return 0;
169
- const toProcessHandlers = [...handlersOfType];
170
- const promises = toProcessHandlers.map((handler) => {
171
- const instance = this.objectToClass(type, data);
172
- const result = handler.callback(instance);
173
- return result instanceof Promise ? result : Promise.resolve();
174
- });
175
- await Promise.all(promises);
176
- return toProcessHandlers.length;
177
- }
178
- /**
179
- * Converts plain object to it's class equivalent.
180
- * It's NOT class-transformer, it performs basic key assigment.
181
- *
182
- * @param ClassConstructor event constructor
183
- * @param data event data to be mapped to constructor
184
- * @return class type of event
185
- */
186
- objectToClass(ClassConstructor, data) {
187
- const instance = new ClassConstructor();
188
- if (data) for (const key of Object.keys(data)) {
189
- const rawInstance = instance;
190
- const rawData = data;
191
- rawInstance[key] = rawData[key];
192
- }
193
- return instance;
194
- }
195
- };
196
-
197
- //#endregion
198
- //#region packages/core/src/Hooks/Router/RouterBeforeInitHook.ts
199
- var RouterBeforeInitHook = class {};
200
-
201
- //#endregion
202
- //#region packages/core/src/Hooks/Router/RouterAfterInitHook.ts
203
- var RouterAfterInitHook = class {};
204
-
205
- //#endregion
206
- //#region packages/core/src/Services/Router/Router.ts
207
- /**
208
- * Router service responsible for managing application routes
209
- *
210
- * This class provides functionality to initialize the router,
211
- * register routes, and resolve incoming requests to their
212
- * appropriate handlers.
213
- */
214
- var Router = class {
215
- /**
216
- * Service for triggering application hooks
217
- */
218
- gHooksService;
219
- /**
220
- * Internal router context that stores all registered routes
221
- * @private
222
- */
223
- fRouterContext;
224
- /**
225
- * Registers a new route in the router
226
- *
227
- * @param {RouterTypes.Route} route - The route configuration to add
228
- * @throws {Error} If router is not initialized
229
- */
230
- addRoute(route) {
231
- if (!this.fRouterContext) throw new Error("Router not initialized. Please call init() before adding routes.");
232
- (0, rou3.addRoute)(this.fRouterContext, route.method.toUpperCase(), route.path, route.handler);
233
- }
234
- /**
235
- * Initializes the router and triggers related hooks
236
- *
237
- * This method creates a new router context and triggers
238
- * the before and after initialization hooks.
239
- */
240
- initialize() {
241
- this.gHooksService.trigger(RouterBeforeInitHook);
242
- this.fRouterContext = (0, rou3.createRouter)();
243
- this.gHooksService.trigger(RouterAfterInitHook);
244
- }
245
- /**
246
- * Resolves a route based on the HTTP method and path
247
- *
248
- * @param {RouterTypes.RouteFind} route - The route to resolve
249
- * @returns {RouterTypes.RouteMatched<RouterTypes.RouterHandler> | undefined} The matched route or undefined if no match found
250
- */
251
- resolve(route) {
252
- let url = route.path;
253
- try {
254
- url = new URL(route.path).pathname;
255
- } catch {}
256
- return (0, rou3.findRoute)(this.fRouterContext, route.method.toUpperCase(), url);
257
- }
258
- };
259
- (0, import_decorate.default)([(0, __vercube_di.Inject)(HooksService)], Router.prototype, "gHooksService", void 0);
260
-
261
- //#endregion
262
- //#region packages/core/src/Resolvers/RouterParam.ts
263
- /**
264
- * Resolves a router parameter from the event object
265
- * @param param - The parameter name to resolve from the router event
266
- * @param event - The router event object containing parameters
267
- * @returns The resolved parameter value if it exists, null otherwise
268
- * @example
269
- * ```typescript
270
- * const value = resolveRouterParam('id', routerEvent);
271
- * // Returns the 'id' parameter value from routerEvent.params or null
272
- * ```
273
- */
274
- function resolveRouterParam(param, event) {
275
- return event.params?.[param] ?? null;
276
- }
277
-
278
- //#endregion
279
- //#region packages/core/src/Errors/HttpError.ts
280
- /**
281
- * Represents an HTTP error.
282
- * @extends {Error}
283
- */
284
- var HttpError = class HttpError extends Error {
285
- /**
286
- * The HTTP status code associated with the error.
287
- * @type {number}
288
- */
289
- status;
290
- /**
291
- * Creates an instance of HttpError.
292
- * @param {number} status - The HTTP status code.
293
- * @param {string} [message] - The error message.
294
- */
295
- constructor(status, message) {
296
- super();
297
- Object.setPrototypeOf(this, HttpError.prototype);
298
- if (status) this.status = status;
299
- if (message) this.message = message;
300
- this.stack = new Error().stack;
301
- }
302
- };
303
-
304
- //#endregion
305
- //#region packages/core/src/Errors/Http/BadRequestError.ts
306
- /**
307
- * Represents a Bad Request error (HTTP 400).
308
- * @extends {HttpError}
309
- */
310
- var BadRequestError = class BadRequestError extends HttpError {
311
- /**
312
- * The name of the error.
313
- * @type {string}
314
- */
315
- name = "BadRequestError";
316
- /**
317
- * Creates an instance of BadRequestError.
318
- * @param {string} [message] - The error message.
319
- */
320
- constructor(message, errors) {
321
- super(400);
322
- Object.setPrototypeOf(this, BadRequestError.prototype);
323
- if (message) this.message = message;
324
- if (errors) this.errors = errors;
325
- }
326
- };
327
-
328
- //#endregion
329
- //#region packages/core/src/Resolvers/Body.ts
330
- /**
331
- * Resolves and parses the request body from a RouterEvent.
332
- *
333
- * @param {RouterTypes.RouterEvent} event - The router event containing the request to process
334
- * @returns {Promise<unknown>} A promise that resolves to:
335
- * - The parsed JSON body if the request contains valid JSON
336
- * - undefined if the request body is empty
337
- * @throws {BadRequestError} If the request body contains invalid JSON
338
- *
339
- * @example
340
- * const body = await resolveRequestBody(event);
341
- * if (body) {
342
- * // Process the parsed body
343
- * }
344
- *
345
- * @remarks
346
- * - Currently only supports JSON content type
347
- * - Returns undefined for empty request bodies
348
- * - Throws BadRequestError for malformed JSON
349
- */
350
- async function resolveRequestBody(event) {
351
- const text = await event.request.text();
352
- if (!text) return void 0;
353
- try {
354
- return JSON.parse(text);
355
- } catch {
356
- throw new BadRequestError("Invalid JSON body");
357
- }
358
- }
359
-
360
- //#endregion
361
- //#region packages/core/src/Resolvers/Query.ts
362
- /**
363
- * Resolves a single query parameter from the URL of a router event
364
- * @param name - The name of the query parameter to resolve
365
- * @param event - The router event containing the request URL
366
- * @returns The value of the query parameter if found, null otherwise
367
- */
368
- function resolveQueryParam(name, event) {
369
- const url = new URL(event.request.url);
370
- return url.searchParams.get(name);
371
- }
372
- /**
373
- * Resolves all query parameters from the URL of a router event
374
- * @param event - The router event containing the request URL
375
- * @returns An object containing all query parameters as key-value pairs
376
- */
377
- function resolveQueryParams(event) {
378
- const url = new URL(event.request.url);
379
- const params = {};
380
- for (const [key, value] of url.searchParams) params[key] = value;
381
- return params;
382
- }
383
-
384
- //#endregion
385
- //#region packages/core/src/Resolvers/Headers.ts
386
- /**
387
- * Retrieves a specific header value from the request
388
- * @param {string} header - The name of the header to retrieve
389
- * @param {RouterTypes.RouterEvent} event - The router event containing the request
390
- * @returns {string | null} The header value if found, null otherwise
391
- */
392
- function getRequestHeader(header, event) {
393
- return event.request.headers.get(header);
394
- }
395
- /**
396
- * Retrieves all headers from the request
397
- * @param {RouterTypes.RouterEvent} event - The router event containing the request
398
- * @returns {Headers} The complete Headers object from the request
399
- */
400
- function getRequestHeaders(event) {
401
- return event.request.headers;
402
- }
403
-
404
- //#endregion
405
- //#region packages/core/src/Services/Metadata/MetadataResolver.ts
406
- /**
407
- * Class responsible for resolving metadata for route handlers.
408
- */
409
- var MetadataResolver = class {
410
- /**
411
- * Resolves the URL for a given instance and path.
412
- *
413
- * @param {MetadataTypes.ResolveUrlParams} params - The parameters for resolving the URL.
414
- * @return {string} The resolved URL.
415
- */
416
- resolveUrl(params) {
417
- const { instance, propertyName, path: rawPath } = params;
418
- const metadata = instance.__metadata;
419
- const basePath = (metadata?.__controller?.path ?? "").replace(/\/$/, "");
420
- const cleanPath = rawPath.replace(/^\//, "");
421
- const url = `${basePath}/${cleanPath}`;
422
- metadata.__methods[propertyName].url = url;
423
- return url;
424
- }
425
- resolveMethod(ctx, propertyName) {
426
- return ctx.__metadata.__methods[propertyName];
427
- }
428
- /**
429
- * Resolves arguments for a given event.
430
- *
431
- * @param {MetadataTypes.Arg[]} args - The arguments to resolve.
432
- * @param {RouterTypes.RouterEvent} event - The event to resolve arguments for.
433
- * @return {unknown[]} The resolved arguments.
434
- * @public
435
- */
436
- async resolveArgs(args, event) {
437
- args.sort((a, b) => a.idx - b.idx);
438
- const resolvedArgs = args.map(async (arg) => ({
439
- ...arg,
440
- resolved: await this.resolveArg(arg, event)
441
- }));
442
- return await Promise.all(resolvedArgs);
443
- }
444
- /**
445
- * Resolves an argument for a given event.
446
- *
447
- * @param {MetadataTypes.Arg} arg - The argument to resolve.
448
- *
449
- * @return {unknown} The resolved argument.
450
- * @private
451
- */
452
- resolveArg(arg, event) {
453
- switch (arg.type) {
454
- case "param": return resolveRouterParam(arg?.data?.name ?? "", event);
455
- case "body": return resolveRequestBody(event);
456
- case "multipart-form-data": return null;
457
- case "query-param": return resolveQueryParam(arg?.data?.name ?? "", event);
458
- case "query-params": return resolveQueryParams(event);
459
- case "header": return getRequestHeader(arg.data?.name ?? "", event);
460
- case "headers": return getRequestHeaders(event);
461
- case "request": return event.request;
462
- case "response": return event.response;
463
- case "custom": return arg.data?.resolve(event);
464
- case "session": return null;
465
- default: throw new Error(`Unknown argument type: ${arg.type}`);
466
- }
467
- }
468
- /**
469
- * Resolves middleware functions for a given context and property name.
470
- *
471
- * @param {MetadataTypes.Ctx} ctx - The metadata context object
472
- * @param {string} propertyName - The name of the property to resolve middlewares for
473
- * @returns {MetadataTypes.Middleware[]} Array of middleware functions that apply globally or to the specific property
474
- * @public
475
- */
476
- resolveMiddlewares(ctx, propertyName) {
477
- const middlewares = ctx?.__metadata?.__middlewares?.filter((m) => m.target === "__global__" || m.target === propertyName) ?? [];
478
- return middlewares.sort((a) => a.target === "__global__" ? -1 : 1);
479
- }
480
- };
481
-
482
- //#endregion
483
- //#region packages/core/src/Services/ErrorHandler/ErrorHandlerProvider.ts
484
- /**
485
- * Abstract class representing an error handler provider
486
- * Provides a common interface for different error handler implementations
487
- *
488
- * @abstract
489
- * @class ErrorHandlerProvider
490
- */
491
- var ErrorHandlerProvider = class {};
492
-
493
- //#endregion
494
- //#region packages/core/src/Services/Middleware/GlobalMiddlewareRegistry.ts
495
- /**
496
- * Manages global middleware registration and retrieval
497
- *
498
- * This class provides functionality to register and retrieve global middleware
499
- * configurations. It allows for adding middleware with specific options and
500
- * retrieving them in a standardized format.
501
- */
502
- var GlobalMiddlewareRegistry = class {
503
- fMiddlewares = new Set();
504
- /**
505
- * Retrieves all registered global middleware configurations
506
- *
507
- * @returns {MetadataTypes.Middleware[]} An array of middleware configurations
508
- */
509
- get middlewares() {
510
- return [...this.fMiddlewares.values()].map((m) => ({
511
- ...m.opts,
512
- target: "__global__",
513
- middleware: m.middleware
514
- }));
515
- }
516
- /**
517
- * Registers a global middleware configuration
518
- *
519
- * @param {typeof BaseMiddleware<T, U>} middleware - The middleware class to register
520
- * @param {GlobalMiddlewareParams<T>} opts - The middleware options
521
- * @returns {void}
522
- */
523
- registerGlobalMiddleware(middleware, opts) {
524
- this.fMiddlewares.add({
525
- middleware,
526
- opts
527
- });
528
- }
529
- };
530
-
531
- //#endregion
532
- //#region packages/core/src/Services/Router/RequestHandler.ts
533
- /**
534
- * Handles HTTP requests by preparing and executing route handlers with their associated middlewares
535
- *
536
- * The RequestHandler is responsible for:
537
- * - Preparing route handlers with their metadata
538
- * - Executing middleware chains (before and after)
539
- * - Processing request/response lifecycle
540
- * - Error handling during request processing
541
- */
542
- var RequestHandler = class {
543
- /** Resolver for extracting metadata from controller classes and methods */
544
- gMetadataResolver;
545
- /** DI container for resolving dependencies */
546
- gContainer;
547
- gGlobalMiddlewareRegistry;
548
- /**
549
- * Prepares a route handler by resolving its metadata and middlewares
550
- *
551
- * @param {RequestHandlerOptions} params - Configuration options for the handler
552
- * @returns {RouterTypes.RouterHandler} A prepared handler with resolved metadata and middlewares
553
- */
554
- prepareHandler(params) {
555
- const { instance, propertyName } = params;
556
- const prototype = Object.getPrototypeOf(instance);
557
- const method = this.gMetadataResolver.resolveMethod(prototype, propertyName);
558
- const middlewares = this.gMetadataResolver.resolveMiddlewares(prototype, propertyName);
559
- const globalMiddlewares = this.gGlobalMiddlewareRegistry.middlewares;
560
- const uniqueMiddlewares = [...middlewares, ...globalMiddlewares].filter((m, index, self) => self.findIndex((t) => t.middleware === m.middleware) === index);
561
- const resolvedMiddlewares = uniqueMiddlewares.map((m) => ({
562
- ...m,
563
- middleware: this.gContainer.resolve(m.middleware)
564
- }));
565
- const beforeMiddlewares = resolvedMiddlewares.filter((m) => !!m.middleware.onRequest);
566
- const afterMiddlewares = resolvedMiddlewares.filter((m) => !!m.middleware.onResponse);
567
- beforeMiddlewares.sort((a, b) => (a?.priority ?? 999) - (b?.priority ?? 999));
568
- afterMiddlewares.sort((a, b) => (a?.priority ?? 999) - (b?.priority ?? 999));
569
- return {
570
- instance,
571
- propertyName,
572
- args: method.args,
573
- middlewares: {
574
- beforeMiddlewares,
575
- afterMiddlewares
576
- },
577
- actions: method.actions
578
- };
579
- }
580
- /**
581
- * Processes an HTTP request through the middleware chain and route handler
582
- *
583
- * The request handling lifecycle:
584
- * 1. Execute "before" middlewares
585
- * 2. Apply route actions (status codes, redirects, etc.)
586
- * 3. Resolve handler arguments
587
- * 4. Execute the route handler
588
- * 5. Execute "after" middlewares
589
- * 6. Format and return the final response
590
- *
591
- * @param {Request} request - The incoming HTTP request
592
- * @param {RouterTypes.RouteMatched<RouterTypes.RouterHandler>} route - The matched route with handler data
593
- * @returns {Promise<Response>} The HTTP response
594
- */
595
- async handleRequest(request, route) {
596
- try {
597
- const { instance, propertyName, actions, args, middlewares } = route.data;
598
- let fakeResponse = new Response(void 0, { headers: { "Content-Type": request.headers.get("Content-Type") ?? "application/json" } });
599
- for await (const hook of middlewares?.beforeMiddlewares ?? []) try {
600
- const hookResponse = await hook.middleware.onRequest?.(request, fakeResponse, {
601
- middlewareArgs: hook.args,
602
- methodArgs: args
603
- });
604
- if (hookResponse instanceof Response) return hookResponse;
605
- } catch (error_) {
606
- this.gContainer.get(ErrorHandlerProvider).handleError(error_);
607
- }
608
- for (const action of actions) {
609
- const actionResponse = action.handler(request, fakeResponse);
610
- if (actionResponse !== null) fakeResponse = this.processOverrideResponse(actionResponse, fakeResponse);
611
- }
612
- const resolvedArgs = await this.gMetadataResolver.resolveArgs(args, {
613
- ...route,
614
- request,
615
- response: fakeResponse
616
- });
617
- let handlerResponse = instance[propertyName].call(instance, ...resolvedArgs?.map((a) => a.resolved) ?? []);
618
- if (handlerResponse instanceof Promise) handlerResponse = await handlerResponse;
619
- for await (const hook of middlewares?.afterMiddlewares ?? []) try {
620
- const hookResponse = await hook.middleware.onResponse?.(request, fakeResponse, handlerResponse);
621
- if (hookResponse !== null) fakeResponse = this.processOverrideResponse(hookResponse, fakeResponse);
622
- } catch (error_) {
623
- this.gContainer.get(ErrorHandlerProvider).handleError(error_);
624
- }
625
- const body = fakeResponse?.body ?? JSON.stringify(handlerResponse);
626
- return new Response(body, {
627
- status: fakeResponse.status,
628
- statusText: fakeResponse.statusText,
629
- headers: fakeResponse.headers
630
- });
631
- } catch (error_) {
632
- return this.gContainer.get(ErrorHandlerProvider).handleError(error_);
633
- }
634
- }
635
- /**
636
- * Processes and merges response overrides from middlewares or actions
637
- *
638
- * This method handles different response formats:
639
- * - If a full Response object is provided, it's used directly
640
- * - If ResponseInit is provided, it's merged with the base response
641
- *
642
- * @param {Response | ResponseInit} response - The response or response options to apply
643
- * @param {Response} [base] - The base response to extend (optional)
644
- * @returns {Response} The processed response with applied overrides
645
- * @private
646
- */
647
- processOverrideResponse(response, base) {
648
- let fakeResponse = base ?? new Response();
649
- if (response != null && response instanceof Response) return response;
650
- else if (response !== null) {
651
- const responseInit = response;
652
- fakeResponse = new Response(void 0, {
653
- status: responseInit?.status ?? fakeResponse.status,
654
- headers: responseInit?.headers ?? fakeResponse.headers,
655
- statusText: responseInit?.statusText ?? fakeResponse.statusText
656
- });
657
- }
658
- return fakeResponse;
659
- }
660
- };
661
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], RequestHandler.prototype, "gMetadataResolver", void 0);
662
- (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_di.Container)], RequestHandler.prototype, "gContainer", void 0);
663
- (0, import_decorate.default)([(0, __vercube_di.Inject)(GlobalMiddlewareRegistry)], RequestHandler.prototype, "gGlobalMiddlewareRegistry", void 0);
664
-
665
- //#endregion
666
- //#region packages/core/src/Utils/Mine.ts
667
- const mime = { getType(ext) {
668
- const types = {
669
- ".html": "text/html",
670
- ".css": "text/css",
671
- ".js": "application/javascript",
672
- ".json": "application/json",
673
- ".png": "image/png",
674
- ".jpg": "image/jpeg",
675
- ".jpeg": "image/jpeg",
676
- ".gif": "image/gif",
677
- ".svg": "image/svg+xml",
678
- ".ico": "image/x-icon"
679
- };
680
- return types[ext] || null;
681
- } };
682
-
683
- //#endregion
684
- //#region packages/core/src/Services/Router/StaticRequestHandler.ts
685
- /**
686
- * Handles serving static files over HTTP
687
- *
688
- * The StaticRequestHandler is responsible for:
689
- * - Serving static files from configured directories
690
- * - Setting appropriate content types and headers
691
- * - Handling caching and ETags
692
- * - Processing GET requests for static assets
693
- */
694
- var StaticRequestHandler = class {
695
- /**
696
- * The options for the static server
697
- */
698
- fOptions;
699
- /**
700
- * Initializes the static server with the given options
701
- *
702
- * @param {ConfigTypes.ServerOptions['static']} options - The options for the static server
703
- * @returns {void}
704
- */
705
- initialize(options) {
706
- this.fOptions = options;
707
- }
708
- /**
709
- * Handles HTTP requests for static files
710
- *
711
- * @param {Request} request - The incoming HTTP request
712
- * @returns {Promise<void | Response>} A promise that resolves to void or a Response object
713
- */
714
- async handleRequest(request) {
715
- const dirs = this.fOptions?.dirs ?? [];
716
- if (!dirs) return;
717
- if (request.method !== "GET") return;
718
- const url = new URL(request.url);
719
- const path = (0, node_path.normalize)(url.pathname);
720
- let relativePath = path;
721
- for (const dir of dirs) relativePath = relativePath.replace(dir, "");
722
- for (const dir of dirs) {
723
- const fullPath = (0, node_path.join)(process.cwd(), dir, relativePath);
724
- try {
725
- const stats = await (0, node_fs_promises.stat)(fullPath);
726
- if (stats.isDirectory()) continue;
727
- if (stats.isFile()) return this.serveFile(fullPath, stats);
728
- } catch {
729
- continue;
730
- }
731
- }
732
- }
733
- /**
734
- * Serves a static file and returns a Response object
735
- *
736
- * @param {string} path - The path to the file to serve
737
- * @param {any} stats - The stats object for the file
738
- * @returns {Promise<Response>} A promise that resolves to a Response object
739
- */
740
- async serveFile(path, stats) {
741
- const headers = new Headers();
742
- const ext = (0, node_path.extname)(path).toLowerCase();
743
- const contentType = mime.getType(ext) || "application/octet-stream";
744
- headers.set("Content-Type", contentType);
745
- headers.set("Content-Length", stats.size.toString());
746
- if (this.fOptions?.maxAge && this.fOptions.maxAge > 0) {
747
- const directives = ["public", `max-age=${this.fOptions.maxAge}`];
748
- if (this.fOptions?.immutable) directives.push("immutable");
749
- headers.set("Cache-Control", directives.join(", "));
750
- }
751
- if (this.fOptions?.etag) headers.set("ETag", `W/"${stats.size}-${stats.mtime.getTime()}"`);
752
- const stream = (0, node_fs.createReadStream)(path);
753
- return new Response(stream, { headers });
754
- }
755
- };
756
-
757
- //#endregion
758
- //#region packages/core/src/Services/HttpServer/HttpServer.ts
759
- /**
760
- * HTTP server implementation for handling incoming web requests
761
- *
762
- * This class is responsible for:
763
- * - Initializing and managing the HTTP server
764
- * - Routing incoming requests to appropriate handlers
765
- * - Processing HTTP responses
766
- */
767
- var HttpServer = class {
768
- /**
769
- * DI container for resolving dependencies
770
- */
771
- gContainer;
772
- /**
773
- * Router service for resolving routes
774
- */
775
- gRouter;
776
- /**
777
- * Handler for processing HTTP requests
778
- */
779
- gRequestHandler;
780
- /**
781
- * Static server for serving static files
782
- */
783
- gStaticRequestHandler;
784
- /**
785
- * Underlying server instance
786
- * @private
787
- */
788
- fServer;
789
- /**
790
- * Initializes the HTTP server and starts listening for requests
791
- *
792
- * @returns {Promise<void>} A promise that resolves when the server is ready
793
- */
794
- async initialize(config) {
795
- const { port, host } = config.server ?? {};
796
- this.fServer = (0, srvx.serve)({
797
- bun: { error: (error) => {
798
- return this.gContainer.get(ErrorHandlerProvider).handleError(error);
799
- } },
800
- deno: { onError: (error) => {
801
- return this.gContainer.get(ErrorHandlerProvider).handleError(error);
802
- } },
803
- hostname: host,
804
- port,
805
- fetch: this.handleRequest.bind(this)
806
- });
807
- }
808
- /**
809
- * Listens for incoming requests on the HTTP server
810
- *
811
- * @returns {Promise<void>} A promise that resolves when the server is ready to listen
812
- */
813
- async listen() {
814
- await this.fServer.ready();
815
- }
816
- /**
817
- * Processes an incoming HTTP request
818
- *
819
- * This method:
820
- * 1. Resolves the route for the request
821
- * 2. Returns a 404 response if no route is found
822
- * 3. Delegates to the request handler for matched routes
823
- *
824
- * @param {Request} request - The incoming HTTP request
825
- * @returns {Promise<Response>} The HTTP response
826
- * @private
827
- */
828
- async handleRequest(request) {
829
- try {
830
- const route = this.gRouter.resolve({
831
- path: request.url,
832
- method: request.method
833
- });
834
- if (!route) {
835
- const response = await this.gStaticRequestHandler.handleRequest(request);
836
- if (response) return response;
837
- else throw new NotFoundError("Route not found");
838
- }
839
- return this.gRequestHandler.handleRequest(request, route);
840
- } catch (error) {
841
- return this.gContainer.get(ErrorHandlerProvider).handleError(error);
842
- }
843
- }
844
- };
845
- (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_di.Container)], HttpServer.prototype, "gContainer", void 0);
846
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], HttpServer.prototype, "gRouter", void 0);
847
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], HttpServer.prototype, "gRequestHandler", void 0);
848
- (0, import_decorate.default)([(0, __vercube_di.Inject)(StaticRequestHandler)], HttpServer.prototype, "gStaticRequestHandler", void 0);
849
-
850
- //#endregion
851
- //#region packages/core/src/Common/App.ts
852
- /**
853
- * Represents the main application class.
854
- */
855
- var App = class {
856
- gRouter;
857
- gPluginsRegistry;
858
- gHttpServer;
859
- gStaticRequestHandler;
860
- gLogger;
861
- /** Holds the initialization status of the application */
862
- fIsInitialized = false;
863
- /** Holds the dependency injection container */
864
- fInternalContainer;
865
- /** Hold app config */
866
- fConfig;
867
- /**
868
- * Gets the dependency injection container.
869
- *
870
- * @returns {Container} The dependency injection container.
871
- */
872
- get container() {
873
- return this.fInternalContainer;
874
- }
875
- /**
876
- * Sets the dependency injection container.
877
- *
878
- * @param {Container} container - The dependency injection container.
879
- */
880
- set container(container) {
881
- this.fInternalContainer = container;
882
- }
883
- /**
884
- * Initializes the application.
885
- *
886
- * @returns {Promise<void>} A promise that resolves when the application is initialized.
887
- */
888
- async init(cfg) {
889
- this.fConfig = cfg;
890
- await this.gHttpServer.initialize(this.fConfig);
891
- if (this.fConfig.server?.static) this.gStaticRequestHandler.initialize(this.fConfig.server?.static);
892
- this.gRouter.initialize();
893
- }
894
- /**
895
- * Registers a plugin.
896
- *
897
- * @param {typeof Plugin} plugin - The plugin to register.
898
- * @param {unknown} options - The options to pass to the plugin.
899
- */
900
- registerPlugin(plugin, options) {
901
- this.gPluginsRegistry.register(plugin, options);
902
- }
903
- /**
904
- * Starts the application and begins listening for incoming requests.
905
- *
906
- * @returns {Promise<void>} A promise that resolves when the application starts listening.
907
- * @throws {Error} If the application is already initialized.
908
- */
909
- async listen() {
910
- if (this.fIsInitialized) throw new Error("App is already initialized");
911
- await this.resolvePlugins();
912
- (0, __vercube_di.initializeContainer)(this.container);
913
- await this.gHttpServer.listen();
914
- this.gLogger?.info(`\n${__vercube_logger.colors.green("➜")} App listening on port ${__vercube_logger.colors.bold(this.fConfig.server?.port?.toString() ?? "3000")}`);
915
- this.fIsInitialized = true;
916
- }
917
- /**
918
- * Handles an incoming HTTP request.
919
- * This method is an adapter for HttpServer.handleRequest method.
920
- *
921
- * @param {Request} request - The incoming HTTP request
922
- * @returns {Promise<Response>} The HTTP response
923
- */
924
- async fetch(request) {
925
- return this.gHttpServer.handleRequest(request);
926
- }
927
- /**
928
- * Resolves and initializes the plugins for the application.
929
- *
930
- * @private
931
- */
932
- async resolvePlugins() {
933
- await this.gPluginsRegistry.init(this);
934
- }
935
- };
936
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], App.prototype, "gRouter", void 0);
937
- (0, import_decorate.default)([(0, __vercube_di.Inject)(PluginsRegistry)], App.prototype, "gPluginsRegistry", void 0);
938
- (0, import_decorate.default)([(0, __vercube_di.Inject)(HttpServer)], App.prototype, "gHttpServer", void 0);
939
- (0, import_decorate.default)([(0, __vercube_di.Inject)(StaticRequestHandler)], App.prototype, "gStaticRequestHandler", void 0);
940
- (0, import_decorate.default)([(0, __vercube_di.InjectOptional)(__vercube_logger.Logger)], App.prototype, "gLogger", void 0);
941
-
942
- //#endregion
943
- //#region packages/logger/dist/Providers/index.mjs
944
- /**
945
- * Abstract base class for implementing log provider.
946
- * Providers are responsible for processing and outputting log messages to various destinations.
947
- * Each appender can be initialized with custom options and handles message processing according to its implementation.
948
- *
949
- * @template T - The type of options used to initialize the appender
950
- */
951
- var LoggerProvider = class {};
952
- const isColorAllowed = () => !process.env.NO_COLOR;
953
- const colorIfAllowed = (colorFn) => {
954
- const wrappedFn = (text) => {
955
- return isColorAllowed() ? colorFn(text) : text;
956
- };
957
- return wrappedFn;
958
- };
959
- const colors = {
960
- bold: colorIfAllowed((text) => `\x1B[1m${text}\x1B[0m`),
961
- green: colorIfAllowed((text) => `\x1B[32m${text}\x1B[39m`),
962
- yellow: colorIfAllowed((text) => `\x1B[33m${text}\x1B[39m`),
963
- red: colorIfAllowed((text) => `\x1B[31m${text}\x1B[39m`),
964
- magentaBright: colorIfAllowed((text) => `\x1B[95m${text}\x1B[39m`),
965
- cyanBright: colorIfAllowed((text) => `\x1B[96m${text}\x1B[39m`)
966
- };
967
- const LOG_LEVEL_COLORS = {
968
- debug: colors.green,
969
- info: colors.bold,
970
- warn: colors.yellow,
971
- error: colors.red
972
- };
973
- /**
974
- * ConsoleProvider class for logging messages to the console.
975
- */
976
- var ConsoleProvider = class extends LoggerProvider {
977
- /**
978
- * Initializes the appender with the provided options.
979
- * This method should be called before using the appender to process messages.
980
- */
981
- initialize() {}
982
- /**
983
- * Prints a log message according to the specified format and level.
984
- * @param message - The log message object containing level, tag, and arguments
985
- * @protected
986
- */
987
- processMessage(message) {
988
- const date = message.timestamp ? new Date(message.timestamp) : new Date();
989
- console[message.level](`%s%s${message?.tag ? "%s" : ""} %s`, LOG_LEVEL_COLORS[message.level](`[${date.toISOString().split("T")[1]?.replace("Z", "")}]`), LOG_LEVEL_COLORS[message.level](`[${message.level.toUpperCase().padEnd(5, " ")}]`), message?.tag ? LOG_LEVEL_COLORS[message.level](`[${message.tag}]`) : "", ...message.args);
990
- }
991
- };
992
-
993
- //#endregion
994
- //#region packages/core/src/Services/Validation/ValidationProvider.ts
995
- /**
996
- * Abstract class representing a validation provider
997
- * Provides a common interface for different validation implementations
998
- *
999
- * @abstract
1000
- * @class ValidationProvider
1001
- */
1002
- var ValidationProvider = class {};
1003
-
1004
- //#endregion
1005
- //#region packages/core/src/Services/Validation/StandardSchemaValidationProvider.ts
1006
- /**
1007
- * StandardSchemaValidationProvider implements validation using StandardSchema schema validation
1008
- * @see https://github.com/standard-schema/standard-schema
1009
- * @class
1010
- * @implements {ValidationProvider}
1011
- */
1012
- var StandardSchemaValidationProvider = class {
1013
- /**
1014
- * Validates data against a schema
1015
- * @param {ValidationTypes.Schema} schema - The schema to validate against
1016
- * @param {ValidationTypes.Input} data - The data to validate
1017
- * @return {ValidationTypes.Result | Promise<ValidationTypes.Result>} The validation result
1018
- */
1019
- validate(schema, data) {
1020
- return schema["~standard"].validate(data);
1021
- }
1022
- };
1023
-
1024
- //#endregion
1025
- //#region packages/core/src/Services/Config/RuntimeConfig.ts
1026
- /**
1027
- * RuntimeConfig class manages the runtime configuration for the Vercube application.
1028
- * This class provides a centralized way to access and modify runtime configuration settings.
1029
- */
1030
- var RuntimeConfig = class {
1031
- /**
1032
- * Private field to store the runtime configuration object.
1033
- * @private
1034
- */
1035
- fRuntimeConfig;
1036
- /**
1037
- * Gets the current runtime configuration.
1038
- * @returns {ConfigTypes.RuntimeConfig} The current runtime configuration object.
1039
- */
1040
- get runtimeConfig() {
1041
- return this.fRuntimeConfig;
1042
- }
1043
- /**
1044
- * Sets the runtime configuration.
1045
- * @param {ConfigTypes.RuntimeConfig} value - The new runtime configuration object to set.
1046
- */
1047
- set runtimeConfig(value) {
1048
- this.fRuntimeConfig = value;
1049
- }
1050
- };
1051
-
1052
- //#endregion
1053
- //#region packages/core/src/Errors/Http/InternalServerError.ts
1054
- /**
1055
- * Represents an Internal Server error (HTTP 500).
1056
- * @extends {HttpError}
1057
- */
1058
- var InternalServerError = class InternalServerError extends HttpError {
1059
- /**
1060
- * The name of the error.
1061
- * @type {string}
1062
- */
1063
- name = "InternalServerError";
1064
- /**
1065
- * Creates an instance of InternalServerError.
1066
- * @param {string} [message] - The error message.
1067
- */
1068
- constructor(message) {
1069
- super(500);
1070
- Object.setPrototypeOf(this, InternalServerError.prototype);
1071
- if (message) this.message = message;
1072
- }
1073
- };
1074
-
1075
- //#endregion
1076
- //#region packages/core/src/Services/ErrorHandler/DefaultErrorHandlerProvider.ts
1077
- /**
1078
- * Default error handler provider
1079
- *
1080
- * @class DefaultErrorHandlerProvider
1081
- */
1082
- var DefaultErrorHandlerProvider = class extends ErrorHandlerProvider {
1083
- gLogger;
1084
- /**
1085
- * Handles an error that occurred during request processing
1086
- *
1087
- * @param error - The Error object containing error details
1088
- * @returns Promise<Response> | Response - The response to be sent to the client
1089
- */
1090
- handleError(error) {
1091
- const _internalError = new InternalServerError(error?.message ?? "Internal server error");
1092
- const status = error?.status ?? 500;
1093
- if (error instanceof HttpError) return new Response(JSON.stringify({ ...error }, void 0, 2), { status });
1094
- this.gLogger.error(error);
1095
- return new Response(JSON.stringify({ ...error?.cause ?? _internalError }, void 0, 2), { status });
1096
- }
1097
- };
1098
- (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_logger.Logger)], DefaultErrorHandlerProvider.prototype, "gLogger", void 0);
1099
-
1100
- //#endregion
1101
- //#region packages/core/src/Common/Container.ts
1102
- /**
1103
- * Creates and configures a new dependency injection container for the application.
1104
- *
1105
- * @returns {Container} A configured dependency injection container.
1106
- */
1107
- function createContainer(config) {
1108
- const container = new __vercube_di.Container();
1109
- container.bindInstance(__vercube_di.Container, container);
1110
- container.bind(__vercube_logger.Logger, __vercube_logger.BaseLogger);
1111
- container.get(__vercube_logger.Logger).configure({
1112
- logLevel: config.logLevel ?? "debug",
1113
- providers: [{
1114
- name: "console",
1115
- provider: ConsoleProvider
1116
- }]
1117
- });
1118
- container.bind(ErrorHandlerProvider, DefaultErrorHandlerProvider);
1119
- container.bind(HttpServer);
1120
- container.bind(StaticRequestHandler);
1121
- container.bind(Router);
1122
- container.bind(HooksService);
1123
- container.bind(MetadataResolver);
1124
- container.bind(PluginsRegistry);
1125
- container.bind(RequestHandler);
1126
- container.bind(RuntimeConfig);
1127
- container.bind(GlobalMiddlewareRegistry);
1128
- container.bind(ValidationProvider, StandardSchemaValidationProvider);
1129
- return container;
1130
- }
1131
-
1132
- //#endregion
1133
- //#region packages/core/src/Utils/InternalUtils.ts
1134
- /**
1135
- * Generate random hash
1136
- * @returns string
1137
- */
1138
- function generateRandomHash() {
1139
- const hashByPerformance = Math.floor(Date.now() * 1e3).toString(16);
1140
- const hashByMath = () => (Math.floor(Math.random() * 16777215) | 1048576).toString(16);
1141
- return `${hashByPerformance}-${hashByMath()}-${hashByMath()}-${hashByMath()}`;
1142
- }
1143
-
1144
- //#endregion
1145
- //#region packages/core/src/Config/DefaultConfig.ts
1146
- /**
1147
- * Default configuration for the Vercube application.
1148
- * This configuration serves as the base settings and can be overridden by user configuration.
1149
- */
1150
- const defaultConfig = {
1151
- logLevel: "debug",
1152
- production: false,
1153
- dev: false,
1154
- build: {
1155
- root: process.cwd(),
1156
- entry: "src/index.ts",
1157
- output: {
1158
- dir: "dist",
1159
- publicDir: "public"
1160
- },
1161
- bundler: "rolldown"
1162
- },
1163
- server: {
1164
- runtime: "node",
1165
- host: "localhost",
1166
- port: 3e3,
1167
- https: false,
1168
- static: { dirs: ["public"] }
1169
- },
1170
- experimental: {},
1171
- runtime: { session: {
1172
- secret: process.env?.SECRET ?? generateRandomHash(),
1173
- name: "vercube_session",
1174
- duration: 60 * 60 * 24 * 7
1175
- } }
1176
- };
1177
-
1178
- //#endregion
1179
- //#region packages/core/src/Config/Loader.ts
1180
- /**
1181
- * Loads the configuration object for the application
1182
- * @param {ConfigTypes.Config} overrides - The configuration object to load
1183
- * @returns {ConfigTypes.Config} The loaded configuration object
1184
- */
1185
- async function loadVercubeConfig(overrides) {
1186
- const config = await (0, c12.loadConfig)({
1187
- name: "vercube",
1188
- dotenv: true,
1189
- rcFile: false,
1190
- globalRc: false,
1191
- defaults: defaultConfig
1192
- });
1193
- return (0, defu.defu)(overrides ?? {}, config?.config ?? {});
1194
- }
1195
-
1196
- //#endregion
1197
- //#region packages/core/src/Common/CreateApp.ts
1198
- /**
1199
- * Creates and initializes an instance of the App.
1200
- *
1201
- * @returns {Promise<App>} A promise that resolves to an instance of the App.
1202
- */
1203
- async function createApp(cfg) {
1204
- const config = await loadVercubeConfig(cfg);
1205
- const container = createContainer(config);
1206
- const app = container.resolve(App);
1207
- container.get(RuntimeConfig).runtimeConfig = config?.runtime ?? {};
1208
- app.container = container;
1209
- await app.init(config);
1210
- (0, __vercube_di.initializeContainer)(container);
1211
- return app;
1212
- }
1213
-
1214
- //#endregion
1215
- //#region packages/core/src/Config/Config.ts
1216
- /**
1217
- * Defines a configuration object for the application
1218
- * @param {ConfigTypes.Config} config - The configuration object to validate
1219
- * @returns {ConfigTypes.Config} The validated configuration object
1220
- */
1221
- function defineConfig(config) {
1222
- return config;
1223
- }
1224
-
1225
- //#endregion
1226
- //#region packages/core/src/Middleware/ValidationMiddleware.ts
1227
- /**
1228
- * Middleware for validating request data against a schema
1229
- * @class ValidationMiddleware
1230
- * @implements {BaseMiddleware}
1231
- * @description Validates incoming request data against a provided schema
1232
- * @example
1233
- * const middleware = new ValidationMiddleware();
1234
- * await middleware.use(event, { schema: myValidationSchema });
1235
- */
1236
- var ValidationMiddleware = class {
1237
- gValidationProvider;
1238
- /**
1239
- * Middleware function that processes the HTTP event
1240
- * @param {Request} request - The HTTP request object
1241
- * @param {Response} response - The HTTP response object
1242
- * @param {MiddlewareOptions} args - Additional arguments for the middleware
1243
- * @returns {Promise<void>} - A promise that resolves when the processing is complete
1244
- * @throws {BadRequestError} - If validation fails
1245
- */
1246
- async onRequest(request, response, args) {
1247
- if (!this.gValidationProvider) {
1248
- console.warn("ValidationMiddleware::ValidationProvider is not registered");
1249
- return;
1250
- }
1251
- const validators = args.methodArgs?.filter((arg) => arg.validate && arg.validationSchema) ?? [];
1252
- for (const validator of validators) {
1253
- const result = await this.gValidationProvider.validate(validator.validationSchema, validator.resolved);
1254
- if (result.issues?.length) throw new BadRequestError(`Validation error - ${validator.type}`, result.issues);
1255
- }
1256
- }
1257
- };
1258
- (0, import_decorate.default)([(0, __vercube_di.InjectOptional)(ValidationProvider)], ValidationMiddleware.prototype, "gValidationProvider", void 0);
1259
-
1260
- //#endregion
1261
- //#region packages/core/src/Utils/Utils.ts
1262
- /**
1263
- * Creates a new metadata context.
1264
- * @returns {MetadataTypes.Ctx} The new metadata context.
1265
- */
1266
- function createMetadataCtx() {
1267
- return {
1268
- __controller: { path: "" },
1269
- __middlewares: [],
1270
- __methods: {}
1271
- };
1272
- }
1273
- /**
1274
- * Creates a new metadata method.
1275
- * @returns {MetadataTypes.Method} The new metadata method.
1276
- */
1277
- function createMetadataMethod() {
1278
- return {
1279
- req: null,
1280
- res: null,
1281
- url: null,
1282
- args: [],
1283
- actions: []
1284
- };
1285
- }
1286
- /**
1287
- * Initializes the metadata for a given target and property name.
1288
- * @param {any} target - The target to initialize metadata for.
1289
- * @param {string} propertyName - The name of the property to initialize metadata for.
1290
- */
1291
- function initializeMetadataMethod(target, propertyName) {
1292
- if (!target.__metadata.__methods[propertyName]) target.__metadata.__methods[propertyName] = createMetadataMethod();
1293
- return target.__metadata.__methods[propertyName];
1294
- }
1295
- /**
1296
- * Initializes the metadata for a given target.
1297
- * @param {any} target - The target to initialize metadata for.
1298
- */
1299
- function initializeMetadata(target) {
1300
- if (!target.__metadata) target.__metadata = createMetadataCtx();
1301
- if (!target.__metadata.__methods) target.__metadata.__methods = {};
1302
- if (!target.__metadata.__middlewares) target.__metadata.__middlewares = [];
1303
- return target.__metadata;
1304
- }
1305
-
1306
- //#endregion
1307
- //#region packages/core/src/Decorators/Http/Body.ts
1308
- /**
1309
- * @class BodyDecorator
1310
- * @extends BaseDecorator<BodyDecoratorOptions>
1311
- *
1312
- * A decorator class that handles the metadata for HTTP request bodies.
1313
- */
1314
- var BodyDecorator = class extends __vercube_di.BaseDecorator {
1315
- /**
1316
- * @method created
1317
- * This method is called when the decorator is created. It ensures that the metadata
1318
- * for the property exists and adds the body argument to the metadata.
1319
- */
1320
- created() {
1321
- const meta = initializeMetadata(this.prototype);
1322
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
1323
- method.args.push({
1324
- idx: this.propertyIndex,
1325
- type: "body",
1326
- validate: this.options?.validationSchema ? true : false,
1327
- validationSchema: this.options?.validationSchema
1328
- });
1329
- meta.__middlewares.unshift({
1330
- target: this.propertyName,
1331
- priority: -1,
1332
- args: {},
1333
- middleware: ValidationMiddleware
1334
- });
1335
- }
1336
- };
1337
- /**
1338
- * @function Body
1339
- * @returns {Function} A decorator function that registers the BodyDecorator.
1340
- *
1341
- * This function creates and returns a decorator that can be used to annotate
1342
- * a parameter in a method to indicate that it should be populated with the
1343
- * body of an HTTP request. The decorator uses the BodyDecorator class to
1344
- * handle the metadata associated with the parameter.
1345
- */
1346
- function Body(options) {
1347
- return (0, __vercube_di.createDecorator)(BodyDecorator, options);
1348
- }
1349
-
1350
- //#endregion
1351
- //#region packages/core/src/Decorators/Http/Connect.ts
1352
- /**
1353
- * A decorator class for handling HTTP CONNECT requests.
1354
- *
1355
- * This class extends the BaseDecorator and is used to register CONNECT routes
1356
- * with the Router. It also resolves metadata for the route handler
1357
- * using the MetadataResolver.
1358
- *
1359
- * @extends {BaseDecorator<ConnectDecoratorOptions>}
1360
- */
1361
- var ConnectDecorator = class extends __vercube_di.BaseDecorator {
1362
- gRouter;
1363
- gRequestHandler;
1364
- gMetadataResolver;
1365
- /**
1366
- * Called when the decorator is created.
1367
- *
1368
- * This method constructs the full path for the route, registers the route
1369
- * with the Router, and sets up the event handler for the CONNECT request.
1370
- */
1371
- created() {
1372
- this.options.path = this.gMetadataResolver.resolveUrl({
1373
- instance: this.instance,
1374
- path: this.options.path,
1375
- propertyName: this.propertyName
1376
- });
1377
- this.gRouter.addRoute({
1378
- path: this.options.path,
1379
- method: "CONNECT",
1380
- handler: this.gRequestHandler.prepareHandler({
1381
- instance: this.instance,
1382
- propertyName: this.propertyName
1383
- })
1384
- });
1385
- }
1386
- };
1387
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], ConnectDecorator.prototype, "gRouter", void 0);
1388
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], ConnectDecorator.prototype, "gRequestHandler", void 0);
1389
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], ConnectDecorator.prototype, "gMetadataResolver", void 0);
1390
- /**
1391
- * A factory function for creating a ConnectDecorator.
1392
- *
1393
- * This function returns a decorator function that can be used to annotate
1394
- * a method with CONNECT route information.
1395
- *
1396
- * @param {string} path - The path for the CONNECT route.
1397
- * @return {Function} The decorator function.
1398
- */
1399
- function Connect(path) {
1400
- return (0, __vercube_di.createDecorator)(ConnectDecorator, { path });
1401
- }
1402
-
1403
- //#endregion
1404
- //#region packages/core/src/Decorators/Http/Controller.ts
1405
- /**
1406
- * A factory function for creating a Controller decorator.
1407
- *
1408
- * This function returns a decorator function that can be used to annotate
1409
- * a class with controller metadata, including the base path for the controller.
1410
- *
1411
- * @param {string} path - The base path for the controller.
1412
- * @return {Function} The decorator function.
1413
- */
1414
- function Controller(path) {
1415
- return function internalDecorator(target) {
1416
- const meta = initializeMetadata(target.prototype);
1417
- meta.__controller = {
1418
- ...meta?.__controller,
1419
- path
1420
- };
1421
- };
1422
- }
1423
-
1424
- //#endregion
1425
- //#region packages/core/src/Decorators/Http/Delete.ts
1426
- /**
1427
- * A decorator class for handling HTTP DELETE requests.
1428
- *
1429
- * This class extends the BaseDecorator and is used to register DELETE routes
1430
- * with the Router. It also resolves metadata for the route handler
1431
- * using the MetadataResolver.
1432
- *
1433
- * @extends {BaseDecorator<DeleteDecoratorOptions>}
1434
- */
1435
- var DeleteDecorator = class extends __vercube_di.BaseDecorator {
1436
- gRouter;
1437
- gRequestHandler;
1438
- gMetadataResolver;
1439
- /**
1440
- * Called when the decorator is created.
1441
- *
1442
- * This method constructs the full path for the route, registers the route
1443
- * with the Router, and sets up the event handler for the DELETE request.
1444
- */
1445
- created() {
1446
- initializeMetadata(this.prototype);
1447
- initializeMetadataMethod(this.prototype, this.propertyName);
1448
- this.options.path = this.gMetadataResolver.resolveUrl({
1449
- instance: this.instance,
1450
- path: this.options.path,
1451
- propertyName: this.propertyName
1452
- });
1453
- this.gRouter.addRoute({
1454
- path: this.options.path,
1455
- method: "DELETE",
1456
- handler: this.gRequestHandler.prepareHandler({
1457
- instance: this.instance,
1458
- propertyName: this.propertyName
1459
- })
1460
- });
1461
- }
1462
- };
1463
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], DeleteDecorator.prototype, "gRouter", void 0);
1464
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], DeleteDecorator.prototype, "gRequestHandler", void 0);
1465
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], DeleteDecorator.prototype, "gMetadataResolver", void 0);
1466
- /**
1467
- * A factory function for creating a DeleteDecorator.
1468
- *
1469
- * This function returns a decorator function that can be used to annotate
1470
- * a method with DELETE route information.
1471
- *
1472
- * @param {string} path - The path for the DELETE route.
1473
- * @return {Function} The decorator function.
1474
- */
1475
- function Delete(path) {
1476
- return (0, __vercube_di.createDecorator)(DeleteDecorator, { path });
1477
- }
1478
-
1479
- //#endregion
1480
- //#region packages/core/src/Decorators/Http/Get.ts
1481
- /**
1482
- * A decorator class for handling HTTP GET requests.
1483
- *
1484
- * This class extends the BaseDecorator and is used to register GET routes
1485
- * with the Router. It also resolves metadata for the route handler
1486
- * using the MetadataResolver.
1487
- *
1488
- * @extends {BaseDecorator<GetDecoratorOptions>}
1489
- */
1490
- var GetDecorator = class extends __vercube_di.BaseDecorator {
1491
- gRouter;
1492
- gRequestHandler;
1493
- gMetadataResolver;
1494
- /**
1495
- * Called when the decorator is created.
1496
- *
1497
- * This method constructs the full path for the route, registers the route
1498
- * with the Router, and sets up the event handler for the GET request.
1499
- */
1500
- created() {
1501
- initializeMetadata(this.prototype);
1502
- initializeMetadataMethod(this.prototype, this.propertyName);
1503
- this.options.path = this.gMetadataResolver.resolveUrl({
1504
- instance: this.instance,
1505
- path: this.options.path,
1506
- propertyName: this.propertyName
1507
- });
1508
- this.gRouter.addRoute({
1509
- path: this.options.path,
1510
- method: "GET",
1511
- handler: this.gRequestHandler.prepareHandler({
1512
- instance: this.instance,
1513
- propertyName: this.propertyName
1514
- })
1515
- });
1516
- }
1517
- };
1518
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], GetDecorator.prototype, "gRouter", void 0);
1519
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], GetDecorator.prototype, "gRequestHandler", void 0);
1520
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], GetDecorator.prototype, "gMetadataResolver", void 0);
1521
- /**
1522
- * A decorator function for handling HTTP GET requests.
1523
- *
1524
- * This function creates an instance of the GetDecorator class and registers
1525
- * the GET route with the specified path.
1526
- *
1527
- * @param {string} path - The path for the GET route.
1528
- * @returns {Function} - The decorator function.
1529
- */
1530
- function Get(path) {
1531
- return (0, __vercube_di.createDecorator)(GetDecorator, { path });
1532
- }
1533
-
1534
- //#endregion
1535
- //#region packages/core/src/Decorators/Http/Head.ts
1536
- /**
1537
- * A decorator class for handling HTTP HEAD requests.
1538
- *
1539
- * This class extends the BaseDecorator and is used to register HEAD routes
1540
- * with the Router. It also resolves metadata for the route handler
1541
- * using the MetadataResolver.
1542
- *
1543
- * @extends {BaseDecorator<HeadDecoratorOptions>}
1544
- */
1545
- var HeadDecorator = class extends __vercube_di.BaseDecorator {
1546
- gRouter;
1547
- gRequestHandler;
1548
- gMetadataResolver;
1549
- /**
1550
- * Called when the decorator is created.
1551
- *
1552
- * This method constructs the full path for the route, registers the route
1553
- * with the Router, and sets up the event handler for the HEAD request.
1554
- */
1555
- created() {
1556
- initializeMetadata(this.prototype);
1557
- initializeMetadataMethod(this.prototype, this.propertyName);
1558
- this.options.path = this.gMetadataResolver.resolveUrl({
1559
- instance: this.instance,
1560
- path: this.options.path,
1561
- propertyName: this.propertyName
1562
- });
1563
- this.gRouter.addRoute({
1564
- path: this.options.path,
1565
- method: "HEAD",
1566
- handler: this.gRequestHandler.prepareHandler({
1567
- instance: this.instance,
1568
- propertyName: this.propertyName
1569
- })
1570
- });
1571
- }
1572
- };
1573
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], HeadDecorator.prototype, "gRouter", void 0);
1574
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], HeadDecorator.prototype, "gRequestHandler", void 0);
1575
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], HeadDecorator.prototype, "gMetadataResolver", void 0);
1576
- /**
1577
- * A factory function for creating a HeadDecorator.
1578
- *
1579
- * This function returns a decorator function that can be used to annotate
1580
- * a method with HEAD route information.
1581
- *
1582
- * @param {string} path - The path for the HEAD route.
1583
- * @return {Function} The decorator function.
1584
- */
1585
- function Head(path) {
1586
- return (0, __vercube_di.createDecorator)(HeadDecorator, { path });
1587
- }
1588
-
1589
- //#endregion
1590
- //#region packages/core/src/Decorators/Http/Header.ts
1591
- /**
1592
- * A decorator class for handling HTTP header parameters.
1593
- *
1594
- * This class extends the BaseDecorator and is used to register header parameters
1595
- * with the MetadataResolver. It ensures that the metadata for the property is created
1596
- * and adds the header information to the metadata.
1597
- *
1598
- * @extends {BaseDecorator<HeaderDecoratorOptions>}
1599
- */
1600
- var HeaderDecorator = class extends __vercube_di.BaseDecorator {
1601
- /**
1602
- * Called when the decorator is created.
1603
- *
1604
- * This method checks if metadata for the property exists, creates it if it doesn't,
1605
- * and then adds the header information to the metadata.
1606
- */
1607
- created() {
1608
- initializeMetadata(this.prototype);
1609
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
1610
- method.args.push({
1611
- idx: this.propertyIndex,
1612
- type: "header",
1613
- data: { name: this.options.name }
1614
- });
1615
- }
1616
- };
1617
- /**
1618
- * A decorator function for handling HTTP header parameters.
1619
- *
1620
- * This function creates a HeaderDecorator with the specified name and registers it.
1621
- * It is used to annotate a parameter in a method to indicate that it should be
1622
- * populated with the value of a specific HTTP header.
1623
- *
1624
- * @param {string} name - The name of the HTTP header to bind to the parameter.
1625
- * @returns {Function} - A decorator function that registers the HeaderDecorator.
1626
- */
1627
- function Header(name) {
1628
- return (0, __vercube_di.createDecorator)(HeaderDecorator, { name });
1629
- }
1630
-
1631
- //#endregion
1632
- //#region packages/core/src/Decorators/Http/Headers.ts
1633
- /**
1634
- * This class is responsible for managing headers decorator.
1635
- *
1636
- * This class extends the BaseDecorator and is used to register headers parameters
1637
- * with the MetadataResolver. It ensures that the metadata for the property is created
1638
- * and adds the headers information to the metadata.
1639
- *
1640
- * @extends {BaseDecorator<{}>}
1641
- */
1642
- var HeadersDecorator = class extends __vercube_di.BaseDecorator {
1643
- /**
1644
- * Called when the decorator is created.
1645
- *
1646
- * This method checks if metadata for the property exists, creates it if it doesn't,
1647
- * and then adds the headers information to the metadata.
1648
- */
1649
- created() {
1650
- initializeMetadata(this.prototype);
1651
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
1652
- method.args.push({
1653
- idx: this.propertyIndex,
1654
- type: "headers"
1655
- });
1656
- }
1657
- };
1658
- /**
1659
- * A factory function for creating a HeadersDecorator.
1660
- *
1661
- * This function returns a decorator function that can be used to annotate
1662
- * a method parameter with headers information.
1663
- *
1664
- * @return {Function} The decorator function.
1665
- */
1666
- function Headers$1() {
1667
- return (0, __vercube_di.createDecorator)(HeadersDecorator, {});
1668
- }
1669
-
1670
- //#endregion
1671
- //#region packages/core/src/Decorators/Http/Options.ts
1672
- /**
1673
- * A decorator class for handling HTTP OPTIONS requests.
1674
- *
1675
- * This class extends the BaseDecorator and is used to register OPTIONS routes
1676
- * with the Router. It also resolves metadata for the route handler
1677
- * using the MetadataResolver.
1678
- *
1679
- * @extends {BaseDecorator<OptionsDecoratorOptions>}
1680
- */
1681
- var OptionsDecorator = class extends __vercube_di.BaseDecorator {
1682
- gRouter;
1683
- gRequestHandler;
1684
- gMetadataResolver;
1685
- /**
1686
- * Called when the decorator is created.
1687
- *
1688
- * This method constructs the full path for the route, registers the route
1689
- * with the Router, and sets up the event handler for the OPTIONS request.
1690
- */
1691
- created() {
1692
- initializeMetadata(this.prototype);
1693
- initializeMetadataMethod(this.prototype, this.propertyName);
1694
- this.options.path = this.gMetadataResolver.resolveUrl({
1695
- instance: this.instance,
1696
- path: this.options.path,
1697
- propertyName: this.propertyName
1698
- });
1699
- this.gRouter.addRoute({
1700
- path: this.options.path,
1701
- method: "OPTIONS",
1702
- handler: this.gRequestHandler.prepareHandler({
1703
- instance: this.instance,
1704
- propertyName: this.propertyName
1705
- })
1706
- });
1707
- }
1708
- };
1709
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], OptionsDecorator.prototype, "gRouter", void 0);
1710
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], OptionsDecorator.prototype, "gRequestHandler", void 0);
1711
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], OptionsDecorator.prototype, "gMetadataResolver", void 0);
1712
- /**
1713
- * A factory function for creating an OptionsDecorator.
1714
- *
1715
- * This function returns a decorator function that can be used to annotate
1716
- * a method with OPTIONS route information.
1717
- *
1718
- * @param {string} path - The path for the OPTIONS route.
1719
- * @return {Function} The decorator function.
1720
- */
1721
- function Options(path) {
1722
- return (0, __vercube_di.createDecorator)(OptionsDecorator, { path });
1723
- }
1724
-
1725
- //#endregion
1726
- //#region packages/core/src/Decorators/Http/Param.ts
1727
- /**
1728
- * This class is responsible for managing parameter decorators.
1729
- *
1730
- * This class extends the BaseDecorator and is used to register parameter information
1731
- * with the MetadataResolver. It ensures that the metadata for the property is created
1732
- * and adds the parameter information to the metadata.
1733
- *
1734
- * @extends {BaseDecorator<ParamDecoratorOptions>}
1735
- */
1736
- var ParamDecorator = class extends __vercube_di.BaseDecorator {
1737
- gMetadataResolver;
1738
- /**
1739
- * Called when the decorator is created.
1740
- *
1741
- * This method checks if metadata for the property exists, creates it if it doesn't,
1742
- * and then adds the parameter information to the metadata.
1743
- */
1744
- created() {
1745
- initializeMetadata(this.prototype);
1746
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
1747
- method.args.push({
1748
- idx: this.propertyIndex,
1749
- type: "param",
1750
- data: { name: this.options.name }
1751
- });
1752
- }
1753
- };
1754
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], ParamDecorator.prototype, "gMetadataResolver", void 0);
1755
- /**
1756
- * A factory function for creating a ParamDecorator.
1757
- *
1758
- * This function returns a decorator function that can be used to annotate
1759
- * a method parameter with parameter information.
1760
- *
1761
- * @param {string} name - The name of the parameter.
1762
- * @param {Object} [opts] - Optional settings for the parameter.
1763
- * @param {boolean} [opts.decode=false] - Whether to decode the parameter.
1764
- * @return {Function} The decorator function.
1765
- */
1766
- function Param(name) {
1767
- return (0, __vercube_di.createDecorator)(ParamDecorator, { name });
1768
- }
1769
-
1770
- //#endregion
1771
- //#region packages/core/src/Decorators/Http/Patch.ts
1772
- /**
1773
- * A decorator class for handling HTTP PATCH requests.
1774
- *
1775
- * This class extends the BaseDecorator and is used to register PATCH routes
1776
- * with the Router. It also resolves metadata for the route handler
1777
- * using the MetadataResolver.
1778
- *
1779
- * @extends {BaseDecorator<PatchDecoratorOptions>}
1780
- */
1781
- var PatchDecorator = class extends __vercube_di.BaseDecorator {
1782
- gRouter;
1783
- gRequestHandler;
1784
- gMetadataResolver;
1785
- /**
1786
- * Called when the decorator is created.
1787
- *
1788
- * This method constructs the full path for the route, registers the route
1789
- * with the Router, and sets up the event handler for the PATCH request.
1790
- */
1791
- created() {
1792
- this.options.path = this.gMetadataResolver.resolveUrl({
1793
- instance: this.instance,
1794
- path: this.options.path,
1795
- propertyName: this.propertyName
1796
- });
1797
- this.gRouter.addRoute({
1798
- path: this.options.path,
1799
- method: "PATCH",
1800
- handler: this.gRequestHandler.prepareHandler({
1801
- instance: this.instance,
1802
- propertyName: this.propertyName
1803
- })
1804
- });
1805
- }
1806
- };
1807
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], PatchDecorator.prototype, "gRouter", void 0);
1808
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], PatchDecorator.prototype, "gRequestHandler", void 0);
1809
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], PatchDecorator.prototype, "gMetadataResolver", void 0);
1810
- /**
1811
- * A factory function for creating a PatchDecorator.
1812
- *
1813
- * This function returns a decorator function that can be used to annotate
1814
- * a method with PATCH route information.
1815
- *
1816
- * @param {string} path - The path for the PATCH route.
1817
- * @return {Function} The decorator function.
1818
- */
1819
- function Patch(path) {
1820
- return (0, __vercube_di.createDecorator)(PatchDecorator, { path });
1821
- }
1822
-
1823
- //#endregion
1824
- //#region packages/core/src/Decorators/Http/Post.ts
1825
- /**
1826
- * A decorator class for handling HTTP POST requests.
1827
- *
1828
- * This class extends the BaseDecorator and is used to register POST routes
1829
- * with the Router. It also resolves metadata for the route handler
1830
- * using the MetadataResolver.
1831
- *
1832
- * @extends {BaseDecorator<PostDecoratorOptions>}
1833
- */
1834
- var PostDecorator = class extends __vercube_di.BaseDecorator {
1835
- gRouter;
1836
- gMetadataResolver;
1837
- gRequestHandler;
1838
- /**
1839
- * Called when the decorator is created.
1840
- *
1841
- * This method constructs the full path for the route, registers the route
1842
- * with the Router, and sets up the event handler for the POST request.
1843
- */
1844
- created() {
1845
- initializeMetadata(this.prototype);
1846
- initializeMetadataMethod(this.prototype, this.propertyName);
1847
- this.options.path = this.gMetadataResolver.resolveUrl({
1848
- instance: this.instance,
1849
- path: this.options.path,
1850
- propertyName: this.propertyName
1851
- });
1852
- this.gRouter.addRoute({
1853
- path: this.options.path,
1854
- method: "POST",
1855
- handler: this.gRequestHandler.prepareHandler({
1856
- instance: this.instance,
1857
- propertyName: this.propertyName
1858
- })
1859
- });
1860
- }
1861
- };
1862
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], PostDecorator.prototype, "gRouter", void 0);
1863
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], PostDecorator.prototype, "gMetadataResolver", void 0);
1864
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], PostDecorator.prototype, "gRequestHandler", void 0);
1865
- /**
1866
- * A factory function for creating a PostDecorator.
1867
- *
1868
- * This function returns a decorator function that can be used to annotate
1869
- * a method with POST route information.
1870
- *
1871
- * @param {string} path - The path for the POST route.
1872
- * @return {Function} The decorator function.
1873
- */
1874
- function Post(path) {
1875
- return (0, __vercube_di.createDecorator)(PostDecorator, { path });
1876
- }
1877
-
1878
- //#endregion
1879
- //#region packages/core/src/Decorators/Http/Put.ts
1880
- /**
1881
- * A decorator class for handling HTTP PUT requests.
1882
- *
1883
- * This class extends the BaseDecorator and is used to register PUT routes
1884
- * with the Router. It also resolves metadata for the route handler
1885
- * using the MetadataResolver.
1886
- *
1887
- * @extends {BaseDecorator<PutDecoratorOptions>}
1888
- */
1889
- var PutDecorator = class extends __vercube_di.BaseDecorator {
1890
- gRouter;
1891
- gRequestHandler;
1892
- gMetadataResolver;
1893
- /**
1894
- * Called when the decorator is created.
1895
- *
1896
- * This method constructs the full path for the route, registers the route
1897
- * with the Router, and sets up the event handler for the PUT request.
1898
- */
1899
- created() {
1900
- initializeMetadata(this.prototype);
1901
- initializeMetadataMethod(this.prototype, this.propertyName);
1902
- this.options.path = this.gMetadataResolver.resolveUrl({
1903
- instance: this.instance,
1904
- path: this.options.path,
1905
- propertyName: this.propertyName
1906
- });
1907
- this.gRouter.addRoute({
1908
- path: this.options.path,
1909
- method: "PUT",
1910
- handler: this.gRequestHandler.prepareHandler({
1911
- instance: this.instance,
1912
- propertyName: this.propertyName
1913
- })
1914
- });
1915
- }
1916
- };
1917
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], PutDecorator.prototype, "gRouter", void 0);
1918
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], PutDecorator.prototype, "gRequestHandler", void 0);
1919
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], PutDecorator.prototype, "gMetadataResolver", void 0);
1920
- /**
1921
- * A factory function for creating a PutDecorator.
1922
- *
1923
- * This function returns a decorator function that can be used to annotate
1924
- * a method with PUT route information.
1925
- *
1926
- * @param {string} path - The path for the PUT route.
1927
- * @return {Function} The decorator function.
1928
- */
1929
- function Put(path) {
1930
- return (0, __vercube_di.createDecorator)(PutDecorator, { path });
1931
- }
1932
-
1933
- //#endregion
1934
- //#region packages/core/src/Decorators/Http/QueryParam.ts
1935
- /**
1936
- * This class is responsible for managing query parameter decorators.
1937
- *
1938
- * This class extends the BaseDecorator and is used to register query parameter information
1939
- * with the MetadataResolver. It ensures that the metadata for the property is created
1940
- * and adds the query parameter information to the metadata.
1941
- *
1942
- * @extends {BaseDecorator<QueryDecoratorOptions>}
1943
- */
1944
- var QueryParamDecorator = class extends __vercube_di.BaseDecorator {
1945
- /**
1946
- * Called when the decorator is created.
1947
- *
1948
- * This method checks if metadata for the property exists, creates it if it doesn't,
1949
- * and then adds the query parameter information to the metadata.
1950
- */
1951
- created() {
1952
- const meta = initializeMetadata(this.prototype);
1953
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
1954
- method.args.push({
1955
- idx: this.propertyIndex,
1956
- type: "query-param",
1957
- data: { name: this.options.name },
1958
- validate: this.options?.validationSchema ? true : false,
1959
- validationSchema: this.options?.validationSchema
1960
- });
1961
- meta.__middlewares.unshift({
1962
- target: this.propertyName,
1963
- priority: -1,
1964
- args: {},
1965
- middleware: ValidationMiddleware
1966
- });
1967
- }
1968
- };
1969
- /**
1970
- * A factory function for creating a QueryDecorator.
1971
- *
1972
- * This function returns a decorator function that can be used to annotate
1973
- * a method parameter with query parameter information.
1974
- *
1975
- * @param {QueryParamDecoratorOptions} options - The options for the decorator.
1976
- * @return {Function} The decorator function.
1977
- */
1978
- function QueryParam(options) {
1979
- return (0, __vercube_di.createDecorator)(QueryParamDecorator, options);
1980
- }
1981
-
1982
- //#endregion
1983
- //#region packages/core/src/Decorators/Http/QueryParams.ts
1984
- /**
1985
- * This class is responsible for managing query parameters decorators.
1986
- *
1987
- * This class extends the BaseDecorator and is used to register query parameters information
1988
- * with the MetadataResolver. It ensures that the metadata for the property is created
1989
- * and adds the query parameters information to the metadata.
1990
- *
1991
- * @extends {BaseDecorator<QueryDecoratorOptions>}
1992
- */
1993
- var QueryParamsDecorator = class extends __vercube_di.BaseDecorator {
1994
- /**
1995
- * Called when the decorator is created.
1996
- *
1997
- * This method checks if metadata for the property exists, creates it if it doesn't,
1998
- * and then adds the query parameters information to the metadata.
1999
- */
2000
- created() {
2001
- const meta = initializeMetadata(this.prototype);
2002
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2003
- method.args.push({
2004
- idx: this.propertyIndex,
2005
- type: "query-params",
2006
- data: {},
2007
- validate: this.options?.validationSchema ? true : false,
2008
- validationSchema: this.options?.validationSchema
2009
- });
2010
- meta.__middlewares.unshift({
2011
- target: this.propertyName,
2012
- priority: -1,
2013
- args: {},
2014
- middleware: ValidationMiddleware
2015
- });
2016
- }
2017
- };
2018
- /**
2019
- * A factory function for creating a QueryParamsDecorator.
2020
- *
2021
- * This function returns a decorator function that can be used to annotate
2022
- * a method parameter with query parameter information.
2023
- *
2024
- * @param {QueryParamsDecoratorOptions} options - The options for the decorator.
2025
- * @return {Function} The decorator function.
2026
- */
2027
- function QueryParams(options) {
2028
- return (0, __vercube_di.createDecorator)(QueryParamsDecorator, options);
2029
- }
2030
-
2031
- //#endregion
2032
- //#region packages/core/src/Decorators/Http/Request.ts
2033
- /**
2034
- * This class is responsible for managing request decorators.
2035
- *
2036
- * This class extends the BaseDecorator and is used to register request information
2037
- * with the MetadataResolver. It ensures that the metadata for the property is created
2038
- * and adds the request information to the metadata.
2039
- *
2040
- * @extends {BaseDecorator<{}>}
2041
- */
2042
- var RequestDecorator = class extends __vercube_di.BaseDecorator {
2043
- /**
2044
- * Called when the decorator is created.
2045
- *
2046
- * This method checks if metadata for the property exists, creates it if it doesn't,
2047
- * and then adds the request information to the metadata.
2048
- */
2049
- created() {
2050
- initializeMetadata(this.prototype);
2051
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2052
- method.args.push({
2053
- idx: this.propertyIndex,
2054
- type: "request"
2055
- });
2056
- }
2057
- };
2058
- /**
2059
- * A factory function for creating a RequestDecorator.
2060
- *
2061
- * This function returns a decorator function that can be used to annotate
2062
- * a method parameter with request information.
2063
- *
2064
- * @return {Function} The decorator function.
2065
- */
2066
- function Request() {
2067
- return (0, __vercube_di.createDecorator)(RequestDecorator, {});
2068
- }
2069
-
2070
- //#endregion
2071
- //#region packages/core/src/Decorators/Http/Response.ts
2072
- /**
2073
- * This class is responsible for managing response decorators.
2074
- *
2075
- * This class extends the BaseDecorator and is used to register response information
2076
- * with the MetadataResolver. It ensures that the metadata for the property is created
2077
- * and adds the response information to the metadata.
2078
- *
2079
- * @extends {BaseDecorator<{}>}
2080
- */
2081
- var ResponseDecorator = class extends __vercube_di.BaseDecorator {
2082
- /**
2083
- * Called when the decorator is created.
2084
- *
2085
- * This method checks if metadata for the property exists, creates it if it doesn't,
2086
- * and then adds the response information to the metadata.
2087
- */
2088
- created() {
2089
- initializeMetadata(this.prototype);
2090
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2091
- method.args.push({
2092
- idx: this.propertyIndex,
2093
- type: "response"
2094
- });
2095
- }
2096
- };
2097
- /**
2098
- * A factory function for creating a ResponseDecorator.
2099
- *
2100
- * This function returns a decorator function that can be used to annotate
2101
- * a method parameter with response information.
2102
- *
2103
- * @return {Function} The decorator function.
2104
- */
2105
- function Response$1() {
2106
- return (0, __vercube_di.createDecorator)(ResponseDecorator, {});
2107
- }
2108
-
2109
- //#endregion
2110
- //#region packages/core/src/Decorators/Http/Trace.ts
2111
- /**
2112
- * A decorator class for handling HTTP TRACE requests.
2113
- *
2114
- * This class extends the BaseDecorator and is used to register TRACE routes
2115
- * with the Router. It also resolves metadata for the route handler
2116
- * using the MetadataResolver.
2117
- *
2118
- * @extends {BaseDecorator<TraceDecoratorOptions>}
2119
- */
2120
- var TraceDecorator = class extends __vercube_di.BaseDecorator {
2121
- gRouter;
2122
- gRequestHandler;
2123
- gMetadataResolver;
2124
- /**
2125
- * Called when the decorator is created.
2126
- *
2127
- * This method constructs the full path for the route, registers the route
2128
- * with the Router, and sets up the event handler for the TRACE request.
2129
- */
2130
- created() {
2131
- initializeMetadata(this.prototype);
2132
- initializeMetadataMethod(this.prototype, this.propertyName);
2133
- this.options.path = this.gMetadataResolver.resolveUrl({
2134
- instance: this.instance,
2135
- path: this.options.path,
2136
- propertyName: this.propertyName
2137
- });
2138
- this.gRouter.addRoute({
2139
- path: this.options.path,
2140
- method: "TRACE",
2141
- handler: this.gRequestHandler.prepareHandler({
2142
- instance: this.instance,
2143
- propertyName: this.propertyName
2144
- })
2145
- });
2146
- }
2147
- };
2148
- (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], TraceDecorator.prototype, "gRouter", void 0);
2149
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], TraceDecorator.prototype, "gRequestHandler", void 0);
2150
- (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], TraceDecorator.prototype, "gMetadataResolver", void 0);
2151
- /**
2152
- * A factory function for creating a TraceDecorator.
2153
- *
2154
- * This function returns a decorator function that can be used to annotate
2155
- * a method with TRACE route information.
2156
- *
2157
- * @param {string} path - The path for the TRACE route.
2158
- * @return {Function} The decorator function.
2159
- */
2160
- function Trace(path) {
2161
- return (0, __vercube_di.createDecorator)(TraceDecorator, { path });
2162
- }
2163
-
2164
- //#endregion
2165
- //#region packages/core/src/Decorators/Http/SetHeader.ts
2166
- /**
2167
- * A decorator that sets a header on the response.
2168
- * @extends {BaseDecorator<SetHeaderDecoratorOptions>}
2169
- */
2170
- var SetHeaderDecorator = class extends __vercube_di.BaseDecorator {
2171
- /**
2172
- * Called when the decorator is created.
2173
- * Adds a query parameter to the metadata.
2174
- * @override
2175
- */
2176
- created() {
2177
- initializeMetadata(this.prototype);
2178
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2179
- method.actions.push({ handler: (req, res) => {
2180
- res.headers.delete(this.options.key);
2181
- res.headers.append(this.options.key, this.options.value);
2182
- return res;
2183
- } });
2184
- }
2185
- };
2186
- /**
2187
- * Creates a SetHeader decorator.
2188
- * @param {string} key - The header key.
2189
- * @param {string} value - The header value.
2190
- * @returns {Function} The decorator function.
2191
- */
2192
- function SetHeader(key, value) {
2193
- return (0, __vercube_di.createDecorator)(SetHeaderDecorator, {
2194
- key,
2195
- value
2196
- });
2197
- }
2198
-
2199
- //#endregion
2200
- //#region packages/core/src/Decorators/Http/Status.ts
2201
- /**
2202
-
2203
- * A decorator that sets a status on the response.
2204
-
2205
- * @extends {BaseDecorator<StatusDecoratorOptions>}
2206
-
2207
- */
2208
- var StatusDecorator = class extends __vercube_di.BaseDecorator {
2209
- /**
2210
-
2211
- * Called when the decorator is created.
2212
-
2213
- * Sets a status on the response
2214
-
2215
- * @override
2216
-
2217
- */
2218
- created() {
2219
- initializeMetadata(this.prototype);
2220
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2221
- method.actions.push({ handler: () => ({ status: this.options.code }) });
2222
- }
2223
- };
2224
- /**
2225
-
2226
- * Creates a Status decorator.
2227
-
2228
- * @param {number} code - The status value.
2229
-
2230
- * @returns {Function} The decorator function.
2231
-
2232
- */
2233
- function Status(code) {
2234
- return (0, __vercube_di.createDecorator)(StatusDecorator, { code });
2235
- }
2236
-
2237
- //#endregion
2238
- //#region packages/core/src/Decorators/Http/Redirect.ts
2239
- var RedirectDecorator = class extends __vercube_di.BaseDecorator {
2240
- /**
2241
-
2242
- * Decorator responsible for redirecting to a specified URL.
2243
-
2244
- * Called when the decorator is created.
2245
-
2246
- * Sets the location header value and status code.
2247
-
2248
- * @override
2249
-
2250
- */
2251
- created() {
2252
- initializeMetadata(this.prototype);
2253
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2254
- method.actions.push({ handler: () => {
2255
- return new Response(void 0, {
2256
- status: this.options.code,
2257
- headers: { "Location": this.options.location }
2258
- });
2259
- } });
2260
- }
2261
- };
2262
- /**
2263
-
2264
- * Creates a Redirect decorator.
2265
-
2266
- * @param {string} location - The location header value.
2267
-
2268
- * @param {number} [code=301] - The status code.
2269
-
2270
- * @returns {Function} The decorator function.
2271
-
2272
- */
2273
- function Redirect(location, code = 301) {
2274
- return (0, __vercube_di.createDecorator)(RedirectDecorator, {
2275
- location,
2276
- code
2277
- });
2278
- }
2279
-
2280
- //#endregion
2281
- //#region packages/core/src/Decorators/Http/Middleware.ts
2282
- /**
2283
- * Decorator that applies middleware to a class or method
2284
- * @param middleware - The middleware class to apply
2285
- * @param opts - Optional configuration parameters
2286
- * @param opts.type - The type of middleware ('before' or 'after')
2287
- * @param opts.priority - Priority order for middleware execution (default: 999)
2288
- * @returns A decorator function that can be applied to classes or methods
2289
- *
2290
- * @example
2291
- * ```typescript
2292
- * @Middleware(AuthMiddleware)
2293
- * class UserController {
2294
- * // ...
2295
- * }
2296
- *
2297
- * // Or on a specific method:
2298
- * @Middleware(ValidationMiddleware, { type: 'before', priority: 1 })
2299
- * public async createUser() {
2300
- * // ...
2301
- * }
2302
- * ```
2303
- */
2304
- function Middleware(middleware, opts) {
2305
- return function internalDecorator(target, propertyName) {
2306
- const ctx = propertyName ? target : target.prototype;
2307
- const meta = initializeMetadata(ctx);
2308
- meta.__middlewares.push({
2309
- target: propertyName ?? "__global__",
2310
- priority: opts?.priority ?? 999,
2311
- middleware
2312
- });
2313
- };
2314
- }
2315
-
2316
- //#endregion
2317
- //#region packages/core/src/Decorators/Http/MultipartFormData.ts
2318
- /**
2319
- * @class MultipartFormDataDecorator
2320
- * @extends BaseDecorator<MultipartFormDataOptions>
2321
- *
2322
- * A decorator class that handles the metadata for HTTP request bodies.
2323
- */
2324
- var MultipartFormDataDecorator = class extends __vercube_di.BaseDecorator {
2325
- /**
2326
- * @method created
2327
- * This method is called when the decorator is created. It ensures that the metadata
2328
- * for the property exists and adds the body argument to the metadata.
2329
- */
2330
- created() {
2331
- initializeMetadata(this.prototype);
2332
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2333
- method.args.push({
2334
- idx: this.propertyIndex,
2335
- type: "multipart-form-data"
2336
- });
2337
- }
2338
- };
2339
- /**
2340
- * Decorator function that marks a parameter as multipart/form-data request body.
2341
- * This decorator will automatically parse incoming multipart form data
2342
- *
2343
- * @decorator
2344
- * @returns {Function} A decorator function that can be applied to method parameters
2345
- *
2346
- * @example
2347
- * class UserController {
2348
- * uploadFile(@MultipartFormData() formData: MyData) {
2349
- * // Handle multipart form data
2350
- * }
2351
- * }
2352
- */
2353
- function MultipartFormData() {
2354
- return (0, __vercube_di.createDecorator)(MultipartFormDataDecorator, {});
2355
- }
2356
-
2357
- //#endregion
2358
- //#region packages/core/src/Decorators/Http/Session.ts
2359
- /**
2360
- * This class is responsible for managing session decorators.
2361
- *
2362
- * This class extends the BaseDecorator and is used to register session information
2363
- * with the MetadataResolver. It ensures that the metadata for the property is created
2364
- * and adds the session information to the metadata.
2365
- *
2366
- * @extends {BaseDecorator<{}>}
2367
- */
2368
- var SessionDecorator = class extends __vercube_di.BaseDecorator {
2369
- gRuntimeConfig;
2370
- /**
2371
- * Called when the decorator is created.
2372
- *
2373
- * This method checks if metadata for the property exists, creates it if it doesn't,
2374
- * and then adds the session information to the metadata.
2375
- */
2376
- created() {
2377
- initializeMetadata(this.prototype);
2378
- const method = initializeMetadataMethod(this.prototype, this.propertyName);
2379
- method.args.push({
2380
- idx: this.propertyIndex,
2381
- type: "session",
2382
- data: {
2383
- name: this.gRuntimeConfig.runtimeConfig.session?.name ?? "vercube_session",
2384
- secret: this.gRuntimeConfig.runtimeConfig.session?.secret ?? generateRandomHash(),
2385
- duration: this.gRuntimeConfig.runtimeConfig.session?.duration ?? 60 * 60 * 24 * 7
2386
- }
2387
- });
2388
- }
2389
- };
2390
- (0, import_decorate.default)([(0, __vercube_di.Inject)(RuntimeConfig)], SessionDecorator.prototype, "gRuntimeConfig", void 0);
2391
- /**
2392
- * A factory function for creating a SessionDecorator.
2393
- *
2394
- * This function returns a decorator function that can be used to annotate
2395
- * a method parameter with session information.
2396
- *
2397
- * @return {Function} The decorator function.
2398
- */
2399
- function Session() {
2400
- return (0, __vercube_di.createDecorator)(SessionDecorator, {});
2401
- }
2402
-
2403
- //#endregion
2404
- //#region packages/core/src/Decorators/Hooks/Listen.ts
2405
- /**
2406
- * This class is responsible for managing cache decorator.
2407
- */
2408
- var ListenDecorator = class extends __vercube_di.BaseDecorator {
2409
- gHooksService;
2410
- fHook;
2411
- /**
2412
- * Called when decorator is initialized. It will register event listener that will call this function
2413
- * once executed.
2414
- */
2415
- created() {
2416
- this.fHook = this.gHooksService.on(this.options.hookType, (data) => this.instance[this.propertyName](data));
2417
- }
2418
- /**
2419
- * Called when decorator is destroyed. It will unregister event listener.
2420
- */
2421
- destroyed() {
2422
- this.gHooksService.off(this.fHook);
2423
- }
2424
- };
2425
- (0, import_decorate.default)([(0, __vercube_di.Inject)(HooksService)], ListenDecorator.prototype, "gHooksService", void 0);
2426
- /**
2427
- * This decorator stores metadata about hook listeners. It can be later used along with function
2428
- * applyEventListeners() to automatically register all listeners.
2429
- *
2430
- * @param hookType hook to listen for
2431
- * @return decorator function
2432
- */
2433
- function Listen(hookType) {
2434
- return (0, __vercube_di.createDecorator)(ListenDecorator, { hookType });
2435
- }
2436
-
2437
- //#endregion
2438
- //#region packages/core/src/Services/Plugins/BasePlugin.ts
2439
- /**
2440
- * Represents a Plugin.
2441
- */
2442
- var BasePlugin = class {
2443
- /**
2444
- * The name of the plugin.
2445
- */
2446
- name;
2447
- /**
2448
- * Uses the plugin with the given app.
2449
- * @param {App} app - The application instance.
2450
- * @returns {void | Promise<void>} - A void or a promise that resolves to void.
2451
- */
2452
- use(app, options) {}
2453
- };
2454
-
2455
- //#endregion
2456
- //#region packages/core/src/Services/Middleware/BaseMiddleware.ts
2457
- /**
2458
- * BaseMiddleware class that serves as a base for all middleware implementations.
2459
- */
2460
- var BaseMiddleware = class {};
2461
-
2462
- //#endregion
2463
- //#region packages/core/src/Errors/Http/ForbiddenError.ts
2464
- /**
2465
- * Represents a Forbidden error (HTTP 403).
2466
- * @extends {HttpError}
2467
- */
2468
- var ForbiddenError = class ForbiddenError extends HttpError {
2469
- /**
2470
- * The name of the error.
2471
- * @type {string}
2472
- */
2473
- name = "ForbiddenError";
2474
- /**
2475
- * Creates an instance of ForbiddenError.
2476
- * @param {string} [message] - The error message.
2477
- */
2478
- constructor(message) {
2479
- super(403);
2480
- Object.setPrototypeOf(this, ForbiddenError.prototype);
2481
- if (message) this.message = message;
2482
- }
2483
- };
2484
-
2485
- //#endregion
2486
- //#region packages/core/src/Errors/Http/MethodNotAllowedError.ts
2487
- /**
2488
- * Represents a Method Not Allowed error (HTTP 405).
2489
- * @extends {HttpError}
2490
- */
2491
- var MethodNotAllowedError = class MethodNotAllowedError extends HttpError {
2492
- /**
2493
- * The name of the error.
2494
- * @type {string}
2495
- */
2496
- name = "MethodNotAllowedError";
2497
- /**
2498
- * Creates an instance of MethodNotAllowedError.
2499
- * @param {string} [message] - The error message.
2500
- */
2501
- constructor(message) {
2502
- super(405);
2503
- Object.setPrototypeOf(this, MethodNotAllowedError.prototype);
2504
- if (message) this.message = message;
2505
- }
2506
- };
2507
-
2508
- //#endregion
2509
- //#region packages/core/src/Errors/Http/NotAcceptableError.ts
2510
- /**
2511
- * Represents a Not Acceptable error (HTTP 406).
2512
- * @extends {HttpError}
2513
- */
2514
- var NotAcceptableError = class NotAcceptableError extends HttpError {
2515
- /**
2516
- * The name of the error.
2517
- * @type {string}
2518
- */
2519
- name = "NotAcceptableError";
2520
- /**
2521
- * Creates an instance of NotAcceptableError.
2522
- * @param {string} [message] - The error message.
2523
- */
2524
- constructor(message) {
2525
- super(406);
2526
- Object.setPrototypeOf(this, NotAcceptableError.prototype);
2527
- if (message) this.message = message;
2528
- }
2529
- };
2530
-
2531
- //#endregion
2532
- //#region packages/core/src/Errors/Http/NotFoundError.ts
2533
- /**
2534
- * Represents a Not Found error (HTTP 404).
2535
- * @extends {HttpError}
2536
- */
2537
- var NotFoundError = class NotFoundError extends HttpError {
2538
- /**
2539
- * The name of the error.
2540
- * @type {string}
2541
- */
2542
- name = "NotFoundError";
2543
- /**
2544
- * Creates an instance of NotFoundError.
2545
- * @param {string} [message] - The error message.
2546
- */
2547
- constructor(message) {
2548
- super(404);
2549
- Object.setPrototypeOf(this, NotFoundError.prototype);
2550
- if (message) this.message = message;
2551
- }
2552
- };
2553
-
2554
- //#endregion
2555
- //#region packages/core/src/Errors/Http/UnauthorizedError.ts
2556
- /**
2557
- * Represents an Unauthorized error (HTTP 401).
2558
- * @extends {HttpError}
2559
- */
2560
- var UnauthorizedError = class UnauthorizedError extends HttpError {
2561
- /**
2562
- * The name of the error.
2563
- * @type {string}
2564
- */
2565
- name = "UnauthorizedError";
2566
- /**
2567
- * Creates an instance of UnauthorizedError.
2568
- * @param {string} [message] - The error message.
2569
- */
2570
- constructor(message) {
2571
- super(401);
2572
- Object.setPrototypeOf(this, UnauthorizedError.prototype);
2573
- if (message) this.message = message;
2574
- }
2575
- };
2576
-
2577
- //#endregion
2578
- //#region packages/core/src/Types/HttpTypes.ts
2579
- let HTTPStatus = /* @__PURE__ */ function(HTTPStatus$1) {
2580
- HTTPStatus$1[HTTPStatus$1["CONTINUE"] = 100] = "CONTINUE";
2581
- HTTPStatus$1[HTTPStatus$1["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
2582
- HTTPStatus$1[HTTPStatus$1["PROCESSING"] = 102] = "PROCESSING";
2583
- HTTPStatus$1[HTTPStatus$1["OK"] = 200] = "OK";
2584
- HTTPStatus$1[HTTPStatus$1["CREATED"] = 201] = "CREATED";
2585
- HTTPStatus$1[HTTPStatus$1["ACCEPTED"] = 202] = "ACCEPTED";
2586
- HTTPStatus$1[HTTPStatus$1["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
2587
- HTTPStatus$1[HTTPStatus$1["NO_CONTENT"] = 204] = "NO_CONTENT";
2588
- HTTPStatus$1[HTTPStatus$1["RESET_CONTENT"] = 205] = "RESET_CONTENT";
2589
- HTTPStatus$1[HTTPStatus$1["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
2590
- HTTPStatus$1[HTTPStatus$1["MULTI_STATUS"] = 207] = "MULTI_STATUS";
2591
- HTTPStatus$1[HTTPStatus$1["ALREADY_REPORTED"] = 208] = "ALREADY_REPORTED";
2592
- HTTPStatus$1[HTTPStatus$1["IM_USED"] = 226] = "IM_USED";
2593
- HTTPStatus$1[HTTPStatus$1["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
2594
- HTTPStatus$1[HTTPStatus$1["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
2595
- HTTPStatus$1[HTTPStatus$1["FOUND"] = 302] = "FOUND";
2596
- HTTPStatus$1[HTTPStatus$1["SEE_OTHER"] = 303] = "SEE_OTHER";
2597
- HTTPStatus$1[HTTPStatus$1["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
2598
- HTTPStatus$1[HTTPStatus$1["USE_PROXY"] = 305] = "USE_PROXY";
2599
- HTTPStatus$1[HTTPStatus$1["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
2600
- HTTPStatus$1[HTTPStatus$1["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
2601
- HTTPStatus$1[HTTPStatus$1["BAD_REQUEST"] = 400] = "BAD_REQUEST";
2602
- HTTPStatus$1[HTTPStatus$1["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
2603
- HTTPStatus$1[HTTPStatus$1["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
2604
- HTTPStatus$1[HTTPStatus$1["FORBIDDEN"] = 403] = "FORBIDDEN";
2605
- HTTPStatus$1[HTTPStatus$1["NOT_FOUND"] = 404] = "NOT_FOUND";
2606
- HTTPStatus$1[HTTPStatus$1["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
2607
- HTTPStatus$1[HTTPStatus$1["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
2608
- HTTPStatus$1[HTTPStatus$1["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
2609
- HTTPStatus$1[HTTPStatus$1["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
2610
- HTTPStatus$1[HTTPStatus$1["CONFLICT"] = 409] = "CONFLICT";
2611
- HTTPStatus$1[HTTPStatus$1["GONE"] = 410] = "GONE";
2612
- HTTPStatus$1[HTTPStatus$1["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
2613
- HTTPStatus$1[HTTPStatus$1["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
2614
- HTTPStatus$1[HTTPStatus$1["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
2615
- HTTPStatus$1[HTTPStatus$1["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
2616
- HTTPStatus$1[HTTPStatus$1["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
2617
- HTTPStatus$1[HTTPStatus$1["RANGE_NOT_SATISFIABLE"] = 416] = "RANGE_NOT_SATISFIABLE";
2618
- HTTPStatus$1[HTTPStatus$1["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
2619
- HTTPStatus$1[HTTPStatus$1["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
2620
- HTTPStatus$1[HTTPStatus$1["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
2621
- HTTPStatus$1[HTTPStatus$1["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
2622
- HTTPStatus$1[HTTPStatus$1["LOCKED"] = 423] = "LOCKED";
2623
- HTTPStatus$1[HTTPStatus$1["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
2624
- HTTPStatus$1[HTTPStatus$1["TOO_EARLY"] = 425] = "TOO_EARLY";
2625
- HTTPStatus$1[HTTPStatus$1["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
2626
- HTTPStatus$1[HTTPStatus$1["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
2627
- HTTPStatus$1[HTTPStatus$1["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
2628
- HTTPStatus$1[HTTPStatus$1["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
2629
- HTTPStatus$1[HTTPStatus$1["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
2630
- HTTPStatus$1[HTTPStatus$1["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
2631
- HTTPStatus$1[HTTPStatus$1["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
2632
- HTTPStatus$1[HTTPStatus$1["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
2633
- HTTPStatus$1[HTTPStatus$1["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
2634
- HTTPStatus$1[HTTPStatus$1["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
2635
- HTTPStatus$1[HTTPStatus$1["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
2636
- HTTPStatus$1[HTTPStatus$1["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
2637
- HTTPStatus$1[HTTPStatus$1["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
2638
- HTTPStatus$1[HTTPStatus$1["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
2639
- HTTPStatus$1[HTTPStatus$1["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
2640
- HTTPStatus$1[HTTPStatus$1["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
2641
- return HTTPStatus$1;
2642
- }({});
2643
-
2644
- //#endregion
2645
- exports.App = App
2646
- exports.BadRequestError = BadRequestError
2647
- exports.BaseMiddleware = BaseMiddleware
2648
- exports.BasePlugin = BasePlugin
2649
- exports.Body = Body
2650
- exports.Connect = Connect
2651
- exports.Controller = Controller
2652
- exports.Delete = Delete
2653
- exports.ErrorHandlerProvider = ErrorHandlerProvider
2654
- exports.ForbiddenError = ForbiddenError
2655
- exports.Get = Get
2656
- exports.GlobalMiddlewareRegistry = GlobalMiddlewareRegistry
2657
- exports.HTTPStatus = HTTPStatus
2658
- exports.Head = Head
2659
- exports.Header = Header
2660
- exports.Headers = Headers$1
2661
- exports.HooksService = HooksService
2662
- exports.HttpError = HttpError
2663
- exports.HttpServer = HttpServer
2664
- exports.InternalServerError = InternalServerError
2665
- exports.Listen = Listen
2666
- exports.MetadataResolver = MetadataResolver
2667
- exports.MethodNotAllowedError = MethodNotAllowedError
2668
- exports.Middleware = Middleware
2669
- exports.MultipartFormData = MultipartFormData
2670
- exports.NotAcceptableError = NotAcceptableError
2671
- exports.NotFoundError = NotFoundError
2672
- exports.Options = Options
2673
- exports.Param = Param
2674
- exports.Patch = Patch
2675
- exports.Post = Post
2676
- exports.Put = Put
2677
- exports.QueryParam = QueryParam
2678
- exports.QueryParams = QueryParams
2679
- exports.Redirect = Redirect
2680
- exports.Request = Request
2681
- exports.Response = Response$1
2682
- exports.Session = Session
2683
- exports.SetHeader = SetHeader
2684
- exports.Status = Status
2685
- exports.Trace = Trace
2686
- exports.UnauthorizedError = UnauthorizedError
2687
- exports.createApp = createApp
2688
- exports.createMetadataCtx = createMetadataCtx
2689
- exports.createMetadataMethod = createMetadataMethod
2690
- exports.defineConfig = defineConfig
2691
- exports.initializeMetadata = initializeMetadata
2692
- exports.initializeMetadataMethod = initializeMetadataMethod
2693
- exports.loadVercubeConfig = loadVercubeConfig