@forinda/kickjs 5.15.1 → 5.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/{application-BiyBwafB.d.mts → application-CAnpDQ8d.d.mts} +18 -4
  2. package/dist/application-CAnpDQ8d.d.mts.map +1 -0
  3. package/dist/application-CRmMytW1.mjs +12 -0
  4. package/dist/application-CRmMytW1.mjs.map +1 -0
  5. package/dist/{bootstrap-Dl4f-ghy.d.mts → bootstrap-8DDzBjhx.d.mts} +2 -2
  6. package/dist/{bootstrap-Dl4f-ghy.d.mts.map → bootstrap-8DDzBjhx.d.mts.map} +1 -1
  7. package/dist/{bootstrap-Bh1Dt4Zj.mjs → bootstrap-CHmCh_cE.mjs} +3 -3
  8. package/dist/{bootstrap-Bh1Dt4Zj.mjs.map → bootstrap-CHmCh_cE.mjs.map} +1 -1
  9. package/dist/config/index.mjs +2 -2
  10. package/dist/{config-IfNt6uOv.mjs → config-BvyPboRZ.mjs} +3 -3
  11. package/dist/{config-IfNt6uOv.mjs.map → config-BvyPboRZ.mjs.map} +1 -1
  12. package/dist/{container-F-qfN8Bx.mjs → container-CPz0l8-b.mjs} +3 -3
  13. package/dist/{container-F-qfN8Bx.mjs.map → container-CPz0l8-b.mjs.map} +1 -1
  14. package/dist/context-C6e-S0uc.mjs +12 -0
  15. package/dist/context-C6e-S0uc.mjs.map +1 -0
  16. package/dist/{context-Dnt2Di7p.d.mts → context-DV7RjM9F.d.mts} +14 -3
  17. package/dist/context-DV7RjM9F.d.mts.map +1 -0
  18. package/dist/core/adapter.mjs +1 -1
  19. package/dist/core/app-module.mjs +1 -1
  20. package/dist/core/cache.mjs +1 -1
  21. package/dist/core/container.mjs +2 -2
  22. package/dist/core/cron.mjs +2 -2
  23. package/dist/core/decorators.mjs +2 -2
  24. package/dist/core/decorators.mjs.map +1 -1
  25. package/dist/core/errors.mjs +1 -1
  26. package/dist/core/errors.mjs.map +1 -1
  27. package/dist/core/interfaces.mjs +1 -1
  28. package/dist/core/logger.d.mts +1 -1
  29. package/dist/core/logger.mjs +2 -2
  30. package/dist/core/logger.mjs.map +1 -1
  31. package/dist/core/path.mjs +1 -1
  32. package/dist/core/path.mjs.map +1 -1
  33. package/dist/core/plugin.mjs +1 -1
  34. package/dist/core/reactivity.mjs +1 -1
  35. package/dist/{core-BK8Rpn_4.mjs → core-C_gfh7JQ.mjs} +3 -3
  36. package/dist/{core-BK8Rpn_4.mjs.map → core-C_gfh7JQ.mjs.map} +1 -1
  37. package/dist/{env-B5XGgcxZ.mjs → env-LIrKUSAJ.mjs} +3 -3
  38. package/dist/{env-B5XGgcxZ.mjs.map → env-LIrKUSAJ.mjs.map} +1 -1
  39. package/dist/http/application.d.mts +1 -1
  40. package/dist/http/application.mjs +2 -2
  41. package/dist/http/bootstrap.d.mts +1 -1
  42. package/dist/http/bootstrap.mjs +2 -2
  43. package/dist/http/context.d.mts +1 -1
  44. package/dist/http/context.mjs +2 -2
  45. package/dist/http/middleware/cors.mjs +1 -1
  46. package/dist/http/middleware/csrf.mjs +1 -1
  47. package/dist/http/middleware/csrf.mjs.map +1 -1
  48. package/dist/http/middleware/error-handler.mjs +2 -2
  49. package/dist/http/middleware/error-handler.mjs.map +1 -1
  50. package/dist/http/middleware/helmet.mjs +1 -1
  51. package/dist/http/middleware/helmet.mjs.map +1 -1
  52. package/dist/http/middleware/rate-limit.mjs +1 -1
  53. package/dist/http/middleware/rate-limit.mjs.map +1 -1
  54. package/dist/http/middleware/request-id.mjs +1 -1
  55. package/dist/http/middleware/request-logger.mjs +2 -2
  56. package/dist/http/middleware/request-logger.mjs.map +1 -1
  57. package/dist/http/middleware/session.mjs +1 -1
  58. package/dist/http/middleware/session.mjs.map +1 -1
  59. package/dist/http/middleware/spa.mjs +2 -2
  60. package/dist/http/middleware/upload.mjs +1 -1
  61. package/dist/http/middleware/upload.mjs.map +1 -1
  62. package/dist/http/middleware/validate.mjs +2 -2
  63. package/dist/http/middleware/validate.mjs.map +1 -1
  64. package/dist/http/middleware/views.d.mts +1 -1
  65. package/dist/http/middleware/views.mjs +2 -2
  66. package/dist/http/query/index.d.mts +2 -2
  67. package/dist/http/query/index.mjs +2 -2
  68. package/dist/http/router-builder.mjs +2 -2
  69. package/dist/http/router-builder.mjs.map +1 -1
  70. package/dist/{index-kEmG8nWU.d.mts → index-BtWJ9SLP.d.mts} +53 -7
  71. package/dist/{index-kEmG8nWU.d.mts.map → index-BtWJ9SLP.d.mts.map} +1 -1
  72. package/dist/index.d.mts +7 -7
  73. package/dist/index.mjs +2 -2
  74. package/dist/index.mjs.map +1 -1
  75. package/dist/{logger-BnBVjmDa.d.mts → logger-COlEkn_C.d.mts} +9 -1
  76. package/dist/logger-COlEkn_C.d.mts.map +1 -0
  77. package/dist/{metadata-DbrSf8E-.mjs → metadata-D8hSFaux.mjs} +2 -2
  78. package/dist/{metadata-DbrSf8E-.mjs.map → metadata-D8hSFaux.mjs.map} +1 -1
  79. package/dist/query-NhwucLHS.mjs +12 -0
  80. package/dist/query-NhwucLHS.mjs.map +1 -0
  81. package/dist/{views-BCl-mETX.d.mts → views-DkllbVB3.d.mts} +2 -2
  82. package/dist/{views-BCl-mETX.d.mts.map → views-DkllbVB3.d.mts.map} +1 -1
  83. package/package.json +4 -4
  84. package/dist/application-BiyBwafB.d.mts.map +0 -1
  85. package/dist/application-CBXFiVW8.mjs +0 -12
  86. package/dist/application-CBXFiVW8.mjs.map +0 -1
  87. package/dist/context-Dj12VEWB.mjs +0 -12
  88. package/dist/context-Dj12VEWB.mjs.map +0 -1
  89. package/dist/context-Dnt2Di7p.d.mts.map +0 -1
  90. package/dist/logger-BnBVjmDa.d.mts.map +0 -1
  91. package/dist/query-BkA-clOb.mjs +0 -12
  92. package/dist/query-BkA-clOb.mjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
 
2
2
  import { i as MetaValue, r as ExecutionContext } from "./execution-context-B4cfhivz.mjs";
3
3
  import { i as ProblemDetails } from "./errors-CRCTjEUK.mjs";
4
- import { g as QueryFieldConfig, y as TypedParsedQuery } from "./index-kEmG8nWU.mjs";
4
+ import { S as QueryFieldConfig, T as TypedParsedQuery, t as ParseQueryOptions } from "./index-BtWJ9SLP.mjs";
5
5
  import { NextFunction, Request, Response } from "express";
6
6
 
7
7
  //#region src/http/context.d.ts
@@ -105,6 +105,13 @@ declare class RequestContext<TBody = any, TParams = any, TQuery = any> implement
105
105
  readonly res: Response;
106
106
  readonly next: NextFunction;
107
107
  constructor(req: Request, res: Response, next: NextFunction);
108
+ /**
109
+ * Memo of the most recent {@link qs} call this request. The query
110
+ * object is immutable for a request's lifetime, so a repeat call with
111
+ * the same `(fieldConfig, options)` references returns the cached
112
+ * parse instead of re-walking the filter/sort strings.
113
+ */
114
+ private _qsMemo?;
108
115
  /**
109
116
  * Read-side accessor for the per-request metadata map.
110
117
  *
@@ -231,6 +238,10 @@ declare class RequestContext<TBody = any, TParams = any, TQuery = any> implement
231
238
  * config and you get the loose `string` fallback.
232
239
  *
233
240
  * @param fieldConfig - Optional whitelist for filterable, sortable, and searchable fields
241
+ * @param options - Limits (`maxLimit`, `defaultLimit`, `maxSearchLength`) and an
242
+ * `onReject` hook. By default a rejected/over-broad field is logged via
243
+ * `console.warn` with the request id; pass an explicit `onReject` to override
244
+ * (e.g. throw to return a 400), or `onReject: () => {}` to silence.
234
245
  *
235
246
  * @example
236
247
  * ```ts
@@ -245,7 +256,7 @@ declare class RequestContext<TBody = any, TParams = any, TQuery = any> implement
245
256
  * }
246
257
  * ```
247
258
  */
248
- qs<TConfig extends QueryFieldConfig | undefined = undefined>(fieldConfig?: TConfig): TypedParsedQuery<TConfig>;
259
+ qs<TConfig extends QueryFieldConfig | undefined = undefined>(fieldConfig?: TConfig, options?: ParseQueryOptions): TypedParsedQuery<TConfig>;
249
260
  /**
250
261
  * Single uploaded file (requires `@FileUpload({ mode: 'single' })`).
251
262
  * Wrapped in a dev-only Proxy that warns on mutation — see {@link body}.
@@ -431,4 +442,4 @@ declare global {
431
442
  } //# sourceMappingURL=context.d.ts.map
432
443
  //#endregion
433
444
  export { RouteShape as i, DeepReadonly as n, RequestContext as r, Ctx as t };
434
- //# sourceMappingURL=context-Dnt2Di7p.d.mts.map
445
+ //# sourceMappingURL=context-DV7RjM9F.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-DV7RjM9F.d.mts","names":[],"sources":["../src/http/context.ts"],"mappings":";;;;;;;;;AAWgB;;;KAOX,YAAA,GAAe,IAAI,CAAC,cAAA;AAAc;AAAA;;;;;;;;;;;;;;;;;;;;;;AAAA,UAyB7B,aAAA;EAAA,CACP,KAAA,EAAO,cAAA,GAAiB,QAAA;EAsBgC;EApBzD,UAAA,CAAW,KAAA,GAAQ,YAAA,GAAe,QAAA;EAFjC;EAID,YAAA,CAAa,KAAA,GAAQ,YAAA,GAAe,QAAA;EAFpC;EAIA,SAAA,CAAU,KAAA,GAAQ,YAAA,GAAe,QAAA;EAJtB;EAMX,QAAA,CAAS,KAAA,GAAQ,YAAA,GAAe,QAAA;EAJhC;EAMA,QAAA,CAAS,KAAA,GAAQ,YAAA,GAAe,QAAA;EANnB;EAQb,aAAA,CAAc,KAAA,GAAQ,YAAA,GAAe,QAAA;EANrC;EAQA,eAAA,CAAgB,KAAA,GAAQ,YAAA,GAAe,QAAA;EAR7B;EAUV,QAAA,CAAS,KAAA,GAAQ,YAAA,GAAe,QAAA;EARhC;;;;;EAcA,UAAA,CAAW,MAAA,SAAe,KAAA,GAAQ,YAAA,GAAe,QAAA;AAAA;;;;;;;;;;;;;;;;;;;;KAsBvC,YAAA,MAAkB,CAAA,cAAc,IAAA,yBACxC,CAAA,GACA,CAAA,SAAU,IAAA,GAAO,MAAA,GACf,CAAA,GACA,CAAA,SAAU,GAAA,qBACR,WAAA,CAAY,YAAA,CAAa,CAAA,GAAI,YAAA,CAAa,CAAA,KAC1C,CAAA,SAAU,GAAA,YACR,WAAA,CAAY,YAAA,CAAa,CAAA,KACzB,C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P,KAAA;EAAA;AAAA;;;;;;;;;;;;;;;;;;;;KA0BM,GAAA,gBAAmB,UAAA,GAAa,UAAA,IAAc,cAAA,CACxD,MAAA;EAAiB,IAAA;AAAA,IAAkB,CAAA,QACnC,MAAA;EAAiB,MAAA;AAAA,IAAoB,CAAA,QACrC,MAAA;EAAiB,KAAA;AAAA,IAAmB,CAAA;;;;;;;;;;;QAa9B,MAAA;EAAA,UAEI,UAAU;AAAA"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{n as tokenName,t as Container}from"../container-F-qfN8Bx.mjs";export{Container,tokenName};
11
+ import{n as tokenName,t as Container}from"../container-CPz0l8-b.mjs";export{Container,tokenName};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{c as pushClassMeta,t as getClassMeta}from"../metadata-DbrSf8E-.mjs";const CRON_META=`kick/cron`;function Cron(expression,options){return(target,propertyKey)=>{pushClassMeta(CRON_META,target.constructor,{expression,handlerName:propertyKey,description:options?.description,timezone:options?.timezone,runOnInit:options?.runOnInit})}}function getCronJobs(target){return getClassMeta(CRON_META,target,[])}export{CRON_META,Cron,getCronJobs};
11
+ import{c as pushClassMeta,t as getClassMeta}from"../metadata-D8hSFaux.mjs";const CRON_META=`kick/cron`;function Cron(expression,options){return(target,propertyKey)=>{pushClassMeta(CRON_META,target.constructor,{expression,handlerName:propertyKey,description:options?.description,timezone:options?.timezone,runOnInit:options?.runOnInit})}}function getCronJobs(target){return getClassMeta(CRON_META,target,[])}export{CRON_META,Cron,getCronJobs};
12
12
  //# sourceMappingURL=cron.mjs.map
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import{t as Container}from"../container-F-qfN8Bx.mjs";import{METADATA}from"./interfaces.mjs";import{c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,l as pushMethodMeta,p as setMethodMeta,u as setClassMeta}from"../metadata-DbrSf8E-.mjs";import"reflect-metadata";const pendingRegistrations=[],allRegistrations=new Map;let containerRef=null;function flushPending(container){containerRef=container;for(let{target,scope}of pendingRegistrations)container.has(target)||container.register(target,target,scope);pendingRegistrations.length=0}Container._onReady=flushPending,Container._onReset=container=>{containerRef=container;for(let[,{target,scope}]of allRegistrations)container.has(target)||container.register(target,target,scope)};function registerInContainer(target,scope){setClassMeta(METADATA.INJECTABLE,!0,target),setClassMeta(METADATA.SCOPE,scope,target);let name=target.name||String(target);allRegistrations.set(name,{target,scope}),containerRef?containerRef.has(target)||containerRef.register(target,target,scope):pendingRegistrations.push({target,scope})}function Injectable(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`injectable`,target),registerInContainer(target,options?.scope??`singleton`)}}function Service(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`service`,target),registerInContainer(target,options?.scope??`singleton`)}}function Component(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`component`,target),registerInContainer(target,options?.scope??`singleton`)}}function Repository(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`repository`,target),registerInContainer(target,options?.scope??`singleton`)}}function Controller(){return target=>{setClassMeta(METADATA.CLASS_KIND,`controller`,target),registerInContainer(target,`singleton`)}}function PostConstruct(){return(target,propertyKey)=>{setClassMeta(METADATA.POST_CONSTRUCT,propertyKey,target)}}function applyInjection(token,target,propertyKey,parameterIndex){if(typeof parameterIndex==`number`){setInMetaRecord(METADATA.INJECT,target,parameterIndex,token);return}propertyKey!=null&&setInMetaMap(METADATA.AUTOWIRED,target,propertyKey,token)}function Autowired(token){return((target,propertyKey,parameterIndex)=>{applyInjection(token,target,propertyKey,parameterIndex)})}function Inject(token){return((target,propertyKey,parameterIndex)=>{applyInjection(token,target,propertyKey,parameterIndex)})}function Value(envKey,defaultValue){return(target,propertyKey)=>{setInMetaMap(METADATA.VALUE,target,propertyKey,{envKey,defaultValue})}}function Asset(assetKey){return(target,propertyKey)=>{setInMetaMap(METADATA.ASSET,target,propertyKey,{assetKey})}}function createRouteDecorator(method){return(path,validation)=>(target,propertyKey)=>{pushClassMeta(METADATA.ROUTES,target.constructor,{method,path:path||`/`,handlerName:propertyKey,validation})}}const Get=createRouteDecorator(`GET`),Post=createRouteDecorator(`POST`),Put=createRouteDecorator(`PUT`),Delete=createRouteDecorator(`DELETE`),Patch=createRouteDecorator(`PATCH`);function normalizeApiQueryParamsConfig(config){return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:config.searchColumns?config.searchColumns.map(col=>col?.name??``).filter(Boolean):void 0}:config}function ApiQueryParams(config){return(target,propertyKey)=>{let normalized=normalizeApiQueryParamsConfig(config);setMethodMeta(METADATA.QUERY_PARAMS,normalized,target.constructor,propertyKey)}}function Middleware(...handlers){return(target,propertyKey)=>{propertyKey?pushMethodMeta(METADATA.METHOD_MIDDLEWARES,target.constructor,propertyKey,...handlers):pushClassMeta(METADATA.CLASS_MIDDLEWARES,target,...handlers)}}function FileUpload(config){return(target,propertyKey)=>{setMethodMeta(METADATA.FILE_UPLOAD,config,target.constructor,propertyKey)}}function attachBuilder(target){setClassMeta(METADATA.BUILDER,!0,target),target.builder=function(){let props={},proxy=new Proxy({},{get(_,key){return key===`build`?()=>Object.assign(new target,props):value=>(props[key]=value,proxy)}});return proxy}}function Builder(target){attachBuilder(target)}function withBuilder(ctor){return attachBuilder(ctor),ctor}export{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder};
11
+ import{t as Container}from"../container-CPz0l8-b.mjs";import{METADATA}from"./interfaces.mjs";import{c as pushClassMeta,d as setInMetaMap,f as setInMetaRecord,l as pushMethodMeta,p as setMethodMeta,u as setClassMeta}from"../metadata-D8hSFaux.mjs";import"reflect-metadata";const pendingRegistrations=[],allRegistrations=new Map;let containerRef=null;function flushPending(container){containerRef=container;for(let{target,scope}of pendingRegistrations)container.has(target)||container.register(target,target,scope);pendingRegistrations.length=0}Container._onReady=flushPending,Container._onReset=container=>{containerRef=container;for(let[,{target,scope}]of allRegistrations)container.has(target)||container.register(target,target,scope)};function registerInContainer(target,scope){setClassMeta(METADATA.INJECTABLE,!0,target),setClassMeta(METADATA.SCOPE,scope,target);let name=target.name||String(target);allRegistrations.set(name,{target,scope}),containerRef?containerRef.has(target)||containerRef.register(target,target,scope):pendingRegistrations.push({target,scope})}function Injectable(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`injectable`,target),registerInContainer(target,options?.scope??`singleton`)}}function Service(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`service`,target),registerInContainer(target,options?.scope??`singleton`)}}function Component(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`component`,target),registerInContainer(target,options?.scope??`singleton`)}}function Repository(options){return target=>{setClassMeta(METADATA.CLASS_KIND,`repository`,target),registerInContainer(target,options?.scope??`singleton`)}}function Controller(){return target=>{setClassMeta(METADATA.CLASS_KIND,`controller`,target),registerInContainer(target,`singleton`)}}function PostConstruct(){return(target,propertyKey)=>{setClassMeta(METADATA.POST_CONSTRUCT,propertyKey,target)}}function applyInjection(token,target,propertyKey,parameterIndex){if(typeof parameterIndex==`number`){setInMetaRecord(METADATA.INJECT,target,parameterIndex,token);return}propertyKey!=null&&setInMetaMap(METADATA.AUTOWIRED,target,propertyKey,token)}function Autowired(token){return((target,propertyKey,parameterIndex)=>{applyInjection(token,target,propertyKey,parameterIndex)})}function Inject(token){return((target,propertyKey,parameterIndex)=>{applyInjection(token,target,propertyKey,parameterIndex)})}function Value(envKey,defaultValue){return(target,propertyKey)=>{setInMetaMap(METADATA.VALUE,target,propertyKey,{envKey,defaultValue})}}function Asset(assetKey){return(target,propertyKey)=>{setInMetaMap(METADATA.ASSET,target,propertyKey,{assetKey})}}function createRouteDecorator(method){return(path,validation)=>(target,propertyKey)=>{pushClassMeta(METADATA.ROUTES,target.constructor,{method,path:path||`/`,handlerName:propertyKey,validation})}}const Get=createRouteDecorator(`GET`),Post=createRouteDecorator(`POST`),Put=createRouteDecorator(`PUT`),Delete=createRouteDecorator(`DELETE`),Patch=createRouteDecorator(`PATCH`);function normalizeApiQueryParamsConfig(config){return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:config.searchColumns?config.searchColumns.map(col=>col?.name??``).filter(Boolean):void 0}:config}function ApiQueryParams(config){return(target,propertyKey)=>{let normalized=normalizeApiQueryParamsConfig(config);setMethodMeta(METADATA.QUERY_PARAMS,normalized,target.constructor,propertyKey)}}function Middleware(...handlers){return(target,propertyKey)=>{propertyKey?pushMethodMeta(METADATA.METHOD_MIDDLEWARES,target.constructor,propertyKey,...handlers):pushClassMeta(METADATA.CLASS_MIDDLEWARES,target,...handlers)}}function FileUpload(config){return(target,propertyKey)=>{setMethodMeta(METADATA.FILE_UPLOAD,config,target.constructor,propertyKey)}}function attachBuilder(target){setClassMeta(METADATA.BUILDER,!0,target),target.builder=function(){let props={},proxy=new Proxy({},{get(_,key){return key===`build`?()=>Object.assign(new target,props):value=>(props[key]=value,proxy)}});return proxy}}function Builder(target){attachBuilder(target)}function withBuilder(ctor){return attachBuilder(ctor),ctor}export{ApiQueryParams,Asset,Autowired,Builder,Component,Controller,Delete,FileUpload,Get,Inject,Injectable,Middleware,Patch,Post,PostConstruct,Put,Repository,Service,Value,normalizeApiQueryParamsConfig,withBuilder};
12
12
  //# sourceMappingURL=decorators.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { METADATA, Scope, type BuilderOf, type ServiceOptions } from './interfaces'\nimport { Container, type KickJsRegistry } from './container'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n setInMetaRecord,\n} from './metadata'\n\n// ── Decorator Registration System ───────────────────────────────────────\n// Decorators execute at class-definition time (module load). The Container\n// may not exist yet when the first decorator fires. We queue registrations\n// and flush them on first Container.getInstance() call.\n//\n// `allRegistrations` is a persistent registry that survives Container.reset().\n// On reset (HMR), all previously decorated classes are re-registered on the\n// fresh container. This ensures @Service, @Controller, @Repository, etc.\n// all survive HMR without manual re-registration.\n\ntype PendingRegistration = { target: any; scope: Scope }\nconst pendingRegistrations: PendingRegistration[] = []\n// Keyed by class name to prevent memory leaks during HMR — new class with\n// the same name replaces the old entry instead of accumulating references.\nconst allRegistrations = new Map<string, { target: any; scope: Scope }>()\nlet containerRef: any = null\n\nfunction flushPending(container: any): void {\n containerRef = container\n for (const { target, scope } of pendingRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n pendingRegistrations.length = 0\n}\n\n// Wire up synchronously — Container._onReady is called on first getInstance()\nContainer._onReady = flushPending\n\n// On Container.reset(), update containerRef and replay ALL decorator\n// registrations on the fresh container. This handles HMR where the container\n// is wiped but not all decorated modules are re-evaluated.\nContainer._onReset = (container: any) => {\n containerRef = container\n for (const [, { target, scope }] of allRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n}\n\n// ── Class Decorators ────────────────────────────────────────────────────\n\nfunction registerInContainer(target: any, scope: Scope): void {\n setClassMeta(METADATA.INJECTABLE, true, target)\n setClassMeta(METADATA.SCOPE, scope, target)\n\n // Track in persistent registry — survives Container.reset() for HMR replay.\n // Keyed by name so HMR class re-creation replaces the old entry.\n const name = target.name || String(target)\n allRegistrations.set(name, { target, scope })\n\n if (containerRef) {\n // Container already initialized — register immediately\n if (!containerRef.has(target)) {\n containerRef.register(target, target, scope)\n }\n } else {\n // Container not ready yet — queue for later\n pendingRegistrations.push({ target, scope })\n }\n}\n\n/** Mark a class as injectable with lifecycle scope */\nexport function Injectable(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'injectable', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a service (semantic alias for Injectable) */\nexport function Service(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'service', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a generic managed component */\nexport function Component(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'component', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a repository */\nexport function Repository(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'repository', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInContainer(target, Scope.SINGLETON)\n }\n}\n\n// ── Method Decorators ───────────────────────────────────────────────────\n\n/** Mark a method as a lifecycle hook called after instantiation */\nexport function PostConstruct(): MethodDecorator {\n return (target, propertyKey) => {\n setClassMeta(METADATA.POST_CONSTRUCT, propertyKey, target)\n }\n}\n\n// ── Injection Decorators (property + constructor parameter) ─────────────\n\n/**\n * A decorator that's valid as either a property decorator OR a\n * constructor-parameter decorator. forinda/kick-js#235 §2 — `@Autowired`\n * and `@Inject` previously diverged at the type level (property-only\n * vs parameter-only) and adopters who picked the wrong name for the\n * position got a cryptic TS1240 error. Both names now accept either\n * position and route to the correct metadata bucket at runtime.\n */\nexport interface PropertyOrParameterDecorator {\n /** Property decorator form — `@Autowired(TOKEN) private foo!: Foo`. */\n (target: object, propertyKey: string | symbol): void\n /** Constructor-parameter form — `constructor(@Inject(TOKEN) foo: Foo) {}`. */\n (target: object, propertyKey: string | symbol | undefined, parameterIndex: number): void\n}\n\nfunction applyInjection(\n token: unknown,\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex: number | undefined,\n): void {\n // Legacy parameter decorators receive 3 args (target, propertyKey,\n // parameterIndex); property decorators receive 2 (target, propertyKey).\n // The 3rd-arg-number-vs-undefined check is the canonical position\n // detection in TypeScript's legacy decorator runtime.\n if (typeof parameterIndex === 'number') {\n setInMetaRecord(METADATA.INJECT, target, parameterIndex, token)\n return\n }\n if (propertyKey != null) {\n // `target` for a property decorator on a non-static field is the\n // class prototype; the AUTOWIRED bucket is keyed off the prototype\n // identity at resolution time, so pass it through unchanged.\n setInMetaMap(METADATA.AUTOWIRED, target, propertyKey as string, token)\n }\n}\n\n/**\n * Inject a dependency. Works in two positions:\n *\n * - **Property decorator** — `@Autowired(TOKEN) private repo!: UserRepo`.\n * Resolved lazily from the container the first time the property is\n * read.\n * - **Constructor parameter decorator** — `constructor(@Autowired(TOKEN) repo: UserRepo) {}`.\n * Resolved at instantiation; injected into the ctor call.\n *\n * `@Inject` is the same function under another name — they share\n * runtime + types so the two names are interchangeable. Pick whichever\n * reads better at the call site.\n *\n * Like `@Inject`, the typed string-literal overload narrows the token\n * to a key of the augmented `KickJsRegistry`. After `kick typegen`\n * populates the registry, `@Autowired('kick/prisma/Client')` auto-\n * completes the key and typo'd literals become TS2345 errors.\n */\nexport function Autowired<K extends keyof KickJsRegistry & string>(\n token: K,\n): PropertyOrParameterDecorator\nexport function Autowired(token?: unknown): PropertyOrParameterDecorator\nexport function Autowired(token?: unknown): PropertyOrParameterDecorator {\n return ((\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex?: number,\n ): void => {\n applyInjection(token, target, propertyKey, parameterIndex)\n }) as PropertyOrParameterDecorator\n}\n\n/**\n * Inject a dependency by token. Same shape as {@link Autowired} —\n * works as either a property decorator or a constructor-parameter\n * decorator. Pick whichever name reads better at the call site.\n *\n * ## Typed string-literal overload\n *\n * When called with a string literal that matches a key of the\n * augmented `KickJsRegistry`, TypeScript narrows the parameter type\n * to the registered type. Typo'd literals become compile errors\n * (the string isn't `keyof KickJsRegistry`). Class identities and\n * `InjectionToken<T>` keep working unchanged via the second overload.\n *\n * @example\n * ```ts\n * import { Service, Inject } from '@forinda/kickjs'\n * import type { PrismaClient } from '@prisma/client'\n *\n * `@Service()`\n * class UserRepo {\n * constructor(@Inject('kick/prisma/Client') private db: PrismaClient) {}\n * // OR property form, same decorator:\n * @Inject('kick/prisma/Client') private db2!: PrismaClient\n * }\n * ```\n *\n * After `kick typegen` runs, the literal autocompletes from the\n * registry and a typo (`@Inject('kick/prisma/Cleint')`) becomes a\n * TS2345 error.\n */\nexport function Inject<K extends keyof KickJsRegistry & string>(\n token: K,\n): PropertyOrParameterDecorator\nexport function Inject(token?: unknown): PropertyOrParameterDecorator\nexport function Inject(token?: unknown): PropertyOrParameterDecorator {\n return ((\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex?: number,\n ): void => {\n applyInjection(token, target, propertyKey, parameterIndex)\n }) as PropertyOrParameterDecorator\n}\n\n/**\n * Global ambient registry of typed environment variables, populated by\n * `kick typegen` from the project's env schema (typically\n * `src/env.ts`'s `export default defineEnv(...)`).\n *\n * Empty by default — declarations come from `.kickjs/types/env.ts`\n * generated alongside the rest of the typegen output. Once populated,\n * `@Value('PORT')` autocompletes the key, type-checks the default\n * value, and `process.env.PORT` is also typed via the parallel\n * `NodeJS.ProcessEnv` augmentation in the same generated file.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface KickEnv {}\n}\n\n/** A string key known to the typed env registry (`never` until typegen runs) */\nexport type EnvKey = keyof KickEnv & string\n\n/**\n * Look up the type of a typed env entry.\n *\n * Decorators can't propagate the property type from the key, so users\n * still need to write the property's type — but `Env<K>` lets them\n * derive it from `KickEnv` instead of duplicating the schema:\n *\n * ```ts\n * @Service()\n * class MyService {\n * @Value('PORT')\n * private port!: Env<'PORT'> // → number, narrowed from KickEnv['PORT']\n * }\n * ```\n */\nexport type Env<K extends EnvKey = EnvKey> = KickEnv[K]\n\n/**\n * Constraint that allows any string when the typed env registry is\n * empty (no `kick typegen` has run yet, so existing code with raw\n * string keys keeps working) but locks the argument down to known\n * `EnvKey` literals once the registry is populated.\n *\n * Implementation: when `EnvKey` is `never`, the conditional resolves\n * to the user's `K`, accepting anything. Once typegen has populated\n * `KickEnv`, `EnvKey` becomes a real union and the conditional forces\n * `K` to be assignable to it.\n */\ntype ValueKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Inject an environment variable value. Evaluated lazily so the env\n * is available at access time, not at decoration time.\n *\n * If no default is provided and the env var is missing, throws at access time\n * to catch misconfiguration early instead of returning undefined.\n *\n * Uses metadata + instance getter to work correctly with `useDefineForClassFields`.\n *\n * Type-safety:\n * - Without `kick typegen` run, any string key is accepted (back-compat).\n * - After typegen, `KickEnv` is populated and unknown keys become a tsc\n * error. The optional `defaultValue` is type-checked against the\n * schema's inferred type for that key.\n */\nexport function Value<K extends string>(\n envKey: ValueKey<K>,\n defaultValue?: K extends EnvKey ? KickEnv[K] : unknown,\n): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.VALUE, target, propertyKey as string, { envKey, defaultValue })\n }\n}\n\n// ── @Asset — typed asset path injection (assets-plan.md PR 3+) ─────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** JSON Schema object for validating the request body */\n body?: any\n /** JSON Schema object for validating query parameters */\n query?: any\n /** JSON Schema object for validating URL params */\n params?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => void | Promise<void>\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n\n// ── Builder Decorator ───────────────────────────────────────────────────\n\nfunction attachBuilder(target: any): void {\n setClassMeta(METADATA.BUILDER, true, target)\n target.builder = function () {\n const props: Record<string, any> = {}\n const proxy: any = new Proxy(\n {},\n {\n get(_, key) {\n if (key === 'build') {\n return () => Object.assign(new target(), props)\n }\n return (value: any) => {\n props[key as string] = value\n return proxy\n }\n },\n },\n )\n return proxy\n }\n}\n\n/**\n * Add a static `builder()` method for fluent construction.\n *\n * Legacy decorators cannot widen the class type, so by default the\n * caller sees the unmodified shape. Opt into typing by adding a single\n * `declare static` line:\n *\n * ```ts\n * @Builder\n * class UserDto {\n * name!: string\n * email!: string\n * declare static readonly builder: () => BuilderOf<UserDto>\n * }\n * ```\n *\n * `readonly` keeps SonarQube's `typescript:S1444` quiet — the runtime\n * assigns `target.builder` once at decoration time and never again.\n *\n * If you'd rather not write the `declare`, use `withBuilder()` instead —\n * same runtime, types inferred automatically.\n */\nexport function Builder(target: any): void {\n attachBuilder(target)\n}\n\n/**\n * Factory variant of `@Builder`. Wraps the class with the same runtime\n * and returns it intersected with `{ builder(): BuilderOf<T> }` so the\n * static is fully typed without any `declare` boilerplate.\n *\n * ```ts\n * class UserDtoBase {\n * name!: string\n * email!: string\n * }\n * export const UserDto = withBuilder(UserDtoBase)\n * export type UserDto = InstanceType<typeof UserDto>\n *\n * UserDto.builder().name('Alice').email('a@b.com').build() // fully typed\n * ```\n */\nexport function withBuilder<C extends new (...args: any[]) => any>(\n ctor: C,\n): C & { builder(): BuilderOf<InstanceType<C>> } {\n attachBuilder(ctor)\n return ctor as C & { builder(): BuilderOf<InstanceType<C>> }\n}\n"],"mappings":";;;;;;;;;;+QAuBA,MAAM,qBAA8C,CAAC,EAG/C,iBAAmB,IAAI,IAC7B,IAAI,aAAoB,KAExB,SAAS,aAAa,UAAsB,CAC1C,aAAe,UACf,IAAK,GAAM,CAAE,OAAQ,SAAW,qBACzB,UAAU,IAAI,MAAM,GACvB,UAAU,SAAS,OAAQ,OAAQ,KAAK,EAG5C,qBAAqB,OAAS,CAChC,CAGA,UAAU,SAAW,aAKrB,UAAU,SAAY,WAAmB,CACvC,aAAe,UACf,IAAK,GAAM,EAAG,CAAE,OAAQ,UAAY,iBAC7B,UAAU,I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AgB,CAC9B,IAAM,WAAa,8BAA8B,MAAM,EACvD,cAAc,SAAS,aAAc,WAAY,OAAO,YAAa,WAAqB,CAC5F,CACF,CAsBA,SAAgB,WAAW,GAAG,SAAiE,CAC7F,OAAQ,OAAa,cAAkC,CACjD,YACF,eACE,SAAS,mBACT,OAAO,YACP,YACA,GAAG,QACL,EAEA,cAAc,SAAS,kBAAmB,OAAQ,GAAG,QAAQ,CAEjE,CACF,CAoCA,SAAgB,WAAW,OAA2C,CACpE,OAAQ,OAAQ,cAAgB,CAC9B,cAAc,SAAS,YAAa,OAAQ,OAAO,YAAa,WAAqB,CACvF,CACF,CAIA,SAAS,cAAc,OAAmB,CACxC,aAAa,SAAS,QAAS,GAAM,MAAM,EAC3C,OAAO,QAAU,UAAY,CAC3B,IAAM,MAA6B,CAAC,EAC9B,MAAa,IAAI,MACrB,CAAC,EACD,CACE,IAAI,EAAG,IAAK,CAIV,OAHI,MAAQ,YACG,OAAO,OAAO,IAAI,OAAU,KAAK,EAExC,QACN,MAAM,KAAiB,MAChB,MAEX,CACF,CACF,EACA,OAAO,KACT,CACF,CAwBA,SAAgB,QAAQ,OAAmB,CACzC,cAAc,MAAM,CACtB,CAkBA,SAAgB,YACd,KAC+C,CAE/C,OADA,cAAc,IAAI,EACX,IACT"}
1
+ {"version":3,"file":"decorators.mjs","names":[],"sources":["../../src/core/decorators.ts"],"sourcesContent":["import 'reflect-metadata'\nimport { METADATA, Scope, type BuilderOf, type ServiceOptions } from './interfaces'\nimport { Container, type KickJsRegistry } from './container'\nimport {\n setClassMeta,\n setMethodMeta,\n pushClassMeta,\n pushMethodMeta,\n setInMetaMap,\n setInMetaRecord,\n} from './metadata'\n\n// ── Decorator Registration System ───────────────────────────────────────\n// Decorators execute at class-definition time (module load). The Container\n// may not exist yet when the first decorator fires. We queue registrations\n// and flush them on first Container.getInstance() call.\n//\n// `allRegistrations` is a persistent registry that survives Container.reset().\n// On reset (HMR), all previously decorated classes are re-registered on the\n// fresh container. This ensures @Service, @Controller, @Repository, etc.\n// all survive HMR without manual re-registration.\n\ntype PendingRegistration = { target: any; scope: Scope }\nconst pendingRegistrations: PendingRegistration[] = []\n// Keyed by class name to prevent memory leaks during HMR — new class with\n// the same name replaces the old entry instead of accumulating references.\nconst allRegistrations = new Map<string, { target: any; scope: Scope }>()\nlet containerRef: any = null\n\nfunction flushPending(container: any): void {\n containerRef = container\n for (const { target, scope } of pendingRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n pendingRegistrations.length = 0\n}\n\n// Wire up synchronously — Container._onReady is called on first getInstance()\nContainer._onReady = flushPending\n\n// On Container.reset(), update containerRef and replay ALL decorator\n// registrations on the fresh container. This handles HMR where the container\n// is wiped but not all decorated modules are re-evaluated.\nContainer._onReset = (container: any) => {\n containerRef = container\n for (const [, { target, scope }] of allRegistrations) {\n if (!container.has(target)) {\n container.register(target, target, scope)\n }\n }\n}\n\n// ── Class Decorators ────────────────────────────────────────────────────\n\nfunction registerInContainer(target: any, scope: Scope): void {\n setClassMeta(METADATA.INJECTABLE, true, target)\n setClassMeta(METADATA.SCOPE, scope, target)\n\n // Track in persistent registry — survives Container.reset() for HMR replay.\n // Keyed by name so HMR class re-creation replaces the old entry.\n const name = target.name || String(target)\n allRegistrations.set(name, { target, scope })\n\n if (containerRef) {\n // Container already initialized — register immediately\n if (!containerRef.has(target)) {\n containerRef.register(target, target, scope)\n }\n } else {\n // Container not ready yet — queue for later\n pendingRegistrations.push({ target, scope })\n }\n}\n\n/** Mark a class as injectable with lifecycle scope */\nexport function Injectable(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'injectable', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a service (semantic alias for Injectable) */\nexport function Service(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'service', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a generic managed component */\nexport function Component(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'component', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/** Mark a class as a repository */\nexport function Repository(options?: ServiceOptions): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'repository', target)\n registerInContainer(target, options?.scope ?? Scope.SINGLETON)\n }\n}\n\n/**\n * Mark a class as an HTTP controller and register it in the DI container.\n *\n * Route prefixes are defined by the module's `routes().path` — the single\n * source of truth for where routes mount. The legacy\n * `@Controller('/path')` parameter was removed in v4; if your code\n * still passes a string, see `docs/guide/migration-v3-to-v4.md` for\n * the rename map.\n */\nexport function Controller(): ClassDecorator {\n return (target: any) => {\n setClassMeta(METADATA.CLASS_KIND, 'controller', target)\n registerInContainer(target, Scope.SINGLETON)\n }\n}\n\n// ── Method Decorators ───────────────────────────────────────────────────\n\n/** Mark a method as a lifecycle hook called after instantiation */\nexport function PostConstruct(): MethodDecorator {\n return (target, propertyKey) => {\n setClassMeta(METADATA.POST_CONSTRUCT, propertyKey, target)\n }\n}\n\n// ── Injection Decorators (property + constructor parameter) ─────────────\n\n/**\n * A decorator that's valid as either a property decorator OR a\n * constructor-parameter decorator. forinda/kick-js#235 §2 — `@Autowired`\n * and `@Inject` previously diverged at the type level (property-only\n * vs parameter-only) and adopters who picked the wrong name for the\n * position got a cryptic TS1240 error. Both names now accept either\n * position and route to the correct metadata bucket at runtime.\n */\nexport interface PropertyOrParameterDecorator {\n /** Property decorator form — `@Autowired(TOKEN) private foo!: Foo`. */\n (target: object, propertyKey: string | symbol): void\n /** Constructor-parameter form — `constructor(@Inject(TOKEN) foo: Foo) {}`. */\n (target: object, propertyKey: string | symbol | undefined, parameterIndex: number): void\n}\n\nfunction applyInjection(\n token: unknown,\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex: number | undefined,\n): void {\n // Legacy parameter decorators receive 3 args (target, propertyKey,\n // parameterIndex); property decorators receive 2 (target, propertyKey).\n // The 3rd-arg-number-vs-undefined check is the canonical position\n // detection in TypeScript's legacy decorator runtime.\n if (typeof parameterIndex === 'number') {\n setInMetaRecord(METADATA.INJECT, target, parameterIndex, token)\n return\n }\n if (propertyKey != null) {\n // `target` for a property decorator on a non-static field is the\n // class prototype; the AUTOWIRED bucket is keyed off the prototype\n // identity at resolution time, so pass it through unchanged.\n setInMetaMap(METADATA.AUTOWIRED, target, propertyKey as string, token)\n }\n}\n\n/**\n * Inject a dependency. Works in two positions:\n *\n * - **Property decorator** — `@Autowired(TOKEN) private repo!: UserRepo`.\n * Resolved lazily from the container the first time the property is\n * read.\n * - **Constructor parameter decorator** — `constructor(@Autowired(TOKEN) repo: UserRepo) {}`.\n * Resolved at instantiation; injected into the ctor call.\n *\n * `@Inject` is the same function under another name — they share\n * runtime + types so the two names are interchangeable. Pick whichever\n * reads better at the call site.\n *\n * Like `@Inject`, the typed string-literal overload narrows the token\n * to a key of the augmented `KickJsRegistry`. After `kick typegen`\n * populates the registry, `@Autowired('kick/prisma/Client')` auto-\n * completes the key and typo'd literals become TS2345 errors.\n */\nexport function Autowired<K extends keyof KickJsRegistry & string>(\n token: K,\n): PropertyOrParameterDecorator\nexport function Autowired(token?: unknown): PropertyOrParameterDecorator\nexport function Autowired(token?: unknown): PropertyOrParameterDecorator {\n return ((\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex?: number,\n ): void => {\n applyInjection(token, target, propertyKey, parameterIndex)\n }) as PropertyOrParameterDecorator\n}\n\n/**\n * Inject a dependency by token. Same shape as {@link Autowired} —\n * works as either a property decorator or a constructor-parameter\n * decorator. Pick whichever name reads better at the call site.\n *\n * ## Typed string-literal overload\n *\n * When called with a string literal that matches a key of the\n * augmented `KickJsRegistry`, TypeScript narrows the parameter type\n * to the registered type. Typo'd literals become compile errors\n * (the string isn't `keyof KickJsRegistry`). Class identities and\n * `InjectionToken<T>` keep working unchanged via the second overload.\n *\n * @example\n * ```ts\n * import { Service, Inject } from '@forinda/kickjs'\n * import type { PrismaClient } from '@prisma/client'\n *\n * `@Service()`\n * class UserRepo {\n * constructor(@Inject('kick/prisma/Client') private db: PrismaClient) {}\n * // OR property form, same decorator:\n * @Inject('kick/prisma/Client') private db2!: PrismaClient\n * }\n * ```\n *\n * After `kick typegen` runs, the literal autocompletes from the\n * registry and a typo (`@Inject('kick/prisma/Cleint')`) becomes a\n * TS2345 error.\n */\nexport function Inject<K extends keyof KickJsRegistry & string>(\n token: K,\n): PropertyOrParameterDecorator\nexport function Inject(token?: unknown): PropertyOrParameterDecorator\nexport function Inject(token?: unknown): PropertyOrParameterDecorator {\n return ((\n target: object,\n propertyKey: string | symbol | undefined,\n parameterIndex?: number,\n ): void => {\n applyInjection(token, target, propertyKey, parameterIndex)\n }) as PropertyOrParameterDecorator\n}\n\n/**\n * Global ambient registry of typed environment variables, populated by\n * `kick typegen` from the project's env schema (typically\n * `src/env.ts`'s `export default defineEnv(...)`).\n *\n * Empty by default — declarations come from `.kickjs/types/env.ts`\n * generated alongside the rest of the typegen output. Once populated,\n * `@Value('PORT')` autocompletes the key, type-checks the default\n * value, and `process.env.PORT` is also typed via the parallel\n * `NodeJS.ProcessEnv` augmentation in the same generated file.\n */\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n interface KickEnv {}\n}\n\n/** A string key known to the typed env registry (`never` until typegen runs) */\nexport type EnvKey = keyof KickEnv & string\n\n/**\n * Look up the type of a typed env entry.\n *\n * Decorators can't propagate the property type from the key, so users\n * still need to write the property's type — but `Env<K>` lets them\n * derive it from `KickEnv` instead of duplicating the schema:\n *\n * ```ts\n * @Service()\n * class MyService {\n * @Value('PORT')\n * private port!: Env<'PORT'> // → number, narrowed from KickEnv['PORT']\n * }\n * ```\n */\nexport type Env<K extends EnvKey = EnvKey> = KickEnv[K]\n\n/**\n * Constraint that allows any string when the typed env registry is\n * empty (no `kick typegen` has run yet, so existing code with raw\n * string keys keeps working) but locks the argument down to known\n * `EnvKey` literals once the registry is populated.\n *\n * Implementation: when `EnvKey` is `never`, the conditional resolves\n * to the user's `K`, accepting anything. Once typegen has populated\n * `KickEnv`, `EnvKey` becomes a real union and the conditional forces\n * `K` to be assignable to it.\n */\ntype ValueKey<K extends string> = [EnvKey] extends [never] ? K : K & EnvKey\n\n/**\n * Inject an environment variable value. Evaluated lazily so the env\n * is available at access time, not at decoration time.\n *\n * If no default is provided and the env var is missing, throws at access time\n * to catch misconfiguration early instead of returning undefined.\n *\n * Uses metadata + instance getter to work correctly with `useDefineForClassFields`.\n *\n * Type-safety:\n * - Without `kick typegen` run, any string key is accepted (back-compat).\n * - After typegen, `KickEnv` is populated and unknown keys become a tsc\n * error. The optional `defaultValue` is type-checked against the\n * schema's inferred type for that key.\n */\nexport function Value<K extends string>(\n envKey: ValueKey<K>,\n defaultValue?: K extends EnvKey ? KickEnv[K] : unknown,\n): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.VALUE, target, propertyKey as string, { envKey, defaultValue })\n }\n}\n\n// ── @Asset — typed asset path injection (assets-plan.md PR 3+) ─────────\n\nimport type { KickAssets } from './assets'\n\n/**\n * Flatten the nested `KickAssets` augmentation (typegen-emitted in\n * PR 4) into a string-literal union of dot/slash-joined paths.\n *\n * `interface KickAssets { mails: { welcome: () => string; orders: {\n * confirmation: () => string } } }` becomes\n * `'mails/welcome' | 'mails/orders/confirmation'`.\n *\n * Returns `never` when `KickAssets` is empty (no typegen has run yet)\n * so `AssetKeyArg` falls through to accept any string.\n */\ntype FlattenAssets<T, Prefix extends string = ''> = {\n [K in keyof T & string]: T[K] extends () => string\n ? `${Prefix}${K}`\n : T[K] extends Record<string, unknown>\n ? FlattenAssets<T[K], `${Prefix}${K}/`>\n : never\n}[keyof T & string]\n\n/** Flat union of every known `<namespace>/<key>` path. */\nexport type AssetKey = FlattenAssets<KickAssets>\n\n/**\n * Constraint mirroring `ValueKey<K>` — accepts any string when\n * `AssetKey` is `never` (back-compat for adopters who haven't run\n * `kick typegen` yet) but locks the argument to known literals once\n * the typegen-augmented `KickAssets` interface is populated.\n */\ntype AssetKeyArg<K extends string> = [AssetKey] extends [never] ? K : K & AssetKey\n\n/**\n * Inject the resolved file-system path for a typed asset. Mirrors\n * `@Value`'s lazy-getter pattern — the asset is resolved on every\n * property access, NOT at class instantiation, so:\n *\n * - Tests can swap fixtures + clear the cache without re-instantiating\n * the consuming class.\n * - The first access cost is paid once per process (the manifest cache\n * in `core/assets.ts` makes subsequent calls cheap).\n *\n * Type-safety:\n *\n * - Without typegen, any string key is accepted (back-compat — same\n * trick as `@Value`).\n * - After typegen, `KickAssets` is populated and `AssetKey` is a\n * union of every flattened `<namespace>/<key>` path. Unknown keys\n * become a TS error.\n *\n * @example\n * ```ts\n * import { Service, Asset } from '@forinda/kickjs'\n *\n * `@Service()`\n * class MailService {\n * `@Asset('mails/welcome')`\n * private welcomeTemplate!: string\n *\n * send(user: User) {\n * return ejs.renderFile(this.welcomeTemplate, { user })\n * }\n * }\n * ```\n */\nexport function Asset<K extends string>(assetKey: AssetKeyArg<K>): PropertyDecorator {\n return (target, propertyKey) => {\n setInMetaMap(METADATA.ASSET, target, propertyKey as string, { assetKey })\n }\n}\n\n// ── HTTP Route Decorators ───────────────────────────────────────────────\n\nexport interface RouteDefinition {\n method: string\n path: string\n handlerName: string\n validation?: {\n /** JSON Schema object for validating the request body */\n body?: any\n /** JSON Schema object for validating query parameters */\n query?: any\n /** JSON Schema object for validating URL params */\n params?: any\n /** Schema name in OpenAPI components/schemas for the request body. Auto-generated from handler name if omitted. */\n name?: string\n }\n}\n\nfunction createRouteDecorator(method: string) {\n return (path?: string, validation?: RouteDefinition['validation']): MethodDecorator => {\n return (target, propertyKey) => {\n pushClassMeta<RouteDefinition>(METADATA.ROUTES, target.constructor, {\n method,\n path: path || '/',\n handlerName: propertyKey as string,\n validation,\n })\n }\n }\n}\n\nexport const Get = createRouteDecorator('GET')\nexport const Post = createRouteDecorator('POST')\nexport const Put = createRouteDecorator('PUT')\nexport const Delete = createRouteDecorator('DELETE')\nexport const Patch = createRouteDecorator('PATCH')\n\n// ── Query Params Decorator ─────────────────────────────────────────────\n\nexport interface ApiQueryParamsConfig {\n /** Fields that can be used in filter queries (e.g., `?filter=status:eq:active`) */\n filterable?: string[]\n /** Fields that can be used in sort queries (e.g., `?sort=createdAt:desc`) */\n sortable?: string[]\n /** Fields that are searched with the `?q=` parameter */\n searchable?: string[]\n}\n\n/**\n * Column-object-based query params config (e.g., from DrizzleQueryParamsConfig).\n * `Object.keys()` is used to derive field names for OpenAPI docs.\n */\nexport interface ColumnApiQueryParamsConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/**\n * Normalize a query params config to the string-based ApiQueryParamsConfig.\n * Handles both string-based and column-object-based configs.\n */\nexport function normalizeApiQueryParamsConfig(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): ApiQueryParamsConfig {\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: config.searchColumns\n ? config.searchColumns.map((col: any) => col?.name ?? '').filter(Boolean)\n : undefined,\n }\n }\n return config as ApiQueryParamsConfig\n}\n\n/**\n * Document the query parameters accepted by a GET endpoint.\n * Used by SwaggerAdapter to generate `filter`, `sort`, `page`, `limit`, and `q` params\n * in the OpenAPI spec, with descriptions listing the allowed fields.\n *\n * Accepts both string-based configs and column-object configs (e.g., DrizzleQueryParamsConfig).\n *\n * @example\n * ```ts\n * // String-based\n * @ApiQueryParams({\n * filterable: ['status', 'category', 'price'],\n * sortable: ['name', 'createdAt', 'price'],\n * searchable: ['name', 'description'],\n * })\n *\n * // Column-object-based (Drizzle)\n * @ApiQueryParams(TASK_QUERY_CONFIG)\n * ```\n */\nexport function ApiQueryParams(\n config: ApiQueryParamsConfig | ColumnApiQueryParamsConfig,\n): MethodDecorator {\n return (target, propertyKey) => {\n const normalized = normalizeApiQueryParamsConfig(config)\n setMethodMeta(METADATA.QUERY_PARAMS, normalized, target.constructor, propertyKey as string)\n }\n}\n\n// ── Middleware Decorators ───────────────────────────────────────────────\n\n/**\n * Middleware handler function.\n * Generic `TCtx` defaults to `any` — import `RequestContext` from\n * `@forinda/kickjs` for full type safety:\n *\n * ```ts\n * import type { MiddlewareHandler } from '@forinda/kickjs'\n * import type { RequestContext } from '@forinda/kickjs'\n *\n * const auth: MiddlewareHandler<RequestContext> = (ctx, next) => {\n * ctx.body // fully typed\n * next()\n * }\n * ```\n */\nexport type MiddlewareHandler<TCtx = any> = (ctx: TCtx, next: () => void) => void | Promise<void>\n\n/** Attach middleware handlers to a class or method */\nexport function Middleware(...handlers: MiddlewareHandler[]): ClassDecorator & MethodDecorator {\n return (target: any, propertyKey?: string | symbol) => {\n if (propertyKey) {\n pushMethodMeta(\n METADATA.METHOD_MIDDLEWARES,\n target.constructor,\n propertyKey as string,\n ...handlers,\n )\n } else {\n pushClassMeta(METADATA.CLASS_MIDDLEWARES, target, ...handlers)\n }\n }\n}\n\n// ── File Upload Decorator ───────────────────────────────────────────────\n\n/**\n * File filter — accepts short extensions ('jpg'), full MIME types ('image/jpeg'),\n * wildcards ('image/*'), or a function `(mimetype, filename) => boolean` for full control.\n */\nexport type FileTypeFilter = string[] | ((mimetype: string, filename: string) => boolean)\n\n/**\n * Shared upload options used by both the `@FileUpload` decorator and the\n * `upload.single()` / `upload.array()` / `upload.none()` middleware.\n */\nexport interface BaseUploadOptions {\n /** Max file size in bytes (default: 5MB) */\n maxSize?: number\n /**\n * Allowed file types:\n * - **string[]** — short extensions ('jpg'), full MIME types ('image/jpeg'), or wildcards ('image/*')\n * - **function** — `(mimetype, filename) => boolean` for full control\n */\n allowedTypes?: FileTypeFilter\n /** Extend the built-in extension-to-MIME map */\n customMimeMap?: Record<string, string>\n}\n\nexport interface FileUploadConfig extends BaseUploadOptions {\n mode: 'single' | 'array' | 'none'\n /** Form field name (default: 'file') */\n fieldName?: string\n /** Max files for array mode (default: 10) */\n maxCount?: number\n}\n\n/** Configure file upload handling for a controller method */\nexport function FileUpload(config: FileUploadConfig): MethodDecorator {\n return (target, propertyKey) => {\n setMethodMeta(METADATA.FILE_UPLOAD, config, target.constructor, propertyKey as string)\n }\n}\n\n// ── Builder Decorator ───────────────────────────────────────────────────\n\nfunction attachBuilder(target: any): void {\n setClassMeta(METADATA.BUILDER, true, target)\n target.builder = function () {\n const props: Record<string, any> = {}\n const proxy: any = new Proxy(\n {},\n {\n get(_, key) {\n if (key === 'build') {\n return () => Object.assign(new target(), props)\n }\n return (value: any) => {\n props[key as string] = value\n return proxy\n }\n },\n },\n )\n return proxy\n }\n}\n\n/**\n * Add a static `builder()` method for fluent construction.\n *\n * Legacy decorators cannot widen the class type, so by default the\n * caller sees the unmodified shape. Opt into typing by adding a single\n * `declare static` line:\n *\n * ```ts\n * @Builder\n * class UserDto {\n * name!: string\n * email!: string\n * declare static readonly builder: () => BuilderOf<UserDto>\n * }\n * ```\n *\n * `readonly` keeps SonarQube's `typescript:S1444` quiet — the runtime\n * assigns `target.builder` once at decoration time and never again.\n *\n * If you'd rather not write the `declare`, use `withBuilder()` instead —\n * same runtime, types inferred automatically.\n */\nexport function Builder(target: any): void {\n attachBuilder(target)\n}\n\n/**\n * Factory variant of `@Builder`. Wraps the class with the same runtime\n * and returns it intersected with `{ builder(): BuilderOf<T> }` so the\n * static is fully typed without any `declare` boilerplate.\n *\n * ```ts\n * class UserDtoBase {\n * name!: string\n * email!: string\n * }\n * export const UserDto = withBuilder(UserDtoBase)\n * export type UserDto = InstanceType<typeof UserDto>\n *\n * UserDto.builder().name('Alice').email('a@b.com').build() // fully typed\n * ```\n */\nexport function withBuilder<C extends new (...args: any[]) => any>(\n ctor: C,\n): C & { builder(): BuilderOf<InstanceType<C>> } {\n attachBuilder(ctor)\n return ctor as C & { builder(): BuilderOf<InstanceType<C>> }\n}\n"],"mappings":";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/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/**\n * IANA HTTP status reason phrases for the codes the framework's typed\n * helpers cover. Used as the default `title` when a {@link ProblemException}\n * is constructed without one. Keep in sync with {@link HttpStatus}.\n */\nconst STATUS_REASONS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * RFC 9457 — Problem Details for HTTP APIs.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * Canonical error shape for HTTP responses. Only `status` is required;\n * everything else has a sensible default. Extension members (any other\n * JSON-compatible field) are allowed per §3.2 — pass them on the same\n * object and the framework forwards them through.\n *\n * @example\n * ```ts\n * const problem: ProblemDetails = {\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * // extension members per §3.2\n * balance: 30,\n * }\n * ```\n */\nexport interface ProblemDetails {\n /**\n * URI reference identifying the problem type. Per §4.2.1, when\n * dereferenced it SHOULD return human-readable documentation. Defaults\n * to `about:blank` when omitted (RFC 9457 §3.1.1).\n */\n type?: string\n /**\n * Short human-readable summary, advisable to be the same regardless of\n * the occurrence (§3.1.4). Defaults to the IANA reason phrase for\n * `status` when omitted.\n */\n title?: string\n /** HTTP status code generated by the origin server. Required. */\n status: number\n /**\n * Human-readable explanation specific to this occurrence (§3.1.5).\n * Per the RFC's safety guidance, do not include sensitive information\n * (tokens, full SQL, stack traces) — those belong in logs.\n */\n detail?: string\n /**\n * URI reference identifying the specific occurrence (§3.1.6).\n * Typically the request path. Adopters set this explicitly — the\n * framework does not auto-populate it to avoid leaking unexpected\n * structure.\n */\n instance?: string\n /**\n * Extension members per §3.2 — any other JSON-compatible field.\n * Common examples: `balance`, `errors`, `traceId`, `accounts`.\n */\n [key: string]: unknown\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n *\n * For RFC 9457 — Problem Details responses, throw {@link ProblemException}\n * instead — the global error handler emits `application/problem+json` for\n * those automatically.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n\n/**\n * Default `title` for an RFC 9457 problem with the given status — the IANA\n * reason phrase, or `'Error'` for codes outside the framework's table.\n * Exposed so {@link ProblemException} construction and {@link RequestContext}'s\n * `problem` helpers share a single source of truth.\n */\nexport function defaultProblemTitle(status: number): string {\n return STATUS_REASONS[status] ?? 'Error'\n}\n\n/**\n * Exception that carries an RFC 9457 — Problem Details payload. When\n * thrown, the framework error handler emits `application/problem+json`\n * with the canonical shape; `type` defaults to `about:blank`, `title`\n * to the IANA reason phrase for `status`.\n *\n * Extends {@link HttpException} so existing `instanceof HttpException`\n * catches still see it. Use `new ProblemException(...)` directly for\n * full control, or {@link Problems} for the pre-filled-status\n * convenience factories.\n *\n * Static factories deliberately live on {@link Problems} rather than\n * this class — putting them here would shadow `HttpException`'s\n * same-named statics with incompatible (object vs string) signatures,\n * which TypeScript correctly rejects.\n *\n * @example\n * ```ts\n * throw new ProblemException({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * balance: 30, // extension\n * })\n *\n * // Or via the Problems convenience factory:\n * throw Problems.forbidden({\n * type: 'https://api.example.com/problems/out-of-credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30,\n * })\n * ```\n */\nexport class ProblemException extends HttpException {\n public readonly problem: ProblemDetails\n\n constructor(problem: ProblemDetails, headers?: Record<string, string>) {\n const title = problem.title ?? defaultProblemTitle(problem.status)\n const detail = problem.detail ?? title\n super(problem.status, detail, undefined, headers)\n this.name = 'ProblemException'\n this.problem = { ...problem, title }\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): ProblemException {\n return new ProblemException(this.problem, { ...this.headers, ...headers })\n }\n}\n\n/**\n * Convenience factories for {@link ProblemException}. Pre-fill `status`\n * (and `title` via {@link defaultProblemTitle}) for the common HTTP\n * codes — same shortcut set the `ctx.problem.*` response helpers cover.\n *\n * Lives in a separate namespace rather than as statics on\n * {@link ProblemException} to avoid shadowing {@link HttpException}'s\n * same-named statics, which would create a TypeScript variance\n * conflict (parent's `notFound(message?: string)` vs the child's\n * desired `notFound(input?: ProblemInput)`).\n *\n * @example\n * ```ts\n * throw Problems.notFound({ detail: 'User abc not found' })\n * throw Problems.tooManyRequests({}, 60) // sets Retry-After: 60\n * throw Problems.fromZodError(zodResult.error)\n * ```\n */\nexport const Problems = {\n /** 400 Bad Request with optional detail / instance / extensions. */\n badRequest(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 400, ...input })\n },\n /** 401 Unauthorized. Pass a `WWW-Authenticate` challenge via the headers arg. */\n unauthorized(\n input: Omit<ProblemDetails, 'status'> = {},\n wwwAuthenticate?: string,\n ): ProblemException {\n return new ProblemException(\n { status: 401, ...input },\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n },\n /** 403 Forbidden. */\n forbidden(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 403, ...input })\n },\n /** 404 Not Found. */\n notFound(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 404, ...input })\n },\n /** 405 Method Not Allowed. Pass the allowed methods so the Allow header is set. */\n methodNotAllowed(\n allowedMethods: string[],\n input: Omit<ProblemDetails, 'status'> = {},\n ): ProblemException {\n return new ProblemException({ status: 405, ...input }, { Allow: allowedMethods.join(', ') })\n },\n /** 409 Conflict. */\n conflict(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 409, ...input })\n },\n /**\n * 422 Unprocessable Entity. Pass per-field issues via the `errors`\n * extension — keep the array shape per the RFC's recommended convention\n * (`{ field, message, code }`).\n */\n unprocessable(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 422, ...input })\n },\n /** 429 Too Many Requests. Pass `retryAfterSeconds` to set the Retry-After header. */\n tooManyRequests(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 429, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 503 Service Unavailable. */\n serviceUnavailable(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 503, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 500 Internal Server Error. */\n internal(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 500, ...input })\n },\n\n /**\n * Build from a Zod error — 422 with the issues serialized into the\n * `errors` extension per RFC 9457 §3.2's array convention.\n */\n fromZodError(error: any, input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n const issues: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new ProblemException({\n status: 422,\n detail: error.issues?.[0]?.message,\n ...input,\n errors: issues,\n })\n },\n} as const\n\n/**\n * Normalize an RFC 9457 problem into the wire shape — fill in `type` →\n * `'about:blank'` and `title` → IANA reason phrase. The same function is\n * used by {@link RequestContext}'s `problem` helpers and the global\n * error handler so the response is identical regardless of entry point.\n *\n * Defaults are applied **after** the spread, so a caller passing\n * `{ type: undefined }` (e.g. a partial built up from optional fields)\n * still gets `'about:blank'` on the wire — `...input` would otherwise\n * re-overwrite the fallback with the explicit `undefined`.\n */\nexport function normalizeProblem(input: ProblemDetails): ProblemDetails {\n return {\n ...input,\n type: input.type ?? 'about:blank',\n title: input.title ?? defaultProblemTitle(input.status),\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IAGZ,kBAAmB,IACnB,MAAO,IACP,aAAc,IACd,mBAAoB,IACpB,mBAAoB,IAGpB,YAAa,IACb,aAAc,IACd,iBAAkB,IAClB,UAAW,IACX,UAAW,IACX,mBAAoB,IACpB,eAAgB,IAChB,SAAU,IACV,KAAM,IACN,qBAAsB,IACtB,kBAAmB,IAGnB,sBAAuB,IACvB,gBAAiB,IACjB,YAAa,IACb,oBAAqB,IACrB,gBAAiB,GACnB,EASM,eAAyC,CAC7C,IAAK,cACL,IAAK,eACL,IAAK,mBACL,IAAK,YACL,IAAK,YACL,IAAK,qBACL,IAAK,iBACL,IAAK,WACL,IAAK,OACL,IAAK,uBACL,IAAK,oBACL,IAAK,wBACL,IAAK,kBACL,IAAK,cACL,IAAK,sBACL,IAAK,iBACP,EAkFA,IAAa,cAAb,MAAa,sBAAsB,KAAM,CAErB,OAEA,QACA,QAJlB,YACE,OACA,QACA,QACA,QACA,CACA,MAAM,OAAO,EALG,KAAA,OAAA,OAEA,KAAA,QAAA,QACA,KAAA,QAAA,QAGhB,KAAK,KAAO,eACd,CAGA,YAAY,QAAgD,CAC1D,OAAO,IAAI,cAAc,KAAK,OAAQ,KAAK,QAAS,KAAK,QAAS,CAChE,GAAG,KAAK,QACR,GAAG,OACL,CAAC,CACH,CAGA,OAAO,aAAa,MAAY,QAAiC,CAC/D,IAAM,WAAa,MAAM,SAAS,GAC5B,SAA8B,MAAM,QAAU,CAAC,GAAG,IAAK,QAAgB,CAC3E,MAAO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AwC,CAAC,EAAqB,CAC1E,OAAO,IAAI,iBAAiB,CAAE,OAAQ,IAAK,GAAG,KAAM,CAAC,CACvD,EAEA,gBACE,MAAwC,CAAC,EACzC,kBACkB,CAClB,OAAO,IAAI,iBACT,CAAE,OAAQ,IAAK,GAAG,KAAM,EACxB,oBAAsB,IAAA,GAA2D,IAAA,GAA/C,CAAE,cAAe,OAAO,iBAAiB,CAAE,CAC/E,CACF,EAEA,mBACE,MAAwC,CAAC,EACzC,kBACkB,CAClB,OAAO,IAAI,iBACT,CAAE,OAAQ,IAAK,GAAG,KAAM,EACxB,oBAAsB,IAAA,GAA2D,IAAA,GAA/C,CAAE,cAAe,OAAO,iBAAiB,CAAE,CAC/E,CACF,EAEA,SAAS,MAAwC,CAAC,EAAqB,CACrE,OAAO,IAAI,iBAAiB,CAAE,OAAQ,IAAK,GAAG,KAAM,CAAC,CACvD,EAMA,aAAa,MAAY,MAAwC,CAAC,EAAqB,CACrF,IAAM,QAA6B,MAAM,QAAU,CAAC,GAAG,IAAK,QAAgB,CAC1E,MAAO,MAAM,MAAM,KAAK,GAAG,GAAK,GAChC,QAAS,MAAM,QACf,KAAM,MAAM,IACd,EAAE,EACF,OAAO,IAAI,iBAAiB,CAC1B,OAAQ,IACR,OAAQ,MAAM,SAAS,IAAI,QAC3B,GAAG,MACH,OAAQ,MACV,CAAC,CACH,CACF,EAaA,SAAgB,iBAAiB,MAAuC,CACtE,MAAO,CACL,GAAG,MACH,KAAM,MAAM,MAAQ,cACpB,MAAO,MAAM,OAAS,oBAAoB,MAAM,MAAM,CACxD,CACF"}
1
+ {"version":3,"file":"errors.mjs","names":[],"sources":["../../src/core/errors.ts"],"sourcesContent":["/**\n * Standard HTTP status codes as a const enum.\n * Use instead of raw numbers for readability and type safety.\n *\n * @example\n * ```ts\n * throw new HttpException(HttpStatus.NOT_FOUND, 'User not found')\n * ctx.res.status(HttpStatus.CREATED).json(data)\n * ```\n */\nexport const HttpStatus = {\n // 2xx Success\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NO_CONTENT: 204,\n\n // 3xx Redirection\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n NOT_MODIFIED: 304,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // 4xx Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n CONFLICT: 409,\n GONE: 410,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // 5xx Server Errors\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const\n\nexport type HttpStatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]\n\n/**\n * IANA HTTP status reason phrases for the codes the framework's typed\n * helpers cover. Used as the default `title` when a {@link ProblemException}\n * is constructed without one. Keep in sync with {@link HttpStatus}.\n */\nconst STATUS_REASONS: Record<number, string> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 402: 'Payment Required',\n 403: 'Forbidden',\n 404: 'Not Found',\n 405: 'Method Not Allowed',\n 406: 'Not Acceptable',\n 409: 'Conflict',\n 410: 'Gone',\n 422: 'Unprocessable Entity',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 501: 'Not Implemented',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n}\n\n/** Validation error detail — shape used by `unprocessable()` and `fromZodError()`. */\nexport interface ValidationError {\n field: string\n message: string\n code?: string\n}\n\n/**\n * RFC 9457 — Problem Details for HTTP APIs.\n * https://datatracker.ietf.org/doc/html/rfc9457\n *\n * Canonical error shape for HTTP responses. Only `status` is required;\n * everything else has a sensible default. Extension members (any other\n * JSON-compatible field) are allowed per §3.2 — pass them on the same\n * object and the framework forwards them through.\n *\n * @example\n * ```ts\n * const problem: ProblemDetails = {\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * // extension members per §3.2\n * balance: 30,\n * }\n * ```\n */\nexport interface ProblemDetails {\n /**\n * URI reference identifying the problem type. Per §4.2.1, when\n * dereferenced it SHOULD return human-readable documentation. Defaults\n * to `about:blank` when omitted (RFC 9457 §3.1.1).\n */\n type?: string\n /**\n * Short human-readable summary, advisable to be the same regardless of\n * the occurrence (§3.1.4). Defaults to the IANA reason phrase for\n * `status` when omitted.\n */\n title?: string\n /** HTTP status code generated by the origin server. Required. */\n status: number\n /**\n * Human-readable explanation specific to this occurrence (§3.1.5).\n * Per the RFC's safety guidance, do not include sensitive information\n * (tokens, full SQL, stack traces) — those belong in logs.\n */\n detail?: string\n /**\n * URI reference identifying the specific occurrence (§3.1.6).\n * Typically the request path. Adopters set this explicitly — the\n * framework does not auto-populate it to avoid leaking unexpected\n * structure.\n */\n instance?: string\n /**\n * Extension members per §3.2 — any other JSON-compatible field.\n * Common examples: `balance`, `errors`, `traceId`, `accounts`.\n */\n [key: string]: unknown\n}\n\n/**\n * Typed HTTP exception with status code, free-form details, and optional\n * response headers. Provides static factory methods for common HTTP errors.\n *\n * `details` is intentionally typed as `unknown` — it serializes straight into\n * the response body's `errors` field, so any JSON-compatible shape works\n * (string, object, array of mixed values, ValidationError[]).\n *\n * `headers` are merged into the response by the global error handler so\n * spec-mandated headers (Retry-After, WWW-Authenticate, Allow, Location)\n * stay on the exception, not on ad-hoc try/catch chains.\n *\n * For RFC 9457 — Problem Details responses, throw {@link ProblemException}\n * instead — the global error handler emits `application/problem+json` for\n * those automatically.\n */\nexport class HttpException extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly details?: unknown,\n public readonly headers?: Record<string, string>,\n ) {\n super(message)\n this.name = 'HttpException'\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): HttpException {\n return new HttpException(this.status, this.message, this.details, {\n ...this.headers,\n ...headers,\n })\n }\n\n /** Create from a Zod error */\n static fromZodError(error: any, message?: string): HttpException {\n const firstIssue = error.issues?.[0]\n const details: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new HttpException(\n HttpStatus.UNPROCESSABLE_ENTITY,\n message || firstIssue?.message || 'Validation failed',\n details,\n )\n }\n\n static badRequest(message = 'Bad Request') {\n return new HttpException(HttpStatus.BAD_REQUEST, message)\n }\n static unauthorized(message = 'Unauthorized', wwwAuthenticate?: string) {\n return new HttpException(\n HttpStatus.UNAUTHORIZED,\n message,\n undefined,\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n }\n static forbidden(message = 'Forbidden') {\n return new HttpException(HttpStatus.FORBIDDEN, message)\n }\n static notFound(message = 'Not Found') {\n return new HttpException(HttpStatus.NOT_FOUND, message)\n }\n static methodNotAllowed(allowedMethods: string[], message = 'Method Not Allowed') {\n return new HttpException(HttpStatus.METHOD_NOT_ALLOWED, message, undefined, {\n Allow: allowedMethods.join(', '),\n })\n }\n static conflict(message = 'Conflict') {\n return new HttpException(HttpStatus.CONFLICT, message)\n }\n static unprocessable(message = 'Unprocessable Entity', details?: ValidationError[]) {\n return new HttpException(HttpStatus.UNPROCESSABLE_ENTITY, message, details)\n }\n static tooManyRequests(message = 'Too Many Requests', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.TOO_MANY_REQUESTS,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static serviceUnavailable(message = 'Service Unavailable', retryAfterSeconds?: number) {\n return new HttpException(\n HttpStatus.SERVICE_UNAVAILABLE,\n message,\n undefined,\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n }\n static internal(message = 'Internal Server Error') {\n return new HttpException(HttpStatus.INTERNAL_SERVER_ERROR, message)\n }\n}\n\n/**\n * Default `title` for an RFC 9457 problem with the given status — the IANA\n * reason phrase, or `'Error'` for codes outside the framework's table.\n * Exposed so {@link ProblemException} construction and {@link RequestContext}'s\n * `problem` helpers share a single source of truth.\n */\nexport function defaultProblemTitle(status: number): string {\n return STATUS_REASONS[status] ?? 'Error'\n}\n\n/**\n * Exception that carries an RFC 9457 — Problem Details payload. When\n * thrown, the framework error handler emits `application/problem+json`\n * with the canonical shape; `type` defaults to `about:blank`, `title`\n * to the IANA reason phrase for `status`.\n *\n * Extends {@link HttpException} so existing `instanceof HttpException`\n * catches still see it. Use `new ProblemException(...)` directly for\n * full control, or {@link Problems} for the pre-filled-status\n * convenience factories.\n *\n * Static factories deliberately live on {@link Problems} rather than\n * this class — putting them here would shadow `HttpException`'s\n * same-named statics with incompatible (object vs string) signatures,\n * which TypeScript correctly rejects.\n *\n * @example\n * ```ts\n * throw new ProblemException({\n * type: 'https://api.example.com/problems/out-of-credit',\n * status: 403,\n * title: 'You do not have enough credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * instance: '/account/12345/messages/abc',\n * balance: 30, // extension\n * })\n *\n * // Or via the Problems convenience factory:\n * throw Problems.forbidden({\n * type: 'https://api.example.com/problems/out-of-credit',\n * detail: 'Your balance is 30, but that costs 50.',\n * balance: 30,\n * })\n * ```\n */\nexport class ProblemException extends HttpException {\n public readonly problem: ProblemDetails\n\n constructor(problem: ProblemDetails, headers?: Record<string, string>) {\n const title = problem.title ?? defaultProblemTitle(problem.status)\n const detail = problem.detail ?? title\n super(problem.status, detail, undefined, headers)\n this.name = 'ProblemException'\n this.problem = { ...problem, title }\n }\n\n /** Return a new exception with `headers` shallow-merged onto this one. */\n withHeaders(headers: Record<string, string>): ProblemException {\n return new ProblemException(this.problem, { ...this.headers, ...headers })\n }\n}\n\n/**\n * Convenience factories for {@link ProblemException}. Pre-fill `status`\n * (and `title` via {@link defaultProblemTitle}) for the common HTTP\n * codes — same shortcut set the `ctx.problem.*` response helpers cover.\n *\n * Lives in a separate namespace rather than as statics on\n * {@link ProblemException} to avoid shadowing {@link HttpException}'s\n * same-named statics, which would create a TypeScript variance\n * conflict (parent's `notFound(message?: string)` vs the child's\n * desired `notFound(input?: ProblemInput)`).\n *\n * @example\n * ```ts\n * throw Problems.notFound({ detail: 'User abc not found' })\n * throw Problems.tooManyRequests({}, 60) // sets Retry-After: 60\n * throw Problems.fromZodError(zodResult.error)\n * ```\n */\nexport const Problems = {\n /** 400 Bad Request with optional detail / instance / extensions. */\n badRequest(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 400, ...input })\n },\n /** 401 Unauthorized. Pass a `WWW-Authenticate` challenge via the headers arg. */\n unauthorized(\n input: Omit<ProblemDetails, 'status'> = {},\n wwwAuthenticate?: string,\n ): ProblemException {\n return new ProblemException(\n { status: 401, ...input },\n wwwAuthenticate ? { 'WWW-Authenticate': wwwAuthenticate } : undefined,\n )\n },\n /** 403 Forbidden. */\n forbidden(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 403, ...input })\n },\n /** 404 Not Found. */\n notFound(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 404, ...input })\n },\n /** 405 Method Not Allowed. Pass the allowed methods so the Allow header is set. */\n methodNotAllowed(\n allowedMethods: string[],\n input: Omit<ProblemDetails, 'status'> = {},\n ): ProblemException {\n return new ProblemException({ status: 405, ...input }, { Allow: allowedMethods.join(', ') })\n },\n /** 409 Conflict. */\n conflict(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 409, ...input })\n },\n /**\n * 422 Unprocessable Entity. Pass per-field issues via the `errors`\n * extension — keep the array shape per the RFC's recommended convention\n * (`{ field, message, code }`).\n */\n unprocessable(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 422, ...input })\n },\n /** 429 Too Many Requests. Pass `retryAfterSeconds` to set the Retry-After header. */\n tooManyRequests(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 429, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 503 Service Unavailable. */\n serviceUnavailable(\n input: Omit<ProblemDetails, 'status'> = {},\n retryAfterSeconds?: number,\n ): ProblemException {\n return new ProblemException(\n { status: 503, ...input },\n retryAfterSeconds !== undefined ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n )\n },\n /** 500 Internal Server Error. */\n internal(input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n return new ProblemException({ status: 500, ...input })\n },\n\n /**\n * Build from a Zod error — 422 with the issues serialized into the\n * `errors` extension per RFC 9457 §3.2's array convention.\n */\n fromZodError(error: any, input: Omit<ProblemDetails, 'status'> = {}): ProblemException {\n const issues: ValidationError[] = (error.issues || []).map((issue: any) => ({\n field: issue.path?.join('.') || '',\n message: issue.message,\n code: issue.code,\n }))\n return new ProblemException({\n status: 422,\n detail: error.issues?.[0]?.message,\n ...input,\n errors: issues,\n })\n },\n} as const\n\n/**\n * Normalize an RFC 9457 problem into the wire shape — fill in `type` →\n * `'about:blank'` and `title` → IANA reason phrase. The same function is\n * used by {@link RequestContext}'s `problem` helpers and the global\n * error handler so the response is identical regardless of entry point.\n *\n * Defaults are applied **after** the spread, so a caller passing\n * `{ type: undefined }` (e.g. a partial built up from optional fields)\n * still gets `'about:blank'` on the wire — `...input` would otherwise\n * re-overwrite the fallback with the explicit `undefined`.\n */\nexport function normalizeProblem(input: ProblemDetails): ProblemDetails {\n return {\n ...input,\n type: input.type ?? 'about:blank',\n title: input.title ?? defaultProblemTitle(input.status),\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,WAAa,CAExB,GAAI,IACJ,QAAS,IACT,SAAU,IACV,WAAY,IA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OAAO,IAAI,iBACT,CAAE,OAAQ,IAAK,GAAG,KAAM,EACxB,oBAAsB,IAAA,GAA2D,IAAA,GAA/C,CAAE,cAAe,OAAO,iBAAiB,CAAE,CAC/E,CACF,EAEA,SAAS,MAAwC,CAAC,EAAqB,CACrE,OAAO,IAAI,iBAAiB,CAAE,OAAQ,IAAK,GAAG,KAAM,CAAC,CACvD,EAMA,aAAa,MAAY,MAAwC,CAAC,EAAqB,CACrF,IAAM,QAA6B,MAAM,QAAU,CAAC,EAAA,CAAG,IAAK,QAAgB,CAC1E,MAAO,MAAM,MAAM,KAAK,GAAG,GAAK,GAChC,QAAS,MAAM,QACf,KAAM,MAAM,IACd,EAAE,EACF,OAAO,IAAI,iBAAiB,CAC1B,OAAQ,IACR,OAAQ,MAAM,SAAS,EAAE,EAAE,QAC3B,GAAG,MACH,OAAQ,MACV,CAAC,CACH,CACF,EAaA,SAAgB,iBAAiB,MAAuC,CACtE,MAAO,CACL,GAAG,MACH,KAAM,MAAM,MAAQ,cACpB,MAAO,MAAM,OAAS,oBAAoB,MAAM,MAAM,CACxD,CACF"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,3 +1,3 @@
1
1
 
2
- import { i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "../logger-BnBVjmDa.mjs";
2
+ import { i as createLogger, n as Logger, r as LoggerProvider, t as ConsoleLoggerProvider } from "../logger-COlEkn_C.mjs";
3
3
  export { ConsoleLoggerProvider, Logger, LoggerProvider, createLogger };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,5 +8,5 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- var ConsoleLoggerProvider=class ConsoleLoggerProvider{prefix;useColor;constructor(prefix){this.prefix=prefix??``,this.useColor=typeof process<`u`&&process.stdout?.isTTY===!0&&!process.env.NO_COLOR}fmt(level,color,msg){let tag=this.prefix?`[${this.prefix}]`:``;return this.useColor?`${color}${level}\x1b[0m ${tag?`\x1b[36m${tag}\x1b[0m `:``}${msg}`:`${level} ${tag?`${tag} `:``}${msg}`}info(msg,...args){console.log(this.fmt(`INFO`,`\x1B[32m`,msg),...args)}warn(msg,...args){console.warn(this.fmt(`WARN`,`\x1B[33m`,msg),...args)}error(msg,...args){console.error(this.fmt(`ERROR`,`\x1B[31m`,msg),...args)}debug(msg,...args){console.debug(this.fmt(`DEBUG`,`\x1B[90m`,msg),...args)}trace(msg,...args){console.trace(this.fmt(`TRACE`,`\x1B[90m`,msg),...args)}fatal(msg,...args){console.error(this.fmt(`FATAL`,`\x1B[1m\x1B[31m`,msg),...args)}child(bindings){return new ConsoleLoggerProvider(bindings.component)}};let activeProvider=new ConsoleLoggerProvider;const loggerCache=new Map;var Logger=class Logger{_provider;_providerVersion;_name;static _providerVersion=0;constructor(name){this._name=name,this._providerVersion=Logger._providerVersion,this._provider=name?activeProvider.child({component:name}):activeProvider}get provider(){return this._providerVersion!==Logger._providerVersion&&(this._providerVersion=Logger._providerVersion,this._provider=this._name?activeProvider.child({component:this._name}):activeProvider),this._provider}static setProvider(provider){activeProvider=provider,Logger._providerVersion++,loggerCache.clear()}static getProvider(){return activeProvider}static resetProvider(){activeProvider=new ConsoleLoggerProvider,Logger._providerVersion++,loggerCache.clear()}static for(name){let cached=loggerCache.get(name);return cached||(cached=new Logger(name),loggerCache.set(name,cached)),cached}child(name){return new Logger(name)}info(msg,...args){this.provider.info(msg,...args)}warn(msg,...args){this.provider.warn(msg,...args)}error(msgOrObj,msg,...args){typeof msgOrObj==`string`?this.provider.error(msgOrObj):msg?this.provider.error(msg,...args):this.provider.error(String(msgOrObj))}debug(msg,...args){this.provider.debug(msg,...args)}trace(msg,...args){this.provider.trace?this.provider.trace(msg,...args):this.provider.debug(msg,...args)}fatal(msg,...args){this.provider.fatal?this.provider.fatal(msg,...args):this.provider.error(msg,...args)}};function createLogger(name){return Logger.for(name)}export{ConsoleLoggerProvider,Logger,createLogger};
11
+ const LEVEL_RANK={trace:10,debug:20,info:30,warn:40,error:50,fatal:60,silent:100};function thresholdRank(){return LEVEL_RANK[(process.env.LOG_LEVEL??`info`).toLowerCase()]??LEVEL_RANK.info}var ConsoleLoggerProvider=class ConsoleLoggerProvider{prefix;useColor;constructor(prefix){this.prefix=prefix??``,this.useColor=typeof process<`u`&&process.stdout?.isTTY===!0&&!process.env.NO_COLOR}fmt(level,color,msg){let tag=this.prefix?`[${this.prefix}]`:``;return this.useColor?`${color}${level}\x1b[0m ${tag?`\x1b[36m${tag}\x1b[0m `:``}${msg}`:`${level} ${tag?`${tag} `:``}${msg}`}enabled(rank){return rank>=thresholdRank()}info(msg,...args){this.enabled(LEVEL_RANK.info)&&console.log(this.fmt(`INFO`,`\x1B[32m`,msg),...args)}warn(msg,...args){this.enabled(LEVEL_RANK.warn)&&console.warn(this.fmt(`WARN`,`\x1B[33m`,msg),...args)}error(msg,...args){this.enabled(LEVEL_RANK.error)&&console.error(this.fmt(`ERROR`,`\x1B[31m`,msg),...args)}debug(msg,...args){this.enabled(LEVEL_RANK.debug)&&console.debug(this.fmt(`DEBUG`,`\x1B[90m`,msg),...args)}trace(msg,...args){this.enabled(LEVEL_RANK.trace)&&console.trace(this.fmt(`TRACE`,`\x1B[90m`,msg),...args)}fatal(msg,...args){this.enabled(LEVEL_RANK.fatal)&&console.error(this.fmt(`FATAL`,`\x1B[1m\x1B[31m`,msg),...args)}child(bindings){return new ConsoleLoggerProvider(bindings.component)}};let activeProvider=new ConsoleLoggerProvider;const loggerCache=new Map;var Logger=class Logger{_provider;_providerVersion;_name;static _providerVersion=0;constructor(name){this._name=name,this._providerVersion=Logger._providerVersion,this._provider=name?activeProvider.child({component:name}):activeProvider}get provider(){return this._providerVersion!==Logger._providerVersion&&(this._providerVersion=Logger._providerVersion,this._provider=this._name?activeProvider.child({component:this._name}):activeProvider),this._provider}static setProvider(provider){activeProvider=provider,Logger._providerVersion++,loggerCache.clear()}static getProvider(){return activeProvider}static resetProvider(){activeProvider=new ConsoleLoggerProvider,Logger._providerVersion++,loggerCache.clear()}static for(name){let cached=loggerCache.get(name);return cached||(cached=new Logger(name),loggerCache.set(name,cached)),cached}child(name){return new Logger(name)}info(msg,...args){this.provider.info(msg,...args)}warn(msg,...args){this.provider.warn(msg,...args)}error(msgOrObj,msg,...args){typeof msgOrObj==`string`?this.provider.error(msgOrObj):msg?this.provider.error(msg,...args):this.provider.error(String(msgOrObj))}debug(msg,...args){this.provider.debug(msg,...args)}trace(msg,...args){this.provider.trace?this.provider.trace(msg,...args):this.provider.debug(msg,...args)}fatal(msg,...args){this.provider.fatal?this.provider.fatal(msg,...args):this.provider.error(msg,...args)}};function createLogger(name){return Logger.for(name)}export{ConsoleLoggerProvider,Logger,createLogger};
12
12
  //# sourceMappingURL=logger.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.mjs","names":[],"sources":["../../src/core/logger.ts"],"sourcesContent":["// ── LoggerProvider interface ───────────────────────────────────────────\n\n/**\n * Pluggable logger backend.\n *\n * Implement this interface to plug in any logging library (pino,\n * winston, bunyan, console, etc.). The framework only ever calls the\n * methods declared here — it doesn't know or care which logger is\n * underneath.\n *\n * Default: `ConsoleLoggerProvider` (zero runtime deps).\n *\n * @example\n * ```ts\n * import pino from 'pino'\n * import { Logger, type LoggerProvider } from '@forinda/kickjs'\n *\n * class PinoProvider implements LoggerProvider {\n * constructor(private p = pino()) {}\n * info(msg, ...args) { this.p.info(msg, ...args) }\n * warn(msg, ...args) { this.p.warn(msg, ...args) }\n * error(msg, ...args) { this.p.error(msg, ...args) }\n * debug(msg, ...args) { this.p.debug(msg, ...args) }\n * child({ component }) { return new PinoProvider(this.p.child({ component })) }\n * }\n *\n * Logger.setProvider(new PinoProvider())\n * ```\n *\n * See `docs/guide/logging.md` for Pino, Winston, and silent-logger recipes.\n */\nexport interface LoggerProvider {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n trace?(msg: string, ...args: any[]): void\n fatal?(msg: string, ...args: any[]): void\n /** Return a child provider scoped to the given component name */\n child(bindings: { component: string }): LoggerProvider\n}\n\n// ── ConsoleLoggerProvider (default) ────────────────────────────────────\n\n/**\n * Default provider — emits through `console.*` methods. Zero deps.\n *\n * Swap it for pino, winston, bunyan, or anything else by implementing\n * the `LoggerProvider` interface and calling `Logger.setProvider()`\n * before `bootstrap()`.\n */\nexport class ConsoleLoggerProvider implements LoggerProvider {\n private prefix: string\n private useColor: boolean\n\n constructor(prefix?: string) {\n this.prefix = prefix ?? ''\n this.useColor =\n typeof process !== 'undefined' && process.stdout?.isTTY === true && !process.env.NO_COLOR\n }\n\n private fmt(level: string, color: string, msg: string): string {\n const tag = this.prefix ? `[${this.prefix}]` : ''\n if (this.useColor) {\n return `${color}${level}\\x1b[0m ${tag ? `\\x1b[36m${tag}\\x1b[0m ` : ''}${msg}`\n }\n return `${level} ${tag ? `${tag} ` : ''}${msg}`\n }\n\n info(msg: string, ...args: any[]) {\n console.log(this.fmt('INFO', '\\x1b[32m', msg), ...args)\n }\n warn(msg: string, ...args: any[]) {\n console.warn(this.fmt('WARN', '\\x1b[33m', msg), ...args)\n }\n error(msg: string, ...args: any[]) {\n console.error(this.fmt('ERROR', '\\x1b[31m', msg), ...args)\n }\n debug(msg: string, ...args: any[]) {\n console.debug(this.fmt('DEBUG', '\\x1b[90m', msg), ...args)\n }\n trace(msg: string, ...args: any[]) {\n console.trace(this.fmt('TRACE', '\\x1b[90m', msg), ...args)\n }\n fatal(msg: string, ...args: any[]) {\n console.error(this.fmt('FATAL', '\\x1b[1m\\x1b[31m', msg), ...args)\n }\n child(bindings: { component: string }): LoggerProvider {\n return new ConsoleLoggerProvider(bindings.component)\n }\n}\n\n// ── Active provider ────────────────────────────────────────────────────\n\nlet activeProvider: LoggerProvider = new ConsoleLoggerProvider()\n\n/** Cache of named loggers to avoid creating duplicates */\nconst loggerCache = new Map<string, Logger>()\n\n/**\n * Named logger with component context.\n *\n * @example\n * ```ts\n * // Static factory — preferred\n * const log = Logger.for('UserService')\n * log.info('User created')\n * // Output: [UserService] User created\n *\n * // Shorthand function\n * const log = createLogger('OrderService')\n *\n * // Pluggable backend — see docs/guide/logging.md\n * Logger.setProvider(new MyCustomProvider())\n *\n * // Injectable — auto-named from class\n * class MyService {\n * @Autowired() private logger!: Logger\n * // or inject a named one:\n * private log = Logger.for('MyService')\n * }\n * ```\n */\nexport class Logger {\n private _provider: LoggerProvider\n private _providerVersion: number\n private _name?: string\n\n /** Incremented on every setProvider/resetProvider so instances know to refresh */\n private static _providerVersion = 0\n\n constructor(name?: string) {\n this._name = name\n this._providerVersion = Logger._providerVersion\n this._provider = name ? activeProvider.child({ component: name }) : activeProvider\n }\n\n /** Re-derive the provider if setProvider() was called since construction/last access */\n private get provider(): LoggerProvider {\n if (this._providerVersion !== Logger._providerVersion) {\n this._providerVersion = Logger._providerVersion\n this._provider = this._name ? activeProvider.child({ component: this._name }) : activeProvider\n }\n return this._provider\n }\n\n /**\n * Replace the logging backend for **all** Logger instances created after\n * this call. Clears the logger cache so subsequent `Logger.for()` calls\n * pick up the new provider.\n *\n * @example\n * ```ts\n * Logger.setProvider(new MyWinstonProvider())\n * ```\n */\n static setProvider(provider: LoggerProvider): void {\n activeProvider = provider\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Return the currently active provider (useful for testing) */\n static getProvider(): LoggerProvider {\n return activeProvider\n }\n\n /**\n * Reset the provider back to the default `ConsoleLoggerProvider`.\n * Primarily intended for test teardown.\n */\n static resetProvider(): void {\n activeProvider = new ConsoleLoggerProvider()\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Create or retrieve a cached named logger */\n static for(name: string): Logger {\n let cached = loggerCache.get(name)\n if (!cached) {\n cached = new Logger(name)\n loggerCache.set(name, cached)\n }\n return cached\n }\n\n /** Create a child logger with a sub-component name */\n child(name: string): Logger {\n return new Logger(name)\n }\n\n info(msg: string, ...args: any[]) {\n this.provider.info(msg, ...args)\n }\n\n warn(msg: string, ...args: any[]) {\n this.provider.warn(msg, ...args)\n }\n\n error(msgOrObj: any, msg?: string, ...args: any[]) {\n if (typeof msgOrObj === 'string') {\n this.provider.error(msgOrObj)\n } else if (msg) {\n this.provider.error(msg, ...args)\n } else {\n this.provider.error(String(msgOrObj))\n }\n }\n\n debug(msg: string, ...args: any[]) {\n this.provider.debug(msg, ...args)\n }\n\n trace(msg: string, ...args: any[]) {\n if (this.provider.trace) this.provider.trace(msg, ...args)\n else this.provider.debug(msg, ...args)\n }\n\n fatal(msg: string, ...args: any[]) {\n if (this.provider.fatal) this.provider.fatal(msg, ...args)\n else this.provider.error(msg, ...args)\n }\n}\n\n/** Shorthand for Logger.for(name) */\nexport function createLogger(name: string): Logger {\n return Logger.for(name)\n}\n"],"mappings":";;;;;;;;;;AAmDA,IAAa,sBAAb,MAAa,qBAAgD,CAC3D,OACA,SAEA,YAAY,OAAiB,CAC3B,KAAK,OAAS,QAAU,GACxB,KAAK,SACH,OAAO,QAAY,KAAe,QAAQ,QAAQ,QAAU,IAAQ,CAAC,QAAQ,IAAI,QACrF,CAEA,IAAY,MAAe,MAAe,IAAqB,CAC7D,IAAM,IAAM,KAAK,OAAS,IAAI,KAAK,OAAO,GAAK,GAI/C,OAHI,KAAK,SACA,GAAG,QAAQ,MAAM,UAAU,IAAM,WAAW,IAAI,UAAY,KAAK,MAEnE,GAAG,MAAM,GAAG,IAAM,GAAG,IAAI,GAAK,KAAK,KAC5C,CAEA,KAAK,IAAa,GAAG,KAAa,CAChC,QAAQ,IAAI,KAAK,IAAI,OAAQ,WAAY,GAAG,EAAG,GAAG,IAAI,CACxD,CACA,KAAK,IAAa,GAAG,KAAa,CAChC,QAAQ,KAAK,KAAK,IAAI,OA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OAAS,IAAI,OAAO,IAAI,EACxB,YAAY,IAAI,KAAM,MAAM,GAEvB,MACT,CAGA,MAAM,KAAsB,CAC1B,OAAO,IAAI,OAAO,IAAI,CACxB,CAEA,KAAK,IAAa,GAAG,KAAa,CAChC,KAAK,SAAS,KAAK,IAAK,GAAG,IAAI,CACjC,CAEA,KAAK,IAAa,GAAG,KAAa,CAChC,KAAK,SAAS,KAAK,IAAK,GAAG,IAAI,CACjC,CAEA,MAAM,SAAe,IAAc,GAAG,KAAa,CAC7C,OAAO,UAAa,SACtB,KAAK,SAAS,MAAM,QAAQ,EACnB,IACT,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,EAEhC,KAAK,SAAS,MAAM,OAAO,QAAQ,CAAC,CAExC,CAEA,MAAM,IAAa,GAAG,KAAa,CACjC,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,CAClC,CAEA,MAAM,IAAa,GAAG,KAAa,CAC7B,KAAK,SAAS,MAAO,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,EACpD,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,CACvC,CAEA,MAAM,IAAa,GAAG,KAAa,CAC7B,KAAK,SAAS,MAAO,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,EACpD,KAAK,SAAS,MAAM,IAAK,GAAG,IAAI,CACvC,CACF,EAGA,SAAgB,aAAa,KAAsB,CACjD,OAAO,OAAO,IAAI,IAAI,CACxB"}
1
+ {"version":3,"file":"logger.mjs","names":[],"sources":["../../src/core/logger.ts"],"sourcesContent":["// ── LoggerProvider interface ───────────────────────────────────────────\n\n/**\n * Pluggable logger backend.\n *\n * Implement this interface to plug in any logging library (pino,\n * winston, bunyan, console, etc.). The framework only ever calls the\n * methods declared here — it doesn't know or care which logger is\n * underneath.\n *\n * Default: `ConsoleLoggerProvider` (zero runtime deps).\n *\n * @example\n * ```ts\n * import pino from 'pino'\n * import { Logger, type LoggerProvider } from '@forinda/kickjs'\n *\n * class PinoProvider implements LoggerProvider {\n * constructor(private p = pino()) {}\n * info(msg, ...args) { this.p.info(msg, ...args) }\n * warn(msg, ...args) { this.p.warn(msg, ...args) }\n * error(msg, ...args) { this.p.error(msg, ...args) }\n * debug(msg, ...args) { this.p.debug(msg, ...args) }\n * child({ component }) { return new PinoProvider(this.p.child({ component })) }\n * }\n *\n * Logger.setProvider(new PinoProvider())\n * ```\n *\n * See `docs/guide/logging.md` for Pino, Winston, and silent-logger recipes.\n */\nexport interface LoggerProvider {\n info(msg: string, ...args: any[]): void\n warn(msg: string, ...args: any[]): void\n error(msg: string, ...args: any[]): void\n debug(msg: string, ...args: any[]): void\n trace?(msg: string, ...args: any[]): void\n fatal?(msg: string, ...args: any[]): void\n /** Return a child provider scoped to the given component name */\n child(bindings: { component: string }): LoggerProvider\n}\n\n// ── Log levels ─────────────────────────────────────────────────────────\n\n/** Severity ordering — a message prints only when its rank ≥ the threshold. */\nconst LEVEL_RANK: Record<string, number> = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60,\n silent: 100,\n}\n\n/**\n * Resolve the active threshold rank from `LOG_LEVEL` (default `info`).\n * Read per-call so a late `process.env.LOG_LEVEL` assignment still\n * takes effect. An unrecognised value falls back to `info`.\n */\nfunction thresholdRank(): number {\n const level = (process.env.LOG_LEVEL ?? 'info').toLowerCase()\n return LEVEL_RANK[level] ?? LEVEL_RANK.info\n}\n\n// ── ConsoleLoggerProvider (default) ────────────────────────────────────\n\n/**\n * Default provider — emits through `console.*` methods. Zero deps.\n *\n * Respects the `LOG_LEVEL` env var (default `info`): messages below the\n * threshold are dropped, so the verbose startup detail (the route table,\n * DI wiring, HMR ticks — all `debug`) stays quiet by default and only\n * appears with `LOG_LEVEL=debug`. `error`/`fatal` always print unless\n * `LOG_LEVEL=silent`.\n *\n * Swap it for pino, winston, bunyan, or anything else by implementing\n * the `LoggerProvider` interface and calling `Logger.setProvider()`\n * before `bootstrap()`.\n */\nexport class ConsoleLoggerProvider implements LoggerProvider {\n private prefix: string\n private useColor: boolean\n\n constructor(prefix?: string) {\n this.prefix = prefix ?? ''\n this.useColor =\n typeof process !== 'undefined' && process.stdout?.isTTY === true && !process.env.NO_COLOR\n }\n\n private fmt(level: string, color: string, msg: string): string {\n const tag = this.prefix ? `[${this.prefix}]` : ''\n if (this.useColor) {\n return `${color}${level}\\x1b[0m ${tag ? `\\x1b[36m${tag}\\x1b[0m ` : ''}${msg}`\n }\n return `${level} ${tag ? `${tag} ` : ''}${msg}`\n }\n\n /** Should a message at `rank` print under the current `LOG_LEVEL`? */\n private enabled(rank: number): boolean {\n return rank >= thresholdRank()\n }\n\n info(msg: string, ...args: any[]) {\n if (this.enabled(LEVEL_RANK.info)) console.log(this.fmt('INFO', '\\x1b[32m', msg), ...args)\n }\n warn(msg: string, ...args: any[]) {\n if (this.enabled(LEVEL_RANK.warn)) console.warn(this.fmt('WARN', '\\x1b[33m', msg), ...args)\n }\n error(msg: string, ...args: any[]) {\n if (this.enabled(LEVEL_RANK.error)) console.error(this.fmt('ERROR', '\\x1b[31m', msg), ...args)\n }\n debug(msg: string, ...args: any[]) {\n if (this.enabled(LEVEL_RANK.debug)) console.debug(this.fmt('DEBUG', '\\x1b[90m', msg), ...args)\n }\n trace(msg: string, ...args: any[]) {\n if (this.enabled(LEVEL_RANK.trace)) console.trace(this.fmt('TRACE', '\\x1b[90m', msg), ...args)\n }\n fatal(msg: string, ...args: any[]) {\n if (this.enabled(LEVEL_RANK.fatal))\n console.error(this.fmt('FATAL', '\\x1b[1m\\x1b[31m', msg), ...args)\n }\n child(bindings: { component: string }): LoggerProvider {\n return new ConsoleLoggerProvider(bindings.component)\n }\n}\n\n// ── Active provider ────────────────────────────────────────────────────\n\nlet activeProvider: LoggerProvider = new ConsoleLoggerProvider()\n\n/** Cache of named loggers to avoid creating duplicates */\nconst loggerCache = new Map<string, Logger>()\n\n/**\n * Named logger with component context.\n *\n * @example\n * ```ts\n * // Static factory — preferred\n * const log = Logger.for('UserService')\n * log.info('User created')\n * // Output: [UserService] User created\n *\n * // Shorthand function\n * const log = createLogger('OrderService')\n *\n * // Pluggable backend — see docs/guide/logging.md\n * Logger.setProvider(new MyCustomProvider())\n *\n * // Injectable — auto-named from class\n * class MyService {\n * @Autowired() private logger!: Logger\n * // or inject a named one:\n * private log = Logger.for('MyService')\n * }\n * ```\n */\nexport class Logger {\n private _provider: LoggerProvider\n private _providerVersion: number\n private _name?: string\n\n /** Incremented on every setProvider/resetProvider so instances know to refresh */\n private static _providerVersion = 0\n\n constructor(name?: string) {\n this._name = name\n this._providerVersion = Logger._providerVersion\n this._provider = name ? activeProvider.child({ component: name }) : activeProvider\n }\n\n /** Re-derive the provider if setProvider() was called since construction/last access */\n private get provider(): LoggerProvider {\n if (this._providerVersion !== Logger._providerVersion) {\n this._providerVersion = Logger._providerVersion\n this._provider = this._name ? activeProvider.child({ component: this._name }) : activeProvider\n }\n return this._provider\n }\n\n /**\n * Replace the logging backend for **all** Logger instances created after\n * this call. Clears the logger cache so subsequent `Logger.for()` calls\n * pick up the new provider.\n *\n * @example\n * ```ts\n * Logger.setProvider(new MyWinstonProvider())\n * ```\n */\n static setProvider(provider: LoggerProvider): void {\n activeProvider = provider\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Return the currently active provider (useful for testing) */\n static getProvider(): LoggerProvider {\n return activeProvider\n }\n\n /**\n * Reset the provider back to the default `ConsoleLoggerProvider`.\n * Primarily intended for test teardown.\n */\n static resetProvider(): void {\n activeProvider = new ConsoleLoggerProvider()\n Logger._providerVersion++\n loggerCache.clear()\n }\n\n /** Create or retrieve a cached named logger */\n static for(name: string): Logger {\n let cached = loggerCache.get(name)\n if (!cached) {\n cached = new Logger(name)\n loggerCache.set(name, cached)\n }\n return cached\n }\n\n /** Create a child logger with a sub-component name */\n child(name: string): Logger {\n return new Logger(name)\n }\n\n info(msg: string, ...args: any[]) {\n this.provider.info(msg, ...args)\n }\n\n warn(msg: string, ...args: any[]) {\n this.provider.warn(msg, ...args)\n }\n\n error(msgOrObj: any, msg?: string, ...args: any[]) {\n if (typeof msgOrObj === 'string') {\n this.provider.error(msgOrObj)\n } else if (msg) {\n this.provider.error(msg, ...args)\n } else {\n this.provider.error(String(msgOrObj))\n }\n }\n\n debug(msg: string, ...args: any[]) {\n this.provider.debug(msg, ...args)\n }\n\n trace(msg: string, ...args: any[]) {\n if (this.provider.trace) this.provider.trace(msg, ...args)\n else this.provider.debug(msg, ...args)\n }\n\n fatal(msg: string, ...args: any[]) {\n if (this.provider.fatal) this.provider.fatal(msg, ...args)\n else this.provider.error(msg, ...args)\n }\n}\n\n/** Shorthand for Logger.for(name) */\nexport function createLogger(name: string): Logger {\n return Logger.for(name)\n}\n"],"mappings":";;;;;;;;;;AA6CA,MAAM,WAAqC,CACzC,MAAO,GACP,MAAO,GACP,KAAM,GACN,KAAM,GACN,MAAO,GACP,MAAO,GACP,OAAQ,GACV,EAOA,SAAS,eAAwB,CAE/B,OAAO,YADQ,QAAQ,IAAI,WAAa,OAAA,CAAQ,YAC1B,IAAM,WAAW,IACzC,CAiBA,IAAa,sBAAb,MAAa,qBAAgD,CAC3D,OACA,SAEA,YAAY,OAAiB,CAC3B,KAAK,OAAS,QAAU,GACxB,KAAK,SACH,OAAO,QAAY,KAAe,QAAQ,QAAQ,QAAU,IAAQ,CAAC,QAAQ,IAAI,QACrF,CAEA,IAAY,MAAe,MAAe,IAAqB,CAC7D,IAAM,IAAM,KAAK,OAAS,IAAI,KAAK,OAAO,GAAK,GAI/C,OAHI,KAAK,SACA,GAAG,QAAQ,MAAM,UAAU,IAAM,WAAW,IAAI,UAAY,KAAK,MAEnE,GAAG,MAAM,GAAG,IAAM,GAAG,IAAI,GAAK,KAAK,KAC5C,CAGA,QAAgB,KAAuB,CACrC,OAAO,MAAQ,cAAc,CAC/B,CAEA,KAAK,IAAa,GAAG,KAAa,CAC5B,KAAK,QAAQ,WAAW,IAAI,GAAG,QAAQ,IAAI,KAAK,IAAI,OAAQ,WAAY,GAAG,EAAG,GA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right (c) Felix Orinda
5
5
  *
@@ -1 +1 @@
1
- {"version":3,"file":"path.mjs","names":[],"sources":["../../src/core/path.ts"],"sourcesContent":["/**\n * Normalize a URL path segment:\n * - '/' or '' or undefined → ''\n * - Ensures leading '/' if non-empty\n * - Strips trailing '/'\n * - Collapses consecutive '//' into single '/'\n */\nexport function normalizePath(path?: string): string {\n let p = path?.trim() || ''\n if (p === '/') return ''\n if (p && !p.startsWith('/')) p = `/${p}`\n // Strip trailing slash\n p = p.replace(/\\/+$/, '')\n // Collapse double slashes\n p = p.replace(/\\/\\/+/g, '/')\n return p\n}\n\n/**\n * Join path segments into a single normalized path.\n * Handles leading/trailing slashes and prevents double slashes.\n *\n * @example\n * joinPaths('/api/v1', '/users') // '/api/v1/users'\n * joinPaths('/api/v1/', '/users') // '/api/v1/users'\n * joinPaths('/api/v1', '/') // '/api/v1'\n * joinPaths('/api/v1', '') // '/api/v1'\n * joinPaths('/api/v1', 'users') // '/api/v1/users'\n */\nexport function joinPaths(...segments: (string | undefined)[]): string {\n const joined = segments\n .map((s) => s?.trim() || '')\n .filter(Boolean)\n .join('/')\n // Ensure leading slash, collapse doubles\n const normalized = ('/' + joined).replace(/\\/\\/+/g, '/')\n // Strip trailing slash (unless it's just '/')\n return normalized === '/' ? '/' : normalized.replace(/\\/+$/, '')\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,cAAc,KAAuB,CACnD,IAAI,EAAI,MAAM,KAAK,GAAK,GAOxB,OANI,IAAM,IAAY,IAClB,GAAK,CAAC,EAAE,WAAW,GAAG,IAAG,EAAI,IAAI,KAErC,EAAI,EAAE,QAAQ,OAAQ,EAAE,EAExB,EAAI,EAAE,QAAQ,SAAU,GAAG,EACpB,EACT,CAaA,SAAgB,UAAU,GAAG,SAA0C,CAMrE,IAAM,YAAc,IALL,SACZ,IAAK,GAAM,GAAG,KAAK,GAAK,EAAE,EAC1B,OAAO,OAAO,EACd,KAAK,GAEuB,GAAG,QAAQ,SAAU,GAAG,EAEvD,OAAO,aAAe,IAAM,IAAM,WAAW,QAAQ,OAAQ,EAAE,CACjE"}
1
+ {"version":3,"file":"path.mjs","names":[],"sources":["../../src/core/path.ts"],"sourcesContent":["/**\n * Normalize a URL path segment:\n * - '/' or '' or undefined → ''\n * - Ensures leading '/' if non-empty\n * - Strips trailing '/'\n * - Collapses consecutive '//' into single '/'\n */\nexport function normalizePath(path?: string): string {\n let p = path?.trim() || ''\n if (p === '/') return ''\n if (p && !p.startsWith('/')) p = `/${p}`\n // Strip trailing slash\n p = p.replace(/\\/+$/, '')\n // Collapse double slashes\n p = p.replace(/\\/\\/+/g, '/')\n return p\n}\n\n/**\n * Join path segments into a single normalized path.\n * Handles leading/trailing slashes and prevents double slashes.\n *\n * @example\n * joinPaths('/api/v1', '/users') // '/api/v1/users'\n * joinPaths('/api/v1/', '/users') // '/api/v1/users'\n * joinPaths('/api/v1', '/') // '/api/v1'\n * joinPaths('/api/v1', '') // '/api/v1'\n * joinPaths('/api/v1', 'users') // '/api/v1/users'\n */\nexport function joinPaths(...segments: (string | undefined)[]): string {\n const joined = segments\n .map((s) => s?.trim() || '')\n .filter(Boolean)\n .join('/')\n // Ensure leading slash, collapse doubles\n const normalized = ('/' + joined).replace(/\\/\\/+/g, '/')\n // Strip trailing slash (unless it's just '/')\n return normalized === '/' ? '/' : normalized.replace(/\\/+$/, '')\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAgB,cAAc,KAAuB,CACnD,IAAI,EAAI,MAAM,KAAK,GAAK,GAOxB,OANI,IAAM,IAAY,IAClB,GAAK,CAAC,EAAE,WAAW,GAAG,IAAG,EAAI,IAAI,KAErC,EAAI,EAAE,QAAQ,OAAQ,EAAE,EAExB,EAAI,EAAE,QAAQ,SAAU,GAAG,EACpB,EACT,CAaA,SAAgB,UAAU,GAAG,SAA0C,CAMrE,IAAM,YAAc,IALL,SACZ,IAAK,GAAM,GAAG,KAAK,GAAK,EAAE,CAAC,CAC3B,OAAO,OAAO,CAAC,CACf,KAAK,GAEuB,EAAA,CAAG,QAAQ,SAAU,GAAG,EAEvD,OAAO,aAAe,IAAM,IAAM,WAAW,QAAQ,OAAQ,EAAE,CACjE"}
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs v5.15.1
2
+ * @forinda/kickjs v5.17.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -8,6 +8,6 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import"./container-F-qfN8Bx.mjs";import{METADATA}from"./core/interfaces.mjs";import"./core/logger.mjs";import{c as pushClassMeta,l as pushMethodMeta}from"./metadata-DbrSf8E-.mjs";import"./core/decorators.mjs";import"./core/cron.mjs";import"./core/cache.mjs";import"reflect-metadata";const mergeConfig$2=(defaults={},overrides={})=>({...defaults,...overrides}),composeName$2=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig$2(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName$2(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}},CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};function defineContextDecoratorImpl(spec){if(typeof spec!=`object`||!spec)throw TypeError(`defineContextDecorator: spec must be an object literal. See architecture.md §20.4 for the spec shape.`);if(typeof spec.key!=`string`||spec.key.length===0){let got=typeof spec.key==`string`?`""`:typeof spec.key;throw TypeError(`defineContextDecorator: spec.key must be a non-empty string (got ${got}). Pick a name that matches a key declared on \`ContextMeta\` (or one of the framework keys).`)}if(typeof spec.resolve!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.resolve is required and must be a function (got ${typeof spec.resolve}). Each contributor needs a resolver that produces the value to write into ctx.set(${JSON.stringify(spec.key)}, …).`);if(spec.onError!==void 0&&typeof spec.onError!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.onError must be a function when provided (got ${typeof spec.onError}).`);if(spec.dependsOn!==void 0&&!Array.isArray(spec.dependsOn))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn must be an array when provided (got ${typeof spec.dependsOn}).`);if(Array.isArray(spec.dependsOn)&&spec.dependsOn.some(dep=>typeof dep!=`string`||dep.length===0))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn entries must be non-empty strings.`);let definedAt=Error().stack,defaults=Object.freeze({...spec.paramDefaults??{}}),sharedDeps=Object.freeze({...spec.deps??{}}),sharedDependsOn=Object.freeze([...spec.dependsOn??[]]),sharedOptional=spec.optional??!1,buildRegistration=params=>{let frozenParams=Object.freeze({...params}),onError=spec.onError?(err,ctx)=>spec.onError(err,ctx,frozenParams):void 0;return Object.freeze({key:spec.key,deps:sharedDeps,dependsOn:sharedDependsOn,optional:sharedOptional,onError,resolve:(ctx,deps)=>spec.resolve(ctx,deps,frozenParams),definedAt})},defaultRegistration=buildRegistration({...defaults}),isDecoratorCall=args=>args.length===0?!1:args.length>=2||typeof args[0]==`function`,applyAsDecorator=(registration,target,propertyKey)=>{if(propertyKey===void 0)pushClassMeta(METADATA.CLASS_CONTRIBUTORS,target,registration);else{let constructor=target.constructor;pushMethodMeta(METADATA.METHOD_CONTRIBUTORS,constructor,String(propertyKey),registration)}},isPlainObject=value=>{let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},mergeParams=override=>{if(override===void 0)return{...defaults};if(typeof override!=`object`||!override||Array.isArray(override)||!isPlainObject(override)){let got=override===null?`null`:Array.isArray(override)?`array`:typeof override==`object`?`instance of ${override.constructor?.name??`unknown class`}`:typeof override;throw TypeError(`defineContextDecorator(${spec.key}): factory call requires a plain object literal, got ${got}. Class instances and built-ins (Map, Date, etc) silently spread to empty objects — call the decorator with a spread object literal instead, e.g. \`MyDecorator({ ...someInstance })\`.`)}return{...defaults,...override}};function decoratorOrFactory(...args){if(isDecoratorCall(args)){let[target,propertyKey]=args;applyAsDecorator(defaultRegistration,target,propertyKey);return}let registration=buildRegistration(mergeParams(args[0]));return(target,propertyKey)=>{applyAsDecorator(registration,target,propertyKey)}}Object.defineProperty(decoratorOrFactory,"name",{value:`ContextDecorator(${spec.key})`,writable:!1,enumerable:!1,configurable:!0});let decorator=Object.assign(decoratorOrFactory,{registration:defaultRegistration,with:params=>({registration:buildRegistration(mergeParams(params))})});return Object.freeze(decorator)}const defineContextDecorator=Object.freeze(Object.assign(defineContextDecoratorImpl,{withParams:()=>spec=>defineContextDecoratorImpl(spec)}));var MissingContributorError=class extends Error{key;dependent;route;dependentDefinedAt;constructor(key,dependent,route,dependentDefinedAt){let where=route?` on route ${route}`:``,declaredAt=formatDeclaredAt(dependentDefinedAt);super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`),this.name=`MissingContributorError`,this.key=key,this.dependent=dependent,this.route=route,this.dependentDefinedAt=dependentDefinedAt}};function formatDeclaredAt(stack){if(!stack)return``;let lines=stack.split(`
11
+ import"./container-CPz0l8-b.mjs";import{METADATA}from"./core/interfaces.mjs";import"./core/logger.mjs";import{c as pushClassMeta,l as pushMethodMeta}from"./metadata-D8hSFaux.mjs";import"./core/decorators.mjs";import"./core/cron.mjs";import"./core/cache.mjs";import"reflect-metadata";const mergeConfig$2=(defaults={},overrides={})=>({...defaults,...overrides}),composeName$2=(base,scope)=>`${base}:${scope}`;function defineModule(options){if(typeof options!=`object`||!options)throw TypeError(`defineModule: options must be an object literal. See architecture.md §21 for the spec shape.`);if(typeof options.name!=`string`||options.name.length===0){let got=typeof options.name==`string`?`""`:typeof options.name;throw TypeError(`defineModule: options.name must be a non-empty string (got ${got}). Module names appear in diagnostics and \`.scoped()\` namespacing — anonymous modules make cycle / missing-dep errors hard to localize.`)}if(typeof options.build!=`function`)throw TypeError(`defineModule(${options.name}): options.build is required and must be a function (got ${typeof options.build}). The build function returns the AppModule shape — register() / routes() / contributors() — wired with the resolved config.`);let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig$2(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return Object.defineProperty(built,"__moduleName",{value:instanceName,enumerable:!1,writable:!1,configurable:!1}),built},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName$2(options.name,scopeName),!0,config),Object.defineProperty(factory,"definition",{value:Object.freeze({...options}),writable:!1,enumerable:!0,configurable:!1}),factory}var ModuleList=class extends Array{mount(module){return this.push(module),this}};function defineModules(...initial){let list=new ModuleList;for(let entry of initial)list.push(entry);return list}var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}},CircuitOpenError=class extends Error{breakerName;constructor(breakerName){super(`Circuit breaker "${breakerName}" is open — request rejected`),this.breakerName=breakerName,this.name=`CircuitOpenError`}},CircuitBreaker=class{name;state=`closed`;failures=0;successes=0;halfOpenAttempts=0;lastFailure;openedAt;failureThreshold;resetTimeout;halfOpenMax;constructor(name,options){this.name=name,this.failureThreshold=options.failureThreshold,this.resetTimeout=options.resetTimeout,this.halfOpenMax=options.halfOpenMax??1}async execute(fn){if(this.maybeTransitionToHalfOpen(),this.state===`open`||this.state===`half_open`&&this.halfOpenAttempts>=this.halfOpenMax)throw new CircuitOpenError(this.name);this.state===`half_open`&&this.halfOpenAttempts++;try{let result=await fn();return this.onSuccess(),result}catch(error){throw this.onFailure(),error}}getState(){return this.maybeTransitionToHalfOpen(),this.state}getStats(){return this.maybeTransitionToHalfOpen(),{failures:this.failures,successes:this.successes,state:this.state,...this.lastFailure?{lastFailure:this.lastFailure}:{}}}reset(){this.state=`closed`,this.failures=0,this.successes=0,this.halfOpenAttempts=0,this.lastFailure=void 0,this.openedAt=void 0}onSuccess(){this.state===`half_open`&&(this.state=`closed`,this.failures=0,this.halfOpenAttempts=0,this.openedAt=void 0),this.successes++}onFailure(){this.failures++,this.lastFailure=new Date,this.state===`half_open`?(this.state=`open`,this.openedAt=Date.now(),this.halfOpenAttempts=0):this.state===`closed`&&this.failures>=this.failureThreshold&&(this.state=`open`,this.openedAt=Date.now())}maybeTransitionToHalfOpen(){this.state===`open`&&this.openedAt!=null&&Date.now()-this.openedAt>=this.resetTimeout&&(this.state=`half_open`,this.halfOpenAttempts=0)}};function defineContextDecoratorImpl(spec){if(typeof spec!=`object`||!spec)throw TypeError(`defineContextDecorator: spec must be an object literal. See architecture.md §20.4 for the spec shape.`);if(typeof spec.key!=`string`||spec.key.length===0){let got=typeof spec.key==`string`?`""`:typeof spec.key;throw TypeError(`defineContextDecorator: spec.key must be a non-empty string (got ${got}). Pick a name that matches a key declared on \`ContextMeta\` (or one of the framework keys).`)}if(typeof spec.resolve!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.resolve is required and must be a function (got ${typeof spec.resolve}). Each contributor needs a resolver that produces the value to write into ctx.set(${JSON.stringify(spec.key)}, …).`);if(spec.onError!==void 0&&typeof spec.onError!=`function`)throw TypeError(`defineContextDecorator(${spec.key}): spec.onError must be a function when provided (got ${typeof spec.onError}).`);if(spec.dependsOn!==void 0&&!Array.isArray(spec.dependsOn))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn must be an array when provided (got ${typeof spec.dependsOn}).`);if(Array.isArray(spec.dependsOn)&&spec.dependsOn.some(dep=>typeof dep!=`string`||dep.length===0))throw TypeError(`defineContextDecorator(${spec.key}): spec.dependsOn entries must be non-empty strings.`);let definedAt=Error().stack,defaults=Object.freeze({...spec.paramDefaults??{}}),sharedDeps=Object.freeze({...spec.deps??{}}),sharedDependsOn=Object.freeze([...spec.dependsOn??[]]),sharedOptional=spec.optional??!1,buildRegistration=params=>{let frozenParams=Object.freeze({...params}),onError=spec.onError?(err,ctx)=>spec.onError(err,ctx,frozenParams):void 0;return Object.freeze({key:spec.key,deps:sharedDeps,dependsOn:sharedDependsOn,optional:sharedOptional,onError,resolve:(ctx,deps)=>spec.resolve(ctx,deps,frozenParams),definedAt})},defaultRegistration=buildRegistration({...defaults}),isDecoratorCall=args=>args.length===0?!1:args.length>=2||typeof args[0]==`function`,applyAsDecorator=(registration,target,propertyKey)=>{if(propertyKey===void 0)pushClassMeta(METADATA.CLASS_CONTRIBUTORS,target,registration);else{let constructor=target.constructor;pushMethodMeta(METADATA.METHOD_CONTRIBUTORS,constructor,String(propertyKey),registration)}},isPlainObject=value=>{let proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null},mergeParams=override=>{if(override===void 0)return{...defaults};if(typeof override!=`object`||!override||Array.isArray(override)||!isPlainObject(override)){let got=override===null?`null`:Array.isArray(override)?`array`:typeof override==`object`?`instance of ${override.constructor?.name??`unknown class`}`:typeof override;throw TypeError(`defineContextDecorator(${spec.key}): factory call requires a plain object literal, got ${got}. Class instances and built-ins (Map, Date, etc) silently spread to empty objects — call the decorator with a spread object literal instead, e.g. \`MyDecorator({ ...someInstance })\`.`)}return{...defaults,...override}};function decoratorOrFactory(...args){if(isDecoratorCall(args)){let[target,propertyKey]=args;applyAsDecorator(defaultRegistration,target,propertyKey);return}let registration=buildRegistration(mergeParams(args[0]));return(target,propertyKey)=>{applyAsDecorator(registration,target,propertyKey)}}Object.defineProperty(decoratorOrFactory,"name",{value:`ContextDecorator(${spec.key})`,writable:!1,enumerable:!1,configurable:!0});let decorator=Object.assign(decoratorOrFactory,{registration:defaultRegistration,with:params=>({registration:buildRegistration(mergeParams(params))})});return Object.freeze(decorator)}const defineContextDecorator=Object.freeze(Object.assign(defineContextDecoratorImpl,{withParams:()=>spec=>defineContextDecoratorImpl(spec)}));var MissingContributorError=class extends Error{key;dependent;route;dependentDefinedAt;constructor(key,dependent,route,dependentDefinedAt){let where=route?` on route ${route}`:``,declaredAt=formatDeclaredAt(dependentDefinedAt);super(`Missing context contributor '${key}' required by '${dependent}'${where}${declaredAt}`),this.name=`MissingContributorError`,this.key=key,this.dependent=dependent,this.route=route,this.dependentDefinedAt=dependentDefinedAt}};function formatDeclaredAt(stack){if(!stack)return``;let lines=stack.split(`
12
12
  `);for(let line of lines){let trimmed=line.trim();if(trimmed.startsWith(`at `)&&!trimmed.includes(`context-decorator.`)&&!trimmed.includes(`context-errors.`))return`\n declared at ${trimmed.replace(/^at /,``)}`}return``}var ContributorCycleError=class extends Error{cycle;route;constructor(cycle,route){let where=route?` on route ${route}`:``;super(`Cycle in context contributors${where}: ${cycle.join(` → `)}`),this.name=`ContributorCycleError`,this.cycle=Object.freeze([...cycle]),this.route=route}},DuplicateContributorError=class extends Error{key;sources;constructor(key,sources){super(`Duplicate context contributor for key '${key}' at the same precedence level. Sources: ${sources.join(`, `)}`),this.name=`DuplicateContributorError`,this.key=key,this.sources=Object.freeze([...sources])}};const PRECEDENCE_ORDER=[`method`,`class`,`module`,`adapter`,`global`];function buildPipeline(sources,options={}){let route=options.route,bySource=new Map;for(let src of PRECEDENCE_ORDER)bySource.set(src,[]);for(let entry of sources)bySource.get(entry.source).push(entry);let winners=new Map;for(let src of PRECEDENCE_ORDER){let rows=bySource.get(src),keysAtThisLevel=new Map;for(let row of rows){let key=row.registration.key,existing=keysAtThisLevel.get(key)??[];existing.push(row),keysAtThisLevel.set(key,existing)}for(let[key,rowsForKey]of keysAtThisLevel){if(rowsForKey.length>1)throw new DuplicateContributorError(key,rowsForKey.map((r,i)=>r.label??`${src}#${i}`));winners.has(key)||winners.set(key,rowsForKey[0])}}let survivors=[...winners.values()].map(r=>r.registration),allKeys=new Set(survivors.map(r=>r.key));for(let reg of survivors)for(let dep of reg.dependsOn)if(!allKeys.has(dep))throw new MissingContributorError(dep,reg.key,route,reg.definedAt);let sorted=topoSort(survivors,route);return Object.freeze({contributors:Object.freeze(sorted),keys:allKeys})}function topoSort(registrations,route){let indegree=new Map,dependents=new Map,byKey=new Map;for(let reg of registrations)indegree.set(reg.key,reg.dependsOn.length),byKey.set(reg.key,reg);for(let reg of registrations)for(let dep of reg.dependsOn){let list=dependents.get(dep)??[];list.push(reg),dependents.set(dep,list)}let queue=[];for(let reg of registrations)indegree.get(reg.key)===0&&queue.push(reg);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.key)??[]){let next=(indegree.get(dependent.key)??0)-1;indegree.set(dependent.key,next),next===0&&queue.push(dependent)}}if(sorted.length!==registrations.length)throw new ContributorCycleError(reconstructCycle$1(registrations.filter(r=>(indegree.get(r.key)??0)>0),byKey),route);return sorted}function reconstructCycle$1(residual,byKey){let residualKeys=new Set(residual.map(r=>r.key)),start=residual[0].key,path=[start],seen=new Set([start]),cursor=start;for(;;){let nextDep=byKey.get(cursor).dependsOn.find(d=>residualKeys.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}async function runContributors(options){let{pipeline,ctx,container}=options;for(let reg of pipeline.contributors)await runOne(reg,ctx,container)}async function runOne(reg,ctx,container){let value;try{let deps=resolveDeps(reg,container);value=await reg.resolve(ctx,deps)}catch(err){if(reg.optional)return;if(reg.onError){let replacement=await reg.onError(err,ctx);if(replacement===void 0)return;ctx.set(reg.key,replacement);return}throw err}ctx.set(reg.key,value)}function resolveDeps(reg,container){let out={};for(let[key,token]of Object.entries(reg.deps))out[key]=container.resolve(token);return out}var DuplicateMountNameError=class extends Error{kind;mountName;constructor(kind,mountName){super(`Duplicate ${kind} name '${mountName}' — every ${kind} must declare a unique name`),this.name=`DuplicateMountNameError`,this.kind=kind,this.mountName=mountName}},MissingMountDepError=class extends Error{kind;missing;dependent;constructor(kind,missing,dependent){super(`Missing ${kind} dependency '${missing}' required by '${dependent}' — is the ${kind} installed and named correctly?`),this.name=`MissingMountDepError`,this.kind=kind,this.missing=missing,this.dependent=dependent}},MountCycleError=class extends Error{kind;cycle;constructor(kind,cycle){super(`Cycle in ${kind} dependsOn declarations: ${cycle.join(` → `)}`),this.name=`MountCycleError`,this.kind=kind,this.cycle=Object.freeze([...cycle])}};function mountSort(items,kind){let byName=new Map;for(let item of items){if(byName.has(item.name))throw new DuplicateMountNameError(kind,item.name);byName.set(item.name,item)}let indegree=new Map,dependents=new Map;for(let item of items)indegree.set(item.name,item.dependsOn?.length??0);for(let item of items)for(let dep of item.dependsOn??[]){if(!byName.has(dep))throw new MissingMountDepError(kind,dep,item.name);let list=dependents.get(dep)??[];list.push(item),dependents.set(dep,list)}let queue=[];for(let item of items)indegree.get(item.name)===0&&queue.push(item);let sorted=[];for(;queue.length>0;){let node=queue.shift();sorted.push(node);for(let dependent of dependents.get(node.name)??[]){let next=(indegree.get(dependent.name)??0)-1;indegree.set(dependent.name,next),next===0&&queue.push(dependent)}}if(sorted.length!==items.length)throw new MountCycleError(kind,reconstructCycle(items.filter(it=>(indegree.get(it.name)??0)>0),byName));return sorted}function reconstructCycle(residual,byName){let residualNames=new Set(residual.map(r=>r.name)),start=residual[0].name,path=[start],seen=new Set([start]),cursor=start;for(;;){let nextDep=byName.get(cursor).dependsOn?.find(d=>residualNames.has(d));if(nextDep===void 0)break;if(seen.has(nextDep)){let cycleStart=path.indexOf(nextDep);return[...path.slice(cycleStart),nextDep]}path.push(nextDep),seen.add(nextDep),cursor=nextDep}return path}const mergeConfig$1=(defaults={},overrides={})=>({...defaults,...overrides}),composeName$1=(base,scope)=>`${base}:${scope}`;function definePlugin(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig$1(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner,ensureInner=async container=>{if(inner)return inner;let deps=(opts.inject??[]).map(tok=>container.resolve(tok));return inner=buildSync(instanceName,!1,await opts.useFactory(...deps)),inner};return{name:instanceName,async onReady(container){let built=await ensureInner(container);built.register?.(container),await built.onReady?.(container)},async shutdown(){await inner?.shutdown?.()}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName$1(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}const mergeConfig=(defaults={},overrides={})=>({...defaults,...overrides}),composeName=(base,scope)=>`${base}:${scope}`;function defineAdapter(options){let buildSync=(instanceName,scoped,overrides)=>{let config=mergeConfig(options.defaults,overrides),built=options.build(config,{name:instanceName,scoped});return built.name=instanceName,built},buildAsync=(instanceName,opts)=>{let inner;return{name:instanceName,async beforeStart(ctx){let deps=(opts.inject??[]).map(tok=>ctx.container.resolve(tok));inner=buildSync(instanceName,!1,await opts.useFactory(...deps)),await inner.beforeStart?.(ctx)},async afterStart(ctx){await inner?.afterStart?.(ctx)},async shutdown(){await inner?.shutdown?.()},async onHealthCheck(){return await inner?.onHealthCheck?.()??{name:instanceName,status:`up`}}}},factory=(config=>buildSync(options.name,!1,config));return factory.scoped=(scopeName,config)=>buildSync(composeName(options.name,scopeName),!0,config),factory.async=opts=>buildAsync(options.name,opts),Object.defineProperty(factory,"definition",{value:Object.freeze({...options})}),factory}function defineAugmentation(name,meta){}export{ModuleList as _,MissingMountDepError as a,runContributors as c,DuplicateContributorError as d,MissingContributorError as f,MutableModuleRegistry as g,CircuitOpenError as h,DuplicateMountNameError as i,buildPipeline as l,CircuitBreaker as m,defineAdapter as n,MountCycleError as o,defineContextDecorator as p,definePlugin as r,mountSort as s,defineAugmentation as t,ContributorCycleError as u,defineModules as v,defineModule as y};
13
- //# sourceMappingURL=core-BK8Rpn_4.mjs.map
13
+ //# sourceMappingURL=core-C_gfh7JQ.mjs.map