@decaf-ts/for-nest 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/for-nest.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e,t;e=this,t=function(e,t,r,o,a,i,s,n,c,p,d,l,u,h,m,f,y,g,_){"use strict";function b(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var A=b(m);const P="swagger",E={API_OPERATION:P+"/apiOperation",API_RESPONSE:P+"/apiResponse",API_PRODUCES:P+"/apiProduces",API_CONSUMES:P+"/apiConsumes",API_TAGS:P+"/apiUseTags",API_CALLBACKS:P+"/apiCallbacks",API_PARAMETERS:P+"/apiParameters",API_HEADERS:P+"/apiHeaders",API_MODEL_PROPERTIES:P+"/apiModelProperties",API_MODEL_PROPERTIES_ARRAY:P+"/apiModelPropertiesArray",API_SECURITY:P+"/apiSecurity",API_EXCLUDE_ENDPOINT:P+"/apiExcludeEndpoint",API_EXCLUDE_CONTROLLER:P+"/apiExcludeController",API_EXTRA_MODELS:P+"/apiExtraModels",API_EXTENSION:P+"/apiExtension",API_SCHEMA:P+"/apiSchema",API_DEFAULT_GETTER:P+"/apiDefaultGetter",API_LINK:P+"/apiLink"},v=e=>void 0===e;function O(e){if("function"==typeof e)return O(e());if(Array.isArray(e))return e;if("object"!=typeof e)return[];const t=Object.values(e).filter(e=>"number"==typeof e).map(e=>e.toString());return Object.keys(e).filter(e=>!t.includes(e)).map(t=>e[t])}function R(e){return e.filter(s.isString).length>0?"string":"number"}function w(e,t,r=!0){return(o,a)=>{const i=Reflect.getMetadata(E.API_MODEL_PROPERTIES_ARRAY,o)||[],n=":"+a;i.includes(n)||Reflect.defineMetadata(E.API_MODEL_PROPERTIES_ARRAY,[...i,":"+a],o);const c=Reflect.getMetadata(e,o,a);if(c){const i=s.pickBy(t,s.negate(v)),n=r?{...c,...i}:{...i,...c};Reflect.defineMetadata(e,n,o,a)}else{const r=o?.constructor?._OPENAPI_METADATA_FACTORY?.()[a]?.type??Reflect.getMetadata("design:type",o,a);Reflect.defineMetadata(e,{type:r,required:!1,...s.pickBy(t,s.negate(v))},o,a)}}}function S(e={}){return D(e)}function D(e={},t=!0){const[r,o]=((e,t)=>{if(!e)return[e,t];if(t)return[e,t];const r=s.isArray(e);return[r?e[0]:e,r]})(e.type,e.isArray);if((a=e={...e,type:r,isArray:o}).isArray&&"enum"in a&&void 0!==a.enum){e.type="array";const t=O(e.enum);e.items={type:R(t),enum:t},delete e.enum}else if("enum"in e&&void 0!==e.enum){const t=O(e.enum);e.enum=t,e.type=R(t)}var a;return Array.isArray(e.type)&&(e.type="array",e.items={type:"array",items:{type:e.type[0]}}),w(E.API_MODEL_PROPERTIES,e,t)}function C(e,r){const{handler:o,args:a}=t.Metadata.get(e,c.OperationKeys.REFLECT+c.OperationKeys.BLOCK)||{};return!!o&&(o(...a,r)??!1)}function T(e,r,a){const i={GET:[c.OperationKeys.READ,o.Get],POST:[c.OperationKeys.CREATE,o.Post],PUT:[c.OperationKeys.UPDATE,o.Put],PATCH:[c.OperationKeys.UPDATE,o.Patch],DELETE:[c.OperationKeys.DELETE,o.Delete]},[s,p]=i[r];return C(e,s)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))}function x(e=[]){const t=e.map(e=>n.ApiParam({name:e.name,description:e.description??"Path parameter: "+e.name,required:e.required??!0,type:e.type??String}));return o.applyDecorators(...t)}const M=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest().body,a=t.getClass(),i=a.class;if(!i)throw new o.InternalServerErrorException(`ModelConstructor not found on controller ${a.name}. Ensure the controller was created via FromModelController.`);return r?Array.isArray(r)?r.map(e=>new i(e)):new i(r):r}),k=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest(),o=r?.params??{},a=e??Object.keys(o),i=a.map(e=>o[e]);return{raw:o,valuesInOrder:i,keysInOrder:a}});function I(e=[]){const t=e.map(e=>e.name);return k(t)}const $=o.createParamDecorator((e,t)=>{const r={...t.switchToHttp().getRequest().query??{}};if(void 0!==r.limit){const e=Number(r.limit);Number.isNaN(e)||(r.limit=e)}if(void 0!==r.offset){const e=Number(r.offset);Number.isNaN(e)||(r.offset=e)}if(void 0!==r.bookmark){const e=Number(r.bookmark);r.bookmark=Number.isNaN(e)?r.bookmark:e}return r});function q(e){const t={GET:o.Get,POST:o.Post,PUT:o.Put,PATCH:o.Patch,DELETE:o.Delete}[e];if(!t)throw Error(`Unsupported HTTP verb "${e}". No NestJS decorator mapping was found.`);return t}const F="DecafModuleOptions",N="DecafAdapter",j="DecafRoute",L=Symbol("DecafHandlers"),B=Symbol("DecafAdapterForOptions"),K=Symbol("AUTH_HANDLER"),U="auth:meta",W=Symbol("decaf:context");function H(t){const r=t?"string"==typeof t?t:t.name:void 0,a=[n.ApiBearerAuth(),o.UseInterceptors(e.AuthInterceptor)];return r&&a.push(o.SetMetadata(U,r)),o.applyDecorators(...a)}e.AuthInterceptor=class{constructor(e,t){this.reflector=e,this.authHandler=t}async intercept(e,t){const r=l.Logging.for(this).for(this.intercept),o=this.reflector.get(U,e.getHandler())??this.reflector.get(U,e.getClass());return r.verbose("Intercepted request"+(o?" for "+o:"")),this.authHandler?await this.authHandler.authorize(e,o):r.debug("No auth handler/model"),t.handle()}},e.AuthInterceptor=p.__decorate([o.Injectable(),p.__param(1,o.Optional()),p.__param(1,o.Inject(K)),p.__metadata("design:paramtypes",[d.Reflector,Object])],e.AuthInterceptor);class G{parseRequest(e){const t=e.headers.authorization?.split(" ")[1];return t}async authorize(e,r){const o=e.switchToHttp().getRequest(),s=this.parseRequest(o);if(!s)throw new i.AuthorizationError("Unauthenticated");if(!t.Metadata.get(a.Model.get(r),i.PersistenceKeys.AUTH_ROLE).includes(s))throw new i.AuthorizationError("Missing role: "+s)}}var z;e.DecafRequestContext=class{constructor(e){this.req=e,this.uuid=i.UUID.instance.generate()}get request(){return this.req}put(e){let t;try{t=this.ctx.get("overrides")}catch(e){t={}}this._ctx=this.ctx.accumulate({overrides:Object.assign(t,e)})}applyCtx(e){if(this._ctx)throw new c.InternalError("Trying to overwrite context");this._ctx=e}get ctx(){if(!this._ctx)throw new c.InternalError("Context not initialized for request");return this._ctx}},e.DecafRequestContext=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(d.REQUEST)),p.__metadata("design:paramtypes",[Request])],e.DecafRequestContext),e.DecafHandlerExecutor=z=class{constructor(e,t){this.handlers=e,this.context=t}async exec(e,t){l.Logging.for(z.name).for(this.exec).debug(`CONTEXT ${this.context.uuid} running ${this.handlers.length} handlers for request ${e.method} ${e.url}`);for(const r of this.handlers)await r.handle(this.context,e,t)}},e.DecafHandlerExecutor=z=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(L)),p.__metadata("design:paramtypes",[Array,e.DecafRequestContext])],e.DecafHandlerExecutor),e.DecafResponseInterceptor=class{constructor(e){this.ctx=e}intercept(e,t){let r=e.switchToHttp().getResponse();return t.handle().pipe(u.tap(e=>{r=this.ctx.ctx.toResponse(r)}))}},e.DecafResponseInterceptor=p.__decorate([o.Injectable(),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.DecafResponseInterceptor);const Q=e=>({name:e,description:e+" parameter for the query",required:!0,type:String});function V(e,t,r,a=!1){const s=q(r),c=(e=>e.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1)))(t).map(Q),p=[];return"GET"===r&&a&&p.push(n.ApiQuery({name:"direction",required:!1,enum:i.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!1,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!1,description:"offset or bookmark when applicable"})),{method:[s(t),...c.map(n.ApiParam),...p,n.ApiOperation({summary:`Retrieve records using according to "${e}".`}),n.ApiOkResponse({description:"Result successfully retrieved."}),n.ApiNoContentResponse({description:"No content returned by the method."})],params:[I(c),o.Query()]}}function Y(e,t,r,o){const a=e?.prototype??e;o.method.forEach(e=>e(a,t,r)),o.params?.forEach((e,r)=>e(a,t,r))}function J(e,t,...r){if(e instanceof i.ModelService)return"function"==typeof e[t]?e[t](...r):e.statement(t,...r);if("function"==typeof e[t])return e[t](...r);throw Error(`Persistence method "${t}" not found on ${e?.constructor?.name}`)}function X(e){return async function(t,r){const o=this.log.for(e);try{o.debug(`Invoking persistence method "${e}" given parameters: ${JSON.stringify(t.valuesInOrder)}`);const{direction:a,limit:i,offset:s}=r;return await J(this.persistence(),e,...t.valuesInOrder,a,i,s)}catch(t){throw o.error(`Custom query "${e}" failed`,t),t}}}function Z(e,t,r){return Object.defineProperty(e.prototype||e,t,{value:r,writable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)}class ee extends i.Service{constructor(e,t){super(),this.clientContext=e}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let s;e=e.filter(e=>void 0!==e),o&&(o.headers||o.ip)&&(s=o,o={});const n=i.ContextualLoggedClass.logCtx.call(this,t,o||{},r,...e,a);return this.bindLoggerToRequest(n,s)}bindLoggerToRequest(e,t){const r=this;function o(e,t){return e.log=((e,t)=>{const o=(e=>{if(!e)return;const t=e.headers,r=re(t?.["x-forwarded-for"])??re(t?.["x-real-ip"])??re(t?.["X-Forwarded-For"])??re(t?.["X-Real-IP"]);if(r)return r;if("string"==typeof e.ip&&e.ip.length)return e.ip;const o=e.socket||e.connection;return o&&"string"==typeof o.remoteAddress&&o.remoteAddress.length?o.remoteAddress:void 0})(t??r.clientContext.request);if(!o)return e;const a={ip:o};return e.for(a)})(e.log,t),e}return(e=>"object"==typeof e&&null!==e&&"function"==typeof e.then)(e)?e.then(e=>o(e,t)):o(e,t)}}class te extends ee{persistence(e){if(!this._persistence)try{this._persistence=i.Service.get(this.class)}catch(e){try{this._persistence=i.ModelService.getService(this.class)}catch(e){this._persistence=i.Repository.forModel(this.class)}}const t=this.clientContext.request[B]||{};return e&&this.clientContext.put(t),e?this._persistence instanceof i.Repository?this._persistence.override(t):this._persistence.for(t):this._persistence}constructor(e,t){super(e,t)}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let s;o&&(o.headers||o.ip)&&(s=o,o={});try{o=a.get("overrides")}catch(e){}const n=this.persistence(a);let c,p;return n instanceof i.ModelService?c=n.repo._adapter:n instanceof i.Repository?c=n._adapter:n.context&&(c=n),r?c.logCtx(e,t,!0,o).then(e=>this.bindLoggerToRequest(e,s)):(p=c.logCtx(e,t,!1,o),this.bindLoggerToRequest(p,s))}}function re(e){if(e)return(Array.isArray(e)?e[0]:e).split(",").map(e=>e.trim()).filter(Boolean)[0]}const oe=new Map;function ae(e,r){if(!i.TransactionOperationKeys.includes(e))return r;const o=(e=>(oe.has(e)||oe.set(e,new WeakMap),oe.get(e)))(e),s=o.get(r);if(s)return s;const n=[c.OperationKeys.UPDATE,c.BulkCrudOperationKeys.UPDATE_ALL].includes(e);class p{}o.set(r,p),Object.defineProperty(p,"name",{value:`${l.toPascalCase(r.name)}${l.toPascalCase(e)}DTO`});const d=(()=>{try{return a.Model.pk(r)}catch{return}})(),u=d?a.Model.pkProps(r):void 0,h=d?Reflect.getMetadata("design:type",r.prototype,d):void 0,m=h===Number||h===BigInt,f=!!u?.generated||!!d&&(a.Model.generatedBySequence(r,d)||ne(r,d)||m),y=Array.from(new Set(t.Metadata.properties(r)||[])),g=new Set(a.Model.relations(r)||[]),_=[];for(const e of y)e&&(g.has(e)||e===d&&!n&&f||e!==d&&ne(r,e)||_.push(e));for(const e of _){const t=ce(r,e),o=!!t?.[a.ValidationKeys.REQUIRED],i=pe(r,e)??Reflect.getMetadata("design:type",r.prototype,e),s={required:o};i&&(s.type=i),S(s)(p.prototype,e);const n=Reflect.getMetadata("design:type",r.prototype,e)??i;void 0!==n&&Reflect.defineMetadata("design:type",n,p.prototype,e),Object.defineProperty(p.prototype,e,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}for(const o of g){const i=t.Metadata.relations(r,o);if(!i)throw new c.InternalError(`Metadata for relation ${o} not found`);let s=i.class;if("function"!=typeof s||s.name||(s=s()),!s||"function"!=typeof s)throw new c.InternalError(`Type for relation ${o} not found`);if(!a.Model.get(s.name))continue;const d=t.Metadata.validationFor(r,o),l=!!d?.[a.ValidationKeys.LIST],u=!!d?.[a.ValidationKeys.REQUIRED],h=ae(e,s);n?se(p,o,s,h,l,u):ie(p,o,h,l,u)}return p}function ie(e,t,r,o,a){S({type:r,required:a,isArray:o})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:r,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function se(e,t,r,o,i,s){const n=Reflect.getMetadata(E.API_EXTRA_MODELS,e)||[];n.includes(o)||Reflect.defineMetadata(E.API_EXTRA_MODELS,[...n,o],e);const c="#/components/schemas/"+o.name,p=(e=>{try{const t=a.Model.pkProps(e),r=t?.type;return r===Number||r===BigInt?"integer":"string"}catch{return"string"}})(r),d=[{$ref:c},{type:p}];S(i?{type:"array",required:s,oneOf:d}:{type:Object,required:s,oneOf:d})(e.prototype,t),Reflect.defineMetadata("design:type",i?Array:Object,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ne(e,t){let r=e;for(;r&&r!==Object&&r!==Function;){if(a.Model.generated(r,t))return!0;r=Object.getPrototypeOf(r)}return!1}function ce(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.validationFor(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}function pe(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.type(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}i.Adapter.transformerFor=(e=>{const r="string"==typeof e?e:e.alias;return t.Metadata.innerGet(Symbol.for("transformers"),r)}).bind(i.Adapter),i.Adapter.flavoursToTransform=(()=>{const e=t.Metadata.innerGet(Symbol.for("transformers"));if(e)return Object.keys(e)}).bind(i.Adapter),i.Context.prototype.toResponse=function(e){const t=this.pending();return t&&e.header("x-pending-task",JSON.stringify(t)),e};const de=a.ModelBuilder.prototype;if(de.decorateClass||(de.decorateClass=function(e){return this._classDecorators||(this._classDecorators=[]),this._classDecorators.push(e),this}),de.Auth=function(e){return this.decorateClass(H(e))},!de.__hasClassDecoratorSupport){const e=de.build;de.build=function(){let t=e.call(this);const r=this._classDecorators;if(r?.length)for(const e of r){const r=e(t);r&&(t=r)}return t},de.__hasClassDecoratorSupport=!0}class le{static{this.log=l.Logging.for(le.name)}static getPersistence(e){try{return i.Service.get(e)}catch(t){try{return i.ModelService.getService(e)}catch(t){return i.Repository.forModel(e)}}}static createQueryRoutesFromRepository(e,r=i.PersistenceKeys.QUERY){const o=le.log.for(le.createQueryRoutesFromRepository),a=e instanceof i.ModelService?e.repo:e,s=a.class,n=t.Metadata.get(a.constructor,t.Metadata.key(i.PersistenceKeys.QUERY))??{},c=t.Metadata.get(e.constructor,t.Metadata.key(j))??{};class p extends te{get class(){throw Error("Method not implemented.")}constructor(e,t){super(e,t)}}for(const[e,t]of Object.entries(c)){const r=[t.path.replace(/^\/+|\/+$/g,"")].filter(e=>e&&e.trim()).join("/"),a=X(e);if(!a){const t=`Invalid or missing handler for model ${s.name} on decorated method ${e}`;throw o.error(t),Error(t)}const i=Z(p,e,a);i&&Y(p,e,i,V(e,r,t.httpMethod))}for(const[e,t]of Object.entries(n)){const o=[r,e,...(t.fields??[]).map(e=>":"+e)].filter(e=>e&&e.trim()).join("/"),a=Z(p,e,X(e));a&&Y(p,e,a,V(e,o,"GET",!0))}return p}static create(t){const r=le.log.for(le.create),s=a.Model.tableName(t),d=l.toKebabCase(s),u=t.name,h=le.getPersistence(t),{description:m,getPK:f,apiProperties:y,path:g}=le.getRouteParametersFromModel(t);r.debug("Creating controller for model: "+u);const _=le.createQueryRoutesFromRepository(h);let b=class extends _{static get class(){return t}get class(){return t}constructor(e){super(e),this.pk=a.Model.pk(t),r.info(`Registering dynamic controller for model: ${this.class.name} route: /${d}`)}async listBy(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.persistence(r).listBy(e,t.direction,r)}async paginateBy(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.persistence(r).paginateBy(e,t.direction,t,r)}async find(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.FIND,!0)).for(this.find),o=t.direction??i.OrderDirection.ASC;return J(this.persistence(r),this.find.name,e,o,r)}async page(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.PAGE,!0)).for(this.page),{direction:o=i.OrderDirection.ASC,limit:a,offset:s,bookmark:n}=t,c={offset:s??1,limit:a??10,bookmark:n};return J(this.persistence(r),this.page.name,e,o,c,r)}async findOneBy(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.persistence(r).findOneBy(e,t,r)}async findBy(e,t,r){const{ctx:o}=(await this.logCtx([],i.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.persistence(o).for(o.toOverrides()).findBy(e,t,o)}async statement(e,t,r){const{ctx:o}=(await this.logCtx([],i.PersistenceKeys.STATEMENT,!0)).for(this.statement),{direction:a,offset:s,limit:n,bookmark:c}=r,p=(t=t.map(e=>("string"==typeof e?parseInt(e):e)||e)).length>1?t[1]:void 0,d=a??p;switch(d&&t.length>1&&(t[1]=d),e){case i.PreparedStatementKeys.FIND:case i.PreparedStatementKeys.FIND_BY:break;case i.PreparedStatementKeys.LIST_BY:t.push(a);break;case i.PreparedStatementKeys.PAGE:case i.PreparedStatementKeys.PAGE_BY:t=[t[0],d,{limit:n,offset:s,bookmark:c}];case i.PreparedStatementKeys.FIND_ONE_BY:case i.PreparedStatementKeys.COUNT_OF:case i.PreparedStatementKeys.MAX_OF:case i.PreparedStatementKeys.MIN_OF:case i.PreparedStatementKeys.AVG_OF:case i.PreparedStatementKeys.SUM_OF:case i.PreparedStatementKeys.DISTINCT_OF:case i.PreparedStatementKeys.GROUP_OF:}return this.persistence(o).statement(e,...t,o)}async createAll(e,r){const{ctx:o,log:a}=(await this.logCtx([],c.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);let i;a.verbose("creating new "+u);try{i=await this.persistence(o).createAll(e.map(e=>new t(e)),o)}catch(e){throw a.error("Failed to create new "+u,e),e}return a.info(`created new ${u} with id ${i[this.pk]}`),o.toResponse(r),i}async create(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.CREATE,!0)).for(this.create);let a;o.verbose("creating new "+u);try{const t=this.persistence(r);a=await t.create(e,r)}catch(e){throw o.error("Failed to create new "+u,e),e}return o.info(`created new ${u} with id ${a[this.pk]}`),r.toResponse(t),a}async readAll(e){const{ctx:t,log:r}=(await this.logCtx([],c.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);let o;try{r.debug(`reading ${e.length} ${u}: ${e}`);const a=this.persistence(t);o=await a.readAll(e,t)}catch(t){throw r.error(`Failed to ${u} with id ${e}`,t),t}return r.info(`read ${o.length} ${u}`),o}async read(e){const{ctx:t,log:r}=(await this.logCtx([],c.OperationKeys.READ,!0)).for(this.read),o=f(...e.valuesInOrder);if(void 0===o)throw new c.ValidationError(`No ${this.pk} provided`);let a;try{r.debug(`reading ${u} with ${this.pk} ${o}`);const e=this.persistence(t);a=await e.read(o,t)}catch(e){throw r.error(`Failed to read ${u} with id ${o}`,e),e}return r.info(`read ${u} with id ${a[this.pk]}`),a}async updateAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);let a;try{o.info(`updating ${e.length} ${u}`),a=await this.persistence(r).updateAll(e,r)}catch(e){throw o.error(e),e}return r.toResponse(t),a}async update(e,r,o){const{ctx:a,log:i}=(await this.logCtx([],c.OperationKeys.UPDATE,!0)).for(this.update),s=f(...e.valuesInOrder);if(void 0===s)throw new c.ValidationError(`No ${this.pk} provided`);let n;try{i.info(`updating ${u} with ${this.pk} ${s}`);const e=JSON.parse(JSON.stringify(r)),o=this.persistence(a);n=await o.update(new t({...e,[this.pk]:s}),a)}catch(e){throw i.error(e),e}return a.toResponse(o),n}async deleteAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);let a;try{o.debug(`deleting ${e.length} ${u}: ${e}`),a=await this.persistence(r).deleteAll(e,r)}catch(t){throw o.error(`Failed to delete ${u} with id ${e}`,t),t}return o.info(`deleted ${a.length} ${u}`),r.toResponse(t),a}async delete(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.DELETE,!0)).for(this.delete),a=f(...e.valuesInOrder);if(void 0===a)throw new c.ValidationError(`No ${this.pk} provided`);let i;try{o.debug(`deleting ${u} with ${this.pk} ${a}`),i=await this.persistence(r).delete(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${u} with id ${a}`),r.toResponse(t),i}};return p.__decorate([T(t,"GET","listBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection}),n.ApiOkResponse({description:u+" listed successfully."}),p.__param(0,o.Param("key")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"listBy",null),p.__decorate([T(t,"GET","paginateBy/:key/:page"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiParam({name:"page",description:"the page to retrieve or the bookmark"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection,description:"the sort order"}),n.ApiQuery({name:"limit",required:!0,description:"the page size"}),n.ApiQuery({name:"offset",description:"the bookmark when necessary"}),n.ApiOkResponse({description:u+" listed paginated."}),p.__param(0,o.Param("key")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"paginateBy",null),p.__decorate([T(t,"GET","find/:value"),n.ApiOperation({summary:`Find ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:i.OrderDirection,description:"the sort order for the matching results"}),n.ApiOkResponse({description:u+" records matching the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"find",null),p.__decorate([T(t,"GET","page/:value"),n.ApiOperation({summary:`Page ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:i.OrderDirection,description:"the sort order for the paged results"}),n.ApiQuery({name:"limit",required:!1,description:"page size"}),n.ApiQuery({name:"offset",required:!1,description:"page number"}),n.ApiQuery({name:"bookmark",required:!1,description:"bookmark for cursor pagination"}),n.ApiOkResponse({description:u+" records paged by the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"page",null),p.__decorate([T(t,"GET","findOneBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"findOneBy",null),p.__decorate([T(t,"GET","findBy/:key/:value"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to compare"}),n.ApiParam({name:"value",description:"the value to match"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection,description:"the sort order when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__param(2,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"findBy",null),p.__decorate([T(t,"GET","statement/:method/*args"),n.ApiOperation({summary:`Executes a prepared statement on ${u}.`}),n.ApiParam({name:"method",description:"the prepared statement to execute"}),n.ApiParam({name:"args",description:"concatenated list of arguments the prepared statement can accept"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!0,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!0,description:"offset or bookmark when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("method")),p.__param(1,o.Param("args")),p.__param(2,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Array,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"statement",null),p.__decorate([T(t,"POST","bulk"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,M()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"createAll",null),p.__decorate([T(t,"POST"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,type:ae(c.OperationKeys.CREATE,t)}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,M()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"create",null),p.__decorate([T(t,"GET","bulk"),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array]),p.__metadata("design:returntype",Promise)],b.prototype,"readAll",null),p.__decorate([T(t,"GET",g),x(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object]),p.__metadata("design:returntype",Promise)],b.prototype,"read",null),p.__decorate([T(t,"PUT","bulk"),x(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,schema:{type:"array",$ref:n.getSchemaPath(ae(c.OperationKeys.UPDATE,t))}}),n.ApiOkResponse({description:u+" updated successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,M()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"updateAll",null),p.__decorate([T(t,"PUT",g),x(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,type:ae(c.OperationKeys.UPDATE,t)}),n.ApiOkResponse({description:u+" updated successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,I(y)),p.__param(1,M()),p.__param(2,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"update",null),p.__decorate([T(t,"DELETE","bulk"),x(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"deleteAll",null),p.__decorate([T(t,"DELETE",g),x(y),n.ApiOperation({summary:`Delete a ${u} record by id.`}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],b.prototype,"delete",null),b=p.__decorate([o.Controller(d),n.ApiTags(u),n.ApiExtraModels(t),H(t),p.__metadata("design:paramtypes",[e.DecafRequestContext])],b),b}static getRouteParametersFromModel(e){const r=a.Model.pk(e),o=t.Metadata.get(e,t.Metadata.key(c.DBKeys.COMPOSED,r)),i=o?.args??[],s=Array.isArray(i)&&i.length>0?Array.from(new Set([...i])):Array.from(new Set([r])),n=t.Metadata.description(e);return{path:":"+s.join("/:"),description:n,apiProperties:s.map(r=>({name:r,description:t.Metadata.description(e,r),required:!0,type:String})),getPK:(...e)=>o?.separator?e.join(o.separator):e.join("")}}}function ue(e){var t;let r=class{static{t=this}static{this.log=l.Logging.for(t.name).for(e)}static createModelServices(e){return e.map(e=>({provide:e.name+"Service",useFactory:()=>i.ModelService.forModel(e)}))}static forRoot(e,r={}){const o=this.log.for(this.forRoot);o.info("Generating controllers for flavour...");const a=i.Adapter.models(e);let s=[];r.autoServices&&(o.info("Auto-services enabled. Initializing service generation."),s=this.createModelServices(a),o.info(`Auto-services completed. ${s.length} services initialized.`));const n=a.map(le.create);return o.info(`Generated ${n.length} controllers`),{module:t,controllers:n,providers:[...s]}}};return r=t=p.__decorate([o.Module({})],r),Object.assign(r,"name",{value:"DecafModule"+e}),r}t.Decoration.for(r.InjectablesKeys.INJECTABLE).extend({decorator:(e,t)=>(t=t||("object"==typeof e?Object.assign(e,r.DefaultInjectablesConfig):r.DefaultInjectablesConfig),o.Injectable({scope:t.singleton?o.Scope.DEFAULT:o.Scope.REQUEST,durable:!t.singleton||void 0}))}).apply(),t.Decoration.for(r.InjectablesKeys.INJECT).extend({decorator:(e,t)=>(t,r,a)=>o.Inject(e||t)(t,r,a)}).apply(),t.Decoration.for(a.ValidationKeys.REQUIRED).extend(S({required:!0})).apply(),t.Decoration.for(a.ValidationKeys.MAX).extend({decorator:e=>S({maximum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN).extend({decorator:e=>S({minimum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MAX_LENGTH).extend({decorator:e=>S({maxLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN_LENGTH).extend({decorator:e=>S({minLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.TYPE).extend({decorator:e=>(t,r)=>("function"!=typeof(e=Array.isArray(e)?e[0]:e)||e.name||(e=e()),S({type:e,required:!1})(t,r))}).apply(),t.Decoration.for(a.ValidationKeys.DATE).extend({decorator:e=>S({type:String,format:"date-time",required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.ENUM).extend({decorator:e=>S({enum:Array.isArray(e)?e:Object.values(e),required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.PATTERN).extend({decorator:e=>S({pattern:"string"==typeof e?e:e.source,required:!1})}).apply(),t.Decoration.for(i.PersistenceKeys.COLUMN).extend({decorator:e=>S({name:e,required:!1})}).apply(),t.Decoration.for(t.DecorationKeys.DESCRIPTION).extend({decorator:e=>S({description:e,required:!1})}).apply(),t.Decoration.for(i.PersistenceKeys.AUTH).extend({decorator:H}).apply();class he extends i.ForbiddenError{constructor(e){super(e,he.name)}}class me extends c.BaseError{constructor(e){super(me.name,e,429)}}e.DecafExceptionFilter=class{catch(e,t){const r=t.switchToHttp(),a=r.getResponse(),s=r.getRequest(),n="production"===l.LoggedEnvironment.env;let p;e instanceof o.NotFoundException||e instanceof i.UnsupportedError?p=(e=new o.NotAcceptableException(e.message)).getStatus():e instanceof c.BaseError||(e=429===e.status?new me(e.message):new c.InternalError(e.message)),a.status(e.code||p).json({status:e.code||p,error:n?e.name:e.message,timestamp:(new Date).toISOString(),path:s.url,method:s.method})}},e.DecafExceptionFilter=p.__decorate([o.Catch()],e.DecafExceptionFilter);const fe={path:"docs",auth:{type:"http",scheme:"bearer",bearerFormat:"JWT",name:"Authorization",description:"Enter JWT token",in:"header"},topbarBgColor:"#000000"};class ye{constructor(e){this.options={...e}}customCSS(){let e="";return this.options.topbarIconPath&&(e+=`.topbar-wrapper { content: url('data:image/png;base64,${this.b64(this.options.topbarIconPath)}'); width: 200px; height: auto; }\n`),e+`\n .topbar-wrapper svg { visibility: hidden; }\n .swagger-ui .topbar { background-color: ${this.options.topbarBgColor||fe.topbarBgColor}; }\n `}getCustomOptions(){const e={};return this.options.faviconPath&&(e.customfavIcon=this.b64(this.options.faviconPath,!0)),{customSiteTitle:this.options.title,...e,customCss:this.customCSS(),swaggerOptions:{persistAuthorization:this.options.persistAuthorization}}}b64(e,t=!1){const r=A.join(this.options.assetsPath||"",e),o=h.readFileSync(r,{encoding:"base64"});return t?"data:image/png;base64,"+o:o}}class ge{constructor(e,t){this.app=e,this.options=t}createDocument(){const e=this.options.path?this.options.description+""+`<br><br><a href="${this.options.openApiJsonPath}">OpenAPI JSON Spec</a> | `+`<a href="${this.options.openApiYamlPath}">OpenAPI YAML Spec</a>`:this.options.description,t=(new n.DocumentBuilder).setTitle(this.options.title).setDescription(e).setVersion(this.options.version||"0.0.1").addBearerAuth(this.options.auth||fe.auth).build();return n.SwaggerModule.createDocument(this.app,t,{extraModels:this.options.extraModels||[]})}registerOpenApiRoute(e,t,r){if(!e)return;const o=this.app.getHttpAdapter();e=e.startsWith("/")?e:"/"+e,o.get(e,(e,a)=>{o.reply(a,r(),200,{"Content-Type":t})})}setupSwagger(){const e=this.createDocument(),t=new ye({title:this.options.title,path:this.options.path||fe.path,persistAuthorization:this.options.persistAuthorization??!0,assetsPath:this.options.assetsPath,faviconPath:this.options.faviconFilePath,topbarIconPath:this.options.topbarIconFilePath,topbarBgColor:this.options.topbarBgColor});n.SwaggerModule.setup(this.options.path||fe.path,this.app,e,{...t.getCustomOptions(),jsonDocumentUrl:this.options.openApiJsonPath?""+this.options.openApiJsonPath:void 0,yamlDocumentUrl:this.options.openApiYamlPath?""+this.options.openApiYamlPath:void 0}),this.registerOpenApiRoute(this.options.openApiJsonPath,"application/json",()=>e),this.registerOpenApiRoute(this.options.openApiYamlPath,"application/x-yaml",()=>f.stringify(e))}}var _e,be;function Ae(e){return r=>(t.Metadata.set("transformers",e,r),"function"==typeof r?t.metadata("transformers",e)(r):r)}e.DecafRequestHandlerInterceptor=_e=class{constructor(e,t){this.requestContext=e,this.executor=t}async contextualize(e){const t={headers:e.headers,overrides:{}},r=i.Adapter.flavoursToTransform();if(r)for(const o of r)try{const r=i.Adapter.transformerFor(o),a=await r.from(e);Object.assign(t.overrides,a)}catch(e){throw new c.InternalError("Failed to contextualize request: "+e)}return(new i.Context).accumulate(Object.assign({},i.DefaultAdapterFlags,{logger:l.Logging.get(),timestamp:new Date},t))}async intercept(e,t){const r=e.switchToHttp().getRequest(),o=e.switchToHttp().getResponse(),a=l.Logging.for(_e).for(this.intercept);a.debug(`CONTEXT ${this.requestContext.uuid} - request: ${r.method} ${r.url}`);const i=await this.contextualize(r);return a.debug(`CONTEXT ${this.requestContext.uuid} contextualized - request: ${r.method} ${r.url}`),this.requestContext.applyCtx(i),a.debug(`CONTEXT ${this.requestContext.uuid} applied - request: ${r.method} ${r.url}`),await this.executor.exec(r,o),a.debug(`CONTEXT ${this.requestContext.uuid} executors finished - request: ${r.method} ${r.url}`),t.handle()}},e.DecafRequestHandlerInterceptor=_e=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__metadata("design:paramtypes",[e.DecafRequestContext,e.DecafHandlerExecutor])],e.DecafRequestHandlerInterceptor),e.DecafCoreModule=class{static{be=this}static get persistence(){if(!this._persistence)throw new c.InternalError("Persistence service not initialized");return this._persistence}static get log(){return this._logger||(this._logger=l.Logging.for(be)),this._logger}constructor(e,t){this.options=e,this.moduleRef=t}static forRoot(t){const r=this.log.for(this.forRoot);return{module:be,providers:[{provide:F,useValue:t},{provide:N,useValue:this.persistence?.client},{provide:L,useFactory:()=>t.handlers?.map(e=>(r.info("Registered request handler: "+e.name),new e))??[]},e.AuthInterceptor,{provide:d.APP_INTERCEPTOR,useExisting:e.AuthInterceptor},e.DecafRequestContext,e.DecafHandlerExecutor,{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[F,N,L,e.DecafRequestContext,e.DecafHandlerExecutor]}}static async bootPersistence(e){const t=this.log.for(this.bootPersistence);if(!this._persistence){const r=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new i.PersistenceService,await this._persistence.boot(r);const o=this._persistence.client;for(let t=0;t<o.length;t++){const r=e.conf[t];let a=r.slice(2,r.length).pop();if(!a||!a.from){const e=i.Adapter.transformerFor(o[t].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${o[t].flavour}. you should either @requestToContextTransformer or provide a transformer in the config`);try{a=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${o[t].flavour}: ${e}`)}}Ae(o[t].flavour)(a)}if(t.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize application: "+e)}}return this.persistence.client}async onApplicationShutdown(){const e=be.log.for(this.onApplicationShutdown),t=this.moduleRef.get(N);for(const r of t)try{r&&(e.info("Shutting down "+r.toString()),await r.shutdown())}catch(t){e.error("Failed to shutdown application",t)}try{await i.Service.shutdown()}catch(t){e.error("Failed to shutdown services",t)}}},e.DecafCoreModule=be=p.__decorate([o.Global(),o.Module({}),p.__param(0,o.Inject(F)),p.__metadata("design:paramtypes",[Object,d.ModuleRef])],e.DecafCoreModule);const Pe=Symbol("LISTENING_ADAPTERS_FLAVOURS");var Ee,ve,Oe,Re;e.EventsController=Ee=class extends ee{constructor(e,t){super(e,Ee.name),this.adapters=t.map(e=>i.Adapter.get(e))}listen(){const e=l.Logging.for(Ee.name),t=new u.Observable(t=>{const r=("B-"+Math.random().toString(36).slice(2,8)).toUpperCase();e.info(`Creating SSE observer: ${r} for client ${this.clientContext.uuid}`);const o=new class{constructor(){this.observerId=r}refresh(...r){return e.debug(`SSE observer ${this.observerId} received refresh event`),Promise.resolve().then(()=>{const o=(e=>{const[t,r,o,a]=e;return[t?.name??t,r,o,Array.isArray(a)?a.map(e=>{try{return"function"==typeof e.serialize?e.serialize():"string"==typeof e?e:JSON.stringify(e)}catch(e){return}}):a&&"function"==typeof a.serialize?a.serialize():"string"==typeof a?a:JSON.stringify(a)]})(r);t.next({type:"message",data:o}),e.debug(`SSE observer ${this.observerId} event pushed to client`)})}};e.verbose(`Registering observer ${r} across ${this.adapters.length} adapter(s)`);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Registering observer ${r} in adapter ${a}`),t.observe(o)}catch(t){e.debug(`Failed to register observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}return()=>{e.debug("Cleaning up SSE observer "+r);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Unregistering observer ${r} from adapter ${a}`),t.unObserve(o)}catch(t){e.debug(`Failed during cleanup of observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}}}),r=u.interval(15e3).pipe(y.tap(()=>{e.debug("Sending heartbeat")}),y.map(()=>({type:"heartbeat",data:{ts:(new Date).toISOString()}})));return u.merge(t,r)}listenForModel(e){const t=l.Logging.for(Ee.name);return new u.Observable(e=>{const r=new class{refresh(...t){return Promise.resolve().then(()=>{e.next({data:t})})}};try{for(const e of this.adapters)e.observe(r)}catch(t){e.error("Failed to observe event: "+(t.message||t))}return()=>{try{for(const e of this.adapters)e.unObserve(r)}catch(e){t.error(e)}}})}},p.__decorate([o.Sse(),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listen",null),p.__decorate([o.Sse("/:model"),p.__param(0,o.Query("model")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listenForModel",null),e.EventsController=Ee=p.__decorate([o.Controller(),p.__param(1,o.Inject(Pe)),p.__metadata("design:paramtypes",[e.DecafRequestContext,Array])],e.EventsController),e.DecafStreamModule=ve=class{static forFlavours(t,r="events"){return{module:ve,controllers:[e.EventsController],imports:[d.RouterModule.register([{path:r.replace(/^\//,""),module:ve}])],providers:[e.DecafRequestContext,{provide:Pe,useValue:t??[]}]}}},e.DecafStreamModule=ve=p.__decorate([o.Module({})],e.DecafStreamModule),e.DecafModule=Oe=class{static async forRootAsync(t){const{autoControllers:r,autoServices:o}=t,a=(await e.DecafCoreModule.bootPersistence(t)).map(e=>e.flavour),i=[e.DecafCoreModule.forRoot(t)];return r&&a.forEach(e=>{i.push(ue(e).forRoot(e,{autoServices:o}))}),t.observerOptions?.enableObserverEvents&&i.push(e.DecafStreamModule.forFlavours(t.observerOptions.observerFlavours||a)),{module:Oe,imports:i}}},e.DecafModule=Oe=p.__decorate([o.Module({})],e.DecafModule);const we=l.Logging.for("DecafMigrationModule");var Se,De,Ce;e.DecafMigrationModule=Re=class{static forRoot(){return{module:Re}}static async migrate(e,t){const r=we.for(this.migrate);if(!t||0===t.length)throw new c.InternalError("No adapters provided. Make sure DecafCoreModule is configured and adapters are available.");return r.info("Running migrations with config: "+JSON.stringify(e)),g.MigrationService.migrateAdapters(t,e||{})}},e.DecafMigrationModule=Re=p.__decorate([o.Global(),o.Module({providers:[{provide:"MIGRATION_ADAPTERS",useFactory:e=>e,inject:[N]}],exports:["MIGRATION_ADAPTERS"]})],e.DecafMigrationModule),e.WebhookSubscriptionActionsController=Se=class extends ee{constructor(e){super(e,Se.name)}async deactivate(e){const{ctx:t}=(await this.logCtx([],"deactivate",!0)).for(this.deactivate),r=i.Repository.forModel(_.WebhookSubscription),o=await r.read(e,t);return o.active=!1,r.update(o,t)}async reactivate(e){const{ctx:t}=(await this.logCtx([],"reactivate",!0)).for(this.reactivate),r=i.Repository.forModel(_.WebhookSubscription),o=await r.read(e,t);return o.active=!0,r.update(o,t)}},p.__decorate([o.Post(":id/deactivate"),p.__param(0,o.Param("id")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",Promise)],e.WebhookSubscriptionActionsController.prototype,"deactivate",null),p.__decorate([o.Post(":id/reactivate"),p.__param(0,o.Param("id")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",Promise)],e.WebhookSubscriptionActionsController.prototype,"reactivate",null),e.WebhookSubscriptionActionsController=Se=p.__decorate([o.Controller("webhook-subscriptions"),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.WebhookSubscriptionActionsController),e.WebhookEventActionsController=De=class extends ee{constructor(e){super(e,De.name)}async replay(e){const{ctx:t}=(await this.logCtx([],"replay",!0)).for(this.replay),r=i.Repository.forModel(_.WebhookEventRecord),o=i.Repository.forModel(_.WebhookDelivery);try{let a;try{a=await r.read(e,t)}catch(o){const i=await r.select().where(r.attr("id").eq(e)).limit(1).execute(t);if(!i.length)throw o;a=i[0]}let s=[];try{s=await _.collectPagedResults(()=>o.select().where(o.attr("eventId").eq(a.id)).orderBy("createdAt",i.OrderDirection.ASC).thenBy("id",i.OrderDirection.ASC).paginate(250,t),250,t)}catch{try{s=await o.select().where(o.attr("eventId").eq(a.id)).execute(t)}catch{s=[]}}const n=new Date;for(const e of s)e.status=_.WebhookStatus.PENDING,e.attempts=0,e.nextAttemptAt=n,e.lastAttemptAt=null,e.errorMessage=void 0,e.responseStatus=void 0,e.responseBody=void 0;if(a.status=_.WebhookStatus.PENDING,a.deliveriesSucceeded=0,a.deliveriesFailed=0,a.nextAttemptAt=n,a.updatedAt=n,s.length)try{await o.updateAll(s,t.override({applyUpdateValidation:!1}))}catch{}return r.update(a,t)}catch(e){throw e}}},p.__decorate([o.Post(":id/replay"),p.__param(0,o.Param("id")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",Promise)],e.WebhookEventActionsController.prototype,"replay",null),e.WebhookEventActionsController=De=p.__decorate([o.Controller("webhook-events"),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.WebhookEventActionsController),e.DecafWebhookModule=class{static{Ce=this}static{this._logger=l.Logging.for(Ce)}static get log(){return this._logger}static async bootPersistence(e){const r=this.log.for(this.bootPersistence);if(!this._persistence){const o=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new i.PersistenceService,await this._persistence.boot(o);const a=this._persistence.client;for(let r=0;r<a.length;r++){const o=i.Adapter._cache||(i.Adapter._cache={}),s=[a[r].flavour,a[r].alias,"webhook_deliveries","webhook_events","webhook_subscriptions"].filter(e=>!!e);for(const e of s)o[e]=a[r];const n=e.conf[r];let p=n.slice(2,n.length).pop();if(!p||!p.from){const e=i.Adapter.transformerFor(a[r].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${a[r].flavour}.`);try{p=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${a[r].flavour}: ${e}`)}}Ae(a[r].flavour)(p),t.uses(a[r].flavour)(_.WebhookSubscription),t.uses(a[r].flavour)(_.WebhookEventRecord),t.uses(a[r].flavour)(_.WebhookDelivery)}if(r.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize webhook module: "+e)}}return this._persistence.client}static async forRoot(e){return this.forRootAsync(e)}static async forRootAsync(t){await this.bootPersistence(t);const r=[le.create(_.WebhookSubscription),le.create(_.WebhookEventRecord),le.create(_.WebhookDelivery),e.WebhookSubscriptionActionsController,e.WebhookEventActionsController];return{module:Ce,controllers:r,imports:[d.RouterModule.register([{path:(t.webhookApiPath||"webhooks").replace(/^\//,""),module:Ce}])],providers:[e.DecafRequestContext,e.DecafHandlerExecutor,{provide:L,useFactory:()=>t.handlers?.map(e=>new e)??[]},{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[e.DecafRequestContext,e.DecafHandlerExecutor]}}},e.DecafWebhookModule=Ce=p.__decorate([o.Module({})],e.DecafWebhookModule);const Te=e.DecafWebhookModule,xe="##VERSION##",Me="##PACKAGE##";t.Metadata.allowReregistration(!0),t.Metadata.registerLibrary(Me,xe),t.Metadata.allowReregistration(!1),Object.defineProperty(e,"WebhookDelivery",{enumerable:!0,get:()=>_.WebhookDelivery}),Object.defineProperty(e,"WebhookDeliveryService",{enumerable:!0,get:()=>_.WebhookDeliveryService}),Object.defineProperty(e,"WebhookEventRecord",{enumerable:!0,get:()=>_.WebhookEventRecord}),Object.defineProperty(e,"WebhookPublisherService",{enumerable:!0,get:()=>_.WebhookPublisherService}),Object.defineProperty(e,"WebhookSignatureMiddleware",{enumerable:!0,get:()=>_.WebhookSignatureMiddleware}),Object.defineProperty(e,"WebhookStatus",{enumerable:!0,get:()=>_.WebhookStatus}),Object.defineProperty(e,"WebhookSubscription",{enumerable:!0,get:()=>_.WebhookSubscription}),Object.defineProperty(e,"WebhookSubscriptionService",{enumerable:!0,get:()=>_.WebhookSubscriptionService}),Object.defineProperty(e,"computeNextAttempt",{enumerable:!0,get:()=>_.computeNextAttempt}),Object.defineProperty(e,"signWebhookPayload",{enumerable:!0,get:()=>_.signWebhookPayload}),Object.defineProperty(e,"verifyWebhookSignature",{enumerable:!0,get:()=>_.verifyWebhookSignature}),e.AUTH_HANDLER=K,e.AUTH_META_KEY=U,e.ApiOperationFromModel=T,e.ApiParamsFromModel=x,e.ApiProperty=S,e.Auth=H,e.BulkApiOperationFromModel=(e,r,a)=>{const i={GET:[c.BulkCrudOperationKeys.READ_ALL,o.Get],POST:[c.BulkCrudOperationKeys.CREATE_ALL,o.Post],PUT:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Put],PATCH:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Patch],DELETE:[c.BulkCrudOperationKeys.DELETE_ALL,o.Delete]},[s,p]=i[r];return C(e,s)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))},e.COMMIT="cee7a8b",e.CorsError=he,e.DECAF_ADAPTER_ID=N,e.DECAF_ADAPTER_OPTIONS=B,e.DECAF_CONTEXT_KEY=W,e.DECAF_HANDLERS=L,e.DECAF_MODULE_OPTIONS=F,e.DECAF_ROUTE=j,e.DECAF_TASK_SERVICE_ID="DecafTaskService",e.DECORATORS=E,e.DECORATORS_PREFIX=P,e.DecafAuthHandler=G,e.DecafBody=M,e.DecafController=ee,e.DecafModelController=te,e.DecafParams=I,e.DecafQuery=$,e.DecafRoleAuthHandler=class extends G{constructor(){super()}async authorize(e,r){const o=e.switchToHttp().getRequest(),s=this.parseRequest(o);if(!s)throw new i.AuthorizationError("Unauthenticated");const n=t.Metadata.get(a.Model.get(r),i.PersistenceKeys.AUTH_ROLE);if(!n.includes(s))throw new i.AuthorizationError("Missing role: "+s);return n}},e.DecafWebhooksModule=Te,e.DtoFor=ae,e.FULL_VERSION="0.10.2-cee7a8b",e.FromModelController=le,e.HttpVerbToDecorator=q,e.NestBootstraper=class{static get logger(){return this._logger||(this._logger=new o.Logger("NestBootstrap")),this._logger}static initialize(e){return this.app=e,this}static enableLogger(e){return this._logger=e||new o.Logger("NestBootstrap"),this.app.useLogger(this._logger),this}static enableCors(e=[],t=["GET","POST","PUT","DELETE"]){const r="*"===e?"*":e.map(e=>e.trim().toLowerCase()),o={origin:(e,t)=>e?"*"===r||Array.isArray(r)&&r.includes(e.toLowerCase())?t(null,!0):void t(new he(`Origin ${e} not allowed`)):t(null,!0),credentials:!0,methods:t.join(",")};return this.app.enableCors(o),this}static useHelmet(e){try{const t=require("helmet");this.app.use(t(e)),this.logger.log("Helmet middleware enabled successfully.")}catch(e){this.logger.warn("Helmet not installed. Skipping middleware.")}return this}static setupSwagger(e){return new ge(this.app,{title:e.title,description:e.description,version:e.version,path:e.path||"api",persistAuthorization:e.persistAuthorization??!0,assetsPath:e.assetsPath,faviconFilePath:e.faviconPath,topbarIconFilePath:e.topbarIconPath,topbarBgColor:e.topbarBgColor,openApiJsonPath:e.openApiJsonPath,openApiYamlPath:e.openApiYamlPath}).setupSwagger(),this}static useGlobalPipes(...e){return e.length>0&&this.app.useGlobalPipes(...e),this}static useGlobalFilters(...t){return this.app.useGlobalFilters(...t.length>0?t:[new e.DecafExceptionFilter]),this}static useGlobalInterceptors(...e){return e.length>0&&this.app.useGlobalInterceptors(...e),this}static async start(e=Number(process.env.PORT)||3e3,t=void 0,r=!0){this.app.listen(e,t).then(async()=>{if(r){const e=await this.app.getUrl();this.logger.log("\ud83d\ude80 Application is running at: "+e)}})}},e.PACKAGE_NAME=Me,e.RequestToContextTransformer=class{},e.SwaggerBuilder=ge,e.UseDecafFilter=()=>o.UseFilters(new e.DecafExceptionFilter),e.UseDecafHeaders=()=>o.UseInterceptors(e.DecafResponseInterceptor),e.VERSION=xe,e.createApiPropertyDecorator=D,e.createPropertyDecorator=w,e.getEnumType=R,e.getEnumValues=O,e.getModuleFor=ue,e.isOperationBlocked=C,e.isUndefined=v,e.repoForModel=e=>{const t=a.Model.get(e);if(!t)throw new c.InternalError("Failed to find repository for "+e);return i.Repository.forModel(t)},e.requestToContextTransformer=Ae,e.runMigrations=async()=>{},e.runWebhooksMigrations=async()=>{}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/injectable-decorators"),require("@nestjs/common"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/core"),require("lodash"),require("@nestjs/swagger"),require("@decaf-ts/db-decorators"),require("tslib"),require("@nestjs/core"),require("@decaf-ts/logging"),require("rxjs"),require("fs"),require("path"),require("yaml"),require("rxjs/operators"),require("@decaf-ts/core/migrations"),require("@decaf-ts/for-http/server")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/injectable-decorators","@nestjs/common","@decaf-ts/decorator-validation","@decaf-ts/core","lodash","@nestjs/swagger","@decaf-ts/db-decorators","tslib","@nestjs/core","@decaf-ts/logging","rxjs","fs","path","yaml","rxjs/operators","@decaf-ts/core/migrations","@decaf-ts/for-http/server"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-nest"]={},e.decafTsDecoration,e.decafTsInjectableDecorators,e.nestjsCommon,e.decafTsDecoratorValidation,e.decafTsCore,e.lodash,e.nestjsSwagger,e.decafTsDbDecorators,e.tslib,e.nestjsCore,e.decafTsLogging,e.rxjs,e.fs,e.path,e.yaml,e.operators,e.migrations,e.server);
1
+ var e,t;e=this,t=function(e,t,r,o,a,i,s,n,c,p,d,l,u,h,m,f,y,g,_){"use strict";function A(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var b=A(m);const P="swagger",E={API_OPERATION:P+"/apiOperation",API_RESPONSE:P+"/apiResponse",API_PRODUCES:P+"/apiProduces",API_CONSUMES:P+"/apiConsumes",API_TAGS:P+"/apiUseTags",API_CALLBACKS:P+"/apiCallbacks",API_PARAMETERS:P+"/apiParameters",API_HEADERS:P+"/apiHeaders",API_MODEL_PROPERTIES:P+"/apiModelProperties",API_MODEL_PROPERTIES_ARRAY:P+"/apiModelPropertiesArray",API_SECURITY:P+"/apiSecurity",API_EXCLUDE_ENDPOINT:P+"/apiExcludeEndpoint",API_EXCLUDE_CONTROLLER:P+"/apiExcludeController",API_EXTRA_MODELS:P+"/apiExtraModels",API_EXTENSION:P+"/apiExtension",API_SCHEMA:P+"/apiSchema",API_DEFAULT_GETTER:P+"/apiDefaultGetter",API_LINK:P+"/apiLink"},v=e=>void 0===e;function O(e){if("function"==typeof e)return O(e());if(Array.isArray(e))return e;if("object"!=typeof e)return[];const t=Object.values(e).filter(e=>"number"==typeof e).map(e=>e.toString());return Object.keys(e).filter(e=>!t.includes(e)).map(t=>e[t])}function R(e){return e.filter(s.isString).length>0?"string":"number"}function w(e,t,r=!0){return(o,a)=>{const i=Reflect.getMetadata(E.API_MODEL_PROPERTIES_ARRAY,o)||[],n=":"+a;i.includes(n)||Reflect.defineMetadata(E.API_MODEL_PROPERTIES_ARRAY,[...i,":"+a],o);const c=Reflect.getMetadata(e,o,a);if(c){const i=s.pickBy(t,s.negate(v)),n=r?{...c,...i}:{...i,...c};Reflect.defineMetadata(e,n,o,a)}else{const r=o?.constructor?._OPENAPI_METADATA_FACTORY?.()[a]?.type??Reflect.getMetadata("design:type",o,a);Reflect.defineMetadata(e,{type:r,required:!1,...s.pickBy(t,s.negate(v))},o,a)}}}function S(e={}){return D(e)}function D(e={},t=!0){const[r,o]=((e,t)=>{if(!e)return[e,t];if(t)return[e,t];const r=s.isArray(e);return[r?e[0]:e,r]})(e.type,e.isArray);if((a=e={...e,type:r,isArray:o}).isArray&&"enum"in a&&void 0!==a.enum){e.type="array";const t=O(e.enum);e.items={type:R(t),enum:t},delete e.enum}else if("enum"in e&&void 0!==e.enum){const t=O(e.enum);e.enum=t,e.type=R(t)}var a;return Array.isArray(e.type)&&(e.type="array",e.items={type:"array",items:{type:e.type[0]}}),w(E.API_MODEL_PROPERTIES,e,t)}function C(e,r){const{handler:o,args:a}=t.Metadata.get(e,c.OperationKeys.REFLECT+c.OperationKeys.BLOCK)||{};return!!o&&(o(...a,r)??!1)}function T(e,r,a){const i={GET:[c.OperationKeys.READ,o.Get],POST:[c.OperationKeys.CREATE,o.Post],PUT:[c.OperationKeys.UPDATE,o.Put],PATCH:[c.OperationKeys.UPDATE,o.Patch],DELETE:[c.OperationKeys.DELETE,o.Delete]},[s,p]=i[r];return C(e,s)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))}function x(e=[]){const t=e.map(e=>n.ApiParam({name:e.name,description:e.description??"Path parameter: "+e.name,required:e.required??!0,type:e.type??String}));return o.applyDecorators(...t)}const M=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest().body,a=t.getClass(),i=a.class;if(!i)throw new o.InternalServerErrorException(`ModelConstructor not found on controller ${a.name}. Ensure the controller was created via FromModelController.`);return r?Array.isArray(r)?r.map(e=>new i(e)):new i(r):r}),k=o.createParamDecorator((e,t)=>{const r=t.switchToHttp().getRequest(),o=r?.params??{},a=e??Object.keys(o),i=a.map(e=>o[e]);return{raw:o,valuesInOrder:i,keysInOrder:a}});function I(e=[]){const t=e.map(e=>e.name);return k(t)}const $=o.createParamDecorator((e,t)=>{const r={...t.switchToHttp().getRequest().query??{}};if(void 0!==r.limit){const e=Number(r.limit);Number.isNaN(e)||(r.limit=e)}if(void 0!==r.offset){const e=Number(r.offset);Number.isNaN(e)||(r.offset=e)}if(void 0!==r.bookmark){const e=Number(r.bookmark);r.bookmark=Number.isNaN(e)?r.bookmark:e}return r});function q(e){const t={GET:o.Get,POST:o.Post,PUT:o.Put,PATCH:o.Patch,DELETE:o.Delete}[e];if(!t)throw Error(`Unsupported HTTP verb "${e}". No NestJS decorator mapping was found.`);return t}const F="DecafModuleOptions",N="DecafAdapter",j="DecafRoute",L=Symbol("DecafHandlers"),B=Symbol("DecafAdapterForOptions"),K=Symbol("AUTH_HANDLER"),U="auth:meta",W=Symbol("decaf:context");function H(t){const r=t?"string"==typeof t?t:t.name:void 0,a=[n.ApiBearerAuth(),o.UseInterceptors(e.AuthInterceptor)];return r&&a.push(o.SetMetadata(U,r)),o.applyDecorators(...a)}e.AuthInterceptor=class{constructor(e,t){this.reflector=e,this.authHandler=t}async intercept(e,t){const r=l.Logging.for(this).for(this.intercept),o=this.reflector.get(U,e.getHandler())??this.reflector.get(U,e.getClass());return r.verbose("Intercepted request"+(o?" for "+o:"")),this.authHandler?await this.authHandler.authorize(e,o):r.debug("No auth handler/model"),t.handle()}},e.AuthInterceptor=p.__decorate([o.Injectable(),p.__param(1,o.Optional()),p.__param(1,o.Inject(K)),p.__metadata("design:paramtypes",[d.Reflector,Object])],e.AuthInterceptor);class G{parseRequest(e){const t=e.headers.authorization?.split(" ")[1];return t}async authorize(e,r){const o=e.switchToHttp().getRequest(),s=this.parseRequest(o);if(!s)throw new i.AuthorizationError("Unauthenticated");if(!t.Metadata.get(a.Model.get(r),i.PersistenceKeys.AUTH_ROLE).includes(s))throw new i.AuthorizationError("Missing role: "+s)}}var z;e.DecafRequestContext=class{constructor(e){this.req=e,this.uuid=i.UUID.instance.generate()}get request(){return this.req}put(e){let t;try{t=this.ctx.get("overrides")}catch(e){t={}}this._ctx=this.ctx.accumulate({overrides:Object.assign(t,e)})}applyCtx(e){if(this._ctx)throw new c.InternalError("Trying to overwrite context");this._ctx=e}get ctx(){if(!this._ctx)throw new c.InternalError("Context not initialized for request");return this._ctx}},e.DecafRequestContext=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(d.REQUEST)),p.__metadata("design:paramtypes",[Request])],e.DecafRequestContext),e.DecafHandlerExecutor=z=class{constructor(e,t){this.handlers=e,this.context=t}async exec(e,t){l.Logging.for(z.name).for(this.exec).debug(`CONTEXT ${this.context.uuid} running ${this.handlers.length} handlers for request ${e.method} ${e.url}`);for(const r of this.handlers)await r.handle(this.context,e,t)}},e.DecafHandlerExecutor=z=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__param(0,o.Inject(L)),p.__metadata("design:paramtypes",[Array,e.DecafRequestContext])],e.DecafHandlerExecutor),e.DecafResponseInterceptor=class{constructor(e){this.ctx=e}intercept(e,t){let r=e.switchToHttp().getResponse();return t.handle().pipe(u.tap(e=>{r=this.ctx.ctx.toResponse(r)}))}},e.DecafResponseInterceptor=p.__decorate([o.Injectable(),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.DecafResponseInterceptor);const Q=e=>({name:e,description:e+" parameter for the query",required:!0,type:String});function V(e,t,r,a=!1){const s=q(r),c=(e=>e.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1)))(t).map(Q),p=[];return"GET"===r&&a&&p.push(n.ApiQuery({name:"direction",required:!1,enum:i.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!1,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!1,description:"offset or bookmark when applicable"})),{method:[s(t),...c.map(n.ApiParam),...p,n.ApiOperation({summary:`Retrieve records using according to "${e}".`}),n.ApiOkResponse({description:"Result successfully retrieved."}),n.ApiNoContentResponse({description:"No content returned by the method."})],params:[I(c),o.Query()]}}function Y(e,t,r,o){const a=e?.prototype??e;o.method.forEach(e=>e(a,t,r)),o.params?.forEach((e,r)=>e(a,t,r))}function J(e,t,...r){if(e instanceof i.ModelService)return"function"==typeof e[t]?e[t](...r):e.statement(t,...r);if("function"==typeof e[t])return e[t](...r);throw Error(`Persistence method "${t}" not found on ${e?.constructor?.name}`)}function X(e){return async function(t,r){const o=this.log.for(e);try{o.debug(`Invoking persistence method "${e}" given parameters: ${JSON.stringify(t.valuesInOrder)}`);const{direction:a,limit:i,offset:s}=r;return await J(this.persistence(),e,...t.valuesInOrder,a,i,s)}catch(t){throw o.error(`Custom query "${e}" failed`,t),t}}}function Z(e,t,r){return Object.defineProperty(e.prototype||e,t,{value:r,writable:!1}),Object.getOwnPropertyDescriptor(e.prototype||e,t)}class ee extends i.Service{constructor(e,t){super(),this.clientContext=e}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let s;e=e.filter(e=>void 0!==e),o&&(o.headers||o.ip)&&(s=o,o={});const n=i.ContextualLoggedClass.logCtx.call(this,t,o||{},r,...e,a);return this.bindLoggerToRequest(n,s)}bindLoggerToRequest(e,t){const r=this;function o(e,t){return e.log=((e,t)=>{const o=(e=>{if(!e)return;const t=e.headers,r=re(t?.["x-forwarded-for"])??re(t?.["x-real-ip"])??re(t?.["X-Forwarded-For"])??re(t?.["X-Real-IP"]);if(r)return r;if("string"==typeof e.ip&&e.ip.length)return e.ip;const o=e.socket||e.connection;return o&&"string"==typeof o.remoteAddress&&o.remoteAddress.length?o.remoteAddress:void 0})(t??r.clientContext.request);if(!o)return e;const a={ip:o};return e.for(a)})(e.log,t),e}return(e=>"object"==typeof e&&null!==e&&"function"==typeof e.then)(e)?e.then(e=>o(e,t)):o(e,t)}}class te extends ee{persistence(e){if(!this._persistence)try{this._persistence=i.Service.get(this.class)}catch(e){try{this._persistence=i.ModelService.getService(this.class)}catch(e){this._persistence=i.Repository.forModel(this.class)}}const t=this.clientContext.request[B]||{};return e&&this.clientContext.put(t),e?this._persistence instanceof i.Repository?this._persistence.override(t):this._persistence.for(t):this._persistence}constructor(e,t){super(e,t)}logCtx(e,t,r=!1,o){const a=this.clientContext.ctx;let s;o&&(o.headers||o.ip)&&(s=o,o={});try{o=a.get("overrides")}catch(e){}const n=this.persistence(a);let c,p;return n instanceof i.ModelService?c=n.repo._adapter:n instanceof i.Repository?c=n._adapter:n.context&&(c=n),r?c.logCtx(e,t,!0,o).then(e=>this.bindLoggerToRequest(e,s)):(p=c.logCtx(e,t,!1,o),this.bindLoggerToRequest(p,s))}}function re(e){if(e)return(Array.isArray(e)?e[0]:e).split(",").map(e=>e.trim()).filter(Boolean)[0]}const oe=new Map;function ae(e,r){if(!i.TransactionOperationKeys.includes(e))return r;const o=(e=>(oe.has(e)||oe.set(e,new WeakMap),oe.get(e)))(e),s=o.get(r);if(s)return s;const n=[c.OperationKeys.UPDATE,c.BulkCrudOperationKeys.UPDATE_ALL].includes(e);class p{}o.set(r,p),Object.defineProperty(p,"name",{value:`${l.toPascalCase(r.name)}${l.toPascalCase(e)}DTO`});const d=(()=>{try{return a.Model.pk(r)}catch{return}})(),u=d?a.Model.pkProps(r):void 0,h=d?Reflect.getMetadata("design:type",r.prototype,d):void 0,m=h===Number||h===BigInt,f=!!u?.generated||!!d&&(a.Model.generatedBySequence(r,d)||ne(r,d)||m),y=Array.from(new Set(t.Metadata.properties(r)||[])),g=new Set(a.Model.relations(r)||[]),_=[];for(const e of y)e&&(g.has(e)||e===d&&!n&&f||e!==d&&ne(r,e)||_.push(e));for(const e of _){const t=ce(r,e),o=!!t?.[a.ValidationKeys.REQUIRED],i=pe(r,e)??Reflect.getMetadata("design:type",r.prototype,e),s={required:o};i&&(s.type=i),S(s)(p.prototype,e);const n=Reflect.getMetadata("design:type",r.prototype,e)??i;void 0!==n&&Reflect.defineMetadata("design:type",n,p.prototype,e),Object.defineProperty(p.prototype,e,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}for(const o of g){const i=t.Metadata.relations(r,o);if(!i)throw new c.InternalError(`Metadata for relation ${o} not found`);let s=i.class;if("function"!=typeof s||s.name||(s=s()),!s||"function"!=typeof s)throw new c.InternalError(`Type for relation ${o} not found`);if(!a.Model.get(s.name))continue;const d=t.Metadata.validationFor(r,o),l=!!d?.[a.ValidationKeys.LIST],u=!!d?.[a.ValidationKeys.REQUIRED],h=ae(e,s);n?se(p,o,s,h,l,u):ie(p,o,h,l,u)}return p}function ie(e,t,r,o,a){S({type:r,required:a,isArray:o})(e.prototype,t),Reflect.defineMetadata("design:type",o?Array:r,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function se(e,t,r,o,i,s){const n=Reflect.getMetadata(E.API_EXTRA_MODELS,e)||[];n.includes(o)||Reflect.defineMetadata(E.API_EXTRA_MODELS,[...n,o],e);const c="#/components/schemas/"+o.name,p=(e=>{try{const t=a.Model.pkProps(e),r=t?.type;return r===Number||r===BigInt?"integer":"string"}catch{return"string"}})(r),d=[{$ref:c},{type:p}];S(i?{type:"array",required:s,oneOf:d}:{type:Object,required:s,oneOf:d})(e.prototype,t),Reflect.defineMetadata("design:type",i?Array:Object,e.prototype,t),Object.defineProperty(e.prototype,t,{value:void 0,writable:!0,enumerable:!0,configurable:!0})}function ne(e,t){let r=e;for(;r&&r!==Object&&r!==Function;){if(a.Model.generated(r,t))return!0;r=Object.getPrototypeOf(r)}return!1}function ce(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.validationFor(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}function pe(e,r){let o=e;for(;o&&o!==Object&&o!==Function;){const e=t.Metadata.type(o,r);if(e)return e;o=Object.getPrototypeOf(o)}}i.Adapter.transformerFor=(e=>{const r="string"==typeof e?e:e.alias;return t.Metadata.innerGet(Symbol.for("transformers"),r)}).bind(i.Adapter),i.Adapter.flavoursToTransform=(()=>{const e=t.Metadata.innerGet(Symbol.for("transformers"));if(e)return Object.keys(e)}).bind(i.Adapter),i.Context.prototype.toResponse=function(e){const t=this.pending();return t&&e.header("x-pending-task",JSON.stringify(t)),e};const de=a.ModelBuilder.prototype;if(de.decorateClass||(de.decorateClass=function(e){return this._classDecorators||(this._classDecorators=[]),this._classDecorators.push(e),this}),de.Auth=function(e){return this.decorateClass(H(e))},!de.__hasClassDecoratorSupport){const e=de.build;de.build=function(){let t=e.call(this);const r=this._classDecorators;if(r?.length)for(const e of r){const r=e(t);r&&(t=r)}return t},de.__hasClassDecoratorSupport=!0}class le{static{this.log=l.Logging.for(le.name)}static getPersistence(e){try{return i.Service.get(e)}catch(t){try{return i.ModelService.getService(e)}catch(t){return i.Repository.forModel(e)}}}static createQueryRoutesFromRepository(e,r=i.PersistenceKeys.QUERY){const o=le.log.for(le.createQueryRoutesFromRepository),a=e instanceof i.ModelService?e.repo:e,s=a.class,n=t.Metadata.get(a.constructor,t.Metadata.key(i.PersistenceKeys.QUERY))??{},c=t.Metadata.get(e.constructor,t.Metadata.key(j))??{};class p extends te{get class(){throw Error("Method not implemented.")}constructor(e,t){super(e,t)}}for(const[e,t]of Object.entries(c)){const r=[t.path.replace(/^\/+|\/+$/g,"")].filter(e=>e&&e.trim()).join("/"),a=X(e);if(!a){const t=`Invalid or missing handler for model ${s.name} on decorated method ${e}`;throw o.error(t),Error(t)}const i=Z(p,e,a);i&&Y(p,e,i,V(e,r,t.httpMethod))}for(const[e,t]of Object.entries(n)){const o=[r,e,...(t.fields??[]).map(e=>":"+e)].filter(e=>e&&e.trim()).join("/"),a=Z(p,e,X(e));a&&Y(p,e,a,V(e,o,"GET",!0))}return p}static create(t){const r=le.log.for(le.create),s=a.Model.tableName(t),d=l.toKebabCase(s),u=t.name,h=le.getPersistence(t),{description:m,getPK:f,apiProperties:y,path:g}=le.getRouteParametersFromModel(t);r.debug("Creating controller for model: "+u);const _=le.createQueryRoutesFromRepository(h);let A=class extends _{static get class(){return t}get class(){return t}constructor(e){super(e),this.pk=a.Model.pk(t),r.info(`Registering dynamic controller for model: ${this.class.name} route: /${d}`)}async listBy(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.persistence(r).listBy(e,t.direction,r)}async paginateBy(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.persistence(r).paginateBy(e,t.direction,t,r)}async find(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.FIND,!0)).for(this.find),o=t.direction??i.OrderDirection.ASC;return J(this.persistence(r),this.find.name,e,o,r)}async page(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.PAGE,!0)).for(this.page),{direction:o=i.OrderDirection.ASC,limit:a,offset:s,bookmark:n}=t,c={offset:s??1,limit:a??10,bookmark:n};return J(this.persistence(r),this.page.name,e,o,c,r)}async findOneBy(e,t){const{ctx:r}=(await this.logCtx([],i.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.persistence(r).findOneBy(e,t,r)}async findBy(e,t,r){const{ctx:o}=(await this.logCtx([],i.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.persistence(o).for(o.toOverrides()).findBy(e,t,o)}async statement(e,t,r){const{ctx:o}=(await this.logCtx([],i.PersistenceKeys.STATEMENT,!0)).for(this.statement),{direction:a,offset:s,limit:n,bookmark:c}=r,p=(t=t.map(e=>("string"==typeof e?parseInt(e):e)||e)).length>1?t[1]:void 0,d=a??p;switch(d&&t.length>1&&(t[1]=d),e){case i.PreparedStatementKeys.FIND:case i.PreparedStatementKeys.FIND_BY:break;case i.PreparedStatementKeys.LIST_BY:t.push(a);break;case i.PreparedStatementKeys.PAGE:case i.PreparedStatementKeys.PAGE_BY:t=[t[0],d,{limit:n,offset:s,bookmark:c}];case i.PreparedStatementKeys.FIND_ONE_BY:case i.PreparedStatementKeys.COUNT_OF:case i.PreparedStatementKeys.MAX_OF:case i.PreparedStatementKeys.MIN_OF:case i.PreparedStatementKeys.AVG_OF:case i.PreparedStatementKeys.SUM_OF:case i.PreparedStatementKeys.DISTINCT_OF:case i.PreparedStatementKeys.GROUP_OF:}return this.persistence(o).statement(e,...t,o)}async createAll(e,r){const{ctx:o,log:a}=(await this.logCtx([],c.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);let i;a.verbose("creating new "+u);try{i=await this.persistence(o).createAll(e.map(e=>new t(e)),o)}catch(e){throw a.error("Failed to create new "+u,e),e}return a.info(`created new ${u} with id ${i[this.pk]}`),o.toResponse(r),i}async create(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.CREATE,!0)).for(this.create);let a;o.verbose("creating new "+u);try{const t=this.persistence(r);a=await t.create(e,r)}catch(e){throw o.error("Failed to create new "+u,e),e}return o.info(`created new ${u} with id ${a[this.pk]}`),r.toResponse(t),a}async readAll(e){const{ctx:t,log:r}=(await this.logCtx([],c.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll),o=Array.isArray(e)?e:[e];let a;try{r.debug(`reading ${o} ${u}: ${o}`);const e=this.persistence(t);a=await e.readAll(o,t)}catch(e){throw r.error(`Failed to ${u} with id ${o}`,e),e}return r.info(`read ${a.length} ${u}`),a}async read(e){const{ctx:t,log:r}=(await this.logCtx([],c.OperationKeys.READ,!0)).for(this.read),o=f(...e.valuesInOrder);if(void 0===o)throw new c.ValidationError(`No ${this.pk} provided`);let a;try{r.debug(`reading ${u} with ${this.pk} ${o}`);const e=this.persistence(t);a=await e.read(o,t)}catch(e){throw r.error(`Failed to read ${u} with id ${o}`,e),e}return r.info(`read ${u} with id ${a[this.pk]}`),a}async updateAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);let a;try{o.info(`updating ${e.length} ${u}`),a=await this.persistence(r).updateAll(e,r)}catch(e){throw o.error(e),e}return r.toResponse(t),a}async update(e,r,o){const{ctx:a,log:i}=(await this.logCtx([],c.OperationKeys.UPDATE,!0)).for(this.update),s=f(...e.valuesInOrder);if(void 0===s)throw new c.ValidationError(`No ${this.pk} provided`);let n;try{i.info(`updating ${u} with ${this.pk} ${s}`);const e=JSON.parse(JSON.stringify(r)),o=this.persistence(a);n=await o.update(new t({...e,[this.pk]:s}),a)}catch(e){throw i.error(e),e}return a.toResponse(o),n}async deleteAll(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll),a=Array.isArray(e)?e:[e];let i;try{o.debug(`deleting ${a.length} ${u}: ${a}`),i=await this.persistence(r).deleteAll(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${i.length} ${u}`),r.toResponse(t),i}async delete(e,t){const{ctx:r,log:o}=(await this.logCtx([],c.OperationKeys.DELETE,!0)).for(this.delete),a=f(...e.valuesInOrder);if(void 0===a)throw new c.ValidationError(`No ${this.pk} provided`);let i;try{o.debug(`deleting ${u} with ${this.pk} ${a}`),i=await this.persistence(r).delete(a,r)}catch(e){throw o.error(`Failed to delete ${u} with id ${a}`,e),e}return o.info(`deleted ${u} with id ${a}`),r.toResponse(t),i}};return p.__decorate([T(t,"GET","listBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection}),n.ApiOkResponse({description:u+" listed successfully."}),p.__param(0,o.Param("key")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"listBy",null),p.__decorate([T(t,"GET","paginateBy/:key/:page"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiParam({name:"page",description:"the page to retrieve or the bookmark"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection,description:"the sort order"}),n.ApiQuery({name:"limit",required:!0,description:"the page size"}),n.ApiQuery({name:"offset",description:"the bookmark when necessary"}),n.ApiOkResponse({description:u+" listed paginated."}),p.__param(0,o.Param("key")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"paginateBy",null),p.__decorate([T(t,"GET","find/:value"),n.ApiOperation({summary:`Find ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:i.OrderDirection,description:"the sort order for the matching results"}),n.ApiOkResponse({description:u+" records matching the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"find",null),p.__decorate([T(t,"GET","page/:value"),n.ApiOperation({summary:`Page ${u} records using the default query attributes.`}),n.ApiParam({name:"value",description:"The string to match against the default query attributes"}),n.ApiQuery({name:"direction",required:!1,enum:i.OrderDirection,description:"the sort order for the paged results"}),n.ApiQuery({name:"limit",required:!1,description:"page size"}),n.ApiQuery({name:"offset",required:!1,description:"page number"}),n.ApiQuery({name:"bookmark",required:!1,description:"bookmark for cursor pagination"}),n.ApiOkResponse({description:u+" records paged by the provided prefix."}),p.__param(0,o.Param("value")),p.__param(1,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"page",null),p.__decorate([T(t,"GET","findOneBy/:key"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to sort by"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findOneBy",null),p.__decorate([T(t,"GET","findBy/:key/:value"),n.ApiOperation({summary:`Retrieve ${u} records by query.`}),n.ApiParam({name:"key",description:"the model key to compare"}),n.ApiParam({name:"value",description:"the value to match"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection,description:"the sort order when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("key")),p.__param(1,o.Param("value")),p.__param(2,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"findBy",null),p.__decorate([T(t,"GET","statement/:method/*args"),n.ApiOperation({summary:`Executes a prepared statement on ${u}.`}),n.ApiParam({name:"method",description:"the prepared statement to execute"}),n.ApiParam({name:"args",description:"concatenated list of arguments the prepared statement can accept"}),n.ApiQuery({name:"direction",required:!0,enum:i.OrderDirection,description:"the sort order when applicable"}),n.ApiQuery({name:"limit",required:!0,description:"limit or page size when applicable"}),n.ApiQuery({name:"offset",required:!0,description:"offset or bookmark when applicable"}),n.ApiOkResponse({description:u+" listed found."}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Param("method")),p.__param(1,o.Param("args")),p.__param(2,$()),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String,Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"statement",null),p.__decorate([T(t,"POST","bulk"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,M()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"createAll",null),p.__decorate([T(t,"POST"),n.ApiOperation({summary:`Create a new ${u}.`}),n.ApiBody({description:"Payload for "+u,type:ae(c.OperationKeys.CREATE,t)}),n.ApiCreatedResponse({description:u+" created successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiBadRequestResponse({description:"Payload validation failed."}),n.ApiUnprocessableEntityResponse({description:"Repository rejected the provided payload."}),p.__param(0,M()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"create",null),p.__decorate([T(t,"GET","bulk"),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array]),p.__metadata("design:returntype",Promise)],A.prototype,"readAll",null),p.__decorate([T(t,"GET",g),x(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiOkResponse({description:u+" retrieved successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object]),p.__metadata("design:returntype",Promise)],A.prototype,"read",null),p.__decorate([T(t,"PUT","bulk"),x(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,schema:{type:"array",$ref:n.getSchemaPath(ae(c.OperationKeys.UPDATE,t))}}),n.ApiOkResponse({description:u+" updated successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,M()),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"updateAll",null),p.__decorate([T(t,"PUT",g),x(y),n.ApiOperation({summary:`Replace an existing ${u} record with a new payload.`}),n.ApiBody({description:"Payload for replace a existing record of "+u,type:ae(c.OperationKeys.UPDATE,t)}),n.ApiOkResponse({description:u+" updated successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),n.ApiBadRequestResponse({description:"Payload validation failed."}),p.__param(0,I(y)),p.__param(1,M()),p.__param(2,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"update",null),p.__decorate([T(t,"DELETE","bulk"),x(y),n.ApiOperation({summary:`Retrieve a ${u} record by id.`}),n.ApiQuery({name:"ids",required:!0,type:"array"}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{type:"array",items:{$ref:n.getSchemaPath(t)}}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,o.Query("ids")),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Array,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"deleteAll",null),p.__decorate([T(t,"DELETE",g),x(y),n.ApiOperation({summary:`Delete a ${u} record by id.`}),n.ApiOkResponse({description:u+" deleted successfully.",schema:{$ref:n.getSchemaPath(t)}}),n.ApiNotFoundResponse({description:`No ${u} record matches the provided identifier.`}),p.__param(0,I(y)),p.__param(1,o.Response({passthrough:!0})),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[Object,Object]),p.__metadata("design:returntype",Promise)],A.prototype,"delete",null),A=p.__decorate([o.Controller(d),n.ApiTags(u),n.ApiExtraModels(t),H(t),p.__metadata("design:paramtypes",[e.DecafRequestContext])],A),A}static getRouteParametersFromModel(e){const r=a.Model.pk(e),o=t.Metadata.get(e,t.Metadata.key(c.DBKeys.COMPOSED,r)),i=o?.args??[],s=Array.isArray(i)&&i.length>0?Array.from(new Set([...i])):Array.from(new Set([r])),n=t.Metadata.description(e);return{path:":"+s.join("/:"),description:n,apiProperties:s.map(r=>({name:r,description:t.Metadata.description(e,r),required:!0,type:String})),getPK:(...e)=>o?.separator?e.join(o.separator):e.join("")}}}function ue(e){var t;let r=class{static{t=this}static{this.log=l.Logging.for(t.name).for(e)}static createModelServices(e){return e.map(e=>({provide:e.name+"Service",useFactory:()=>i.ModelService.forModel(e)}))}static forRoot(e,r={}){const o=this.log.for(this.forRoot);o.info("Generating controllers for flavour...");const a=i.Adapter.models(e);let s=[];r.autoServices&&(o.info("Auto-services enabled. Initializing service generation."),s=this.createModelServices(a),o.info(`Auto-services completed. ${s.length} services initialized.`));const n=a.map(le.create);return o.info(`Generated ${n.length} controllers`),{module:t,controllers:n,providers:[...s]}}};return r=t=p.__decorate([o.Module({})],r),Object.assign(r,"name",{value:"DecafModule"+e}),r}t.Decoration.for(r.InjectablesKeys.INJECTABLE).extend({decorator:(e,t)=>(t=t||("object"==typeof e?Object.assign(e,r.DefaultInjectablesConfig):r.DefaultInjectablesConfig),o.Injectable({scope:t.singleton?o.Scope.DEFAULT:o.Scope.REQUEST,durable:!t.singleton||void 0}))}).apply(),t.Decoration.for(r.InjectablesKeys.INJECT).extend({decorator:(e,t)=>(t,r,a)=>o.Inject(e||t)(t,r,a)}).apply(),t.Decoration.for(a.ValidationKeys.REQUIRED).extend(S({required:!0})).apply(),t.Decoration.for(a.ValidationKeys.MAX).extend({decorator:e=>S({maximum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN).extend({decorator:e=>S({minimum:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MAX_LENGTH).extend({decorator:e=>S({maxLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.MIN_LENGTH).extend({decorator:e=>S({minLength:e,required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.TYPE).extend({decorator:e=>(t,r)=>("function"!=typeof(e=Array.isArray(e)?e[0]:e)||e.name||(e=e()),S({type:e,required:!1})(t,r))}).apply(),t.Decoration.for(a.ValidationKeys.DATE).extend({decorator:e=>S({type:String,format:"date-time",required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.ENUM).extend({decorator:e=>S({enum:Array.isArray(e)?e:Object.values(e),required:!1})}).apply(),t.Decoration.for(a.ValidationKeys.PATTERN).extend({decorator:e=>S({pattern:"string"==typeof e?e:e.source,required:!1})}).apply(),t.Decoration.for(i.PersistenceKeys.COLUMN).extend({decorator:e=>S({name:e,required:!1})}).apply(),t.Decoration.for(t.DecorationKeys.DESCRIPTION).extend({decorator:e=>S({description:e,required:!1})}).apply(),t.Decoration.for(i.PersistenceKeys.AUTH).extend({decorator:H}).apply();class he extends i.ForbiddenError{constructor(e){super(e,he.name)}}class me extends c.BaseError{constructor(e){super(me.name,e,429)}}e.DecafExceptionFilter=class{catch(e,t){const r=t.switchToHttp(),a=r.getResponse(),s=r.getRequest(),n="production"===l.LoggedEnvironment.env;let p;e instanceof o.NotFoundException||e instanceof i.UnsupportedError?p=(e=new o.NotAcceptableException(e.message)).getStatus():e instanceof c.BaseError||(e=429===e.status?new me(e.message):new c.InternalError(e.message)),a.status(e.code||p).json({status:e.code||p,error:n?e.name:e.message,timestamp:(new Date).toISOString(),path:s.url,method:s.method})}},e.DecafExceptionFilter=p.__decorate([o.Catch()],e.DecafExceptionFilter);const fe={path:"docs",auth:{type:"http",scheme:"bearer",bearerFormat:"JWT",name:"Authorization",description:"Enter JWT token",in:"header"},topbarBgColor:"#000000"};class ye{constructor(e){this.options={...e}}customCSS(){let e="";return this.options.topbarIconPath&&(e+=`.topbar-wrapper { content: url('data:image/png;base64,${this.b64(this.options.topbarIconPath)}'); width: 200px; height: auto; }\n`),e+`\n .topbar-wrapper svg { visibility: hidden; }\n .swagger-ui .topbar { background-color: ${this.options.topbarBgColor||fe.topbarBgColor}; }\n `}getCustomOptions(){const e={};return this.options.faviconPath&&(e.customfavIcon=this.b64(this.options.faviconPath,!0)),{customSiteTitle:this.options.title,...e,customCss:this.customCSS(),swaggerOptions:{persistAuthorization:this.options.persistAuthorization}}}b64(e,t=!1){const r=b.join(this.options.assetsPath||"",e),o=h.readFileSync(r,{encoding:"base64"});return t?"data:image/png;base64,"+o:o}}class ge{constructor(e,t){this.app=e,this.options=t}createDocument(){const e=this.options.path?this.options.description+""+`<br><br><a href="${this.options.openApiJsonPath}">OpenAPI JSON Spec</a> | `+`<a href="${this.options.openApiYamlPath}">OpenAPI YAML Spec</a>`:this.options.description,t=(new n.DocumentBuilder).setTitle(this.options.title).setDescription(e).setVersion(this.options.version||"0.0.1").addBearerAuth(this.options.auth||fe.auth).build();return n.SwaggerModule.createDocument(this.app,t,{extraModels:this.options.extraModels||[]})}registerOpenApiRoute(e,t,r){if(!e)return;const o=this.app.getHttpAdapter();e=e.startsWith("/")?e:"/"+e,o.get(e,(e,a)=>{o.reply(a,r(),200,{"Content-Type":t})})}setupSwagger(){const e=this.createDocument(),t=new ye({title:this.options.title,path:this.options.path||fe.path,persistAuthorization:this.options.persistAuthorization??!0,assetsPath:this.options.assetsPath,faviconPath:this.options.faviconFilePath,topbarIconPath:this.options.topbarIconFilePath,topbarBgColor:this.options.topbarBgColor});n.SwaggerModule.setup(this.options.path||fe.path,this.app,e,{...t.getCustomOptions(),jsonDocumentUrl:this.options.openApiJsonPath?""+this.options.openApiJsonPath:void 0,yamlDocumentUrl:this.options.openApiYamlPath?""+this.options.openApiYamlPath:void 0}),this.registerOpenApiRoute(this.options.openApiJsonPath,"application/json",()=>e),this.registerOpenApiRoute(this.options.openApiYamlPath,"application/x-yaml",()=>f.stringify(e))}}var _e,Ae;function be(e){return r=>(t.Metadata.set("transformers",e,r),"function"==typeof r?t.metadata("transformers",e)(r):r)}e.DecafRequestHandlerInterceptor=_e=class{constructor(e,t){this.requestContext=e,this.executor=t}async contextualize(e){const t={headers:e.headers,overrides:{}},r=i.Adapter.flavoursToTransform();if(r)for(const o of r)try{const r=i.Adapter.transformerFor(o),a=await r.from(e);Object.assign(t.overrides,a)}catch(e){throw new c.InternalError("Failed to contextualize request: "+e)}return(new i.Context).accumulate(Object.assign({},i.DefaultAdapterFlags,{logger:l.Logging.get(),timestamp:new Date},t))}async intercept(e,t){const r=e.switchToHttp().getRequest(),o=e.switchToHttp().getResponse(),a=l.Logging.for(_e).for(this.intercept);a.debug(`CONTEXT ${this.requestContext.uuid} - request: ${r.method} ${r.url}`);const i=await this.contextualize(r);return a.debug(`CONTEXT ${this.requestContext.uuid} contextualized - request: ${r.method} ${r.url}`),this.requestContext.applyCtx(i),a.debug(`CONTEXT ${this.requestContext.uuid} applied - request: ${r.method} ${r.url}`),await this.executor.exec(r,o),a.debug(`CONTEXT ${this.requestContext.uuid} executors finished - request: ${r.method} ${r.url}`),t.handle()}},e.DecafRequestHandlerInterceptor=_e=p.__decorate([o.Injectable({scope:o.Scope.REQUEST}),p.__metadata("design:paramtypes",[e.DecafRequestContext,e.DecafHandlerExecutor])],e.DecafRequestHandlerInterceptor),e.DecafCoreModule=class{static{Ae=this}static get persistence(){if(!this._persistence)throw new c.InternalError("Persistence service not initialized");return this._persistence}static get log(){return this._logger||(this._logger=l.Logging.for(Ae)),this._logger}constructor(e,t){this.options=e,this.moduleRef=t}static forRoot(t){const r=this.log.for(this.forRoot);return{module:Ae,providers:[{provide:F,useValue:t},{provide:N,useValue:this.persistence?.client},{provide:L,useFactory:()=>t.handlers?.map(e=>(r.info("Registered request handler: "+e.name),new e))??[]},e.AuthInterceptor,{provide:d.APP_INTERCEPTOR,useExisting:e.AuthInterceptor},e.DecafRequestContext,e.DecafHandlerExecutor,{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[F,N,L,e.DecafRequestContext,e.DecafHandlerExecutor]}}static async bootPersistence(e){const t=this.log.for(this.bootPersistence);if(!this._persistence){const r=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new i.PersistenceService,await this._persistence.boot(r);const o=this._persistence.client;for(let t=0;t<o.length;t++){const r=e.conf[t];let a=r.slice(2,r.length).pop();if(!a||!a.from){const e=i.Adapter.transformerFor(o[t].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${o[t].flavour}. you should either @requestToContextTransformer or provide a transformer in the config`);try{a=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${o[t].flavour}: ${e}`)}}be(o[t].flavour)(a)}if(t.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize application: "+e)}}return this.persistence.client}async onApplicationShutdown(){const e=Ae.log.for(this.onApplicationShutdown),t=this.moduleRef.get(N);for(const r of t)try{r&&(e.info("Shutting down "+r.toString()),await r.shutdown())}catch(t){e.error("Failed to shutdown application",t)}try{await i.Service.shutdown()}catch(t){e.error("Failed to shutdown services",t)}}},e.DecafCoreModule=Ae=p.__decorate([o.Global(),o.Module({}),p.__param(0,o.Inject(F)),p.__metadata("design:paramtypes",[Object,d.ModuleRef])],e.DecafCoreModule);const Pe=Symbol("LISTENING_ADAPTERS_FLAVOURS");var Ee,ve,Oe,Re;e.EventsController=Ee=class extends ee{constructor(e,t){super(e,Ee.name),this.adapters=t.map(e=>i.Adapter.get(e))}listen(){const e=l.Logging.for(Ee.name),t=new u.Observable(t=>{const r=("B-"+Math.random().toString(36).slice(2,8)).toUpperCase();e.info(`Creating SSE observer: ${r} for client ${this.clientContext.uuid}`);const o=new class{constructor(){this.observerId=r}refresh(...r){return e.debug(`SSE observer ${this.observerId} received refresh event`),Promise.resolve().then(()=>{const o=(e=>{const[t,r,o,a]=e;return[t?.name??t,r,o,Array.isArray(a)?a.map(e=>{try{return"function"==typeof e.serialize?e.serialize():"string"==typeof e?e:JSON.stringify(e)}catch(e){return}}):a&&"function"==typeof a.serialize?a.serialize():"string"==typeof a?a:JSON.stringify(a)]})(r);t.next({type:"message",data:o}),e.debug(`SSE observer ${this.observerId} event pushed to client`)})}};e.verbose(`Registering observer ${r} across ${this.adapters.length} adapter(s)`);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Registering observer ${r} in adapter ${a}`),t.observe(o)}catch(t){e.debug(`Failed to register observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}return()=>{e.debug("Cleaning up SSE observer "+r);for(const t of this.adapters){const a=t?.constructor?.name??"UnknownAdapter";try{e.debug(`Unregistering observer ${r} from adapter ${a}`),t.unObserve(o)}catch(t){e.debug(`Failed during cleanup of observer ${r} in adapter ${a}: ${t?.message||t}`),e.error(t)}}}}),r=u.interval(15e3).pipe(y.tap(()=>{e.debug("Sending heartbeat")}),y.map(()=>({type:"heartbeat",data:{ts:(new Date).toISOString()}})));return u.merge(t,r)}listenForModel(e){const t=l.Logging.for(Ee.name);return new u.Observable(e=>{const r=new class{refresh(...t){return Promise.resolve().then(()=>{e.next({data:t})})}};try{for(const e of this.adapters)e.observe(r)}catch(t){e.error("Failed to observe event: "+(t.message||t))}return()=>{try{for(const e of this.adapters)e.unObserve(r)}catch(e){t.error(e)}}})}},p.__decorate([o.Sse(),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listen",null),p.__decorate([o.Sse("/:model"),p.__param(0,o.Query("model")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",u.Observable)],e.EventsController.prototype,"listenForModel",null),e.EventsController=Ee=p.__decorate([o.Controller(),p.__param(1,o.Inject(Pe)),p.__metadata("design:paramtypes",[e.DecafRequestContext,Array])],e.EventsController),e.DecafStreamModule=ve=class{static forFlavours(t,r="events"){return{module:ve,controllers:[e.EventsController],imports:[d.RouterModule.register([{path:r.replace(/^\//,""),module:ve}])],providers:[e.DecafRequestContext,{provide:Pe,useValue:t??[]}]}}},e.DecafStreamModule=ve=p.__decorate([o.Module({})],e.DecafStreamModule),e.DecafModule=Oe=class{static async forRootAsync(t){const{autoControllers:r,autoServices:o}=t,a=(await e.DecafCoreModule.bootPersistence(t)).map(e=>e.flavour),i=[e.DecafCoreModule.forRoot(t)];return r&&a.forEach(e=>{i.push(ue(e).forRoot(e,{autoServices:o}))}),t.observerOptions?.enableObserverEvents&&i.push(e.DecafStreamModule.forFlavours(t.observerOptions.observerFlavours||a)),{module:Oe,imports:i}}},e.DecafModule=Oe=p.__decorate([o.Module({})],e.DecafModule);const we=l.Logging.for("DecafMigrationModule");var Se,De,Ce;e.DecafMigrationModule=Re=class{static forRoot(){return{module:Re}}static async migrate(e,t){const r=we.for(this.migrate);if(!t||0===t.length)throw new c.InternalError("No adapters provided. Make sure DecafCoreModule is configured and adapters are available.");return r.info("Running migrations with config: "+JSON.stringify(e)),g.MigrationService.migrateAdapters(t,e||{})}},e.DecafMigrationModule=Re=p.__decorate([o.Global(),o.Module({providers:[{provide:"MIGRATION_ADAPTERS",useFactory:e=>e,inject:[N]}],exports:["MIGRATION_ADAPTERS"]})],e.DecafMigrationModule),e.WebhookSubscriptionActionsController=Se=class extends ee{constructor(e){super(e,Se.name)}async deactivate(e){const{ctx:t}=(await this.logCtx([],"deactivate",!0)).for(this.deactivate),r=i.Repository.forModel(_.WebhookSubscription),o=await r.read(e,t);return o.active=!1,r.update(o,t)}async reactivate(e){const{ctx:t}=(await this.logCtx([],"reactivate",!0)).for(this.reactivate),r=i.Repository.forModel(_.WebhookSubscription),o=await r.read(e,t);return o.active=!0,r.update(o,t)}},p.__decorate([o.Post(":id/deactivate"),p.__param(0,o.Param("id")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",Promise)],e.WebhookSubscriptionActionsController.prototype,"deactivate",null),p.__decorate([o.Post(":id/reactivate"),p.__param(0,o.Param("id")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",Promise)],e.WebhookSubscriptionActionsController.prototype,"reactivate",null),e.WebhookSubscriptionActionsController=Se=p.__decorate([o.Controller("webhook-subscriptions"),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.WebhookSubscriptionActionsController),e.WebhookEventActionsController=De=class extends ee{constructor(e){super(e,De.name)}async replay(e){const{ctx:t}=(await this.logCtx([],"replay",!0)).for(this.replay),r=i.Repository.forModel(_.WebhookEventRecord),o=i.Repository.forModel(_.WebhookDelivery);try{let a;try{a=await r.read(e,t)}catch(o){const i=await r.select().where(r.attr("id").eq(e)).limit(1).execute(t);if(!i.length)throw o;a=i[0]}let s=[];try{s=await _.collectPagedResults(()=>o.select().where(o.attr("eventId").eq(a.id)).orderBy("createdAt",i.OrderDirection.ASC).thenBy("id",i.OrderDirection.ASC).paginate(250,t),250,t)}catch{try{s=await o.select().where(o.attr("eventId").eq(a.id)).execute(t)}catch{s=[]}}const n=new Date;for(const e of s)e.status=_.WebhookStatus.PENDING,e.attempts=0,e.nextAttemptAt=n,e.lastAttemptAt=null,e.errorMessage=void 0,e.responseStatus=void 0,e.responseBody=void 0;if(a.status=_.WebhookStatus.PENDING,a.deliveriesSucceeded=0,a.deliveriesFailed=0,a.nextAttemptAt=n,a.updatedAt=n,s.length)try{await o.updateAll(s,t.override({applyUpdateValidation:!1}))}catch{}return r.update(a,t)}catch(e){throw e}}},p.__decorate([o.Post(":id/replay"),p.__param(0,o.Param("id")),p.__metadata("design:type",Function),p.__metadata("design:paramtypes",[String]),p.__metadata("design:returntype",Promise)],e.WebhookEventActionsController.prototype,"replay",null),e.WebhookEventActionsController=De=p.__decorate([o.Controller("webhook-events"),p.__metadata("design:paramtypes",[e.DecafRequestContext])],e.WebhookEventActionsController),e.DecafWebhookModule=class{static{Ce=this}static{this._logger=l.Logging.for(Ce)}static get log(){return this._logger}static async bootPersistence(e){const r=this.log.for(this.bootPersistence);if(!this._persistence){const o=e.conf.map(([e,t,...r])=>r.pop()?[e,t,...r]:[e,t]);this._persistence=new i.PersistenceService,await this._persistence.boot(o);const a=this._persistence.client;for(let r=0;r<a.length;r++){const o=i.Adapter._cache||(i.Adapter._cache={}),s=[a[r].flavour,a[r].alias,"webhook_deliveries","webhook_events","webhook_subscriptions"].filter(e=>!!e);for(const e of s)o[e]=a[r];const n=e.conf[r];let p=n.slice(2,n.length).pop();if(!p||!p.from){const e=i.Adapter.transformerFor(a[r].flavour);if(!e)throw new c.InternalError(`No transformer found for flavour ${a[r].flavour}.`);try{p=e.from?e:new e}catch(e){throw new c.InternalError(`Failed to boot transformer for ${a[r].flavour}: ${e}`)}}be(a[r].flavour)(p),t.uses(a[r].flavour)(_.WebhookSubscription),t.uses(a[r].flavour)(_.WebhookEventRecord),t.uses(a[r].flavour)(_.WebhookDelivery)}if(r.info("persistence layer created successfully!"),e.initialization)try{await e.initialization()}catch(e){throw new c.InternalError("Failed to initialize webhook module: "+e)}}return this._persistence.client}static async forRoot(e){return this.forRootAsync(e)}static async forRootAsync(t){await this.bootPersistence(t);const r=[le.create(_.WebhookSubscription),le.create(_.WebhookEventRecord),le.create(_.WebhookDelivery),e.WebhookSubscriptionActionsController,e.WebhookEventActionsController];return{module:Ce,controllers:r,imports:[d.RouterModule.register([{path:(t.webhookApiPath||"webhooks").replace(/^\//,""),module:Ce}])],providers:[e.DecafRequestContext,e.DecafHandlerExecutor,{provide:L,useFactory:()=>t.handlers?.map(e=>new e)??[]},{provide:d.APP_INTERCEPTOR,useClass:e.DecafRequestHandlerInterceptor}],exports:[e.DecafRequestContext,e.DecafHandlerExecutor]}}},e.DecafWebhookModule=Ce=p.__decorate([o.Module({})],e.DecafWebhookModule);const Te=e.DecafWebhookModule,xe="##VERSION##",Me="##PACKAGE##";t.Metadata.allowReregistration(!0),t.Metadata.registerLibrary(Me,xe),t.Metadata.allowReregistration(!1),Object.defineProperty(e,"WebhookDelivery",{enumerable:!0,get:()=>_.WebhookDelivery}),Object.defineProperty(e,"WebhookDeliveryService",{enumerable:!0,get:()=>_.WebhookDeliveryService}),Object.defineProperty(e,"WebhookEventRecord",{enumerable:!0,get:()=>_.WebhookEventRecord}),Object.defineProperty(e,"WebhookPublisherService",{enumerable:!0,get:()=>_.WebhookPublisherService}),Object.defineProperty(e,"WebhookSignatureMiddleware",{enumerable:!0,get:()=>_.WebhookSignatureMiddleware}),Object.defineProperty(e,"WebhookStatus",{enumerable:!0,get:()=>_.WebhookStatus}),Object.defineProperty(e,"WebhookSubscription",{enumerable:!0,get:()=>_.WebhookSubscription}),Object.defineProperty(e,"WebhookSubscriptionService",{enumerable:!0,get:()=>_.WebhookSubscriptionService}),Object.defineProperty(e,"computeNextAttempt",{enumerable:!0,get:()=>_.computeNextAttempt}),Object.defineProperty(e,"signWebhookPayload",{enumerable:!0,get:()=>_.signWebhookPayload}),Object.defineProperty(e,"verifyWebhookSignature",{enumerable:!0,get:()=>_.verifyWebhookSignature}),e.AUTH_HANDLER=K,e.AUTH_META_KEY=U,e.ApiOperationFromModel=T,e.ApiParamsFromModel=x,e.ApiProperty=S,e.Auth=H,e.BulkApiOperationFromModel=(e,r,a)=>{const i={GET:[c.BulkCrudOperationKeys.READ_ALL,o.Get],POST:[c.BulkCrudOperationKeys.CREATE_ALL,o.Post],PUT:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Put],PATCH:[c.BulkCrudOperationKeys.UPDATE_ALL,o.Patch],DELETE:[c.BulkCrudOperationKeys.DELETE_ALL,o.Delete]},[s,p]=i[r];return C(e,s)?t.apply(n.ApiExcludeEndpoint()):t.apply(p(a))},e.COMMIT="356fbe1",e.CorsError=he,e.DECAF_ADAPTER_ID=N,e.DECAF_ADAPTER_OPTIONS=B,e.DECAF_CONTEXT_KEY=W,e.DECAF_HANDLERS=L,e.DECAF_MODULE_OPTIONS=F,e.DECAF_ROUTE=j,e.DECAF_TASK_SERVICE_ID="DecafTaskService",e.DECORATORS=E,e.DECORATORS_PREFIX=P,e.DecafAuthHandler=G,e.DecafBody=M,e.DecafController=ee,e.DecafModelController=te,e.DecafParams=I,e.DecafQuery=$,e.DecafRoleAuthHandler=class extends G{constructor(){super()}async authorize(e,r){const o=e.switchToHttp().getRequest(),s=this.parseRequest(o);if(!s)throw new i.AuthorizationError("Unauthenticated");const n=t.Metadata.get(a.Model.get(r),i.PersistenceKeys.AUTH_ROLE);if(!n.includes(s))throw new i.AuthorizationError("Missing role: "+s);return n}},e.DecafWebhooksModule=Te,e.DtoFor=ae,e.FULL_VERSION="0.11.0-356fbe1",e.FromModelController=le,e.HttpVerbToDecorator=q,e.NestBootstraper=class{static get logger(){return this._logger||(this._logger=new o.Logger("NestBootstrap")),this._logger}static initialize(e){return this.app=e,this}static enableLogger(e){return this._logger=e||new o.Logger("NestBootstrap"),this.app.useLogger(this._logger),this}static enableCors(e=[],t=["GET","POST","PUT","DELETE"]){const r="*"===e?"*":e.map(e=>e.trim().toLowerCase()),o={origin:(e,t)=>e?"*"===r||Array.isArray(r)&&r.includes(e.toLowerCase())?t(null,!0):void t(new he(`Origin ${e} not allowed`)):t(null,!0),credentials:!0,methods:t.join(",")};return this.app.enableCors(o),this}static useHelmet(e){try{const t=require("helmet");this.app.use(t(e)),this.logger.log("Helmet middleware enabled successfully.")}catch(e){this.logger.warn("Helmet not installed. Skipping middleware.")}return this}static setupSwagger(e){return new ge(this.app,{title:e.title,description:e.description,version:e.version,path:e.path||"api",persistAuthorization:e.persistAuthorization??!0,assetsPath:e.assetsPath,faviconFilePath:e.faviconPath,topbarIconFilePath:e.topbarIconPath,topbarBgColor:e.topbarBgColor,openApiJsonPath:e.openApiJsonPath,openApiYamlPath:e.openApiYamlPath}).setupSwagger(),this}static useGlobalPipes(...e){return e.length>0&&this.app.useGlobalPipes(...e),this}static useGlobalFilters(...t){return this.app.useGlobalFilters(...t.length>0?t:[new e.DecafExceptionFilter]),this}static useGlobalInterceptors(...e){return e.length>0&&this.app.useGlobalInterceptors(...e),this}static async start(e=Number(process.env.PORT)||3e3,t=void 0,r=!0){this.app.listen(e,t).then(async()=>{if(r){const e=await this.app.getUrl();this.logger.log("\ud83d\ude80 Application is running at: "+e)}})}},e.PACKAGE_NAME=Me,e.RequestToContextTransformer=class{},e.SwaggerBuilder=ge,e.UseDecafFilter=()=>o.UseFilters(new e.DecafExceptionFilter),e.UseDecafHeaders=()=>o.UseInterceptors(e.DecafResponseInterceptor),e.VERSION=xe,e.createApiPropertyDecorator=D,e.createPropertyDecorator=w,e.getEnumType=R,e.getEnumValues=O,e.getModuleFor=ue,e.isOperationBlocked=C,e.isUndefined=v,e.repoForModel=e=>{const t=a.Model.get(e);if(!t)throw new c.InternalError("Failed to find repository for "+e);return i.Repository.forModel(t)},e.requestToContextTransformer=be,e.runMigrations=async()=>{},e.runWebhooksMigrations=async()=>{}},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/decoration"),require("@decaf-ts/injectable-decorators"),require("@nestjs/common"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/core"),require("lodash"),require("@nestjs/swagger"),require("@decaf-ts/db-decorators"),require("tslib"),require("@nestjs/core"),require("@decaf-ts/logging"),require("rxjs"),require("fs"),require("path"),require("yaml"),require("rxjs/operators"),require("@decaf-ts/core/migrations"),require("@decaf-ts/for-http/server")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/decoration","@decaf-ts/injectable-decorators","@nestjs/common","@decaf-ts/decorator-validation","@decaf-ts/core","lodash","@nestjs/swagger","@decaf-ts/db-decorators","tslib","@nestjs/core","@decaf-ts/logging","rxjs","fs","path","yaml","rxjs/operators","@decaf-ts/core/migrations","@decaf-ts/for-http/server"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["for-nest"]={},e.decafTsDecoration,e.decafTsInjectableDecorators,e.nestjsCommon,e.decafTsDecoratorValidation,e.decafTsCore,e.lodash,e.nestjsSwagger,e.decafTsDbDecorators,e.tslib,e.nestjsCore,e.decafTsLogging,e.rxjs,e.fs,e.path,e.yaml,e.operators,e.migrations,e.server);
2
2
  //# sourceMappingURL=for-nest.cjs.map