@carno.js/core 1.0.9 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Carno.d.js +14 -0
- package/dist/Carno.d.mjs +1 -0
- package/dist/Carno.js +46 -2
- package/dist/Carno.mjs +46 -2
- package/dist/DefaultRoutes.d.js +13 -0
- package/dist/DefaultRoutes.d.mjs +0 -0
- package/dist/bun/index.js +4 -4
- package/dist/bun/index.js.map +3 -3
- package/dist/cache/CacheDriver.d.js +13 -0
- package/dist/cache/CacheDriver.d.mjs +0 -0
- package/dist/cache/CacheService.d.js +13 -0
- package/dist/cache/CacheService.d.mjs +0 -0
- package/dist/cache/MemoryDriver.d.js +13 -0
- package/dist/cache/MemoryDriver.d.mjs +0 -0
- package/dist/cache/RedisDriver.d.js +13 -0
- package/dist/cache/RedisDriver.d.mjs +0 -0
- package/dist/compiler/JITCompiler.d.js +13 -0
- package/dist/compiler/JITCompiler.d.mjs +0 -0
- package/dist/container/Container.d.js +13 -0
- package/dist/container/Container.d.mjs +0 -0
- package/dist/context/Context.d.js +13 -0
- package/dist/context/Context.d.mjs +0 -0
- package/dist/cors/CorsHandler.d.js +13 -0
- package/dist/cors/CorsHandler.d.mjs +0 -0
- package/dist/decorators/Controller.d.js +13 -0
- package/dist/decorators/Controller.d.mjs +0 -0
- package/dist/decorators/Inject.d.js +13 -0
- package/dist/decorators/Inject.d.mjs +0 -0
- package/dist/decorators/Middleware.d.js +13 -0
- package/dist/decorators/Middleware.d.mjs +0 -0
- package/dist/decorators/Service.d.js +13 -0
- package/dist/decorators/Service.d.mjs +0 -0
- package/dist/decorators/methods.d.js +13 -0
- package/dist/decorators/methods.d.mjs +0 -0
- package/dist/decorators/params.d.js +13 -0
- package/dist/decorators/params.d.mjs +0 -0
- package/dist/events/Lifecycle.d.js +13 -0
- package/dist/events/Lifecycle.d.mjs +0 -0
- package/dist/exceptions/HttpException.d.js +13 -0
- package/dist/exceptions/HttpException.d.mjs +0 -0
- package/dist/index.d.js +130 -0
- package/dist/index.d.mjs +78 -0
- package/dist/metadata.d.js +13 -0
- package/dist/metadata.d.mjs +0 -0
- package/dist/middleware/CarnoMiddleware.d.js +13 -0
- package/dist/middleware/CarnoMiddleware.d.mjs +0 -0
- package/dist/router/RadixRouter.d.js +13 -0
- package/dist/router/RadixRouter.d.mjs +0 -0
- package/dist/testing/TestHarness.d.js +13 -0
- package/dist/testing/TestHarness.d.mjs +0 -0
- package/dist/utils/Metadata.d.js +13 -0
- package/dist/utils/Metadata.d.mjs +0 -0
- package/dist/utils/parseQuery.d.js +13 -0
- package/dist/utils/parseQuery.d.mjs +0 -0
- package/dist/validation/ValibotAdapter.d.js +13 -0
- package/dist/validation/ValibotAdapter.d.mjs +0 -0
- package/dist/validation/ValidatorAdapter.d.js +13 -0
- package/dist/validation/ValidatorAdapter.d.mjs +0 -0
- package/dist/validation/ZodAdapter.d.js +13 -0
- package/dist/validation/ZodAdapter.d.mjs +0 -0
- package/package.json +2 -2
- package/src/Carno.d.ts +135 -0
- package/src/Carno.ts +69 -1
- package/src/DefaultRoutes.d.ts +19 -0
- package/src/cache/CacheDriver.d.ts +43 -0
- package/src/cache/CacheService.d.ts +89 -0
- package/src/cache/MemoryDriver.d.ts +32 -0
- package/src/cache/RedisDriver.d.ts +34 -0
- package/src/compiler/JITCompiler.d.ts +36 -0
- package/src/container/Container.d.ts +38 -0
- package/src/context/Context.d.ts +36 -0
- package/src/cors/CorsHandler.d.ts +47 -0
- package/src/decorators/Controller.d.ts +13 -0
- package/src/decorators/Inject.d.ts +6 -0
- package/src/decorators/Middleware.d.ts +5 -0
- package/src/decorators/Service.d.ts +9 -0
- package/src/decorators/methods.d.ts +7 -0
- package/src/decorators/params.d.ts +13 -0
- package/src/events/Lifecycle.d.ts +54 -0
- package/src/exceptions/HttpException.d.ts +43 -0
- package/src/index.d.ts +42 -0
- package/src/metadata.d.ts +41 -0
- package/src/middleware/CarnoMiddleware.d.ts +12 -0
- package/src/router/RadixRouter.d.ts +19 -0
- package/src/testing/TestHarness.d.ts +71 -0
- package/src/utils/Metadata.d.ts +20 -0
- package/src/utils/parseQuery.d.ts +23 -0
- package/src/validation/ValibotAdapter.d.ts +30 -0
- package/src/validation/ValidatorAdapter.d.ts +54 -0
- package/src/validation/ZodAdapter.d.ts +35 -0
package/dist/Carno.d.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __copyProps = (to, from, except, desc) => {
|
|
6
|
+
if (from && typeof from == "object" || typeof from == "function")
|
|
7
|
+
for (let key of __getOwnPropNames(from))
|
|
8
|
+
!__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
9
|
+
return to;
|
|
10
|
+
};
|
|
11
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
|
|
12
|
+
var Carno_d_exports = {};
|
|
13
|
+
module.exports = __toCommonJS(Carno_d_exports);
|
|
14
|
+
var import_reflect_metadata = require("reflect-metadata");
|
package/dist/Carno.d.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "reflect-metadata";
|
package/dist/Carno.js
CHANGED
|
@@ -52,7 +52,7 @@ class Carno {
|
|
|
52
52
|
}
|
|
53
53
|
/**
|
|
54
54
|
* Use a Carno plugin.
|
|
55
|
-
* Imports controllers, services and
|
|
55
|
+
* Imports controllers, services, middlewares, and routes from another Carno instance.
|
|
56
56
|
*/
|
|
57
57
|
use(plugin) {
|
|
58
58
|
plugin._controllers.length > 0 && this._controllers.push(...plugin._controllers);
|
|
@@ -60,7 +60,10 @@ class Carno {
|
|
|
60
60
|
const existingService = this.findServiceInPlugin(plugin, exported), serviceToAdd = this.shouldCloneService(existingService) ? { ...existingService } : exported;
|
|
61
61
|
this._services.push(serviceToAdd);
|
|
62
62
|
}
|
|
63
|
-
|
|
63
|
+
plugin._services.length > 0 && this._services.push(...plugin._services), plugin.config.globalMiddlewares && this._middlewares.push(...plugin.config.globalMiddlewares), plugin._middlewares.length > 0 && this._middlewares.push(...plugin._middlewares);
|
|
64
|
+
for (const [path, methods] of Object.entries(plugin.routes))
|
|
65
|
+
this.routes[path] || (this.routes[path] = {}), typeof methods == "object" && methods !== null && !(methods instanceof Response) ? Object.assign(this.routes[path], methods) : this.routes[path] = methods;
|
|
66
|
+
return this;
|
|
64
67
|
}
|
|
65
68
|
findServiceInPlugin(plugin, exported) {
|
|
66
69
|
return plugin._services.find(
|
|
@@ -94,6 +97,47 @@ class Carno {
|
|
|
94
97
|
const items = Array.isArray(controllerClass) ? controllerClass : [controllerClass];
|
|
95
98
|
return this._controllers.push(...items), this;
|
|
96
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* Register a route programmatically.
|
|
102
|
+
* Useful for plugins that need to register routes without controllers.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```ts
|
|
106
|
+
* app.route('GET', '/health', () => ({ status: 'ok' }));
|
|
107
|
+
* app.route('POST', '/webhook', async (ctx) => {
|
|
108
|
+
* const data = await ctx.parseBody();
|
|
109
|
+
* return { received: true };
|
|
110
|
+
* });
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
route(method, path, handler) {
|
|
114
|
+
const normalizedMethod = method.toUpperCase();
|
|
115
|
+
return this.routes[path] || (this.routes[path] = {}), this.routes[path][normalizedMethod] = handler, this;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Bulk register multiple routes at once.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```ts
|
|
122
|
+
* app.addRoutes({
|
|
123
|
+
* '/api/users': {
|
|
124
|
+
* 'GET': () => ({ users: [] }),
|
|
125
|
+
* 'POST': (ctx) => ({ created: true })
|
|
126
|
+
* },
|
|
127
|
+
* '/api/health': {
|
|
128
|
+
* 'GET': () => ({ status: 'ok' })
|
|
129
|
+
* }
|
|
130
|
+
* });
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
addRoutes(routes) {
|
|
134
|
+
for (const [path, methods] of Object.entries(routes)) {
|
|
135
|
+
this.routes[path] || (this.routes[path] = {});
|
|
136
|
+
for (const [method, handler] of Object.entries(methods))
|
|
137
|
+
this.routes[path][method.toUpperCase()] = handler;
|
|
138
|
+
}
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
97
141
|
/**
|
|
98
142
|
* Get a service instance from the container.
|
|
99
143
|
*/
|
package/dist/Carno.mjs
CHANGED
|
@@ -44,7 +44,7 @@ class Carno {
|
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
46
|
* Use a Carno plugin.
|
|
47
|
-
* Imports controllers, services and
|
|
47
|
+
* Imports controllers, services, middlewares, and routes from another Carno instance.
|
|
48
48
|
*/
|
|
49
49
|
use(plugin) {
|
|
50
50
|
plugin._controllers.length > 0 && this._controllers.push(...plugin._controllers);
|
|
@@ -52,7 +52,10 @@ class Carno {
|
|
|
52
52
|
const existingService = this.findServiceInPlugin(plugin, exported), serviceToAdd = this.shouldCloneService(existingService) ? { ...existingService } : exported;
|
|
53
53
|
this._services.push(serviceToAdd);
|
|
54
54
|
}
|
|
55
|
-
|
|
55
|
+
plugin._services.length > 0 && this._services.push(...plugin._services), plugin.config.globalMiddlewares && this._middlewares.push(...plugin.config.globalMiddlewares), plugin._middlewares.length > 0 && this._middlewares.push(...plugin._middlewares);
|
|
56
|
+
for (const [path, methods] of Object.entries(plugin.routes))
|
|
57
|
+
this.routes[path] || (this.routes[path] = {}), typeof methods == "object" && methods !== null && !(methods instanceof Response) ? Object.assign(this.routes[path], methods) : this.routes[path] = methods;
|
|
58
|
+
return this;
|
|
56
59
|
}
|
|
57
60
|
findServiceInPlugin(plugin, exported) {
|
|
58
61
|
return plugin._services.find(
|
|
@@ -86,6 +89,47 @@ class Carno {
|
|
|
86
89
|
const items = Array.isArray(controllerClass) ? controllerClass : [controllerClass];
|
|
87
90
|
return this._controllers.push(...items), this;
|
|
88
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* Register a route programmatically.
|
|
94
|
+
* Useful for plugins that need to register routes without controllers.
|
|
95
|
+
*
|
|
96
|
+
* @example
|
|
97
|
+
* ```ts
|
|
98
|
+
* app.route('GET', '/health', () => ({ status: 'ok' }));
|
|
99
|
+
* app.route('POST', '/webhook', async (ctx) => {
|
|
100
|
+
* const data = await ctx.parseBody();
|
|
101
|
+
* return { received: true };
|
|
102
|
+
* });
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
route(method, path, handler) {
|
|
106
|
+
const normalizedMethod = method.toUpperCase();
|
|
107
|
+
return this.routes[path] || (this.routes[path] = {}), this.routes[path][normalizedMethod] = handler, this;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Bulk register multiple routes at once.
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```ts
|
|
114
|
+
* app.addRoutes({
|
|
115
|
+
* '/api/users': {
|
|
116
|
+
* 'GET': () => ({ users: [] }),
|
|
117
|
+
* 'POST': (ctx) => ({ created: true })
|
|
118
|
+
* },
|
|
119
|
+
* '/api/health': {
|
|
120
|
+
* 'GET': () => ({ status: 'ok' })
|
|
121
|
+
* }
|
|
122
|
+
* });
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
addRoutes(routes) {
|
|
126
|
+
for (const [path, methods] of Object.entries(routes)) {
|
|
127
|
+
this.routes[path] || (this.routes[path] = {});
|
|
128
|
+
for (const [method, handler] of Object.entries(methods))
|
|
129
|
+
this.routes[path][method.toUpperCase()] = handler;
|
|
130
|
+
}
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
89
133
|
/**
|
|
90
134
|
* Get a service instance from the container.
|
|
91
135
|
*/
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __copyProps = (to, from, except, desc) => {
|
|
6
|
+
if (from && typeof from == "object" || typeof from == "function")
|
|
7
|
+
for (let key of __getOwnPropNames(from))
|
|
8
|
+
!__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
9
|
+
return to;
|
|
10
|
+
};
|
|
11
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
|
|
12
|
+
var DefaultRoutes_d_exports = {};
|
|
13
|
+
module.exports = __toCommonJS(DefaultRoutes_d_exports);
|
|
File without changes
|
package/dist/bun/index.js
CHANGED
|
@@ -154,10 +154,10 @@ jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK
|
|
|
154
154
|
mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs
|
|
155
155
|
Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH
|
|
156
156
|
WD9f
|
|
157
|
-
-----END CERTIFICATE-----`,TLSProfiles={RedisCloudFixed:{ca:RedisCloudCA},RedisCloudFlexible:{ca:RedisCloudCA}};exports.default=TLSProfiles});var require_utils2=__commonJS((exports)=>{var __dirname="E:\\Projects\\
|
|
157
|
+
-----END CERTIFICATE-----`,TLSProfiles={RedisCloudFixed:{ca:RedisCloudCA},RedisCloudFlexible:{ca:RedisCloudCA}};exports.default=TLSProfiles});var require_utils2=__commonJS((exports)=>{var __dirname="E:\\Projects\\carno.js\\node_modules\\ioredis\\built\\utils";Object.defineProperty(exports,"__esModule",{value:!0});exports.noop=exports.defaults=exports.Debug=exports.getPackageMeta=exports.zipMap=exports.CONNECTION_CLOSED_ERROR_MSG=exports.shuffle=exports.sample=exports.resolveTLSProfile=exports.parseURL=exports.optimizeErrorStack=exports.toArg=exports.convertMapToArray=exports.convertObjectToArray=exports.timeout=exports.packObject=exports.isInt=exports.wrapMultiResult=exports.convertBufferToString=void 0;var fs_1=__require("fs"),path_1=__require("path"),url_1=__require("url"),lodash_1=require_lodash3();Object.defineProperty(exports,"defaults",{enumerable:!0,get:function(){return lodash_1.defaults}});Object.defineProperty(exports,"noop",{enumerable:!0,get:function(){return lodash_1.noop}});var debug_1=require_debug();exports.Debug=debug_1.default;var TLSProfiles_1=require_TLSProfiles();function convertBufferToString(value,encoding){if(value instanceof Buffer)return value.toString(encoding);if(Array.isArray(value)){let length=value.length,res=Array(length);for(let i=0;i<length;++i)res[i]=value[i]instanceof Buffer&&encoding==="utf8"?value[i].toString():convertBufferToString(value[i],encoding);return res}return value}exports.convertBufferToString=convertBufferToString;function wrapMultiResult(arr){if(!arr)return null;let result=[],length=arr.length;for(let i=0;i<length;++i){let item=arr[i];if(item instanceof Error)result.push([item]);else result.push([null,item])}return result}exports.wrapMultiResult=wrapMultiResult;function isInt(value){let x=parseFloat(value);return!isNaN(value)&&(x|0)===x}exports.isInt=isInt;function packObject(array){let result={},length=array.length;for(let i=1;i<length;i+=2)result[array[i-1]]=array[i];return result}exports.packObject=packObject;function timeout(callback,timeout2){let timer=null,run=function(){if(timer)clearTimeout(timer),timer=null,callback.apply(this,arguments)};return timer=setTimeout(run,timeout2,Error("timeout")),run}exports.timeout=timeout;function convertObjectToArray(obj){let result=[],keys=Object.keys(obj);for(let i=0,l=keys.length;i<l;i++)result.push(keys[i],obj[keys[i]]);return result}exports.convertObjectToArray=convertObjectToArray;function convertMapToArray(map){let result=[],pos=0;return map.forEach(function(value,key){result[pos]=key,result[pos+1]=value,pos+=2}),result}exports.convertMapToArray=convertMapToArray;function toArg(arg){if(arg===null||typeof arg>"u")return"";return String(arg)}exports.toArg=toArg;function optimizeErrorStack(error,friendlyStack,filterPath){let stacks=friendlyStack.split(`
|
|
158
158
|
`),lines="",i;for(i=1;i<stacks.length;++i)if(stacks[i].indexOf(filterPath)===-1)break;for(let j=i;j<stacks.length;++j)lines+=`
|
|
159
159
|
`+stacks[j];if(error.stack){let pos=error.stack.indexOf(`
|
|
160
|
-
`);error.stack=error.stack.slice(0,pos)+lines}return error}exports.optimizeErrorStack=optimizeErrorStack;function parseURL(url){if(isInt(url))return{port:url};let parsed=(0,url_1.parse)(url,!0,!0);if(!parsed.slashes&&url[0]!=="/")url="//"+url,parsed=(0,url_1.parse)(url,!0,!0);let options=parsed.query||{},result={};if(parsed.auth){let index=parsed.auth.indexOf(":");result.username=index===-1?parsed.auth:parsed.auth.slice(0,index),result.password=index===-1?"":parsed.auth.slice(index+1)}if(parsed.pathname)if(parsed.protocol==="redis:"||parsed.protocol==="rediss:"){if(parsed.pathname.length>1)result.db=parsed.pathname.slice(1)}else result.path=parsed.pathname;if(parsed.host)result.host=parsed.hostname;if(parsed.port)result.port=parsed.port;if(typeof options.family==="string"){let intFamily=Number.parseInt(options.family,10);if(!Number.isNaN(intFamily))result.family=intFamily}return(0,lodash_1.defaults)(result,options),result}exports.parseURL=parseURL;function resolveTLSProfile(options){let tls=options===null||options===void 0?void 0:options.tls;if(typeof tls==="string")tls={profile:tls};let profile=TLSProfiles_1.default[tls===null||tls===void 0?void 0:tls.profile];if(profile)tls=Object.assign({},profile,tls),delete tls.profile,options=Object.assign({},options,{tls});return options}exports.resolveTLSProfile=resolveTLSProfile;function sample(array,from=0){let length=array.length;if(from>=length)return null;return array[from+Math.floor(Math.random()*(length-from))]}exports.sample=sample;function shuffle(array){let counter=array.length;while(counter>0){let index=Math.floor(Math.random()*counter);counter--,[array[counter],array[index]]=[array[index],array[counter]]}return array}exports.shuffle=shuffle;exports.CONNECTION_CLOSED_ERROR_MSG="Connection is closed.";function zipMap(keys,values){let map=new Map;return keys.forEach((key,index)=>{map.set(key,values[index])}),map}exports.zipMap=zipMap;var cachedPackageMeta=null;async function getPackageMeta(){if(cachedPackageMeta)return cachedPackageMeta;try{let filePath=(0,path_1.resolve)(__dirname,"..","..","package.json"),data=await fs_1.promises.readFile(filePath,"utf8");return cachedPackageMeta={version:JSON.parse(data).version},cachedPackageMeta}catch(err){return cachedPackageMeta={version:"error-fetching-version"},cachedPackageMeta}}exports.getPackageMeta=getPackageMeta});var require_Command=__commonJS((exports)=>{var __dirname="E:\\Projects\\
|
|
160
|
+
`);error.stack=error.stack.slice(0,pos)+lines}return error}exports.optimizeErrorStack=optimizeErrorStack;function parseURL(url){if(isInt(url))return{port:url};let parsed=(0,url_1.parse)(url,!0,!0);if(!parsed.slashes&&url[0]!=="/")url="//"+url,parsed=(0,url_1.parse)(url,!0,!0);let options=parsed.query||{},result={};if(parsed.auth){let index=parsed.auth.indexOf(":");result.username=index===-1?parsed.auth:parsed.auth.slice(0,index),result.password=index===-1?"":parsed.auth.slice(index+1)}if(parsed.pathname)if(parsed.protocol==="redis:"||parsed.protocol==="rediss:"){if(parsed.pathname.length>1)result.db=parsed.pathname.slice(1)}else result.path=parsed.pathname;if(parsed.host)result.host=parsed.hostname;if(parsed.port)result.port=parsed.port;if(typeof options.family==="string"){let intFamily=Number.parseInt(options.family,10);if(!Number.isNaN(intFamily))result.family=intFamily}return(0,lodash_1.defaults)(result,options),result}exports.parseURL=parseURL;function resolveTLSProfile(options){let tls=options===null||options===void 0?void 0:options.tls;if(typeof tls==="string")tls={profile:tls};let profile=TLSProfiles_1.default[tls===null||tls===void 0?void 0:tls.profile];if(profile)tls=Object.assign({},profile,tls),delete tls.profile,options=Object.assign({},options,{tls});return options}exports.resolveTLSProfile=resolveTLSProfile;function sample(array,from=0){let length=array.length;if(from>=length)return null;return array[from+Math.floor(Math.random()*(length-from))]}exports.sample=sample;function shuffle(array){let counter=array.length;while(counter>0){let index=Math.floor(Math.random()*counter);counter--,[array[counter],array[index]]=[array[index],array[counter]]}return array}exports.shuffle=shuffle;exports.CONNECTION_CLOSED_ERROR_MSG="Connection is closed.";function zipMap(keys,values){let map=new Map;return keys.forEach((key,index)=>{map.set(key,values[index])}),map}exports.zipMap=zipMap;var cachedPackageMeta=null;async function getPackageMeta(){if(cachedPackageMeta)return cachedPackageMeta;try{let filePath=(0,path_1.resolve)(__dirname,"..","..","package.json"),data=await fs_1.promises.readFile(filePath,"utf8");return cachedPackageMeta={version:JSON.parse(data).version},cachedPackageMeta}catch(err){return cachedPackageMeta={version:"error-fetching-version"},cachedPackageMeta}}exports.getPackageMeta=getPackageMeta});var require_Command=__commonJS((exports)=>{var __dirname="E:\\Projects\\carno.js\\node_modules\\ioredis\\built";Object.defineProperty(exports,"__esModule",{value:!0});var commands_1=require_built(),calculateSlot=require_lib(),standard_as_callback_1=require_built2(),utils_1=require_utils2();class Command{constructor(name,args=[],options={},callback){if(this.name=name,this.inTransaction=!1,this.isResolved=!1,this.transformed=!1,this.replyEncoding=options.replyEncoding,this.errorStack=options.errorStack,this.args=args.flat(),this.callback=callback,this.initPromise(),options.keyPrefix){let isBufferKeyPrefix=options.keyPrefix instanceof Buffer,keyPrefixBuffer=isBufferKeyPrefix?options.keyPrefix:null;this._iterateKeys((key)=>{if(key instanceof Buffer){if(keyPrefixBuffer===null)keyPrefixBuffer=Buffer.from(options.keyPrefix);return Buffer.concat([keyPrefixBuffer,key])}else if(isBufferKeyPrefix)return Buffer.concat([options.keyPrefix,Buffer.from(String(key))]);return options.keyPrefix+key})}if(options.readOnly)this.isReadOnly=!0}static checkFlag(flagName,commandName){return!!this.getFlagMap()[flagName][commandName]}static setArgumentTransformer(name,func){this._transformer.argument[name]=func}static setReplyTransformer(name,func){this._transformer.reply[name]=func}static getFlagMap(){if(!this.flagMap)this.flagMap=Object.keys(Command.FLAGS).reduce((map,flagName)=>{return map[flagName]={},Command.FLAGS[flagName].forEach((commandName)=>{map[flagName][commandName]=!0}),map},{});return this.flagMap}getSlot(){if(typeof this.slot>"u"){let key=this.getKeys()[0];this.slot=key==null?null:calculateSlot(key)}return this.slot}getKeys(){return this._iterateKeys()}toWritable(_socket){let result,commandStr="*"+(this.args.length+1)+`\r
|
|
161
161
|
$`+Buffer.byteLength(this.name)+`\r
|
|
162
162
|
`+this.name+`\r
|
|
163
163
|
`;if(this.bufferMode){let buffers=new MixedBuffers;buffers.push(commandStr);for(let i=0;i<this.args.length;++i){let arg=this.args[i];if(arg instanceof Buffer)if(arg.length===0)buffers.push(`$0\r
|
|
@@ -177,7 +177,7 @@ return h(${argsCode});
|
|
|
177
177
|
return await h(${argsCode});
|
|
178
178
|
}`;return{fn:Function("h",code2)(bound),isAsync:!0,isStatic:!1}}let code=`return function(c){
|
|
179
179
|
return h(${argsCode});
|
|
180
|
-
}`;return{fn:Function("h",code)(bound),isAsync:!1,isStatic:!1}}function escapeKey(key){return key.replace(/['\"\\]/g,"\\$&")}function buildArgExpression(param){let key=param.key?escapeKey(param.key):void 0;switch(param.type){case"param":return key?`c.params['${key}']`:"c.params";case"query":return key?`c.query['${key}']`:"c.query";case"body":return key?`c.body['${key}']`:"c.body";case"header":return key?`c.req.headers.get('${key}')`:"c.req.headers";case"req":return"c.req";case"ctx":return"c";case"locals":return key?`c.locals['${key}']`:"c.locals";default:return"undefined"}}function parseQueryFromURL(url){let queryStart=url.indexOf("?");if(queryStart===-1)return Object.create(null);let queryEnd=url.indexOf("#",queryStart);if(queryEnd===-1)queryEnd=url.length;return parseQuery(url,queryStart+1,queryEnd)}function parseQuery(input,startIndex,endIndex){let result=Object.create(null),flags=0,startingIndex=startIndex-1,equalityIndex=startingIndex;for(let i=startIndex;i<endIndex;i++)switch(input.charCodeAt(i)){case 38:processKeyValuePair(i),startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}if(startingIndex<endIndex)processKeyValuePair(endIndex);return result;function processKeyValuePair(pairEndIndex){let hasBothKeyValuePair=equalityIndex>startingIndex,effectiveEqualityIndex=hasBothKeyValuePair?equalityIndex:pairEndIndex,keySlice=input.slice(startingIndex+1,effectiveEqualityIndex);if(!hasBothKeyValuePair&&keySlice.length===0)return;let finalKey=keySlice;if(flags&1)finalKey=finalKey.replace(/\+/g," ");if(flags&2)try{finalKey=decodeURIComponent(finalKey)}catch{}let finalValue="";if(hasBothKeyValuePair){let valueSlice=input.slice(equalityIndex+1,pairEndIndex);if(flags&4)valueSlice=valueSlice.replace(/\+/g," ");if(flags&8)try{finalValue=decodeURIComponent(valueSlice)}catch{finalValue=valueSlice}else finalValue=valueSlice}result[finalKey]=finalValue}}var EMPTY_PARAMS=Object.freeze({});class Context{req;params;locals={};_query=null;_body;_bodyParsed=!1;_url=null;_status=0;constructor(req,params=EMPTY_PARAMS){this.req=req,this.params=params}get status(){return this._status||200}set status(value){this._status=value}get url(){if(!this._url)this._url=new URL(this.req.url);return this._url}get query(){if(!this._query)this._query=parseQueryFromURL(this.req.url);return this._query}get body(){return this._body}async parseBody(){if(this._bodyParsed)return this._body;this._bodyParsed=!0;let contentType=this.req.headers.get("content-type")||"";if(contentType.includes("application/json"))this._body=await this.req.json();else if(contentType.includes("form")){let formData=await this.req.formData();this._body=Object.fromEntries(formData)}else if(contentType.includes("text"))this._body=await this.req.text();else this._body=await this.req.arrayBuffer();return this._body}get method(){return this.req.method}get headers(){return this.req.headers}get path(){return this.url.pathname}json(data,status){if(status)this.status=status;return Response.json(data,{status:this.status})}text(data,status){if(status)this.status=status;return new Response(data,{status:this.status,headers:{"Content-Type":"text/plain"}})}html(data,status){if(status)this.status=status;return new Response(data,{status:this.status,headers:{"Content-Type":"text/html"}})}redirect(url,status=302){return Response.redirect(url,status)}static createFromJob(job){let fakeRequest=new Request("http://localhost/job"),ctx=new Context(fakeRequest);return ctx.locals.job=job,ctx}}var Scope;((Scope2)=>{Scope2.SINGLETON="singleton";Scope2.REQUEST="request";Scope2.INSTANCE="instance"})(Scope||={});class Container{configs=new Map;instances=new Map;resolving=new Set;register(config){let normalized=this.normalizeConfig(config);if(this.configs.set(normalized.token,normalized),normalized.useValue!==void 0)this.instances.set(normalized.token,normalized.useValue);return this}get(token){let cached=this.instances.get(token);if(cached!==void 0)return cached;return this.resolveInternal(token).instance}has(token){return this.configs.has(token)}resolveInternal(token,requestLocals){if(requestLocals?.has(token))return{instance:requestLocals.get(token),scope:"request"};let cached=this.instances.get(token);if(cached!==void 0)return{instance:cached,scope:"singleton"};let config=this.configs.get(token);if(!config)throw Error(`Provider not found: ${token.name}`);let creation=this.createInstance(config,requestLocals);if(creation.scope==="singleton")this.instances.set(token,creation.instance);else if(creation.scope==="request"&&requestLocals)requestLocals.set(token,creation.instance);return creation}createInstance(config,requestLocals){let target=config.useClass??config.token;if(this.resolving.has(target))throw Error(`Circular dependency detected: ${target.name}`);this.resolving.add(target);try{let depsToken=this.getDependencies(target);if(depsToken.length===0)return{instance:new target,scope:config.scope||"singleton"};let args=[],effectiveScope=config.scope||"singleton";for(let depToken of depsToken){let depResult=this.resolveInternal(depToken,requestLocals);if(args.push(depResult.instance),depResult.scope==="request"&&effectiveScope==="singleton")effectiveScope="request"}return{instance:new target(...args),scope:effectiveScope}}finally{this.resolving.delete(target)}}getDependencies(target){return(Reflect.getMetadata("design:paramtypes",target)||[]).filter((t)=>t&&typeof t==="function"&&!this.isPrimitive(t))}isPrimitive(type){return type===String||type===Number||type===Boolean||type===Object||type===Array||type===Symbol}normalizeConfig(config){if(typeof config==="function")return{token:config,useClass:config,scope:"singleton"};return{...config,useClass:config.useClass??config.token,scope:config.scope??"singleton"}}clear(){this.configs.clear(),this.instances.clear()}}var DEFAULT_CORS_METHODS=["GET","HEAD","PUT","PATCH","POST","DELETE"],DEFAULT_CORS_HEADERS=["Content-Type","Authorization","X-Requested-With","Accept","Origin"];class CorsHandler{cache=new Map;methodsStr;headersStr;exposedStr;maxAgeStr;hasCredentials;isWildcard;matcher;preflightResponse=null;constructor(config){if(this.methodsStr=(config.methods||DEFAULT_CORS_METHODS).join(", "),this.headersStr=(config.allowedHeaders||DEFAULT_CORS_HEADERS).join(", "),this.exposedStr=config.exposedHeaders?.join(", ")||null,this.maxAgeStr=config.maxAge?.toString()||null,this.hasCredentials=!!config.credentials,this.isWildcard=config.origins==="*",this.matcher=this.buildMatcher(config.origins),this.isWildcard)this.preflightResponse=new Response(null,{status:204,headers:this.buildHeaders("*")})}preflight(origin){if(this.isWildcard&&this.preflightResponse)return this.preflightResponse.clone();if(!this.isAllowed(origin))return new Response(null,{status:403});return new Response(null,{status:204,headers:this.getHeaders(origin)})}apply(response,origin){if(!this.isAllowed(origin))return response;let headers=this.getHeaders(origin);for(let[key,value]of Object.entries(headers))response.headers.set(key,value);return response}isAllowed(origin){return this.matcher(origin)}getHeaders(origin){let key=this.isWildcard?"*":origin,headers=this.cache.get(key);if(!headers)headers=this.buildHeaders(origin),this.cache.set(key,headers);return headers}buildHeaders(origin){let headers={"Access-Control-Allow-Origin":this.isWildcard?"*":origin,"Access-Control-Allow-Methods":this.methodsStr,"Access-Control-Allow-Headers":this.headersStr};if(this.hasCredentials)headers["Access-Control-Allow-Credentials"]="true";if(this.exposedStr)headers["Access-Control-Expose-Headers"]=this.exposedStr;if(this.maxAgeStr)headers["Access-Control-Max-Age"]=this.maxAgeStr;return headers}buildMatcher(origins){if(origins==="*")return()=>!0;if(typeof origins==="string")return(o)=>o===origins;if(Array.isArray(origins)){let set=new Set(origins);return(o)=>set.has(o)}if(origins instanceof RegExp)return(o)=>origins.test(o);if(typeof origins==="function")return origins;return()=>!1}}class HttpException extends Error{statusCode;errors;constructor(statusCode,message,errors){super(message);this.statusCode=statusCode;this.errors=errors;this.name="HttpException"}toResponse(){let body={statusCode:this.statusCode,message:this.message,...this.errors&&{errors:this.errors}};return Response.json(body,{status:this.statusCode})}}class BadRequestException extends HttpException{constructor(message="Bad Request",errors){super(400,message,errors);this.name="BadRequestException"}}class UnauthorizedException extends HttpException{constructor(message="Unauthorized"){super(401,message);this.name="UnauthorizedException"}}class ForbiddenException extends HttpException{constructor(message="Forbidden"){super(403,message);this.name="ForbiddenException"}}class NotFoundException extends HttpException{constructor(message="Not Found"){super(404,message);this.name="NotFoundException"}}class MethodNotAllowedException extends HttpException{constructor(message="Method Not Allowed"){super(405,message);this.name="MethodNotAllowedException"}}class ConflictException extends HttpException{constructor(message="Conflict"){super(409,message);this.name="ConflictException"}}class UnprocessableEntityException extends HttpException{constructor(message="Unprocessable Entity",errors){super(422,message,errors);this.name="UnprocessableEntityException"}}class TooManyRequestsException extends HttpException{constructor(message="Too Many Requests"){super(429,message);this.name="TooManyRequestsException"}}class InternalServerErrorException extends HttpException{constructor(message="Internal Server Error"){super(500,message);this.name="InternalServerErrorException"}}class ServiceUnavailableException extends HttpException{constructor(message="Service Unavailable"){super(503,message);this.name="ServiceUnavailableException"}}var VALIDATION_SCHEMA=Symbol("turbo:validation");function Schema(schema){return(target)=>{Reflect.defineMetadata(VALIDATION_SCHEMA,schema,target)}}function getSchema(target){return Reflect.getMetadata(VALIDATION_SCHEMA,target)}class ZodAdapter{name="ZodAdapter";schemaCache=new Map;hasValidation(target){return getSchema(target)!==void 0}validate(target,value){let schema=this.getOrCacheSchema(target);if(!schema)return{success:!0,data:value};let result=schema.safeParse(value);if(result.success)return{success:!0,data:result.data};return{success:!1,errors:this.formatErrors(result.error)}}validateOrThrow(target,value){let schema=this.getOrCacheSchema(target);if(!schema)return value;let result=schema.safeParse(value);if(result.success)return result.data;let errors=this.formatErrors(result.error);throw new ValidationException(errors)}getOrCacheSchema(target){let schema=this.schemaCache.get(target);if(schema===void 0)schema=getSchema(target)??null,this.schemaCache.set(target,schema);return schema}formatErrors(zodError){return zodError.issues.map((issue)=>({path:issue.path.join("."),message:issue.message}))}}class ValidationException extends Error{errors;constructor(errors){super(`Validation failed: ${errors.map((e)=>`${e.path}: ${e.message}`).join(", ")}`);this.errors=errors;this.name="ValidationException"}toResponse(){return Response.json({statusCode:400,message:"Validation failed",errors:this.errors},{status:400})}}var EventType;((EventType2)=>{EventType2.INIT="onInit";EventType2.BOOT="onBoot";EventType2.SHUTDOWN="onShutdown"})(EventType||={});var EVENTS_META=Symbol("turbo:events"),eventRegistry=new Map;function registerEvent(type,target,methodName,priority=0){let handlers=eventRegistry.get(type);if(!handlers)handlers=[],eventRegistry.set(type,handlers);handlers.push({target,methodName,priority})}function getEventHandlers(type){return(eventRegistry.get(type)||[]).sort((a,b)=>b.priority-a.priority)}function hasEventHandlers(type){return(eventRegistry.get(type)?.length??0)>0}function OnApplicationInit(priority=0){return function(target,propertyKey){registerEvent("onInit",target.constructor,propertyKey,priority)}}function OnApplicationBoot(priority=0){return function(target,propertyKey){registerEvent("onBoot",target.constructor,propertyKey,priority)}}function OnApplicationShutdown(priority=0){return function(target,propertyKey){registerEvent("onShutdown",target.constructor,propertyKey,priority)}}class MemoryDriver{name="MemoryDriver";cache=new Map;cleanupInterval=null;constructor(cleanupIntervalMs=0){if(cleanupIntervalMs>0)this.cleanupInterval=setInterval(()=>this.cleanup(),cleanupIntervalMs)}async get(key){let entry=this.cache.get(key);if(!entry)return null;if(entry.expiresAt!==null&&Date.now()>entry.expiresAt)return this.cache.delete(key),null;return entry.value}async set(key,value,ttl){let expiresAt=ttl?Date.now()+ttl:null;return this.cache.set(key,{value,expiresAt}),!0}async del(key){return this.cache.delete(key)}async has(key){let entry=this.cache.get(key);if(!entry)return!1;if(entry.expiresAt!==null&&Date.now()>entry.expiresAt)return this.cache.delete(key),!1;return!0}async clear(){this.cache.clear()}async close(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.cache.clear()}cleanup(){let now=Date.now();for(let[key,entry]of this.cache)if(entry.expiresAt!==null&&now>entry.expiresAt)this.cache.delete(key)}stats(){return{size:this.cache.size}}}class CacheService{driver;prefix;defaultTtl;constructor(config={}){this.driver=config.driver||new MemoryDriver,this.prefix=config.prefix||"",this.defaultTtl=config.defaultTtl}key(key){return this.prefix?`${this.prefix}:${key}`:key}async get(key){return this.driver.get(this.key(key))}async set(key,value,ttl){return this.driver.set(this.key(key),value,ttl??this.defaultTtl)}async del(key){return this.driver.del(this.key(key))}async has(key){return this.driver.has(this.key(key))}async clear(){return this.driver.clear()}async getOrSet(key,cb,ttl){let cached=await this.get(key);if(cached!==null)return cached;let value=await cb();return await this.set(key,value,ttl),value}async getMany(keys){return Promise.all(keys.map((key)=>this.get(key)))}async setMany(entries){return Promise.all(entries.map((entry)=>this.set(entry.key,entry.value,entry.ttl)))}async delMany(keys){return Promise.all(keys.map((key)=>this.del(key)))}async close(){await this.driver.close?.()}getDriver(){return this.driver}}function normalizeOptions(pathOrOptions){if(!pathOrOptions)return{};if(typeof pathOrOptions==="string")return{path:pathOrOptions};return pathOrOptions}function normalizePath(path){if(!path)return"";let normalized=path.startsWith("/")?path:"/"+path;if(normalized!=="/"&&normalized.endsWith("/"))normalized=normalized.slice(0,-1);return normalized}function Controller(pathOrOptions){return(target)=>{let options=normalizeOptions(pathOrOptions),meta={path:normalizePath(options.path||""),scope:options.scope,children:options.children};if(Reflect.defineMetadata(CONTROLLER_META,meta,target),!Reflect.hasMetadata(ROUTES_META,target))Reflect.defineMetadata(ROUTES_META,[],target)}}function createMethodDecorator(method){return function(path=""){return function(targetOrMethod,contextOrPropertyKey,descriptor){if(contextOrPropertyKey&&typeof contextOrPropertyKey==="object"&&"kind"in contextOrPropertyKey){let context=contextOrPropertyKey;return context.addInitializer(function(){let constructor2=this.constructor,routes2=Reflect.getMetadata(ROUTES_META,constructor2)||[];routes2.push({method,path:path.startsWith("/")?path:"/"+path,handlerName:String(context.name)}),Reflect.defineMetadata(ROUTES_META,routes2,constructor2)}),targetOrMethod}let constructor=targetOrMethod.constructor,propertyKey=contextOrPropertyKey,routes=Reflect.getMetadata(ROUTES_META,constructor)||[];routes.push({method,path:path.startsWith("/")?path:"/"+path,handlerName:String(propertyKey)}),Reflect.defineMetadata(ROUTES_META,routes,constructor)}}}var Get=createMethodDecorator("get"),Post=createMethodDecorator("post"),Put=createMethodDecorator("put"),Delete=createMethodDecorator("delete"),Patch=createMethodDecorator("patch"),Head=createMethodDecorator("head"),Options=createMethodDecorator("options");class DefaultRoutes{favicon(){return new Response(null,{status:204})}}__legacyDecorateClassTS([Get("/favicon.ico"),__legacyMetadataTS("design:type",Function),__legacyMetadataTS("design:paramtypes",[]),__legacyMetadataTS("design:returntype",void 0)],DefaultRoutes.prototype,"favicon",null),DefaultRoutes=__legacyDecorateClassTS([Controller()],DefaultRoutes);var DEFAULT_STATIC_ROUTES={"/health":new Response('{"status":"ok"}',{status:200,headers:{"Content-Type":"application/json"}}),"/ready":new Response('{"ready":true}',{status:200,headers:{"Content-Type":"application/json"}}),"/favicon.ico":new Response(null,{status:204})};var NOT_FOUND_RESPONSE=new Response("Not Found",{status:404}),TEXT_OPTS=Object.freeze({status:200,headers:{"Content-Type":"text/plain"}}),JSON_OPTS=Object.freeze({status:200,headers:{"Content-Type":"application/json"}}),INTERNAL_ERROR_RESPONSE=new Response('{"statusCode":500,"message":"Internal Server Error"}',{status:500,headers:{"Content-Type":"application/json"}});class Carno{config;_controllers=[];_services=[];_middlewares=[];routes={};container=new Container;corsHandler=null;hasCors=!1;validator=null;server;hasInitHooks=!1;hasBootHooks=!1;hasShutdownHooks=!1;constructor(config={}){this.config=config;if(this.config.exports=this.config.exports||[],this.config.globalMiddlewares=this.config.globalMiddlewares||[],this.config.cors)this.corsHandler=new CorsHandler(this.config.cors),this.hasCors=!0;if(this.config.validation===void 0||this.config.validation===!0)this.validator=new ZodAdapter;else if(typeof this.config.validation==="function"){let AdapterClass=this.config.validation;this.validator=new AdapterClass}else if(this.config.validation)this.validator=this.config.validation}use(plugin){if(plugin._controllers.length>0)this._controllers.push(...plugin._controllers);for(let exported of plugin.config.exports||[]){let existingService=this.findServiceInPlugin(plugin,exported),serviceToAdd=this.shouldCloneService(existingService)?{...existingService}:exported;this._services.push(serviceToAdd)}if(plugin._services.length>0)this._services.push(...plugin._services);if(plugin.config.globalMiddlewares)this._middlewares.push(...plugin.config.globalMiddlewares);if(plugin._middlewares.length>0)this._middlewares.push(...plugin._middlewares);return this}findServiceInPlugin(plugin,exported){return plugin._services.find((s)=>this.getServiceToken(s)===this.getServiceToken(exported))}getServiceToken(service){return service?.token||service}shouldCloneService(service){return!!(service?.useValue!==void 0||service?.useClass)}services(serviceClass){let items=Array.isArray(serviceClass)?serviceClass:[serviceClass];return this._services.push(...items),this}middlewares(handler){let items=Array.isArray(handler)?handler:[handler];return this._middlewares.push(...items),this}controllers(controllerClass){let items=Array.isArray(controllerClass)?controllerClass:[controllerClass];return this._controllers.push(...items),this}get(token){return this.container.get(token)}listen(port=3000){this.bootstrap(),this.compileRoutes();let config={port,fetch:this.handleNotFound.bind(this),error:this.handleError.bind(this),routes:{...DEFAULT_STATIC_ROUTES,...this.routes}};if(this.server=Bun.serve(config),this.hasBootHooks)this.executeLifecycleHooks("onBoot");if(this.hasShutdownHooks)this.registerShutdownHandlers();if(!this.config.disableStartupLog)console.log(`Carno running on port ${port}`)}bootstrap(){this.hasInitHooks=hasEventHandlers("onInit"),this.hasBootHooks=hasEventHandlers("onBoot"),this.hasShutdownHooks=hasEventHandlers("onShutdown"),this.container.register({token:Container,useValue:this.container});let cacheConfig=typeof this.config.cache==="object"?this.config.cache:{};this.container.register({token:CacheService,useValue:new CacheService(cacheConfig)});for(let service of this._services)this.container.register(service);for(let ControllerClass of this._controllers)this.container.register(ControllerClass);if(this.hasInitHooks)this.executeLifecycleHooks("onInit");for(let service of this._services){let token=typeof service==="function"?service:service.token,serviceConfig=typeof service==="function"?null:service;if(!serviceConfig||serviceConfig.scope!=="request")this.container.get(token)}}compileRoutes(){for(let ControllerClass of this._controllers)this.compileController(ControllerClass)}compileController(ControllerClass,parentPath="",inheritedMiddlewares=[]){let meta=Reflect.getMetadata(CONTROLLER_META,ControllerClass)||{path:""},basePath=parentPath+(meta.path||""),routes=Reflect.getMetadata(ROUTES_META,ControllerClass)||[],middlewares=Reflect.getMetadata(MIDDLEWARE_META,ControllerClass)||[],instance=this.container.get(ControllerClass),controllerMiddlewares=middlewares.filter((m)=>!m.target).map((m)=>m.handler),scopedMiddlewares=[...inheritedMiddlewares,...controllerMiddlewares];for(let route of routes){let fullPath=this.normalizePath(basePath+route.path),params=Reflect.getMetadata(PARAMS_META,ControllerClass,route.handlerName)||[],routeMiddlewares=middlewares.filter((m)=>m.target===route.handlerName).map((m)=>m.handler),paramTypes=Reflect.getMetadata("design:paramtypes",ControllerClass.prototype,route.handlerName)||[],bodyDtoType=null;for(let param of params)if(param.type==="body"&&!param.key){let dtoType=paramTypes[param.index];if(dtoType&&this.validator?.hasValidation(dtoType))bodyDtoType=dtoType}let compiled=compileHandler(instance,route.handlerName,params),resolvedMiddlewares=[...this.config.globalMiddlewares||[],...this._middlewares,...scopedMiddlewares,...routeMiddlewares].map((m)=>this.resolveMiddleware(m)),hasMiddlewares=resolvedMiddlewares.length>0,method=route.method.toUpperCase();if(compiled.isStatic&&!hasMiddlewares)this.registerRoute(fullPath,method,this.createStaticResponse(compiled.staticValue));else this.registerRoute(fullPath,method,this.createHandler(compiled,params,resolvedMiddlewares,bodyDtoType))}if(meta.children)for(let ChildController of meta.children){if(!this.container.has(ChildController))this.container.register(ChildController);this.compileController(ChildController,basePath,scopedMiddlewares)}}registerRoute(path,method,handler){if(!this.routes[path])this.routes[path]={};this.routes[path][method]=handler}createStaticResponse(value){let isString=typeof value==="string",body=isString?value:JSON.stringify(value);return new Response(body,isString?TEXT_OPTS:JSON_OPTS)}createHandler(compiled,params,middlewares,bodyDtoType){let handler=compiled.fn,hasMiddlewares=middlewares.length>0,hasParams=params.length>0,applyCors=this.hasCors?this.applyCors.bind(this):null,validator=bodyDtoType?this.validator:null,hasMiddlewaresOrValidation=hasMiddlewares||!!validator;if(!hasMiddlewaresOrValidation&&!hasParams){if(compiled.isAsync)return async(req)=>{let ctx=new Context(req),result=await handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response};return(req)=>{let ctx=new Context(req),result=handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response}}if(!hasMiddlewaresOrValidation&&hasParams){if(compiled.isAsync)return async(req)=>{let ctx=new Context(req,req.params),result=await handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response};return(req)=>{let ctx=new Context(req,req.params),result=handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response}}return async(req)=>{let ctx=new Context(req,req.params||{});for(let middleware of middlewares){let result2=await middleware(ctx);if(result2 instanceof Response)return applyCors?applyCors(result2,req):result2}if(validator&&bodyDtoType)await ctx.parseBody(),validator.validateOrThrow(bodyDtoType,ctx.body);let result=compiled.isAsync?await handler(ctx):handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response}}resolveMiddleware(middleware){if(typeof middleware==="function"&&middleware.prototype?.handle){let instance=this.container.get(middleware);return(ctx)=>instance.handle(ctx,()=>{})}return middleware}applyCors(response,req){let origin=req.headers.get("origin");if(origin&&this.corsHandler)return this.corsHandler.apply(response,origin);return response}handleNotFound(req){if(this.hasCors&&req.method==="OPTIONS"){let origin=req.headers.get("origin");if(origin)return this.corsHandler.preflight(origin)}return NOT_FOUND_RESPONSE}buildResponse(result){if(result instanceof Response)return result;if(typeof result==="string")return new Response(result,TEXT_OPTS);if(result===void 0)return new Response(null,{status:204});return Response.json(result)}normalizePath(path){if(!path.startsWith("/"))path="/"+path;if(path!=="/"&&path.endsWith("/"))path=path.slice(0,-1);return path.replace(/\/+/g,"/")}hasParams(path){return path.includes(":")||path.includes("*")}stop(){this.server?.stop?.()}handleError(error){let response;if(error instanceof HttpException)response=error.toResponse();else if(error instanceof ValidationException)response=error.toResponse();else console.error("Unhandled error:",error),response=INTERNAL_ERROR_RESPONSE;if(this.hasCors&&this.corsHandler)return this.corsHandler.apply(response,"*");return response}executeLifecycleHooks(type){let handlers=getEventHandlers(type);for(let handler of handlers)try{let instance=this.container.has(handler.target)?this.container.get(handler.target):null;if(instance&&typeof instance[handler.methodName]==="function"){let result=instance[handler.methodName]();if(result instanceof Promise)result.catch((err)=>console.error(`Error in ${type} hook ${handler.methodName}:`,err))}}catch(err){console.error(`Error in ${type} hook ${handler.methodName}:`,err)}}registerShutdownHandlers(){let shutdown=()=>{this.executeLifecycleHooks("onShutdown"),this.stop(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown)}}function createParamDecorator(type,key){return function(target,propertyKey,index){let params=Reflect.getMetadata(PARAMS_META,target.constructor,propertyKey)||[];params.push({type,key,index}),Reflect.defineMetadata(PARAMS_META,params,target.constructor,propertyKey)}}function Param(key){return createParamDecorator("param",key)}function Query(key){return createParamDecorator("query",key)}function Body(key){return createParamDecorator("body",key)}function Header(key){return createParamDecorator("header",key)}function Req(){return createParamDecorator("req")}function Ctx(){return createParamDecorator("ctx")}function Locals(key){return createParamDecorator("locals",key)}function Use(...middlewares){return function(target,propertyKey){let isMethod=propertyKey!==void 0,metaTarget=isMethod?target.constructor:target,existing=Reflect.getMetadata(MIDDLEWARE_META,metaTarget)||[];for(let handler of middlewares)existing.push({handler,target:isMethod?propertyKey:void 0});Reflect.defineMetadata(MIDDLEWARE_META,existing,metaTarget)}}function Service(options={}){return(target)=>{Reflect.defineMetadata(SERVICE_META,{scope:options.scope??"singleton"},target)}}function Inject(token){return(target,propertyKey,parameterIndex)=>{let existing=Reflect.getMetadata(INJECT_META,target)||new Map;existing.set(parameterIndex,token),Reflect.defineMetadata(INJECT_META,existing,target)}}var EMPTY_PARAMS2=Object.freeze({});function createNode(part){return{part,store:null,children:null,paramChild:null,wildcardStore:null}}class RadixRouter{roots={};add(method,path,store){if(path==="")path="/";if(path[0]!=="/")path="/"+path;let isWildcard=path.endsWith("*");if(isWildcard)path=path.slice(0,-1);let node=this.roots[method];if(!node)node=this.roots[method]=createNode("/");let i=0,len=path.length;while(i<len){if(path.charCodeAt(i)===58){let paramStart=i+1,paramEnd=paramStart;while(paramEnd<len&&path.charCodeAt(paramEnd)!==47)paramEnd++;let paramName=path.slice(paramStart,paramEnd);if(!node.paramChild)node.paramChild={name:paramName,store:null,child:null};if(paramEnd>=len){node.paramChild.store=store;return}if(!node.paramChild.child)node.paramChild.child=createNode(path.slice(paramEnd));node=node.paramChild.child,i=paramEnd;continue}let segmentEnd=i;while(segmentEnd<len&&path.charCodeAt(segmentEnd)!==47&&path.charCodeAt(segmentEnd)!==58)segmentEnd++;if(segmentEnd<len&&path.charCodeAt(segmentEnd)===47)segmentEnd++;let segment=path.slice(i,segmentEnd);if(segment===node.part){i=segmentEnd;continue}if(!node.children)node.children=new Map;let firstChar=segment.charCodeAt(0),child=node.children.get(firstChar);if(!child)child=createNode(segment),node.children.set(firstChar,child);node=child,i=segmentEnd}if(isWildcard)node.wildcardStore=store;else node.store=store}find(method,path){let root=this.roots[method];if(!root)return null;return this.matchPath(root,path,0,path.length)}matchPath(node,path,start,len){let partLen=node.part.length,end=start+partLen;if(partLen>1){if(end>len)return null;for(let i=1,j=start+1;i<partLen;i++,j++)if(node.part.charCodeAt(i)!==path.charCodeAt(j))return null}if(end===len){if(node.store!==null)return{store:node.store,params:EMPTY_PARAMS2};if(node.wildcardStore!==null)return{store:node.wildcardStore,params:{"*":""}};return null}if(node.children){let child=node.children.get(path.charCodeAt(end));if(child){let result=this.matchPath(child,path,end,len);if(result)return result}}if(node.paramChild){let param=node.paramChild,paramEnd=end;while(paramEnd<len&&path.charCodeAt(paramEnd)!==47)paramEnd++;if(paramEnd===end)return null;let paramValue=path.slice(end,paramEnd);if(paramEnd>=len){if(param.store!==null)return{store:param.store,params:{[param.name]:paramValue}}}else if(param.child){let result=this.matchPath(param.child,path,paramEnd,len);if(result){if(result.params===EMPTY_PARAMS2)result.params={[param.name]:paramValue};else result.params[param.name]=paramValue;return result}}}if(node.wildcardStore!==null)return{store:node.wildcardStore,params:{"*":path.slice(end)}};return null}}class ValibotAdapter{name="ValibotAdapter";schemaCache=new Map;valibot=null;constructor(){try{this.valibot=__require("valibot")}catch{}}ensureValibot(){if(!this.valibot)this.valibot=__require("valibot");return this.valibot}hasValidation(target){return getSchema(target)!==void 0}validate(target,value){let schema=this.getOrCacheSchema(target);if(!schema)return{success:!0,data:value};let result=this.ensureValibot().safeParse(schema,value);if(result.success)return{success:!0,data:result.output};return{success:!1,errors:this.formatErrors(result.issues)}}validateOrThrow(target,value){let result=this.validate(target,value);if(result.success)return result.data;throw new ValidationException(result.errors)}getOrCacheSchema(target){let schema=this.schemaCache.get(target);if(schema===void 0)schema=getSchema(target)??null,this.schemaCache.set(target,schema);return schema}formatErrors(issues){return issues.map((issue)=>({path:issue.path?.map((p)=>p.key).join(".")||"",message:issue.message}))}}class RedisDriver{config;name="RedisDriver";client=null;connected=!1;constructor(config={}){this.config=config}async ensureConnected(){if(this.connected)return;let url=this.config.url||`redis://${this.config.host||"localhost"}:${this.config.port||6379}`;if(typeof Bun<"u"&&Bun.redis)this.client=new Bun.redis(url);else try{let Redis=require_built3();this.client=new Redis({host:this.config.host||"localhost",port:this.config.port||6379,password:this.config.password,db:this.config.db||0})}catch{throw Error("Redis client not available. Install ioredis or use Bun with Redis support.")}this.connected=!0}async get(key){await this.ensureConnected();let value=await this.client.get(key);if(value===null)return null;try{return JSON.parse(value)}catch{return value}}async set(key,value,ttl){await this.ensureConnected();let serialized=typeof value==="string"?value:JSON.stringify(value);if(ttl)await this.client.setex(key,ttl,serialized);else await this.client.set(key,serialized);return!0}async del(key){return await this.ensureConnected(),await this.client.del(key)>0}async has(key){return await this.ensureConnected(),await this.client.exists(key)>0}async clear(){await this.ensureConnected(),await this.client.flushdb()}async close(){if(this.client&&this.connected)await this.client.quit?.(),this.connected=!1}}async function createTestHarness(options={}){let config={...options.config,disableStartupLog:!0},app=new Carno(config);if(options.plugins)for(let plugin of options.plugins)app.use(plugin);if(options.controllers)app.controllers(options.controllers);if(options.services)app.services(options.services);let port=resolvePort(options),server;if(shouldListen(options.listen))app.listen(port),server=app.server;let actualPort=server?.port??port,container=app.container,baseUrl=`http://127.0.0.1:${actualPort}`,request=async(path,init)=>{if(!server)throw Error("Server not running. Set listen: true in options.");let url=path.startsWith("http")?path:`${baseUrl}${path.startsWith("/")?path:"/"+path}`;return fetch(url,init)};return{app,container,server,port:actualPort,resolve:(token)=>container.get(token),request,get:(path,init)=>request(path,{...init,method:"GET"}),post:(path,body,init)=>request(path,{...init,method:"POST",body:body?JSON.stringify(body):void 0,headers:{"Content-Type":"application/json",...init?.headers}}),put:(path,body,init)=>request(path,{...init,method:"PUT",body:body?JSON.stringify(body):void 0,headers:{"Content-Type":"application/json",...init?.headers}}),delete:(path,init)=>request(path,{...init,method:"DELETE"}),close:async()=>{app.stop()}}}async function withTestApp(routine,options={}){let harness=await createTestHarness(options);try{await routine(harness)}finally{await harness.close()}}function shouldListen(value){return typeof value==="number"||Boolean(value)}function resolvePort(options){if(typeof options.listen==="number")return options.listen;if(typeof options.port==="number")return options.port;return 0}class Metadata{static get(key,target){return Reflect.getMetadata(key,target)}static set(key,value,target){Reflect.defineMetadata(key,value,target)}static has(key,target){return Reflect.hasMetadata(key,target)}static delete(key,target){return Reflect.deleteMetadata(key,target)}static keys(target){return Reflect.getMetadataKeys(target)}static getType(target,propertyKey){return Reflect.getMetadata("design:type",target,propertyKey)}}function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isString(value){return typeof value==="string"}export{withTestApp,isString,isObject,getSchema,createTestHarness,ZodAdapter,ValidationException,ValibotAdapter,VALIDATION_SCHEMA,Use,UnprocessableEntityException,UnauthorizedException,TooManyRequestsException,ServiceUnavailableException,Service,Scope,Schema,Req,RedisDriver,RadixRouter,Query,Put,Post,Patch,Param,Options,OnApplicationShutdown,OnApplicationInit,OnApplicationBoot,NotFoundException,Use as Middleware,MethodNotAllowedException,Metadata,MemoryDriver,Locals,InternalServerErrorException,Inject,HttpException,Header,Head,Get,ForbiddenException,EventType,Delete,Ctx,CorsHandler,Controller,Context,Container,ConflictException,Carno,CacheService,Body,BadRequestException};
|
|
180
|
+
}`;return{fn:Function("h",code)(bound),isAsync:!1,isStatic:!1}}function escapeKey(key){return key.replace(/['\"\\]/g,"\\$&")}function buildArgExpression(param){let key=param.key?escapeKey(param.key):void 0;switch(param.type){case"param":return key?`c.params['${key}']`:"c.params";case"query":return key?`c.query['${key}']`:"c.query";case"body":return key?`c.body['${key}']`:"c.body";case"header":return key?`c.req.headers.get('${key}')`:"c.req.headers";case"req":return"c.req";case"ctx":return"c";case"locals":return key?`c.locals['${key}']`:"c.locals";default:return"undefined"}}function parseQueryFromURL(url){let queryStart=url.indexOf("?");if(queryStart===-1)return Object.create(null);let queryEnd=url.indexOf("#",queryStart);if(queryEnd===-1)queryEnd=url.length;return parseQuery(url,queryStart+1,queryEnd)}function parseQuery(input,startIndex,endIndex){let result=Object.create(null),flags=0,startingIndex=startIndex-1,equalityIndex=startingIndex;for(let i=startIndex;i<endIndex;i++)switch(input.charCodeAt(i)){case 38:processKeyValuePair(i),startingIndex=i,equalityIndex=i,flags=0;break;case 61:if(equalityIndex<=startingIndex)equalityIndex=i;else flags|=8;break;case 43:if(equalityIndex>startingIndex)flags|=4;else flags|=1;break;case 37:if(equalityIndex>startingIndex)flags|=8;else flags|=2;break}if(startingIndex<endIndex)processKeyValuePair(endIndex);return result;function processKeyValuePair(pairEndIndex){let hasBothKeyValuePair=equalityIndex>startingIndex,effectiveEqualityIndex=hasBothKeyValuePair?equalityIndex:pairEndIndex,keySlice=input.slice(startingIndex+1,effectiveEqualityIndex);if(!hasBothKeyValuePair&&keySlice.length===0)return;let finalKey=keySlice;if(flags&1)finalKey=finalKey.replace(/\+/g," ");if(flags&2)try{finalKey=decodeURIComponent(finalKey)}catch{}let finalValue="";if(hasBothKeyValuePair){let valueSlice=input.slice(equalityIndex+1,pairEndIndex);if(flags&4)valueSlice=valueSlice.replace(/\+/g," ");if(flags&8)try{finalValue=decodeURIComponent(valueSlice)}catch{finalValue=valueSlice}else finalValue=valueSlice}result[finalKey]=finalValue}}var EMPTY_PARAMS=Object.freeze({});class Context{req;params;locals={};_query=null;_body;_bodyParsed=!1;_url=null;_status=0;constructor(req,params=EMPTY_PARAMS){this.req=req,this.params=params}get status(){return this._status||200}set status(value){this._status=value}get url(){if(!this._url)this._url=new URL(this.req.url);return this._url}get query(){if(!this._query)this._query=parseQueryFromURL(this.req.url);return this._query}get body(){return this._body}async parseBody(){if(this._bodyParsed)return this._body;this._bodyParsed=!0;let contentType=this.req.headers.get("content-type")||"";if(contentType.includes("application/json"))this._body=await this.req.json();else if(contentType.includes("form")){let formData=await this.req.formData();this._body=Object.fromEntries(formData)}else if(contentType.includes("text"))this._body=await this.req.text();else this._body=await this.req.arrayBuffer();return this._body}get method(){return this.req.method}get headers(){return this.req.headers}get path(){return this.url.pathname}json(data,status){if(status)this.status=status;return Response.json(data,{status:this.status})}text(data,status){if(status)this.status=status;return new Response(data,{status:this.status,headers:{"Content-Type":"text/plain"}})}html(data,status){if(status)this.status=status;return new Response(data,{status:this.status,headers:{"Content-Type":"text/html"}})}redirect(url,status=302){return Response.redirect(url,status)}static createFromJob(job){let fakeRequest=new Request("http://localhost/job"),ctx=new Context(fakeRequest);return ctx.locals.job=job,ctx}}var Scope;((Scope2)=>{Scope2.SINGLETON="singleton";Scope2.REQUEST="request";Scope2.INSTANCE="instance"})(Scope||={});class Container{configs=new Map;instances=new Map;resolving=new Set;register(config){let normalized=this.normalizeConfig(config);if(this.configs.set(normalized.token,normalized),normalized.useValue!==void 0)this.instances.set(normalized.token,normalized.useValue);return this}get(token){let cached=this.instances.get(token);if(cached!==void 0)return cached;return this.resolveInternal(token).instance}has(token){return this.configs.has(token)}resolveInternal(token,requestLocals){if(requestLocals?.has(token))return{instance:requestLocals.get(token),scope:"request"};let cached=this.instances.get(token);if(cached!==void 0)return{instance:cached,scope:"singleton"};let config=this.configs.get(token);if(!config)throw Error(`Provider not found: ${token.name}`);let creation=this.createInstance(config,requestLocals);if(creation.scope==="singleton")this.instances.set(token,creation.instance);else if(creation.scope==="request"&&requestLocals)requestLocals.set(token,creation.instance);return creation}createInstance(config,requestLocals){let target=config.useClass??config.token;if(this.resolving.has(target))throw Error(`Circular dependency detected: ${target.name}`);this.resolving.add(target);try{let depsToken=this.getDependencies(target);if(depsToken.length===0)return{instance:new target,scope:config.scope||"singleton"};let args=[],effectiveScope=config.scope||"singleton";for(let depToken of depsToken){let depResult=this.resolveInternal(depToken,requestLocals);if(args.push(depResult.instance),depResult.scope==="request"&&effectiveScope==="singleton")effectiveScope="request"}return{instance:new target(...args),scope:effectiveScope}}finally{this.resolving.delete(target)}}getDependencies(target){return(Reflect.getMetadata("design:paramtypes",target)||[]).filter((t)=>t&&typeof t==="function"&&!this.isPrimitive(t))}isPrimitive(type){return type===String||type===Number||type===Boolean||type===Object||type===Array||type===Symbol}normalizeConfig(config){if(typeof config==="function")return{token:config,useClass:config,scope:"singleton"};return{...config,useClass:config.useClass??config.token,scope:config.scope??"singleton"}}clear(){this.configs.clear(),this.instances.clear()}}var DEFAULT_CORS_METHODS=["GET","HEAD","PUT","PATCH","POST","DELETE"],DEFAULT_CORS_HEADERS=["Content-Type","Authorization","X-Requested-With","Accept","Origin"];class CorsHandler{cache=new Map;methodsStr;headersStr;exposedStr;maxAgeStr;hasCredentials;isWildcard;matcher;preflightResponse=null;constructor(config){if(this.methodsStr=(config.methods||DEFAULT_CORS_METHODS).join(", "),this.headersStr=(config.allowedHeaders||DEFAULT_CORS_HEADERS).join(", "),this.exposedStr=config.exposedHeaders?.join(", ")||null,this.maxAgeStr=config.maxAge?.toString()||null,this.hasCredentials=!!config.credentials,this.isWildcard=config.origins==="*",this.matcher=this.buildMatcher(config.origins),this.isWildcard)this.preflightResponse=new Response(null,{status:204,headers:this.buildHeaders("*")})}preflight(origin){if(this.isWildcard&&this.preflightResponse)return this.preflightResponse.clone();if(!this.isAllowed(origin))return new Response(null,{status:403});return new Response(null,{status:204,headers:this.getHeaders(origin)})}apply(response,origin){if(!this.isAllowed(origin))return response;let headers=this.getHeaders(origin);for(let[key,value]of Object.entries(headers))response.headers.set(key,value);return response}isAllowed(origin){return this.matcher(origin)}getHeaders(origin){let key=this.isWildcard?"*":origin,headers=this.cache.get(key);if(!headers)headers=this.buildHeaders(origin),this.cache.set(key,headers);return headers}buildHeaders(origin){let headers={"Access-Control-Allow-Origin":this.isWildcard?"*":origin,"Access-Control-Allow-Methods":this.methodsStr,"Access-Control-Allow-Headers":this.headersStr};if(this.hasCredentials)headers["Access-Control-Allow-Credentials"]="true";if(this.exposedStr)headers["Access-Control-Expose-Headers"]=this.exposedStr;if(this.maxAgeStr)headers["Access-Control-Max-Age"]=this.maxAgeStr;return headers}buildMatcher(origins){if(origins==="*")return()=>!0;if(typeof origins==="string")return(o)=>o===origins;if(Array.isArray(origins)){let set=new Set(origins);return(o)=>set.has(o)}if(origins instanceof RegExp)return(o)=>origins.test(o);if(typeof origins==="function")return origins;return()=>!1}}class HttpException extends Error{statusCode;errors;constructor(statusCode,message,errors){super(message);this.statusCode=statusCode;this.errors=errors;this.name="HttpException"}toResponse(){let body={statusCode:this.statusCode,message:this.message,...this.errors&&{errors:this.errors}};return Response.json(body,{status:this.statusCode})}}class BadRequestException extends HttpException{constructor(message="Bad Request",errors){super(400,message,errors);this.name="BadRequestException"}}class UnauthorizedException extends HttpException{constructor(message="Unauthorized"){super(401,message);this.name="UnauthorizedException"}}class ForbiddenException extends HttpException{constructor(message="Forbidden"){super(403,message);this.name="ForbiddenException"}}class NotFoundException extends HttpException{constructor(message="Not Found"){super(404,message);this.name="NotFoundException"}}class MethodNotAllowedException extends HttpException{constructor(message="Method Not Allowed"){super(405,message);this.name="MethodNotAllowedException"}}class ConflictException extends HttpException{constructor(message="Conflict"){super(409,message);this.name="ConflictException"}}class UnprocessableEntityException extends HttpException{constructor(message="Unprocessable Entity",errors){super(422,message,errors);this.name="UnprocessableEntityException"}}class TooManyRequestsException extends HttpException{constructor(message="Too Many Requests"){super(429,message);this.name="TooManyRequestsException"}}class InternalServerErrorException extends HttpException{constructor(message="Internal Server Error"){super(500,message);this.name="InternalServerErrorException"}}class ServiceUnavailableException extends HttpException{constructor(message="Service Unavailable"){super(503,message);this.name="ServiceUnavailableException"}}var VALIDATION_SCHEMA=Symbol("turbo:validation");function Schema(schema){return(target)=>{Reflect.defineMetadata(VALIDATION_SCHEMA,schema,target)}}function getSchema(target){return Reflect.getMetadata(VALIDATION_SCHEMA,target)}class ZodAdapter{name="ZodAdapter";schemaCache=new Map;hasValidation(target){return getSchema(target)!==void 0}validate(target,value){let schema=this.getOrCacheSchema(target);if(!schema)return{success:!0,data:value};let result=schema.safeParse(value);if(result.success)return{success:!0,data:result.data};return{success:!1,errors:this.formatErrors(result.error)}}validateOrThrow(target,value){let schema=this.getOrCacheSchema(target);if(!schema)return value;let result=schema.safeParse(value);if(result.success)return result.data;let errors=this.formatErrors(result.error);throw new ValidationException(errors)}getOrCacheSchema(target){let schema=this.schemaCache.get(target);if(schema===void 0)schema=getSchema(target)??null,this.schemaCache.set(target,schema);return schema}formatErrors(zodError){return zodError.issues.map((issue)=>({path:issue.path.join("."),message:issue.message}))}}class ValidationException extends Error{errors;constructor(errors){super(`Validation failed: ${errors.map((e)=>`${e.path}: ${e.message}`).join(", ")}`);this.errors=errors;this.name="ValidationException"}toResponse(){return Response.json({statusCode:400,message:"Validation failed",errors:this.errors},{status:400})}}var EventType;((EventType2)=>{EventType2.INIT="onInit";EventType2.BOOT="onBoot";EventType2.SHUTDOWN="onShutdown"})(EventType||={});var EVENTS_META=Symbol("turbo:events"),eventRegistry=new Map;function registerEvent(type,target,methodName,priority=0){let handlers=eventRegistry.get(type);if(!handlers)handlers=[],eventRegistry.set(type,handlers);handlers.push({target,methodName,priority})}function getEventHandlers(type){return(eventRegistry.get(type)||[]).sort((a,b)=>b.priority-a.priority)}function hasEventHandlers(type){return(eventRegistry.get(type)?.length??0)>0}function OnApplicationInit(priority=0){return function(target,propertyKey){registerEvent("onInit",target.constructor,propertyKey,priority)}}function OnApplicationBoot(priority=0){return function(target,propertyKey){registerEvent("onBoot",target.constructor,propertyKey,priority)}}function OnApplicationShutdown(priority=0){return function(target,propertyKey){registerEvent("onShutdown",target.constructor,propertyKey,priority)}}class MemoryDriver{name="MemoryDriver";cache=new Map;cleanupInterval=null;constructor(cleanupIntervalMs=0){if(cleanupIntervalMs>0)this.cleanupInterval=setInterval(()=>this.cleanup(),cleanupIntervalMs)}async get(key){let entry=this.cache.get(key);if(!entry)return null;if(entry.expiresAt!==null&&Date.now()>entry.expiresAt)return this.cache.delete(key),null;return entry.value}async set(key,value,ttl){let expiresAt=ttl?Date.now()+ttl:null;return this.cache.set(key,{value,expiresAt}),!0}async del(key){return this.cache.delete(key)}async has(key){let entry=this.cache.get(key);if(!entry)return!1;if(entry.expiresAt!==null&&Date.now()>entry.expiresAt)return this.cache.delete(key),!1;return!0}async clear(){this.cache.clear()}async close(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null;this.cache.clear()}cleanup(){let now=Date.now();for(let[key,entry]of this.cache)if(entry.expiresAt!==null&&now>entry.expiresAt)this.cache.delete(key)}stats(){return{size:this.cache.size}}}class CacheService{driver;prefix;defaultTtl;constructor(config={}){this.driver=config.driver||new MemoryDriver,this.prefix=config.prefix||"",this.defaultTtl=config.defaultTtl}key(key){return this.prefix?`${this.prefix}:${key}`:key}async get(key){return this.driver.get(this.key(key))}async set(key,value,ttl){return this.driver.set(this.key(key),value,ttl??this.defaultTtl)}async del(key){return this.driver.del(this.key(key))}async has(key){return this.driver.has(this.key(key))}async clear(){return this.driver.clear()}async getOrSet(key,cb,ttl){let cached=await this.get(key);if(cached!==null)return cached;let value=await cb();return await this.set(key,value,ttl),value}async getMany(keys){return Promise.all(keys.map((key)=>this.get(key)))}async setMany(entries){return Promise.all(entries.map((entry)=>this.set(entry.key,entry.value,entry.ttl)))}async delMany(keys){return Promise.all(keys.map((key)=>this.del(key)))}async close(){await this.driver.close?.()}getDriver(){return this.driver}}function normalizeOptions(pathOrOptions){if(!pathOrOptions)return{};if(typeof pathOrOptions==="string")return{path:pathOrOptions};return pathOrOptions}function normalizePath(path){if(!path)return"";let normalized=path.startsWith("/")?path:"/"+path;if(normalized!=="/"&&normalized.endsWith("/"))normalized=normalized.slice(0,-1);return normalized}function Controller(pathOrOptions){return(target)=>{let options=normalizeOptions(pathOrOptions),meta={path:normalizePath(options.path||""),scope:options.scope,children:options.children};if(Reflect.defineMetadata(CONTROLLER_META,meta,target),!Reflect.hasMetadata(ROUTES_META,target))Reflect.defineMetadata(ROUTES_META,[],target)}}function createMethodDecorator(method){return function(path=""){return function(targetOrMethod,contextOrPropertyKey,descriptor){if(contextOrPropertyKey&&typeof contextOrPropertyKey==="object"&&"kind"in contextOrPropertyKey){let context=contextOrPropertyKey;return context.addInitializer(function(){let constructor2=this.constructor,routes2=Reflect.getMetadata(ROUTES_META,constructor2)||[];routes2.push({method,path:path.startsWith("/")?path:"/"+path,handlerName:String(context.name)}),Reflect.defineMetadata(ROUTES_META,routes2,constructor2)}),targetOrMethod}let constructor=targetOrMethod.constructor,propertyKey=contextOrPropertyKey,routes=Reflect.getMetadata(ROUTES_META,constructor)||[];routes.push({method,path:path.startsWith("/")?path:"/"+path,handlerName:String(propertyKey)}),Reflect.defineMetadata(ROUTES_META,routes,constructor)}}}var Get=createMethodDecorator("get"),Post=createMethodDecorator("post"),Put=createMethodDecorator("put"),Delete=createMethodDecorator("delete"),Patch=createMethodDecorator("patch"),Head=createMethodDecorator("head"),Options=createMethodDecorator("options");class DefaultRoutes{favicon(){return new Response(null,{status:204})}}__legacyDecorateClassTS([Get("/favicon.ico"),__legacyMetadataTS("design:type",Function),__legacyMetadataTS("design:paramtypes",[]),__legacyMetadataTS("design:returntype",void 0)],DefaultRoutes.prototype,"favicon",null),DefaultRoutes=__legacyDecorateClassTS([Controller()],DefaultRoutes);var DEFAULT_STATIC_ROUTES={"/health":new Response('{"status":"ok"}',{status:200,headers:{"Content-Type":"application/json"}}),"/ready":new Response('{"ready":true}',{status:200,headers:{"Content-Type":"application/json"}}),"/favicon.ico":new Response(null,{status:204})};var NOT_FOUND_RESPONSE=new Response("Not Found",{status:404}),TEXT_OPTS=Object.freeze({status:200,headers:{"Content-Type":"text/plain"}}),JSON_OPTS=Object.freeze({status:200,headers:{"Content-Type":"application/json"}}),INTERNAL_ERROR_RESPONSE=new Response('{"statusCode":500,"message":"Internal Server Error"}',{status:500,headers:{"Content-Type":"application/json"}});class Carno{config;_controllers=[];_services=[];_middlewares=[];routes={};container=new Container;corsHandler=null;hasCors=!1;validator=null;server;hasInitHooks=!1;hasBootHooks=!1;hasShutdownHooks=!1;constructor(config={}){this.config=config;if(this.config.exports=this.config.exports||[],this.config.globalMiddlewares=this.config.globalMiddlewares||[],this.config.cors)this.corsHandler=new CorsHandler(this.config.cors),this.hasCors=!0;if(this.config.validation===void 0||this.config.validation===!0)this.validator=new ZodAdapter;else if(typeof this.config.validation==="function"){let AdapterClass=this.config.validation;this.validator=new AdapterClass}else if(this.config.validation)this.validator=this.config.validation}use(plugin){if(plugin._controllers.length>0)this._controllers.push(...plugin._controllers);for(let exported of plugin.config.exports||[]){let existingService=this.findServiceInPlugin(plugin,exported),serviceToAdd=this.shouldCloneService(existingService)?{...existingService}:exported;this._services.push(serviceToAdd)}if(plugin._services.length>0)this._services.push(...plugin._services);if(plugin.config.globalMiddlewares)this._middlewares.push(...plugin.config.globalMiddlewares);if(plugin._middlewares.length>0)this._middlewares.push(...plugin._middlewares);for(let[path,methods]of Object.entries(plugin.routes)){if(!this.routes[path])this.routes[path]={};if(typeof methods==="object"&&methods!==null&&!(methods instanceof Response))Object.assign(this.routes[path],methods);else this.routes[path]=methods}return this}findServiceInPlugin(plugin,exported){return plugin._services.find((s)=>this.getServiceToken(s)===this.getServiceToken(exported))}getServiceToken(service){return service?.token||service}shouldCloneService(service){return!!(service?.useValue!==void 0||service?.useClass)}services(serviceClass){let items=Array.isArray(serviceClass)?serviceClass:[serviceClass];return this._services.push(...items),this}middlewares(handler){let items=Array.isArray(handler)?handler:[handler];return this._middlewares.push(...items),this}controllers(controllerClass){let items=Array.isArray(controllerClass)?controllerClass:[controllerClass];return this._controllers.push(...items),this}route(method,path,handler){let normalizedMethod=method.toUpperCase();if(!this.routes[path])this.routes[path]={};return this.routes[path][normalizedMethod]=handler,this}addRoutes(routes){for(let[path,methods]of Object.entries(routes)){if(!this.routes[path])this.routes[path]={};for(let[method,handler]of Object.entries(methods))this.routes[path][method.toUpperCase()]=handler}return this}get(token){return this.container.get(token)}listen(port=3000){this.bootstrap(),this.compileRoutes();let config={port,fetch:this.handleNotFound.bind(this),error:this.handleError.bind(this),routes:{...DEFAULT_STATIC_ROUTES,...this.routes}};if(this.server=Bun.serve(config),this.hasBootHooks)this.executeLifecycleHooks("onBoot");if(this.hasShutdownHooks)this.registerShutdownHandlers();if(!this.config.disableStartupLog)console.log(`Carno running on port ${port}`)}bootstrap(){this.hasInitHooks=hasEventHandlers("onInit"),this.hasBootHooks=hasEventHandlers("onBoot"),this.hasShutdownHooks=hasEventHandlers("onShutdown"),this.container.register({token:Container,useValue:this.container});let cacheConfig=typeof this.config.cache==="object"?this.config.cache:{};this.container.register({token:CacheService,useValue:new CacheService(cacheConfig)});for(let service of this._services)this.container.register(service);for(let ControllerClass of this._controllers)this.container.register(ControllerClass);if(this.hasInitHooks)this.executeLifecycleHooks("onInit");for(let service of this._services){let token=typeof service==="function"?service:service.token,serviceConfig=typeof service==="function"?null:service;if(!serviceConfig||serviceConfig.scope!=="request")this.container.get(token)}}compileRoutes(){for(let ControllerClass of this._controllers)this.compileController(ControllerClass)}compileController(ControllerClass,parentPath="",inheritedMiddlewares=[]){let meta=Reflect.getMetadata(CONTROLLER_META,ControllerClass)||{path:""},basePath=parentPath+(meta.path||""),routes=Reflect.getMetadata(ROUTES_META,ControllerClass)||[],middlewares=Reflect.getMetadata(MIDDLEWARE_META,ControllerClass)||[],instance=this.container.get(ControllerClass),controllerMiddlewares=middlewares.filter((m)=>!m.target).map((m)=>m.handler),scopedMiddlewares=[...inheritedMiddlewares,...controllerMiddlewares];for(let route of routes){let fullPath=this.normalizePath(basePath+route.path),params=Reflect.getMetadata(PARAMS_META,ControllerClass,route.handlerName)||[],routeMiddlewares=middlewares.filter((m)=>m.target===route.handlerName).map((m)=>m.handler),paramTypes=Reflect.getMetadata("design:paramtypes",ControllerClass.prototype,route.handlerName)||[],bodyDtoType=null;for(let param of params)if(param.type==="body"&&!param.key){let dtoType=paramTypes[param.index];if(dtoType&&this.validator?.hasValidation(dtoType))bodyDtoType=dtoType}let compiled=compileHandler(instance,route.handlerName,params),resolvedMiddlewares=[...this.config.globalMiddlewares||[],...this._middlewares,...scopedMiddlewares,...routeMiddlewares].map((m)=>this.resolveMiddleware(m)),hasMiddlewares=resolvedMiddlewares.length>0,method=route.method.toUpperCase();if(compiled.isStatic&&!hasMiddlewares)this.registerRoute(fullPath,method,this.createStaticResponse(compiled.staticValue));else this.registerRoute(fullPath,method,this.createHandler(compiled,params,resolvedMiddlewares,bodyDtoType))}if(meta.children)for(let ChildController of meta.children){if(!this.container.has(ChildController))this.container.register(ChildController);this.compileController(ChildController,basePath,scopedMiddlewares)}}registerRoute(path,method,handler){if(!this.routes[path])this.routes[path]={};this.routes[path][method]=handler}createStaticResponse(value){let isString=typeof value==="string",body=isString?value:JSON.stringify(value);return new Response(body,isString?TEXT_OPTS:JSON_OPTS)}createHandler(compiled,params,middlewares,bodyDtoType){let handler=compiled.fn,hasMiddlewares=middlewares.length>0,hasParams=params.length>0,applyCors=this.hasCors?this.applyCors.bind(this):null,validator=bodyDtoType?this.validator:null,hasMiddlewaresOrValidation=hasMiddlewares||!!validator;if(!hasMiddlewaresOrValidation&&!hasParams){if(compiled.isAsync)return async(req)=>{let ctx=new Context(req),result=await handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response};return(req)=>{let ctx=new Context(req),result=handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response}}if(!hasMiddlewaresOrValidation&&hasParams){if(compiled.isAsync)return async(req)=>{let ctx=new Context(req,req.params),result=await handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response};return(req)=>{let ctx=new Context(req,req.params),result=handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response}}return async(req)=>{let ctx=new Context(req,req.params||{});for(let middleware of middlewares){let result2=await middleware(ctx);if(result2 instanceof Response)return applyCors?applyCors(result2,req):result2}if(validator&&bodyDtoType)await ctx.parseBody(),validator.validateOrThrow(bodyDtoType,ctx.body);let result=compiled.isAsync?await handler(ctx):handler(ctx),response=this.buildResponse(result);return applyCors?applyCors(response,req):response}}resolveMiddleware(middleware){if(typeof middleware==="function"&&middleware.prototype?.handle){let instance=this.container.get(middleware);return(ctx)=>instance.handle(ctx,()=>{})}return middleware}applyCors(response,req){let origin=req.headers.get("origin");if(origin&&this.corsHandler)return this.corsHandler.apply(response,origin);return response}handleNotFound(req){if(this.hasCors&&req.method==="OPTIONS"){let origin=req.headers.get("origin");if(origin)return this.corsHandler.preflight(origin)}return NOT_FOUND_RESPONSE}buildResponse(result){if(result instanceof Response)return result;if(typeof result==="string")return new Response(result,TEXT_OPTS);if(result===void 0)return new Response(null,{status:204});return Response.json(result)}normalizePath(path){if(!path.startsWith("/"))path="/"+path;if(path!=="/"&&path.endsWith("/"))path=path.slice(0,-1);return path.replace(/\/+/g,"/")}hasParams(path){return path.includes(":")||path.includes("*")}stop(){this.server?.stop?.()}handleError(error){let response;if(error instanceof HttpException)response=error.toResponse();else if(error instanceof ValidationException)response=error.toResponse();else console.error("Unhandled error:",error),response=INTERNAL_ERROR_RESPONSE;if(this.hasCors&&this.corsHandler)return this.corsHandler.apply(response,"*");return response}executeLifecycleHooks(type){let handlers=getEventHandlers(type);for(let handler of handlers)try{let instance=this.container.has(handler.target)?this.container.get(handler.target):null;if(instance&&typeof instance[handler.methodName]==="function"){let result=instance[handler.methodName]();if(result instanceof Promise)result.catch((err)=>console.error(`Error in ${type} hook ${handler.methodName}:`,err))}}catch(err){console.error(`Error in ${type} hook ${handler.methodName}:`,err)}}registerShutdownHandlers(){let shutdown=()=>{this.executeLifecycleHooks("onShutdown"),this.stop(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown)}}function createParamDecorator(type,key){return function(target,propertyKey,index){let params=Reflect.getMetadata(PARAMS_META,target.constructor,propertyKey)||[];params.push({type,key,index}),Reflect.defineMetadata(PARAMS_META,params,target.constructor,propertyKey)}}function Param(key){return createParamDecorator("param",key)}function Query(key){return createParamDecorator("query",key)}function Body(key){return createParamDecorator("body",key)}function Header(key){return createParamDecorator("header",key)}function Req(){return createParamDecorator("req")}function Ctx(){return createParamDecorator("ctx")}function Locals(key){return createParamDecorator("locals",key)}function Use(...middlewares){return function(target,propertyKey){let isMethod=propertyKey!==void 0,metaTarget=isMethod?target.constructor:target,existing=Reflect.getMetadata(MIDDLEWARE_META,metaTarget)||[];for(let handler of middlewares)existing.push({handler,target:isMethod?propertyKey:void 0});Reflect.defineMetadata(MIDDLEWARE_META,existing,metaTarget)}}function Service(options={}){return(target)=>{Reflect.defineMetadata(SERVICE_META,{scope:options.scope??"singleton"},target)}}function Inject(token){return(target,propertyKey,parameterIndex)=>{let existing=Reflect.getMetadata(INJECT_META,target)||new Map;existing.set(parameterIndex,token),Reflect.defineMetadata(INJECT_META,existing,target)}}var EMPTY_PARAMS2=Object.freeze({});function createNode(part){return{part,store:null,children:null,paramChild:null,wildcardStore:null}}class RadixRouter{roots={};add(method,path,store){if(path==="")path="/";if(path[0]!=="/")path="/"+path;let isWildcard=path.endsWith("*");if(isWildcard)path=path.slice(0,-1);let node=this.roots[method];if(!node)node=this.roots[method]=createNode("/");let i=0,len=path.length;while(i<len){if(path.charCodeAt(i)===58){let paramStart=i+1,paramEnd=paramStart;while(paramEnd<len&&path.charCodeAt(paramEnd)!==47)paramEnd++;let paramName=path.slice(paramStart,paramEnd);if(!node.paramChild)node.paramChild={name:paramName,store:null,child:null};if(paramEnd>=len){node.paramChild.store=store;return}if(!node.paramChild.child)node.paramChild.child=createNode(path.slice(paramEnd));node=node.paramChild.child,i=paramEnd;continue}let segmentEnd=i;while(segmentEnd<len&&path.charCodeAt(segmentEnd)!==47&&path.charCodeAt(segmentEnd)!==58)segmentEnd++;if(segmentEnd<len&&path.charCodeAt(segmentEnd)===47)segmentEnd++;let segment=path.slice(i,segmentEnd);if(segment===node.part){i=segmentEnd;continue}if(!node.children)node.children=new Map;let firstChar=segment.charCodeAt(0),child=node.children.get(firstChar);if(!child)child=createNode(segment),node.children.set(firstChar,child);node=child,i=segmentEnd}if(isWildcard)node.wildcardStore=store;else node.store=store}find(method,path){let root=this.roots[method];if(!root)return null;return this.matchPath(root,path,0,path.length)}matchPath(node,path,start,len){let partLen=node.part.length,end=start+partLen;if(partLen>1){if(end>len)return null;for(let i=1,j=start+1;i<partLen;i++,j++)if(node.part.charCodeAt(i)!==path.charCodeAt(j))return null}if(end===len){if(node.store!==null)return{store:node.store,params:EMPTY_PARAMS2};if(node.wildcardStore!==null)return{store:node.wildcardStore,params:{"*":""}};return null}if(node.children){let child=node.children.get(path.charCodeAt(end));if(child){let result=this.matchPath(child,path,end,len);if(result)return result}}if(node.paramChild){let param=node.paramChild,paramEnd=end;while(paramEnd<len&&path.charCodeAt(paramEnd)!==47)paramEnd++;if(paramEnd===end)return null;let paramValue=path.slice(end,paramEnd);if(paramEnd>=len){if(param.store!==null)return{store:param.store,params:{[param.name]:paramValue}}}else if(param.child){let result=this.matchPath(param.child,path,paramEnd,len);if(result){if(result.params===EMPTY_PARAMS2)result.params={[param.name]:paramValue};else result.params[param.name]=paramValue;return result}}}if(node.wildcardStore!==null)return{store:node.wildcardStore,params:{"*":path.slice(end)}};return null}}class ValibotAdapter{name="ValibotAdapter";schemaCache=new Map;valibot=null;constructor(){try{this.valibot=__require("valibot")}catch{}}ensureValibot(){if(!this.valibot)this.valibot=__require("valibot");return this.valibot}hasValidation(target){return getSchema(target)!==void 0}validate(target,value){let schema=this.getOrCacheSchema(target);if(!schema)return{success:!0,data:value};let result=this.ensureValibot().safeParse(schema,value);if(result.success)return{success:!0,data:result.output};return{success:!1,errors:this.formatErrors(result.issues)}}validateOrThrow(target,value){let result=this.validate(target,value);if(result.success)return result.data;throw new ValidationException(result.errors)}getOrCacheSchema(target){let schema=this.schemaCache.get(target);if(schema===void 0)schema=getSchema(target)??null,this.schemaCache.set(target,schema);return schema}formatErrors(issues){return issues.map((issue)=>({path:issue.path?.map((p)=>p.key).join(".")||"",message:issue.message}))}}class RedisDriver{config;name="RedisDriver";client=null;connected=!1;constructor(config={}){this.config=config}async ensureConnected(){if(this.connected)return;let url=this.config.url||`redis://${this.config.host||"localhost"}:${this.config.port||6379}`;if(typeof Bun<"u"&&Bun.redis)this.client=new Bun.redis(url);else try{let Redis=require_built3();this.client=new Redis({host:this.config.host||"localhost",port:this.config.port||6379,password:this.config.password,db:this.config.db||0})}catch{throw Error("Redis client not available. Install ioredis or use Bun with Redis support.")}this.connected=!0}async get(key){await this.ensureConnected();let value=await this.client.get(key);if(value===null)return null;try{return JSON.parse(value)}catch{return value}}async set(key,value,ttl){await this.ensureConnected();let serialized=typeof value==="string"?value:JSON.stringify(value);if(ttl)await this.client.setex(key,ttl,serialized);else await this.client.set(key,serialized);return!0}async del(key){return await this.ensureConnected(),await this.client.del(key)>0}async has(key){return await this.ensureConnected(),await this.client.exists(key)>0}async clear(){await this.ensureConnected(),await this.client.flushdb()}async close(){if(this.client&&this.connected)await this.client.quit?.(),this.connected=!1}}async function createTestHarness(options={}){let config={...options.config,disableStartupLog:!0},app=new Carno(config);if(options.plugins)for(let plugin of options.plugins)app.use(plugin);if(options.controllers)app.controllers(options.controllers);if(options.services)app.services(options.services);let port=resolvePort(options),server;if(shouldListen(options.listen))app.listen(port),server=app.server;let actualPort=server?.port??port,container=app.container,baseUrl=`http://127.0.0.1:${actualPort}`,request=async(path,init)=>{if(!server)throw Error("Server not running. Set listen: true in options.");let url=path.startsWith("http")?path:`${baseUrl}${path.startsWith("/")?path:"/"+path}`;return fetch(url,init)};return{app,container,server,port:actualPort,resolve:(token)=>container.get(token),request,get:(path,init)=>request(path,{...init,method:"GET"}),post:(path,body,init)=>request(path,{...init,method:"POST",body:body?JSON.stringify(body):void 0,headers:{"Content-Type":"application/json",...init?.headers}}),put:(path,body,init)=>request(path,{...init,method:"PUT",body:body?JSON.stringify(body):void 0,headers:{"Content-Type":"application/json",...init?.headers}}),delete:(path,init)=>request(path,{...init,method:"DELETE"}),close:async()=>{app.stop()}}}async function withTestApp(routine,options={}){let harness=await createTestHarness(options);try{await routine(harness)}finally{await harness.close()}}function shouldListen(value){return typeof value==="number"||Boolean(value)}function resolvePort(options){if(typeof options.listen==="number")return options.listen;if(typeof options.port==="number")return options.port;return 0}class Metadata{static get(key,target){return Reflect.getMetadata(key,target)}static set(key,value,target){Reflect.defineMetadata(key,value,target)}static has(key,target){return Reflect.hasMetadata(key,target)}static delete(key,target){return Reflect.deleteMetadata(key,target)}static keys(target){return Reflect.getMetadataKeys(target)}static getType(target,propertyKey){return Reflect.getMetadata("design:type",target,propertyKey)}}function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isString(value){return typeof value==="string"}export{withTestApp,isString,isObject,getSchema,createTestHarness,ZodAdapter,ValidationException,ValibotAdapter,VALIDATION_SCHEMA,Use,UnprocessableEntityException,UnauthorizedException,TooManyRequestsException,ServiceUnavailableException,Service,Scope,Schema,Req,RedisDriver,RadixRouter,Query,Put,Post,Patch,Param,Options,OnApplicationShutdown,OnApplicationInit,OnApplicationBoot,NotFoundException,Use as Middleware,MethodNotAllowedException,Metadata,MemoryDriver,Locals,InternalServerErrorException,Inject,HttpException,Header,Head,Get,ForbiddenException,EventType,Delete,Ctx,CorsHandler,Controller,Context,Container,ConflictException,Carno,CacheService,Body,BadRequestException};
|
|
181
181
|
|
|
182
|
-
//# debugId=
|
|
182
|
+
//# debugId=852FE8AECF5D534E64756E2164756E21
|
|
183
183
|
//# sourceMappingURL=index.js.map
|