@decaf-ts/core 0.7.13 → 0.7.14

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/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,InternalError as a,Context as c,OperationKeys as l,Repository as h,wrapMethodWithContext as u,enforceDBDecorators as d,ValidationError as p,reduceErrorsToPrint as g,NotFoundError as f,DefaultSeparator as y,BadRequestError as m,ConflictError as w,onCreateUpdate as b,timestamp as v,onCreate as x,onUpdate as A,onDelete as E,afterAny as O,DBKeys as N,BulkCrudOperationKeys as C,readonly as T,prefixMethod as _,BaseError as R}from"@decaf-ts/db-decorators";import{LoggedClass as B,Logging as $,final as D,isClass as P,toCamelCase as I}from"@decaf-ts/logging";import{Model as k,hashObj as j,required as L,sf as F,ValidationKeys as M,async as U,type as G,list as q,model as Y}from"@decaf-ts/decorator-validation";import{Decoration as z,DefaultFlavour as H,Metadata as Q,apply as V,methodMetadata as W,DecorationKeys as X,uses as J,metadata as K,propMetadata as Z,prop as tt}from"@decaf-ts/decoration";import{Lock as et}from"@decaf-ts/transactional-decorators";var rt;(t=>{t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.GENERATED="generated"})(rt||(rt={}));const st=Object.assign({},o,{allowRawStatements:!0,allowGenerationOverride:!1,squashSimpleQueries:!0,allowComplexStatements:!0});class it{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new a("Observer already registered");this.observers.push({observer:t,filter:e})}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new a("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=ut.logCtx(s,this.updateObservers);(await Promise.allSettled(this.observers.filter(s=>{const{filter:o}=s;if(!o)return!0;try{return o(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(s=>{s.observer.refresh(t,e,r,...n)}))).forEach((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class nt extends c{constructor(){super()}}class ot extends a{constructor(t){super(t,ot.name,500)}}class at extends a{constructor(t,e=at.name){super(t,e,500)}}class ct extends at{constructor(t){super(t,ct.name)}}class lt extends B{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return lt.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new a("No context provided");const r=t.pop();if(!(r instanceof c))throw new a("No context provided");if(t.filter(t=>t instanceof c).length>1)throw Error("here");const s=this?r.logger.for(this).for(e):r.logger.clear().for(this).for(e);return{ctx:r,log:e?s.for(e):s,ctxArgs:[...t,r]}}}const ht=z.flavourResolver.bind(z);z.flavourResolver=t=>{try{const e=ht(t);if(e&&e!==H)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof Q.registeredFlavour?Q.registeredFlavour(r):void 0;if(s&&s!==H)return s;const i=ut._currentFlavour;if(i){const t=ut._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return H}};class ut extends lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ut._baseRepository)throw new a("This should be overridden when necessary. Otherwise it will be replaced lazily");return ut._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new a("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.Context=nt,this.alias in ut._cache)throw new a(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ut._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ut._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ut._currentFlavour=this.alias)}Dispatch(){return new ut._baseDispatch}ObserverHandler(){return new it}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new ut._baseSequence(t,this)}async flags(t,e,r,...s){let i=r.logger||$.for(this.toString());return r.correlationId&&(i=i.for({correlationId:r.correlationId})),Object.assign({},st,r,{affectedTables:(Array.isArray(e)?e:[e]).map(k.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:Array.isArray(e)?[]:Q.validationExceptions(e,t),logger:i})}async context(t,e,r,...s){this.log.for(this.context).debug(`Creating new context for ${t} operation on ${Array.isArray(r)?r.map(t=>t.name):r.name} model with flag overrides: ${JSON.stringify(e)}`);const i=await this.flags(t,r,e,...s);return(new this.Context).accumulate(i)}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const i=k.columnName(t.constructor,r);if(this.isReserved(i))throw new a(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[rt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[rt.METADATA]),Object.defineProperty(i,rt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[rt.METADATA]})),{record:i,id:t[k.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),c={},l=k.pk(e);c[l]=r;const h=new e(c);n.silly(`Rebuilding model ${h.constructor.name} id ${r}`);const u=t[rt.METADATA],d=Object.keys(h).reduce((r,s)=>(s===l||(r[s]=t[k.columnName(e,s)]),r),h);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in d)throw new a(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);d[t]=e})),u&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${u}`),Object.defineProperty(d,rt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),d}async createAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),o=k.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Promise.all(e.map((e,s)=>this.create(t,e,r[s],...n)))}async readAll(t,e,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=k.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Promise.all(e.map(e=>this.read(t,e,...i)))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),o=k.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Promise.all(e.map((e,s)=>this.update(t,e,r[s],...n)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=ut.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map(e=>this.delete(t,e,...i)))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);r.verbose("Registering new observer "+t.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=ut.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(t,e,r,...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return Q.flavourOf(t)}static get currentFlavour(){if(!ut._currentFlavour)throw new a("No persistence flavour set. Please initialize your adapter");return ut._currentFlavour}static get current(){return ut.get(this.currentFlavour)}static get(t){if(!t)return ut.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new a(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return Q.flavouredAs(t)}catch(t){throw new a(t)}}static decoration(){}static logCtx(t,e){return super.logCtx(t,e)}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${j(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return this.proxies[r]=i,i}migrations(){return Q.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof nt&&(e=[t],t=this.migrations());const{ctx:r}=ut.logCtx(e,this.migrate),s=await this.getQueryRunner();for(const e of t)try{const t=new e;await t.up(s,this,r),await t.down(s,this,r)}catch(t){throw new at(t)}}}i([D(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],ut.prototype,"shutdownProxies",null),i([D(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],ut.prototype,"context",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],ut.prototype,"observe",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ut.prototype,"unObserve",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],ut.prototype,"client",null);class dt extends a{constructor(t){super(t,dt.name,500)}}class pt extends a{constructor(t){super(t,pt.name,500)}}var gt,ft,yt,mt,wt,bt;(t=>{t.FIND_BY="findBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(gt||(gt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP"})(ft||(ft={})),(t=>{t.AND="AND",t.OR="OR"})(yt||(yt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy"})(mt||(mt={}));class vt extends k{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):k.fromModel(this,t)}and(t){return vt.and(this,t)}or(t){return vt.or(this,t)}not(t){return new vt(this,ft.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof vt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ft).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof vt){if(!(this.comparison instanceof vt)&&this.operator!==ft.NOT)return{comparison:{condition:t}};if(-1===Object.values(yt).indexOf(this.operator)&&this.operator!==ft.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return vt.group(t,yt.AND,e)}static or(t,e){return vt.group(t,yt.OR,e)}static group(t,e,r){return new vt(t,e,r)}static attribute(t){return(new vt.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(ft.EQUAL,t)}dif(t){return this.setOp(ft.DIFFERENT,t)}gt(t){return this.setOp(ft.BIGGER,t)}lt(t){return this.setOp(ft.SMALLER,t)}gte(t){return this.setOp(ft.BIGGER_EQ,t)}lte(t){return this.setOp(ft.SMALLER_EQ,t)}in(t){return this.setOp(ft.IN,t)}regexp(t){return this.setOp(ft.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new vt(this.attr1,this.operator,this.comparison)}catch(t){throw new dt(t)}}}}static builder(){return new vt.Builder}static from(t){return new vt(t)}}i([L(),n("design:type",Object)],vt.prototype,"attr1",void 0),i([L(),n("design:type",String)],vt.prototype,"operator",void 0),i([L(),n("design:type",Object)],vt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(wt||(wt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(bt||(bt={}));const xt={update:bt.CASCADE,delete:bt.NONE},At={Equals:(t,e)=>vt.attribute(t).eq(e),Diff:(t,e)=>vt.attribute(t).dif(e),LessThan:(t,e)=>vt.attribute(t).lt(e),LessThanEqual:(t,e)=>vt.attribute(t).lte(e),GreaterThan:(t,e)=>vt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>vt.attribute(t).gte(e),Between:(t,e,r)=>vt.attribute(t).gte(e).and(vt.attribute(t).lte(r)),In:(t,e)=>vt.attribute(t).in(e),Matches:(t,e)=>vt.attribute(t).regexp(e)},Et=t=>t.charAt(0).toLowerCase()+t.slice(1);class Ot{static build(t,...e){if(!t.startsWith(gt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),i=this.extractGroupBy(t),n=this.buildWhere(r,e),{orderBy:o,limit:a,offset:c}=this.extractOrderLimitOffset(r,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(t){const e=t.substring(gt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static getFieldsFromMethodName(t){return(this.extractCore(t).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(t=>{const{field:e}=this.parseFieldAndOperator(t);return e})}static extractSelect(t){const e=t.indexOf(gt.SELECT);if(-1===e)return;const r=t.substring(e+gt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(gt.AND).map(Et).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(gt.GROUP_BY);if(-1!==e)return t.substring(e+gt.GROUP_BY.length).split(gt.ORDER_BY)[0].split(gt.THEN_BY).map(Et).filter(Boolean)}static buildWhere(t,e){if(!t&&0===e.length)return;const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let i;if(r.forEach((t,r)=>{const{field:n,operator:o}=this.parseFieldAndOperator(t),a=o?At[o]:At.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===gt.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(t){for(const e of Object.keys(At))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:Et(r),operator:e}}return{field:Et(t)}}static extractOrderLimitOffset(t,e){const r=t.split(/And|Or/).length,s=e.slice(r);let i,n,o;return s.length>=1&&Array.isArray(s[0])&&(i=s[0]),2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function St(){return z.for(rt.STATEMENT).define({decorator:()=>(t,e,r)=>V(W(Q.key(rt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function Nt(t={}){return z.for(rt.QUERY).define({decorator:t=>(e,r,s)=>{const i=Ot.getFieldsFromMethodName(r);return V(W(Q.key(rt.QUERY,r),{...t,fields:i}),St(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=Ot.build(e.name,...s);let h=r.select(i);n&&(h=h.where(n));const{allowLimit:u,allowOffset:d,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(a||[])[0],allowed:p},{key:"limit",value:c,allowed:u},{key:"offset",value:l,allowed:d}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new dt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(h=h[t.key](t.value))}return h.execute()}})})(t))(e,r,s)},args:[t]}).apply()}class Ct extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=k.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],t&&(this._adapter=t),e&&(Ct.register(e,this,this.adapter.alias),t)&&Q.get(e,X.FLAVOUR)===H&&J(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(t=>{const e=t.name;u(this,this[e+"Prefix"],t,this[e+"Suffix"])})}logCtx(t,e){return ut.logCtx(t,e)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new it}async createPrefix(t,...e){const r=await nt.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(t=new this.class(t),s||await d(this,r.context,t,l.CREATE,l.ON),!i){const e=await Promise.resolve(t.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${k.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createSuffix(t,e){return super.createSuffix(t,e)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),o=n.map(t=>t.id);let a=n.map(t=>t.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((t,e)=>this.adapter.revert(t,this.class,o[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async createAllPrefix(t,...e){const r=await nt.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const n=k.sequenceFor(t[0]);let o=[];if(n.type?(n.name||(n.name=k.sequenceName(t[0],"pk")),o=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):o=t.map((t,e)=>{if(void 0===t[this.pk])throw new a("Primary key is not defined for model in position "+e);return t[this.pk]}),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),n.type&&(t[this.pk]="String"!==n.type||n.generated?o[e]:""+t[this.pk]),s||await d(this,r.context,t,l.CREATE,l.ON),t))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async readPrefix(t,...e){const r=await nt.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await d(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${k.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const r=await nt.args(l.READ,this.class,e,this.adapter,this._overrides||{});return await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,d(this,r.context,e,l.READ,l.ON)})),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${k.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(t,...e){const r=await nt.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation"),n=t[this.pk];if(!n)throw new a("No value for the Id is defined under the property "+this.pk);const o=await this.read(n,...r.args);if(t=k.merge(o,t,this.class),s||await d(this,r.context,t,l.UPDATE,l.ON,o),!i){const e=await Promise.resolve(t.hasErrors(o,...k.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const r=await nt.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation"),n=t.map(t=>{const e=t[this.pk];if(!e)throw new a("missing id on update operation");return e}),o=await this.readAll(n,...r.args);if(t=t.map((t,e)=>k.merge(o[e],t,this.class)),s||await Promise.all(t.map((t,e)=>d(this,r.context,t,l.UPDATE,l.ON,o[e]))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(o[r],t,...e)))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async deletePrefix(t,...e){const r=await nt.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await d(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${k.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const r=await nt.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.readAll(t,...r.args);return await Promise.all(s.map(async t=>d(this,r.context,t,l.DELETE,l.ON))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement().select(t).from(this.class)}async query(t,e,r=wt.ASC,s,i,...n){const o=await nt.args(rt.QUERY,this.class,n,this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(o.args,this.query),c=[e,r],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(a)}async listBy(t,e,...r){const s=await nt.args(mt.LIST_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.listBy);return i.verbose(`listing ${k.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...n)}async paginateBy(t,e,r,...s){const i=await nt.args(mt.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:n,ctxArgs:o}=this.logCtx(i.args,this.paginateBy);return n.verbose(`paginating ${k.tableName(this.class)} with page size ${r}`),this.select().orderBy([t,e]).paginate(r,...o)}async findOneBy(t,e,...r){const s=await nt.args(mt.FIND_ONE_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findOneBy);i.verbose(`finding ${k.tableName(this.class)} with ${t} ${e}`);const o=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...n);if(!o.length)throw new f("No results found");return o[0]}async findBy(t,e,...r){const s=await nt.args(mt.FIND_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findBy);return i.verbose(`finding ${k.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...n)}async statement(t,...e){if(!Ct.statements(this,t))throw new dt("Invalid prepared statement requested "+t);const r=await nt.args(rt.STATEMENT,this.class,e,this.adapter,this._overrides||{}),{log:s,ctxArgs:i}=this.logCtx(r.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...i)}attr(t){return vt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=k.tableName(this.class);this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:Q.constr(t)===Q.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString())}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>ut._baseSequence.parseValue(k.sequenceFor(this.class).type,t)):ut._baseSequence.parseValue(k.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||Q.flavourOf(t)||ut.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ct)return s;const n=e||Q.flavourOf(t)||s&&Q.get(s,rt.ADAPTER)||ut.currentFlavour,o=n?ut.get(n):void 0;if(!o)throw new a("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=k.tableName(t);let s=r;if(e&&(s=[r,e].join(y)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a("Could not find repository registered under "+r)}static register(t,e,r){let s=k.tableName(t);if(r&&(s=[s,r].join(y)),s in this._cache&&this._cache[s]instanceof Ct)throw new a(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ct?t.constructor:t,s=Q.get(r,e?Q.key(rt.STATEMENT,e):rt.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ct?t.constructor:t;return Q.get(r,e?Q.key(rt.QUERY,e):rt.QUERY)}}function Tt(t,e){if(!(e||(e=z.flavourResolver(t instanceof k?t.constructor:t))&&e!==H))throw new a("Could not retrieve flavour from model "+(t instanceof k?t.constructor.name:t.name));return F(rt.INJECTABLE,e,k.tableName(t))}i([St(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ct.prototype,"listBy",null),i([St(),n("design:type",Function),n("design:paramtypes",[Object,String,Number,void 0]),n("design:returntype",Promise)],Ct.prototype,"paginateBy",null),i([St(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"findOneBy",null),i([St(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"findBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],Ct.prototype,"observe",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ct.prototype,"unObserve",null),ut&&(ut._baseRepository=Ct);class _t extends t{get log(){return this.logger||(this.logger=$.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=k.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(n=k.get(t.toString())),!n)return;const o=rt.ADAPTER,a=r||Q.get(n,o);try{let t=a;try{a&&ut.get(a)}catch{const e=ut.current;e&&e.flavour===a&&(t=e.alias)}if(i=Ct.forModel(n,t),i instanceof Ct)return i;const r=a||Q.get(i.constructor,o)||Q.get(n,o);e.register(i,Tt(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=Ct.get(n,a);if("function"==typeof e){const t=a?ut.get(a):ut.current;if(!t)return;return new e(t,n)}}}return i}}async function Rt(t,e,r,s){if(!s){const e=k.get(t.constructor.name);if(!e)throw new a("Could not find model "+t.constructor.name);s=Ct.forModel(e,r)}if(void 0===t[k.pk(s.class)])return s.create(t,e);try{return s.update(t,e)}catch(r){if(!(r instanceof f))throw r;return s.create(t,e)}}async function Bt(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=Ut(s,r,this.adapter.alias),n=await e.read(i);return await Lt(t,s,r,i,n),void(s[r]=i)}const n=P(e.class)?e.class:e.class();if(!n)throw new a("Could not find model "+e.class);const o=Ct.forModel(n,this.adapter.alias),c=await o.create(i),l=k.pk(c);await Lt(t,s,r,c[l],c),s[r]=c[l]}async function $t(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==bt.CASCADE)return;if("object"!=typeof i){const e=Ut(s,r,this.adapter.alias),n=await e.read(i);return await Lt(t,s,r,i,n),void(s[r]=i)}const n=await Rt(s[r],t,this.adapter.alias),o=k.pk(n);await Lt(t,s,r,n[o],n),s[r]=n[o]}async function Dt(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==bt.CASCADE)return;const n=Ut(s,r,this.adapter.alias);let o;o=i instanceof k?await n.delete(s[r][n.pk]):await n.delete(s[r]),await Lt(t,s,r,o[n.pk],o)}async function Pt(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o=new Set([...i]);if("object"!==n){const e=Ut(s,r,this.adapter.alias);for(const i of o){const n=await e.read(i);await Lt(t,s,r,i,n)}return void(s[r]=[...o])}const c=k.pk(i[0]),l=new Set;for(const e of i){const i=await Rt(e,t,this.adapter.alias);await Lt(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function It(t,e,r,s){const{cascade:i}=e;if(i.update===bt.CASCADE)return Pt.call(this,t,e,r,s)}async function kt(t,e,r,s){if(e.cascade.delete!==bt.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o="object"===n,c=o?Ct.forModel(i[0],this.adapter.alias):Ut(s,r,this.adapter.alias),l=new Set([...o?i.map(t=>t[c.pk]):i]);for(const e of l.values()){const i=await c.delete(e);await Lt(t,s,r,e,i)}s[r]=[...l]}function jt(t,e,r){return[rt.POPULATE,t,e,r].join(".")}async function Lt(t,e,r,s,i){const n=jt(e.constructor.name,r,s);return t.accumulate({[n]:i})}async function Ft(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,e,r,s,i)=>{let n,o;const c=[];for(const l of s){n=jt(e.constructor.name,r,l);try{o=await t.get(n)}catch(t){const s=Ut(e,r,i);if(!s)throw new a("Could not find repo");o=await s.read(l)}c.push(o)}return c})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?o:o[0]}const Mt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Ut(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=Q.get(t instanceof k?t.constructor:t,Q.key(M.REFLECT,e,M.LIST))?.clazz;if(!r)throw new a("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map(t=>"function"!=typeof t||t.name?t:t())}else s=Q.getPropDesignTypes(t instanceof k?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Mt.includes((""+t.name).toLowerCase()));return Ct.forModel(i,r)}class Gt extends m{constructor(t,e=Gt.name,r=401){super(t,e,r)}}class qt extends Gt{constructor(t,e=qt.name){super(t,e,403)}}class Yt extends a{constructor(t){super(t,Yt.name,503)}}function zt(t){return z.for(rt.TABLE).define({decorator:t=>e=>K(rt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Ht(t){return z.for(rt.COLUMN).define({decorator:t=>(e,r)=>Z(Q.key(rt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Qt(t,e,r){return z.for(rt.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![wt.ASC,wt.DSC].includes(t))&&(e=t,t=void 0),Z(Q.key(`${rt.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Vt(t,e,r,s){if(s[r]&&(await this.select().where(vt.attribute(r).eq(s[r])).execute()).length)throw new w(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Wt(){const t=rt.UNIQUE;return z.for(t).define(U(),b(Vt),Z(t,{})).apply()}async function Xt(t,e,r,s){throw new Gt("This adapter does not support user identification")}function Jt(){return z.for(rt.CREATED_BY).define({decorator:()=>(t,e)=>V(x(Xt),Z(rt.CREATED_BY,e),ne())(t,e),args:[]}).apply()}function Kt(){return z.for(rt.UPDATED_BY).define({decorator:()=>(t,e)=>V(A(Xt),Z(rt.UPDATED_BY,e),ne())(t,e),args:[]}).apply()}function Zt(){return v([l.CREATE])}function te(){return v()}function ee(t,e=xt,r=!0,s,i){const n=rt.ONE_TO_ONE;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),G([t,String,Number,BigInt]),x(Bt,o),A($t,o),E(Dt,o),O(Ft,o))},args:[t,e,r,s,i]}).apply()}function re(t,e=xt,r=!0,s,i){const n=rt.ONE_TO_MANY;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),q([t,String,Number,BigInt]),x(Pt,o),A(It,o),E(kt,o),O(Ft,o))},args:[t,e,r,s,i]}).apply()}function se(t,e=xt,r=!0,s,i){const n=rt.MANY_TO_ONE;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),G([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ie(t,e=xt,r=!0,s,i){const n=rt.MANY_TO_MANY;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),q([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ne(){return(t,e)=>Z(Q.key(rt.GENERATED,e),!0)(t,e)}function oe(...t){return(e,r)=>{const s=Q.get(e,Q.key(rt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return V(K(Q.key(rt.NO_VALIDATE,r),i))(e,r)}}function ae(){return oe(l.CREATE)}function ce(){return oe(l.UPDATE)}function le(){return oe(l.UPDATE,l.CREATE)}function he(t,e){return z.for(rt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(Z(t,e)(r,s),Z(Q.key(rt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}z.for(N.TIMESTAMP).extend(ne()).apply(),z.for(N.COMPOSED).extend(ne()).apply(),Q.validationExceptions=((t,e)=>{const r=Q.get(t,rt.NO_VALIDATE);return r?Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t):[]}).bind(Q),k.shouldValidateNestedHandler=((t,e)=>{const r=Q.get(t.constructor);if(!r)return!1;const s=r[rt.RELATIONS],i=r[rt.RELATION];if(Array.isArray(s)&&s?.includes(e)){const r=Object.keys(i)[0],s=k.isPropertyModel(t,e);return i[r]?.class!==s}return!0}).bind(k),Q.migrationsFor=(t=>{if(!(t=t??ut.current))throw new a("Could not get adapter for migrations");return Q.innerGet(Symbol.for(rt.MIGRATION),t.alias).map(t=>t.class)}).bind(Q),Q.relations=((t,e)=>{const r=Q.get(t,rt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new a("No relations metadata found for property "+e);return r[e]}}).bind(Q),k.relations=(t,e)=>Q.relations(t instanceof k?t.constructor:t,e)||[],Q.generated=((t,e)=>!!Q.get("function"!=typeof t?t.constructor:t,Q.key(rt.GENERATED,e))).bind(Q),Q.createdBy=(t=>{const e=Q.get("function"!=typeof t?t.constructor:t,rt.CREATED_BY);if(!e)throw new a("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(Q),Q.updatedBy=(t=>{const e=Q.get("function"!=typeof t?t.constructor:t,rt.UPDATED_BY);if(!e)throw new a("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(Q),k.tableName=t=>{if(!(t instanceof k?k.get(t.constructor.name):t))throw new a("Unable to find model "+t);return Q.get(t instanceof k?t.constructor:t,rt.TABLE)||(t instanceof k?t.constructor.name:t.name)},k.columnName=(t,e)=>Q.get(t instanceof k?t.constructor:t,Q.key(rt.COLUMN,e))||e,k.sequenceName=(t,...e)=>[k.tableName(t),...e].join("_"),k.sequenceFor=(t,e)=>{if(e)throw new ot("not currently supported");const r=k.pkProps(t instanceof k?t.constructor:t);if(!r)throw new a("No sequence options defined for model. did you use the @pk decorator?");return r},k.indexes=t=>{const e=Q.get(t instanceof k?t.constructor:t,rt.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[rt.INDEX]:e[r]},t),{})},e.services=()=>Q.innerGet(Symbol.for(rt.SERVICE)),e.repositories=()=>Q.innerGet(Symbol.for(N.REPOSITORY));class ue extends lt{constructor(){super()}async initialize(){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const t=this.adapter;[l.CREATE,l.UPDATE,l.DELETE,C.CREATE_ALL,C.UPDATE_ALL,C.DELETE_ALL].forEach(e=>{if(!t[e])throw new a(`Method ${e} not found in ${t.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(t,e),s=t;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,e);r&&r.writable?t[e]=new Proxy(t[e],{apply:async(t,r,s)=>{const{log:i,ctxArgs:n}=r.logCtx(s,t),[o,a]=s,c=await t.apply(r,n);return this.updateObservers(o,(t=>{switch(t){case C.CREATE_ALL:return l.CREATE;case C.UPDATE_ALL:return l.UPDATE;case C.DELETE_ALL:return l.DELETE;default:return t}})(e),a,c,...n.slice(s.length)).then(()=>{i.verbose(`Observer refresh dispatched by ${e} for ${o}`),i.debug("pks: "+a)}).catch(t=>i.error(`Failed to dispatch observer refresh for ${e} on ${o}: ${t}`)),c}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof ut))throw new ot("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ut.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}unObserve(t){if(this.adapter!==t)throw new ot("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){const i="string"==typeof t?t:k.tableName(t),{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`Dispatching ${e} from table ${i} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new a("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}ut&&(ut._baseDispatch=ue);class de{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})}static get instance(){return de._instance||(de._instance=new de),de._instance}}class pe{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return pe._instance||(pe._instance=new pe),pe._instance}}function ge(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof ct)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class fe extends B{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;ge(this,t,this.prefix(e))})}get adapter(){const t=Q.get(this.constructor,rt.MIGRATION);if(!t)throw new a("No migration metadata for "+this.constructor.name);const e=t.flavour;return ut.get(e)}async enforceRules(t,e,r){const s=Q.get(this.constructor,rt.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const i of s)if(!await i(t,e,r))return!1;return!0}prefix(t){return async function(e){let r;e instanceof ut?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await nt.args("migration",k,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new ct("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function ye(t,e){return z.for(rt.MIGRATION).define({decorator:(t,e)=>r=>{const s=Q.innerGet(Symbol.for(rt.MIGRATION),t)||[];return Q.set(rt.MIGRATION,t,[...s,{class:r}]),K(rt.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}class me extends k{constructor(t){super(t)}}i([Zt(),n("design:type",Date)],me.prototype,"createdAt",void 0),i([te(),n("design:type",Date)],me.prototype,"updatedAt",void 0);const we={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},be=we,ve={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},xe=Object.assign({},ve,{type:"BigInt"});async function Ae(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=k.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e)}catch(t){throw new a(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,o,c;n=s,o=r,c=await i.next(t),Reflect.set(n,o,c)}function Ee(t,e){return(r,s)=>{switch(tt()(r,s),t.type){case void 0:{const e=Q.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e;break}case String.name||String.name.toLowerCase():case String:t.generated=!1,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=!0,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=!0;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const i=[Qt([wt.ASC,wt.DSC]),L(),T(),Z(Q.key(N.ID,s),t),x(Ae,t,e)];return t.generated&&i.push(ne()),V(...i)(r,s)}}function Oe(t=be){return t=Object.assign({},be,t),z.for(N.ID).define({decorator:Ee,args:[t,{priority:60}]}).apply()}let Se=class extends me{constructor(t){super(t)}};i([Oe({type:"String",generated:!1}),n("design:type",String)],Se.prototype,"id",void 0),i([L(),Qt(),n("design:type",Object)],Se.prototype,"current",void 0),Se=i([zt("??sequence"),Y(),n("design:paramtypes",[Object])],Se);class Ne extends lt{constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=Ct.forModel(Se,e.alias)}async current(...t){const e=(await nt.args(l.READ,Se,t,this.adapter)).context,{name:r,startWith:s}=this.options;try{const t=await this.repo.read(r,e);return this.parse(t.current)}catch(t){if(t instanceof f){if(void 0===s)throw new a("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new a(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new a(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let o;const c=e||i;if(c%i!==0)throw new a("Value to increment does not consider the incrementBy setting: "+i);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:o=this.parse(t)+c;break;case BigInt.name:o=this.parse(t)+BigInt(c);break;case String.name:o=this.parse(t);break;case"serial":o=pe.instance.generate(t);break;case"uuid":o=de.instance.generate(t);break;default:throw new a("Should never happen")}let l;try{l=await this.repo.update(new Se({id:n,current:o}),r)}catch(i){if(!(i instanceof f))throw i;try{l=await this.repo.create(new Se({id:n,current:o}),r)}catch(i){if(!(i instanceof w)||"uuid"!==s)throw i;return this.increment(t,e,r)}}return l.current}async next(...t){const e=await nt.args(l.UPDATE,Se,t,this.adapter),{context:r,args:s}=e,i=await this.current(...s);return this.increment(i,void 0,r)}async range(t,...e){const r=await nt.args(l.UPDATE,Se,e,this.adapter),{context:s,args:i}=r,n=await this.current(...i),o=this.parse(this.options.incrementBy),c=await this.increment(n,this.parse(t)*o,s),h=[];for(let e=1;t>=e;e++)h.push(n+o*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new ot(`type ${this.options.type} is currently not suppported for this adapter`);const u="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(h[h.length-1]!==c&&"String"!==u)throw new a("Miscalculation of range");return h}parse(t){return Ne.parseValue(this.options.type,t)}static pk(t){return k.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new ot(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Ce(t,e){return(i,n)=>n?r(Q.constr(t))(i,n):(Q.set(N.REPOSITORY,Q.key(e||ut.currentFlavour,k.tableName(t)),i),K(N.REPOSITORY,i.name)(t),e=e||Q.get(i.constructor,rt.ADAPTER),Ct.register(Q.constr(t),i,e),s(Q.constr(t),{callback:e=>(Object.defineProperty(e,N.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ut._baseSequence=Ne;class Te extends a{constructor(t){super(t,Te.name,500)}}class _e extends B{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new pt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new pt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}}function Re(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&((t,e)=>{const{handler:r,args:s}=Q.get(t,l.REFLECT+l.BLOCK)||{};return!!r&&(r(...s,e)??!1)})(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}const Be=()=>Re(l.CREATE),$e=()=>Re(l.READ),De=()=>Re(l.UPDATE),Pe=()=>Re(l.DELETE);function Ie(t){return t="string"==typeof t?t:Q.Symbol(t).toString(),(e,i,n)=>{Q.set(rt.SERVICE,t,e);const o=[];if(n&&"number"==typeof n.value)o.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(t))}else o.push(s(t,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return o.push(K(rt.SERVICE,t)),V(...o)(e,i,n)}}class ke{constructor(t){this.name=t,this.Context=nt}async flags(t,e,...r){let s=e.logger||$.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},st,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=e,i=await this.flags(t,s,...r);return(new this.Context).accumulate(i)}async logCtx(t,e,r=!1){return await ke.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const i=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await i()]);const n=t.pop();n instanceof nt||(t=[...t,await i()]);const o=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?o.for(e):o,ctxArgs:[...t,n]}}static get(t){if(!t)throw new a("No name provided");const r=e.get(t);if(r)return r;throw new a("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){const r={context:async t=>(new nt).accumulate(Object.assign({},st,{timestamp:new Date,operation:t,logger:$.get()}))},{log:s,ctxArgs:i}=await this.logCtx.bind(r)(t,this.boot,!0),n=e.services();for(const[t,e]of Object.entries(n))try{const t=new e;t instanceof je&&await t.boot(...i)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class je extends ke{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=await this.logCtx(t,this.boot,!0);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new a("Config not initialized");return this._config}get client(){if(!this._client)throw new a("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],je.prototype,"boot",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],je.prototype,"config",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],je.prototype,"client",null);const Le=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Fe extends ke{get class(){if(!this.clazz)throw new a("Class not initialized");return this.clazz}constructor(t){super(),this.clazz=t,this.repo=Ct.forModel(t)}static getService(t){if(!t)throw new a("No name provided");const e=Le(t);try{const t=ke.get(e);if(t)return t}catch(t){}throw new a("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,i)})}async create(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.create,!0);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.createAll,!0);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.delete,!0);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.deleteAll,!0);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.read,!0);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.readAll,!0);return this.repo.readAll(t,...r)}async query(t,...e){const r=this.repo?.[t];if("function"!=typeof r)throw Error(`Method "${t}" is not implemented`);return r.apply(this.repo,e)}async update(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.update,!0);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.updateAll,!0);return this.repo.updateAll(t,...r)}async logCtx(t,e,r=!1){return await Fe.logCtx.bind(this.repo.adapter)(t,e,r,{},this.class)}static forModel(t,e){let r;e=Le(e||t);try{r=Fe.get(e)}catch(t){r=void 0}if(r instanceof Fe)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([Ie(e),n("design:paramtypes",[])],o),new o}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);const o=t.pop();o instanceof nt||(t=[...t,await n()]);const c=this?o.logger.for(this).for(e):o.logger.clear().for(this).for(e);return{ctx:o,log:e?c.for(e):c,ctxArgs:[...t,o]}}}var Me,Ue,Ge,qe;i([Be(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"create",null),i([Be(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"createAll",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"delete",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"deleteAll",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"read",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"readAll",null),i([$e(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Fe.prototype,"query",null),i([De(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"update",null),i([De(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Fe.prototype,"updateAll",null);class Ye extends lt{constructor(t){super(),this.adapter=t,[this.execute,this.paginate].forEach(t=>{_(this,t,async(...e)=>{let r=e;if((!r.length||!(r[r.length-1]instanceof nt))&&this.fromSelector){const t=await this.adapter.context(rt.QUERY,{},this.fromSelector);r=[...r,t]}const{ctx:s,ctxArgs:i}=ut.logCtx(r,t.name);return s.get("allowRawStatements")||this.prepared||await this.prepare(s),i},t.name)})}get log(){return this.adapter.log.for(Ye)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}count(t){return this.countSelector=t,this}from(t){if(this.fromSelector="string"==typeof t?k.get(t):t,!this.fromSelector)throw new dt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const e=t.pop();try{const t=this.build();return await this.raw(t,e)}catch(t){throw new a(t)}}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw),i=await this.adapter.raw(t,...s);if(!this.selectSelector)return i;const n=k.pk(this.fromSelector),o=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case yt.AND:case yt.OR:{let t=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof vt){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case ft.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case ft.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case ft.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case ft.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case ft.BIGGER_EQ:n.method=r+" bigger than equal";break;case ft.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case ft.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case ft.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new dt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof vt)return;e=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:e?[e,wt.DSC]:[k.pk(this.fromSelector),wt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:mt.LIST_BY,args:[s],params:n};return e&&(o.method=mt.FIND_BY,o.args=[e,this.whereCondition.comparison],o.params=n),o}async prepare(t){if((t=t||await this.adapter.context(rt.QUERY,{},this.fromSelector)).get("squashSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},i=[gt.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);i.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&i.push(gt.SELECT,this.selectSelector.join(` ${gt.AND.toLowerCase()} `)),this.orderBySelector&&i.push(gt.ORDER_BY,...this.orderBySelector),this.groupBySelector&&i.push(gt.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=I(i.join(" ")),s.params=r,this.prepared=s,!t.get("squashSimpleQueries")||this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector||(this.prepared=s),this}async paginate(t,...e){e.pop();try{const e=this.build();return this.adapter.Paginator(e,t,this.fromSelector)}catch(t){throw new dt(t)}}toString(){return this.adapter.flavour+" statement"}}i([D(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ye.prototype,"select",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Me="undefined"!=typeof S&&S)?Me:Object]),n("design:returntype",Object)],Ye.prototype,"distinct",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ue="undefined"!=typeof S&&S)?Ue:Object]),n("design:returntype",Object)],Ye.prototype,"max",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ge="undefined"!=typeof S&&S)?Ge:Object]),n("design:returntype",Object)],Ye.prototype,"min",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(qe="undefined"!=typeof S&&S)?qe:Object]),n("design:returntype",Object)],Ye.prototype,"count",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ye.prototype,"from",null),i([D(),n("design:type",Function),n("design:paramtypes",[vt]),n("design:returntype",Object)],Ye.prototype,"where",null),i([D(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ye.prototype,"orderBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ye.prototype,"groupBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ye.prototype,"limit",null),i([D(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ye.prototype,"offset",null),i([D(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Ye.prototype,"execute",null);class ze extends Ye{constructor(t){super(t)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new a("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=Q.getPropDesignTypes(t.constructor,s);if(!n)throw new dt("type not compatible with sorting: "+n);switch(n.name){case"string":case"String":return("asc"===i?1:-1)*t[s].localeCompare(e[s]);case"number":case"Number":return("asc"===i?1:-1)*(t[s]-e[s]);case"object":case"Object":if(t[s]instanceof Date&&e[s]instanceof Date)return("asc"===i?1:-1)*(t[s].valueOf()-e[s].valueOf());throw new dt("Sorting not supported for not date classes");default:throw new dt("sorting not supported for type "+n)}}}build(){const t={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:t=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(t.sort=this.getSort()),t}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:i}=t;if(-1===[yt.AND,yt.OR,ft.NOT].indexOf(s))switch(s){case ft.BIGGER:return e[r]>i;case ft.BIGGER_EQ:return e[r]>=i;case ft.DIFFERENT:return e[r]!==i;case ft.EQUAL:return e[r]===i;case ft.REGEXP:if("string"!=typeof e[r])throw new dt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(i,"g"));case ft.SMALLER:return e[r]<i;case ft.SMALLER_EQ:return e[r]<=i;default:throw new a("Invalid operator for standard comparisons: "+s)}else{if(s===ft.NOT)throw new a("Not implemented");{const t=this.parseCondition(r),n=this.parseCondition(i);switch(s){case yt.AND:return t.where(e)&&n.where(e);case yt.OR:return t.where(e)||n.where(e);default:throw new a("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function He(t,e,r,s){const i=t.get("UUID");if(!i)throw new ot("This adapter does not support user identification");s[r]=i}const Qe="ram";class Ve extends _e{constructor(t,e,r,s){super(t,e,r,s)}prepare(t){const e=Object.assign({},t);return e.limit=this.size,e}async page(t=1,...e){const r=await nt.args(rt.QUERY,this.clazz,e,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=t.length,this._recordCount>0){const t=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const i=await this.adapter.raw(s,...e,r.context);return this._currentPage=t,i}}class We extends ut{constructor(t={},e){super(t,Qe,e),this.indexes={},this.lock=new et}repository(){return super.repository()}async flags(t,e,r){return Object.assign(await super.flags(t,e,r),{UUID:this.config.user||""+Date.now()})}Dispatch(){return super.Dispatch()}async index(...t){return Promise.resolve(void 0)}prepare(t,...e){const r=e.pop(),s=super.prepare(t,...e,r);return delete s.record[k.pk(t.constructor)],s}revert(t,e,r,s,...i){return super.revert(t,e,r,s,...i)}async create(t,e,r,s){const i=s.logger.for(this.create),n=k.tableName(t);if(i.debug(`creating record in table ${n} with id ${e}`),await this.lock.acquire(),this.client.has(n)||this.client.set(n,new Map),this.client.get(n)&&this.client.get(n)?.has(e))throw new w(`Record with id ${e} already exists in table ${n}`);return this.client.get(n)?.set(e,r),this.lock.release(),r}async read(t,e,r){const s=k.tableName(t);if(!this.client.has(s))throw new f(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new f(`Record with id ${e} not found in table ${s}`);return this.client.get(s)?.get(e)}async update(t,e,r,s){const i=s.logger.for(this.update),n=k.tableName(t);if(i.debug(`updating record in table ${n} with id ${e}`),await this.lock.acquire(),!this.client.has(n))throw new f(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new f(`Record with id ${e} not found in table ${n}`);return this.client.get(n)?.set(e,r),this.lock.release(),r}async delete(t,e,r){const s=r.logger.for(this.delete),i=k.tableName(t);if(s.debug(`deleting record from table ${i} with pk ${e}`),await this.lock.acquire(),!this.client.has(i))throw new f(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new f(`Record with id ${e} not found in table ${i}`);const n=this.client.get(i)?.get(e);return this.client.get(i)?.delete(e),this.lock.release(),n}tableFor(t){"string"==typeof t&&(t=k.get(t));const e=k.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e){e.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:r,sort:s,limit:i,skip:n,from:o}=t;let{select:c}=t;const l=this.tableFor(o);if(!l)throw new a(`Table ${o} not found in RamAdapter`);const h=k.pk(o),u=Q.get(o,Q.key(N.ID,h));let d=Array.from(l.entries()).map(([t,r])=>this.revert(r,o,Ne.parseValue(u.type,t),void 0,e));return d=r?d.filter(r):d,s&&(d=d.sort(s)),n&&(d=d.slice(n)),i&&(d=d.slice(0,i)),c&&(c=Array.isArray(c)?c:[c],d=d.map(t=>Object.entries(t).reduce((t,[e,r])=>(c.includes(e)&&(t[e]=r),t),{}))),d}parseError(t){return t instanceof R?t:new a(t)}Statement(){return new ze(this)}Paginator(t,e,r){return new Ve(this,t,e,r)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${j(t)}`;if(r in this.proxies)return this.proxies[r];const s=new Proxy(this,{get:(e,r,s)=>{if("_config"===r){const i=Reflect.get(e,r,s);return Object.assign({},i,t)}return Reflect.get(e,r,s)}});return this.proxies[r]=s,s}static decoration(){super.decoration();const t=rt.CREATED_BY,e=rt.UPDATED_BY;z.flavouredAs(Qe).for(t).define(x(He),Z(t,{})).apply(),z.flavouredAs(Qe).for(e).define(b(He),Z(e,{})).apply()}getClient(){return new Map}}We.decoration(),e.setRegistry(new _t);const Xe="##VERSION##",Je="##PACKAGE##";Q.registerLibrary(Je,Xe);export{fe as AbsMigration,ut as Adapter,Gt as AuthorizationError,me as BaseModel,xe as BigIntSequence,bt as Cascade,je as ClientBasedService,vt as Condition,Yt as ConnectionError,nt as Context,lt as ContextualLoggedClass,st as DefaultAdapterFlags,xt as DefaultCascade,be as DefaultSequenceOptions,ue as Dispatch,qt as ForbiddenError,yt as GroupOperator,_t as InjectablesRegistry,Ot as MethodQueryBuilder,at as MigrationError,ct as MigrationRuleError,Fe as ModelService,we as NoneSequenceOptions,ve as NumericSequence,Te as ObserverError,it as ObserverHandler,ft as Operator,At as OperatorsMap,wt as OrderDirection,Je as PACKAGE_NAME,_e as Paginator,pt as PagingError,rt as PersistenceKeys,mt as PreparedStatementKeys,gt as QueryClause,dt as QueryError,We as RamAdapter,Qe as RamFlavour,Ve as RamPaginator,ze as RamStatement,Ct as Repository,Ne as Sequence,Se as SequenceModel,pe as Serial,ke as Service,Ye as Statement,de as UUID,ot as UnsupportedError,Xe as VERSION,Lt as cacheModelForPopulate,Ht as column,Be as create,Rt as createOrUpdate,Zt as createdAt,Jt as createdBy,Xt as createdByOnCreateUpdate,He as createdByOnRamCreateUpdate,Pe as del,Tt as generateInjectableNameForRepository,ne as generated,jt as getPopulateKey,Qt as index,ie as manyToMany,se as manyToOne,ye as migration,oe as noValidateOn,ae as noValidateOnCreate,le as noValidateOnCreateUpdate,ce as noValidateOnUpdate,re as oneToMany,Pt as oneToManyOnCreate,kt as oneToManyOnDelete,It as oneToManyOnUpdate,ee as oneToOne,Bt as oneToOneOnCreate,Dt as oneToOneOnDelete,$t as oneToOneOnUpdate,Oe as pk,Ee as pkDec,Ae as pkOnCreate,Ft as populate,ge as prefixMethod,St as prepared,Nt as query,$e as read,he as relation,Ce as repository,Ut as repositoryFromTypeMetadata,Ie as service,zt as table,Wt as unique,Vt as uniqueOnCreateUpdate,De as update,te as updatedAt,Kt as updatedBy};
1
+ import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,InternalError as a,Context as c,OperationKeys as l,Repository as h,wrapMethodWithContext as u,enforceDBDecorators as d,ValidationError as p,reduceErrorsToPrint as g,NotFoundError as f,DefaultSeparator as y,BadRequestError as m,ConflictError as w,onCreateUpdate as b,timestamp as v,onCreate as x,onUpdate as A,onDelete as E,afterAny as O,DBKeys as N,BulkCrudOperationKeys as C,readonly as T,prefixMethod as _,BaseError as R}from"@decaf-ts/db-decorators";import{LoggedClass as B,Logging as $,final as D,isClass as P,toCamelCase as I}from"@decaf-ts/logging";import{Model as k,hashObj as j,required as L,sf as F,ValidationKeys as M,async as U,type as G,list as q,model as Y}from"@decaf-ts/decorator-validation";import{Decoration as z,DefaultFlavour as H,Metadata as Q,apply as V,methodMetadata as W,DecorationKeys as X,uses as J,metadata as K,propMetadata as Z,prop as tt}from"@decaf-ts/decoration";import{Lock as et}from"@decaf-ts/transactional-decorators";var rt;(t=>{t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.GENERATED="generated"})(rt||(rt={}));const st=Object.assign({},o,{allowRawStatements:!0,allowGenerationOverride:!1,squashSimpleQueries:!0,allowComplexStatements:!0});class it{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map((t=>t.observer)).indexOf(t))throw new a("Observer already registered");this.observers.push({observer:t,filter:e})}unObserve(t){const e=this.observers.map((t=>t.observer)).indexOf(t);if(-1===e)throw new a("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=ut.logCtx(s,this.updateObservers);(await Promise.allSettled(this.observers.filter((s=>{const{filter:o}=s;if(!o)return!0;try{return o(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}})).map((s=>{s.observer.refresh(t,e,r,...n)})))).forEach(((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)}))}}class nt extends c{constructor(){super()}}class ot extends a{constructor(t){super(t,ot.name,500)}}class at extends a{constructor(t,e=at.name){super(t,e,500)}}class ct extends at{constructor(t){super(t,ct.name)}}class lt extends B{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return lt.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new a("No context provided");const r=t.pop();if(!(r instanceof c))throw new a("No context provided");if(t.filter((t=>t instanceof c)).length>1)throw Error("here");const s=this?r.logger.for(this).for(e):r.logger.clear().for(this).for(e);return{ctx:r,log:e?s.for(e):s,ctxArgs:[...t,r]}}}const ht=z.flavourResolver.bind(z);z.flavourResolver=t=>{try{const e=ht(t);if(e&&e!==H)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof Q.registeredFlavour?Q.registeredFlavour(r):void 0;if(s&&s!==H)return s;const i=ut._currentFlavour;if(i){const t=ut._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return H}};class ut extends lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ut._baseRepository)throw new a("This should be overridden when necessary. Otherwise it will be replaced lazily");return ut._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new a("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.Context=nt,this.alias in ut._cache)throw new a(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ut._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ut._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ut._currentFlavour=this.alias)}Dispatch(){return new ut._baseDispatch}ObserverHandler(){return new it}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new ut._baseSequence(t,this)}async flags(t,e,r,...s){let i=r.logger||$.for(this.toString());return r.correlationId&&(i=i.for({correlationId:r.correlationId})),Object.assign({},st,r,{affectedTables:(Array.isArray(e)?e:[e]).map(k.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:Array.isArray(e)?[]:Q.validationExceptions(e,t),logger:i})}async context(t,e,r,...s){this.log.for(this.context).debug(`Creating new context for ${t} operation on ${Array.isArray(r)?r.map((t=>t.name)):r.name} model with flag overrides: ${JSON.stringify(e)}`);const i=await this.flags(t,r,e,...s);return(new this.Context).accumulate(i)}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce(((e,[r,s])=>{if(void 0===s)return e;const i=k.columnName(t.constructor,r);if(this.isReserved(i))throw new a(`Property name ${i} is reserved`);return e[i]=s,e}),{});return t[rt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[rt.METADATA]),Object.defineProperty(i,rt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[rt.METADATA]})),{record:i,id:t[k.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),c={},l=k.pk(e);c[l]=r;const h=new e(c);n.silly(`Rebuilding model ${h.constructor.name} id ${r}`);const u=t[rt.METADATA],d=Object.keys(h).reduce(((r,s)=>(s===l||(r[s]=t[k.columnName(e,s)]),r)),h);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach((([t,e])=>{if(t in d)throw new a(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);d[t]=e}))),u&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${u}`),Object.defineProperty(d,rt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),d}async createAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),o=k.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Promise.all(e.map(((e,s)=>this.create(t,e,r[s],...n))))}async readAll(t,e,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=k.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Promise.all(e.map((e=>this.read(t,e,...i))))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),o=k.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Promise.all(e.map(((e,s)=>this.update(t,e,r[s],...n))))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=ut.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map((e=>this.delete(t,e,...i))))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);r.verbose("Registering new observer "+t.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=ut.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for adapter ${this.alias}: Event: `),await this.observerHandler.updateObservers(t,e,r,...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return Q.flavourOf(t)}static get currentFlavour(){if(!ut._currentFlavour)throw new a("No persistence flavour set. Please initialize your adapter");return ut._currentFlavour}static get current(){return ut.get(this.currentFlavour)}static get(t){if(!t)return ut.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new a(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return Q.flavouredAs(t)}catch(t){throw new a(t)}}static decoration(){}static logCtx(t,e){return super.logCtx(t,e)}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${j(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return this.proxies[r]=i,i}migrations(){return Q.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof nt&&(e=[t],t=this.migrations());const{ctx:r}=ut.logCtx(e,this.migrate),s=await this.getQueryRunner();for(const e of t)try{const t=new e;await t.up(s,this,r),await t.down(s,this,r)}catch(t){throw new at(t)}}}i([D(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],ut.prototype,"shutdownProxies",null),i([D(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],ut.prototype,"context",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],ut.prototype,"observe",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ut.prototype,"unObserve",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],ut.prototype,"client",null);class dt extends a{constructor(t){super(t,dt.name,500)}}class pt extends a{constructor(t){super(t,pt.name,500)}}var gt,ft,yt,mt,wt,bt;(t=>{t.FIND_BY="findBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(gt||(gt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP"})(ft||(ft={})),(t=>{t.AND="AND",t.OR="OR"})(yt||(yt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy"})(mt||(mt={}));class vt extends k{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):k.fromModel(this,t)}and(t){return vt.and(this,t)}or(t){return vt.or(this,t)}not(t){return new vt(this,ft.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof vt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ft).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof vt){if(!(this.comparison instanceof vt)&&this.operator!==ft.NOT)return{comparison:{condition:t}};if(-1===Object.values(yt).indexOf(this.operator)&&this.operator!==ft.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return vt.group(t,yt.AND,e)}static or(t,e){return vt.group(t,yt.OR,e)}static group(t,e,r){return new vt(t,e,r)}static attribute(t){return(new vt.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(ft.EQUAL,t)}dif(t){return this.setOp(ft.DIFFERENT,t)}gt(t){return this.setOp(ft.BIGGER,t)}lt(t){return this.setOp(ft.SMALLER,t)}gte(t){return this.setOp(ft.BIGGER_EQ,t)}lte(t){return this.setOp(ft.SMALLER_EQ,t)}in(t){return this.setOp(ft.IN,t)}regexp(t){return this.setOp(ft.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new vt(this.attr1,this.operator,this.comparison)}catch(t){throw new dt(t)}}}}static builder(){return new vt.Builder}static from(t){return new vt(t)}}i([L(),n("design:type",Object)],vt.prototype,"attr1",void 0),i([L(),n("design:type",String)],vt.prototype,"operator",void 0),i([L(),n("design:type",Object)],vt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(wt||(wt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(bt||(bt={}));const xt={update:bt.CASCADE,delete:bt.NONE},At={Equals:(t,e)=>vt.attribute(t).eq(e),Diff:(t,e)=>vt.attribute(t).dif(e),LessThan:(t,e)=>vt.attribute(t).lt(e),LessThanEqual:(t,e)=>vt.attribute(t).lte(e),GreaterThan:(t,e)=>vt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>vt.attribute(t).gte(e),Between:(t,e,r)=>vt.attribute(t).gte(e).and(vt.attribute(t).lte(r)),In:(t,e)=>vt.attribute(t).in(e),Matches:(t,e)=>vt.attribute(t).regexp(e)},Et=t=>t.charAt(0).toLowerCase()+t.slice(1);class Ot{static build(t,...e){if(!t.startsWith(gt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),i=this.extractGroupBy(t),n=this.buildWhere(r,e),{orderBy:o,limit:a,offset:c}=this.extractOrderLimitOffset(r,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(t){const e=t.substring(gt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static getFieldsFromMethodName(t){return(this.extractCore(t).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map((t=>{const{field:e}=this.parseFieldAndOperator(t);return e}))}static extractSelect(t){const e=t.indexOf(gt.SELECT);if(-1===e)return;const r=t.substring(e+gt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(gt.AND).map(Et).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(gt.GROUP_BY);if(-1!==e)return t.substring(e+gt.GROUP_BY.length).split(gt.ORDER_BY)[0].split(gt.THEN_BY).map(Et).filter(Boolean)}static buildWhere(t,e){if(!t&&0===e.length)return;const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let i;if(r.forEach(((t,r)=>{const{field:n,operator:o}=this.parseFieldAndOperator(t),a=o?At[o]:At.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===gt.AND?i.and(l):i.or(l)})),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(t){for(const e of Object.keys(At))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:Et(r),operator:e}}return{field:Et(t)}}static extractOrderLimitOffset(t,e){const r=t.split(/And|Or/).length,s=e.slice(r);let i,n,o;return s.length>=1&&Array.isArray(s[0])&&(i=s[0]),2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function St(){return z.for(rt.STATEMENT).define({decorator:()=>(t,e,r)=>V(W(Q.key(rt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function Nt(t={}){return z.for(rt.QUERY).define({decorator:t=>(e,r,s)=>{const i=Ot.getFieldsFromMethodName(r);return V(W(Q.key(rt.QUERY,r),{...t,fields:i}),St(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=Ot.build(e.name,...s);let h=r.select(i);n&&(h=h.where(n));const{allowLimit:u,allowOffset:d,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(a||[])[0],allowed:p},{key:"limit",value:c,allowed:u},{key:"offset",value:l,allowed:d}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new dt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(h=h[t.key](t.value))}return h.execute()}})})(t))(e,r,s)},args:[t]}).apply()}class Ct extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=k.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],t&&(this._adapter=t),e&&(Ct.register(e,this,this.adapter.alias),t)&&Q.get(e,X.FLAVOUR)===H&&J(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach((t=>{const e=t.name;u(this,this[e+"Prefix"],t,this[e+"Suffix"])}))}logCtx(t,e){return ut.logCtx(t,e)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new it}async createPrefix(t,...e){const r=await nt.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(t=new this.class(t),s||await d(this,r.context,t,l.CREATE,l.ON),!i){const e=await Promise.resolve(t.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${k.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createSuffix(t,e){return super.createSuffix(t,e)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r))),o=n.map((t=>t.id));let a=n.map((t=>t.record));return a=await this.adapter.createAll(this.class,o,a,...i),a.map(((t,e)=>this.adapter.revert(t,this.class,o[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}async createAllPrefix(t,...e){const r=await nt.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const n=k.sequenceFor(t[0]);let o=[];if(n.type?(n.name||(n.name=k.sequenceName(t[0],"pk")),o=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):o=t.map(((t,e)=>{if(void 0===t[this.pk])throw new a("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map((async(t,e)=>(t=new this.class(t),n.type&&(t[this.pk]="String"!==n.type||n.generated?o[e]:""+t[this.pk]),s||await d(this,r.context,t,l.CREATE,l.ON),t)))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async readPrefix(t,...e){const r=await nt.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await d(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${k.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const r=await nt.args(l.READ,this.class,e,this.adapter,this._overrides||{});return await Promise.all(t.map((async t=>{const e=new this.class;return e[this.pk]=t,d(this,r.context,e,l.READ,l.ON)}))),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${k.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(t,...e){const r=await nt.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation"),n=t[this.pk];if(!n)throw new a("No value for the Id is defined under the property "+this.pk);const o=await this.read(n,...r.args);if(t=k.merge(o,t,this.class),s||await d(this,r.context,t,l.UPDATE,l.ON,o),!i){const e=await Promise.resolve(t.hasErrors(o,...k.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=t.map((t=>this.adapter.prepare(t,r)));return(await this.adapter.updateAll(this.class,n.map((t=>t.id)),n.map((t=>t.record)),...i)).map(((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r)))}async updateAllPrefix(t,...e){const r=await nt.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=r.context.get("ignoreHandlers"),i=r.context.get("ignoreValidation"),n=t.map((t=>{const e=t[this.pk];if(!e)throw new a("missing id on update operation");return e})),o=await this.readAll(n,...r.args);if(t=t.map(((t,e)=>k.merge(o[e],t,this.class))),s||await Promise.all(t.map(((t,e)=>d(this,r.context,t,l.UPDATE,l.ON,o[e])))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(((t,r)=>Promise.resolve(t.hasErrors(o[r],t,...e))))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async deletePrefix(t,...e){const r=await nt.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await d(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${k.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const r=await nt.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.readAll(t,...r.args);return await Promise.all(s.map((async t=>d(this,r.context,t,l.DELETE,l.ON)))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}select(t){return this.adapter.Statement().select(t).from(this.class)}async query(t,e,r=wt.ASC,s,i,...n){const o=await nt.args(rt.QUERY,this.class,n,this.adapter,this._overrides||{}),{ctx:a}=this.logCtx(o.args,this.query),c=[e,r],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(a)}async listBy(t,e,...r){const s=await nt.args(mt.LIST_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.listBy);return i.verbose(`listing ${k.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...n)}async paginateBy(t,e,r,...s){const i=await nt.args(mt.PAGE_BY,this.class,s,this.adapter,this._overrides||{}),{log:n,ctxArgs:o}=this.logCtx(i.args,this.paginateBy);return n.verbose(`paginating ${k.tableName(this.class)} with page size ${r}`),this.select().orderBy([t,e]).paginate(r,...o)}async findOneBy(t,e,...r){const s=await nt.args(mt.FIND_ONE_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findOneBy);i.verbose(`finding ${k.tableName(this.class)} with ${t} ${e}`);const o=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...n);if(!o.length)throw new f("No results found");return o[0]}async findBy(t,e,...r){const s=await nt.args(mt.FIND_BY,this.class,r,this.adapter,this._overrides||{}),{log:i,ctxArgs:n}=this.logCtx(s.args,this.findBy);return i.verbose(`finding ${k.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...n)}async statement(t,...e){if(!Ct.statements(this,t))throw new dt("Invalid prepared statement requested "+t);const r=await nt.args(rt.STATEMENT,this.class,e,this.adapter,this._overrides||{}),{log:s,ctxArgs:i}=this.logCtx(r.args,this.statement);return s.verbose("Executing prepared statement "+t),this[t](...i)}attr(t){return vt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=k.tableName(this.class);this.adapter.observe(this,((t,e,r,...i)=>"string"==typeof t?t===s:Q.constr(t)===Q.constr(this.class))),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString())}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map((t=>ut._baseSequence.parseValue(k.sequenceFor(this.class).type,t))):ut._baseSequence.parseValue(k.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||Q.flavourOf(t)||ut.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ct)return s;const n=e||Q.flavourOf(t)||s&&Q.get(s,rt.ADAPTER)||ut.currentFlavour,o=n?ut.get(n):void 0;if(!o)throw new a("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=k.tableName(t);let s=r;if(e&&(s=[r,e].join(y)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a("Could not find repository registered under "+r)}static register(t,e,r){let s=k.tableName(t);if(r&&(s=[s,r].join(y)),s in this._cache&&this._cache[s]instanceof Ct)throw new a(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ct?t.constructor:t,s=Q.get(r,e?Q.key(rt.STATEMENT,e):rt.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof Ct?t.constructor:t;return Q.get(r,e?Q.key(rt.QUERY,e):rt.QUERY)}}function Tt(t,e){if(!(e||(e=z.flavourResolver(t instanceof k?t.constructor:t))&&e!==H))throw new a("Could not retrieve flavour from model "+(t instanceof k?t.constructor.name:t.name));return F(rt.INJECTABLE,e,k.tableName(t))}i([St(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],Ct.prototype,"listBy",null),i([St(),n("design:type",Function),n("design:paramtypes",[Object,String,Number,void 0]),n("design:returntype",Promise)],Ct.prototype,"paginateBy",null),i([St(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"findOneBy",null),i([St(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],Ct.prototype,"findBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],Ct.prototype,"observe",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ct.prototype,"unObserve",null),ut&&(ut._baseRepository=Ct);class _t extends t{get log(){return this.logger||(this.logger=$.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=k.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(n=k.get(t.toString())),!n)return;const o=rt.ADAPTER,a=r||Q.get(n,o);try{let t=a;try{a&&ut.get(a)}catch{const e=ut.current;e&&e.flavour===a&&(t=e.alias)}if(i=Ct.forModel(n,t),i instanceof Ct)return i;const r=a||Q.get(i.constructor,o)||Q.get(n,o);e.register(i,Tt(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=Ct.get(n,a);if("function"==typeof e){const t=a?ut.get(a):ut.current;if(!t)return;return new e(t,n)}}}return i}}async function Rt(t,e,r,s){if(!s){const e=k.get(t.constructor.name);if(!e)throw new a("Could not find model "+t.constructor.name);s=Ct.forModel(e,r)}if(void 0===t[k.pk(s.class)])return s.create(t,e);try{return s.update(t,e)}catch(r){if(!(r instanceof f))throw r;return s.create(t,e)}}async function Bt(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=Ut(s,r,this.adapter.alias),n=await e.read(i);return await Lt(t,s,r,i,n),void(s[r]=i)}const n=P(e.class)?e.class:e.class();if(!n)throw new a("Could not find model "+e.class);const o=Ct.forModel(n,this.adapter.alias),c=await o.create(i),l=k.pk(c);await Lt(t,s,r,c[l],c),s[r]=c[l]}async function $t(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==bt.CASCADE)return;if("object"!=typeof i){const e=Ut(s,r,this.adapter.alias),n=await e.read(i);return await Lt(t,s,r,i,n),void(s[r]=i)}const n=await Rt(s[r],t,this.adapter.alias),o=k.pk(n);await Lt(t,s,r,n[o],n),s[r]=n[o]}async function Dt(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==bt.CASCADE)return;const n=Ut(s,r,this.adapter.alias);let o;o=i instanceof k?await n.delete(s[r][n.pk]):await n.delete(s[r]),await Lt(t,s,r,o[n.pk],o)}async function Pt(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o=new Set([...i]);if("object"!==n){const e=Ut(s,r,this.adapter.alias);for(const i of o){const n=await e.read(i);await Lt(t,s,r,i,n)}return void(s[r]=[...o])}const c=k.pk(i[0]),l=new Set;for(const e of i){const i=await Rt(e,t,this.adapter.alias);await Lt(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function It(t,e,r,s){const{cascade:i}=e;if(i.update===bt.CASCADE)return Pt.call(this,t,e,r,s)}async function kt(t,e,r,s){if(e.cascade.delete!==bt.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o="object"===n,c=o?Ct.forModel(i[0],this.adapter.alias):Ut(s,r,this.adapter.alias),l=new Set([...o?i.map((t=>t[c.pk])):i]);for(const e of l.values()){const i=await c.delete(e);await Lt(t,s,r,e,i)}s[r]=[...l]}function jt(t,e,r){return[rt.POPULATE,t,e,r].join(".")}async function Lt(t,e,r,s,i){const n=jt(e.constructor.name,r,s);return t.accumulate({[n]:i})}async function Ft(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,e,r,s,i)=>{let n,o;const c=[];for(const l of s){n=jt(e.constructor.name,r,l);try{o=await t.get(n)}catch(t){const s=Ut(e,r,i);if(!s)throw new a("Could not find repo");o=await s.read(l)}c.push(o)}return c})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?o:o[0]}const Mt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Ut(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=Q.get(t instanceof k?t.constructor:t,Q.key(M.REFLECT,e,M.LIST))?.clazz;if(!r)throw new a("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map((t=>"function"!=typeof t||t.name?t:t()))}else s=Q.getPropDesignTypes(t instanceof k?t.constructor:t,e)?.designTypes;const i=s?.find((t=>!Mt.includes((""+t.name).toLowerCase())));return Ct.forModel(i,r)}class Gt extends m{constructor(t,e=Gt.name,r=401){super(t,e,r)}}class qt extends Gt{constructor(t,e=qt.name){super(t,e,403)}}class Yt extends a{constructor(t){super(t,Yt.name,503)}}function zt(t){return z.for(rt.TABLE).define({decorator:t=>e=>K(rt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Ht(t){return z.for(rt.COLUMN).define({decorator:t=>(e,r)=>Z(Q.key(rt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Qt(t,e,r){return z.for(rt.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find((t=>![wt.ASC,wt.DSC].includes(t)))&&(e=t,t=void 0),Z(Q.key(`${rt.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Vt(t,e,r,s){if(s[r]&&(await this.select().where(vt.attribute(r).eq(s[r])).execute()).length)throw new w(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Wt(){const t=rt.UNIQUE;return z.for(t).define(U(),b(Vt),Z(t,{})).apply()}async function Xt(t,e,r,s){throw new Gt("This adapter does not support user identification")}function Jt(){return z.for(rt.CREATED_BY).define({decorator:()=>(t,e)=>V(x(Xt),Z(rt.CREATED_BY,e),ne())(t,e),args:[]}).apply()}function Kt(){return z.for(rt.UPDATED_BY).define({decorator:()=>(t,e)=>V(A(Xt),Z(rt.UPDATED_BY,e),ne())(t,e),args:[]}).apply()}function Zt(){return v([l.CREATE])}function te(){return v()}function ee(t,e=xt,r=!0,s,i){const n=rt.ONE_TO_ONE;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),G([t,String,Number,BigInt]),x(Bt,o),A($t,o),E(Dt,o),O(Ft,o))},args:[t,e,r,s,i]}).apply()}function re(t,e=xt,r=!0,s,i){const n=rt.ONE_TO_MANY;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),q([t,String,Number,BigInt]),x(Pt,o),A(It,o),E(kt,o),O(Ft,o))},args:[t,e,r,s,i]}).apply()}function se(t,e=xt,r=!0,s,i){const n=rt.MANY_TO_ONE;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),G([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ie(t,e=xt,r=!0,s,i){const n=rt.MANY_TO_MANY;return z.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};return s&&(o.joinTable=s),i&&(o.name=i),V(tt(),he(n,o),q([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ne(){return(t,e)=>Z(Q.key(rt.GENERATED,e),!0)(t,e)}function oe(...t){return(e,r)=>{const s=Q.get(e,Q.key(rt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return V(K(Q.key(rt.NO_VALIDATE,r),i))(e,r)}}function ae(){return oe(l.CREATE)}function ce(){return oe(l.UPDATE)}function le(){return oe(l.UPDATE,l.CREATE)}function he(t,e){return z.for(rt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(Z(t,e)(r,s),Z(Q.key(rt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}z.for(N.TIMESTAMP).extend(ne()).apply(),z.for(N.COMPOSED).extend(ne()).apply(),Q.validationExceptions=((t,e)=>{const r=Q.get(t,rt.NO_VALIDATE);return r?Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t)):[]}).bind(Q),k.shouldValidateNestedHandler=((t,e)=>{const r=Q.get(t.constructor);if(!r)return!1;const s=r[rt.RELATIONS],i=r[rt.RELATION];if(Array.isArray(s)&&s?.includes(e)){const r=Object.keys(i)[0],s=k.isPropertyModel(t,e);return i[r]?.class!==s}return!0}).bind(k),Q.migrationsFor=(t=>{if(!(t=t??ut.current))throw new a("Could not get adapter for migrations");return Q.innerGet(Symbol.for(rt.MIGRATION),t.alias).map((t=>t.class))}).bind(Q),Q.relations=((t,e)=>{const r=Q.get(t,rt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new a("No relations metadata found for property "+e);return r[e]}}).bind(Q),k.relations=(t,e)=>Q.relations(t instanceof k?t.constructor:t,e)||[],Q.generated=((t,e)=>!!Q.get("function"!=typeof t?t.constructor:t,Q.key(rt.GENERATED,e))).bind(Q),Q.createdBy=(t=>{const e=Q.get("function"!=typeof t?t.constructor:t,rt.CREATED_BY);if(!e)throw new a("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(Q),Q.updatedBy=(t=>{const e=Q.get("function"!=typeof t?t.constructor:t,rt.UPDATED_BY);if(!e)throw new a("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(Q),k.tableName=t=>{if(!(t instanceof k?k.get(t.constructor.name):t))throw new a("Unable to find model "+t);return Q.get(t instanceof k?t.constructor:t,rt.TABLE)||(t instanceof k?t.constructor.name:t.name)},k.columnName=(t,e)=>Q.get(t instanceof k?t.constructor:t,Q.key(rt.COLUMN,e))||e,k.sequenceName=(t,...e)=>[k.tableName(t),...e].join("_"),k.sequenceFor=(t,e)=>{if(e)throw new ot("not currently supported");const r=k.pkProps(t instanceof k?t.constructor:t);if(!r)throw new a("No sequence options defined for model. did you use the @pk decorator?");return r},k.indexes=t=>{const e=Q.get(t instanceof k?t.constructor:t,rt.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[rt.INDEX]:e[r]},t)),{})},e.services=()=>Q.innerGet(Symbol.for(rt.SERVICE)),e.repositories=()=>Q.innerGet(Symbol.for(N.REPOSITORY));class ue extends lt{constructor(){super()}async initialize(){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const t=this.adapter;[l.CREATE,l.UPDATE,l.DELETE,C.CREATE_ALL,C.UPDATE_ALL,C.DELETE_ALL].forEach((e=>{if(!t[e])throw new a(`Method ${e} not found in ${t.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(t,e),s=t;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,e);r&&r.writable?t[e]=new Proxy(t[e],{apply:async(t,r,s)=>{const{log:i,ctxArgs:n}=r.logCtx(s,t),[o,a]=s,c=await t.apply(r,n);return this.updateObservers(o,(t=>{switch(t){case C.CREATE_ALL:return l.CREATE;case C.UPDATE_ALL:return l.UPDATE;case C.DELETE_ALL:return l.DELETE;default:return t}})(e),a,c,...n.slice(s.length)).then((()=>{i.verbose(`Observer refresh dispatched by ${e} for ${o}`),i.debug("pks: "+a)})).catch((t=>i.error(`Failed to dispatch observer refresh for ${e} on ${o}: ${t}`))),c}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)}))}async close(){}observe(t){if(!(t instanceof ut))throw new ot("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ut.models(this.adapter.alias),this.initialize().then((()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)))}unObserve(t){if(this.adapter!==t)throw new ot("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){const i="string"==typeof t?t:k.tableName(t),{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`Dispatching ${e} from table ${i} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new a("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}ut&&(ut._baseDispatch=ue);class de{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)}))}static get instance(){return de._instance||(de._instance=new de),de._instance}}class pe{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return pe._instance||(pe._instance=new pe),pe._instance}}function ge(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof ct)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class fe extends B{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach((t=>{const e=t.name;ge(this,t,this.prefix(e))}))}get adapter(){const t=Q.get(this.constructor,rt.MIGRATION);if(!t)throw new a("No migration metadata for "+this.constructor.name);const e=t.flavour;return ut.get(e)}async enforceRules(t,e,r){const s=Q.get(this.constructor,rt.MIGRATION)?.rules;if(!s||!s.length)return!0;for(const i of s)if(!await i(t,e,r))return!1;return!0}prefix(t){return async function(e){let r;e instanceof ut?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await nt.args("migration",k,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new ct("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function ye(t,e){return z.for(rt.MIGRATION).define({decorator:(t,e)=>r=>{const s=Q.innerGet(Symbol.for(rt.MIGRATION),t)||[];return Q.set(rt.MIGRATION,t,[...s,{class:r}]),K(rt.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}class me extends k{constructor(t){super(t)}}i([Zt(),n("design:type",Date)],me.prototype,"createdAt",void 0),i([te(),n("design:type",Date)],me.prototype,"updatedAt",void 0);const we={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},be=we,ve={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},xe=Object.assign({},ve,{type:"BigInt"});async function Ae(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=k.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e)}catch(t){throw new a(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,o,c;n=s,o=r,c=await i.next(t),Reflect.set(n,o,c)}function Ee(t,e){return(r,s)=>{switch(tt()(r,s),t.type){case void 0:{const e=Q.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e;break}case String.name||String.name.toLowerCase():case String:t.generated=!1,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=!0,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=!0;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const i=[Qt([wt.ASC,wt.DSC]),L(),T(),Z(Q.key(N.ID,s),t),x(Ae,t,e)];return t.generated&&i.push(ne()),V(...i)(r,s)}}function Oe(t=be){return t=Object.assign({},be,t),z.for(N.ID).define({decorator:Ee,args:[t,{priority:60}]}).apply()}let Se=class extends me{constructor(t){super(t)}};i([Oe({type:"String",generated:!1}),n("design:type",String)],Se.prototype,"id",void 0),i([L(),Qt(),n("design:type",Object)],Se.prototype,"current",void 0),Se=i([zt("??sequence"),Y(),n("design:paramtypes",[Object])],Se);class Ne extends lt{constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=Ct.forModel(Se,e.alias)}async current(...t){const e=(await nt.args(l.READ,Se,t,this.adapter)).context,{name:r,startWith:s}=this.options;try{const t=await this.repo.read(r,e);return this.parse(t.current)}catch(t){if(t instanceof f){if(void 0===s)throw new a("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new a(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new a(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let o;const c=e||i;if(c%i!=0)throw new a("Value to increment does not consider the incrementBy setting: "+i);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:o=this.parse(t)+c;break;case BigInt.name:o=this.parse(t)+BigInt(c);break;case String.name:o=this.parse(t);break;case"serial":o=pe.instance.generate(t);break;case"uuid":o=de.instance.generate(t);break;default:throw new a("Should never happen")}let l;try{l=await this.repo.update(new Se({id:n,current:o}),r)}catch(i){if(!(i instanceof f))throw i;try{l=await this.repo.create(new Se({id:n,current:o}),r)}catch(i){if(!(i instanceof w)||"uuid"!==s)throw i;return this.increment(t,e,r)}}return l.current}async next(...t){const e=await nt.args(l.UPDATE,Se,t,this.adapter),{context:r,args:s}=e,i=await this.current(...s);return this.increment(i,void 0,r)}async range(t,...e){const r=await nt.args(l.UPDATE,Se,e,this.adapter),{context:s,args:i}=r,n=await this.current(...i),o=this.parse(this.options.incrementBy),c=await this.increment(n,this.parse(t)*o,s),h=[];for(let e=1;t>=e;e++)h.push(n+o*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new ot(`type ${this.options.type} is currently not suppported for this adapter`);const u="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(h[h.length-1]!==c&&"String"!==u)throw new a("Miscalculation of range");return h}parse(t){return Ne.parseValue(this.options.type,t)}static pk(t){return k.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new ot(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Ce(t,e){return(i,n)=>n?r(Q.constr(t))(i,n):(Q.set(N.REPOSITORY,Q.key(e||ut.currentFlavour,k.tableName(t)),i),K(N.REPOSITORY,i.name)(t),e=e||Q.get(i.constructor,rt.ADAPTER),Ct.register(Q.constr(t),i,e),s(Q.constr(t),{callback:e=>(Object.defineProperty(e,N.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}ut._baseSequence=Ne;class Te extends a{constructor(t){super(t,Te.name,500)}}class _e extends B{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new pt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new pt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}}function Re(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&((t,e)=>{const{handler:r,args:s}=Q.get(t,l.REFLECT+l.BLOCK)||{};return!!r&&(r(...s,e)??!1)})(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}const Be=()=>Re(l.CREATE),$e=()=>Re(l.READ),De=()=>Re(l.UPDATE),Pe=()=>Re(l.DELETE);function Ie(t){return t="string"==typeof t?t:Q.Symbol(t).toString(),(e,i,n)=>{Q.set(rt.SERVICE,t,e);const o=[];if(n&&"number"==typeof n.value)o.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(t))}else o.push(s(t,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return o.push(K(rt.SERVICE,t)),V(...o)(e,i,n)}}class ke{constructor(t){this.name=t,this.Context=nt}async flags(t,e,...r){let s=e.logger||$.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},st,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=e,i=await this.flags(t,s,...r);return(new this.Context).accumulate(i)}async logCtx(t,e,r=!1){return await ke.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const i=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await i()]);const n=t.pop();n instanceof nt||(t=[...t,await i()]);const o=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?o.for(e):o,ctxArgs:[...t,n]}}static get(t){if(!t)throw new a("No name provided");const r=e.get(t);if(r)return r;throw new a("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){const r={context:async t=>(new nt).accumulate(Object.assign({},st,{timestamp:new Date,operation:t,logger:$.get()}))},{log:s,ctxArgs:i}=await this.logCtx.bind(r)(t,this.boot,!0),n=e.services();for(const[t,e]of Object.entries(n))try{const t=new e;t instanceof je&&await t.boot(...i)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class je extends ke{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=await this.logCtx(t,this.boot,!0);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new a("Config not initialized");return this._config}get client(){if(!this._client)throw new a("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],je.prototype,"boot",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],je.prototype,"config",null),i([D(),n("design:type",Object),n("design:paramtypes",[])],je.prototype,"client",null);const Le=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Fe extends ke{get class(){if(!this.clazz)throw new a("Class not initialized");return this.clazz}constructor(t){super(),this.clazz=t,this.repo=Ct.forModel(t)}static getService(t){if(!t)throw new a("No name provided");const e=Le(t);try{const t=ke.get(e);if(t)return t}catch(t){}throw new a("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,i)})}async create(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.create,!0);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.createAll,!0);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.delete,!0);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.deleteAll,!0);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.read,!0);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.readAll,!0);return this.repo.readAll(t,...r)}async query(t,...e){const r=this.repo?.[t];if("function"!=typeof r)throw Error(`Method "${t}" is not implemented`);return r.apply(this.repo,e)}async update(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.update,!0);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.updateAll,!0);return this.repo.updateAll(t,...r)}async logCtx(t,e,r=!1){return await Fe.logCtx.bind(this.repo.adapter)(t,e,r,{},this.class)}static forModel(t,e){let r;e=Le(e||t);try{r=Fe.get(e)}catch(t){r=void 0}if(r instanceof Fe)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([Ie(e),n("design:paramtypes",[])],o),new o}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);const o=t.pop();o instanceof nt||(t=[...t,await n()]);const c=this?o.logger.for(this).for(e):o.logger.clear().for(this).for(e);return{ctx:o,log:e?c.for(e):c,ctxArgs:[...t,o]}}}var Me,Ue,Ge,qe;i([Be(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"create",null),i([Be(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"createAll",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"delete",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"deleteAll",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"read",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"readAll",null),i([$e(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Fe.prototype,"query",null),i([De(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"update",null),i([De(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Fe.prototype,"updateAll",null);class Ye extends lt{constructor(t){super(),this.adapter=t,[this.execute,this.paginate].forEach((t=>{_(this,t,(async(...e)=>{let r=e;if((!r.length||!(r[r.length-1]instanceof nt))&&this.fromSelector){const t=await this.adapter.context(rt.QUERY,{},this.fromSelector);r=[...r,t]}const{ctx:s,ctxArgs:i}=ut.logCtx(r,t.name);return s.get("allowRawStatements")||this.prepared||await this.prepare(s),i}),t.name)}))}get log(){return this.adapter.log.for(Ye)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}count(t){return this.countSelector=t,this}from(t){if(this.fromSelector="string"==typeof t?k.get(t):t,!this.fromSelector)throw new dt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const e=t.pop();try{const t=this.build();return await this.raw(t,e)}catch(t){throw new a(t)}}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw),i=await this.adapter.raw(t,...s);if(!this.selectSelector)return i;const n=k.pk(this.fromSelector),o=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case yt.AND:case yt.OR:{let t=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof vt){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case ft.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case ft.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case ft.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case ft.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case ft.BIGGER_EQ:n.method=r+" bigger than equal";break;case ft.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case ft.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case ft.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new dt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof vt)return;e=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:e?[e,wt.DSC]:[k.pk(this.fromSelector),wt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:mt.LIST_BY,args:[s],params:n};return e&&(o.method=mt.FIND_BY,o.args=[e,this.whereCondition.comparison],o.params=n),o}async prepare(t){if((t=t||await this.adapter.context(rt.QUERY,{},this.fromSelector)).get("squashSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},i=[gt.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);i.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&i.push(gt.SELECT,this.selectSelector.join(` ${gt.AND.toLowerCase()} `)),this.orderBySelector&&i.push(gt.ORDER_BY,...this.orderBySelector),this.groupBySelector&&i.push(gt.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=I(i.join(" ")),s.params=r,this.prepared=s,!t.get("squashSimpleQueries")||this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector||(this.prepared=s),this}async paginate(t,...e){e.pop();try{const e=this.build();return this.adapter.Paginator(e,t,this.fromSelector)}catch(t){throw new dt(t)}}toString(){return this.adapter.flavour+" statement"}}i([D(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ye.prototype,"select",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Me="undefined"!=typeof S&&S)?Me:Object]),n("design:returntype",Object)],Ye.prototype,"distinct",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ue="undefined"!=typeof S&&S)?Ue:Object]),n("design:returntype",Object)],Ye.prototype,"max",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ge="undefined"!=typeof S&&S)?Ge:Object]),n("design:returntype",Object)],Ye.prototype,"min",null),i([D(),n("design:type",Function),n("design:paramtypes",["function"==typeof(qe="undefined"!=typeof S&&S)?qe:Object]),n("design:returntype",Object)],Ye.prototype,"count",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ye.prototype,"from",null),i([D(),n("design:type",Function),n("design:paramtypes",[vt]),n("design:returntype",Object)],Ye.prototype,"where",null),i([D(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ye.prototype,"orderBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ye.prototype,"groupBy",null),i([D(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ye.prototype,"limit",null),i([D(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ye.prototype,"offset",null),i([D(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Ye.prototype,"execute",null);class ze extends Ye{constructor(t){super(t)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new a("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=Q.getPropDesignTypes(t.constructor,s);if(!n)throw new dt("type not compatible with sorting: "+n);switch(n.name){case"string":case"String":return("asc"===i?1:-1)*t[s].localeCompare(e[s]);case"number":case"Number":return("asc"===i?1:-1)*(t[s]-e[s]);case"object":case"Object":if(t[s]instanceof Date&&e[s]instanceof Date)return("asc"===i?1:-1)*(t[s].valueOf()-e[s].valueOf());throw new dt("Sorting not supported for not date classes");default:throw new dt("sorting not supported for type "+n)}}}build(){const t={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:t=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(t.sort=this.getSort()),t}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:i}=t;if(-1===[yt.AND,yt.OR,ft.NOT].indexOf(s))switch(s){case ft.BIGGER:return e[r]>i;case ft.BIGGER_EQ:return e[r]>=i;case ft.DIFFERENT:return e[r]!==i;case ft.EQUAL:return e[r]===i;case ft.REGEXP:if("string"!=typeof e[r])throw new dt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(i,"g"));case ft.SMALLER:return e[r]<i;case ft.SMALLER_EQ:return e[r]<=i;default:throw new a("Invalid operator for standard comparisons: "+s)}else{if(s===ft.NOT)throw new a("Not implemented");{const t=this.parseCondition(r),n=this.parseCondition(i);switch(s){case yt.AND:return t.where(e)&&n.where(e);case yt.OR:return t.where(e)||n.where(e);default:throw new a("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function He(t,e,r,s){const i=t.get("UUID");if(!i)throw new ot("This adapter does not support user identification");s[r]=i}const Qe="ram";class Ve extends _e{constructor(t,e,r,s){super(t,e,r,s)}prepare(t){const e=Object.assign({},t);return e.limit=this.size,e}async page(t=1,...e){const r=await nt.args(rt.QUERY,this.clazz,e,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=t.length,this._recordCount>0){const t=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const i=await this.adapter.raw(s,...e,r.context);return this._currentPage=t,i}}class We extends ut{constructor(t={},e){super(t,Qe,e),this.indexes={},this.lock=new et}repository(){return super.repository()}async flags(t,e,r){return Object.assign(await super.flags(t,e,r),{UUID:this.config.user||""+Date.now()})}Dispatch(){return super.Dispatch()}async index(...t){return Promise.resolve(void 0)}prepare(t,...e){const r=e.pop(),s=super.prepare(t,...e,r);return delete s.record[k.pk(t.constructor)],s}revert(t,e,r,s,...i){return super.revert(t,e,r,s,...i)}async create(t,e,r,s){const i=s.logger.for(this.create),n=k.tableName(t);if(i.debug(`creating record in table ${n} with id ${e}`),await this.lock.acquire(),this.client.has(n)||this.client.set(n,new Map),this.client.get(n)&&this.client.get(n)?.has(e))throw new w(`Record with id ${e} already exists in table ${n}`);return this.client.get(n)?.set(e,r),this.lock.release(),r}async read(t,e,r){const s=k.tableName(t);if(!this.client.has(s))throw new f(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new f(`Record with id ${e} not found in table ${s}`);return this.client.get(s)?.get(e)}async update(t,e,r,s){const i=s.logger.for(this.update),n=k.tableName(t);if(i.debug(`updating record in table ${n} with id ${e}`),await this.lock.acquire(),!this.client.has(n))throw new f(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new f(`Record with id ${e} not found in table ${n}`);return this.client.get(n)?.set(e,r),this.lock.release(),r}async delete(t,e,r){const s=r.logger.for(this.delete),i=k.tableName(t);if(s.debug(`deleting record from table ${i} with pk ${e}`),await this.lock.acquire(),!this.client.has(i))throw new f(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new f(`Record with id ${e} not found in table ${i}`);const n=this.client.get(i)?.get(e);return this.client.get(i)?.delete(e),this.lock.release(),n}tableFor(t){"string"==typeof t&&(t=k.get(t));const e=k.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e){e.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:r,sort:s,limit:i,skip:n,from:o}=t;let{select:c}=t;const l=this.tableFor(o);if(!l)throw new a(`Table ${o} not found in RamAdapter`);const h=k.pk(o),u=Q.get(o,Q.key(N.ID,h));let d=Array.from(l.entries()).map((([t,r])=>this.revert(r,o,Ne.parseValue(u.type,t),void 0,e)));return d=r?d.filter(r):d,s&&(d=d.sort(s)),n&&(d=d.slice(n)),i&&(d=d.slice(0,i)),c&&(c=Array.isArray(c)?c:[c],d=d.map((t=>Object.entries(t).reduce(((t,[e,r])=>(c.includes(e)&&(t[e]=r),t)),{})))),d}parseError(t){return t instanceof R?t:new a(t)}Statement(){return new ze(this)}Paginator(t,e,r){return new Ve(this,t,e,r)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${j(t)}`;if(r in this.proxies)return this.proxies[r];const s=new Proxy(this,{get:(e,r,s)=>{if("_config"===r){const i=Reflect.get(e,r,s);return Object.assign({},i,t)}return Reflect.get(e,r,s)}});return this.proxies[r]=s,s}static decoration(){super.decoration();const t=rt.CREATED_BY,e=rt.UPDATED_BY;z.flavouredAs(Qe).for(t).define(x(He),Z(t,{})).apply(),z.flavouredAs(Qe).for(e).define(b(He),Z(e,{})).apply()}getClient(){return new Map}}We.decoration(),e.setRegistry(new _t);const Xe="##VERSION##",Je="##PACKAGE##";Q.registerLibrary(Je,Xe);export{fe as AbsMigration,ut as Adapter,Gt as AuthorizationError,me as BaseModel,xe as BigIntSequence,bt as Cascade,je as ClientBasedService,vt as Condition,Yt as ConnectionError,nt as Context,lt as ContextualLoggedClass,st as DefaultAdapterFlags,xt as DefaultCascade,be as DefaultSequenceOptions,ue as Dispatch,qt as ForbiddenError,yt as GroupOperator,_t as InjectablesRegistry,Ot as MethodQueryBuilder,at as MigrationError,ct as MigrationRuleError,Fe as ModelService,we as NoneSequenceOptions,ve as NumericSequence,Te as ObserverError,it as ObserverHandler,ft as Operator,At as OperatorsMap,wt as OrderDirection,Je as PACKAGE_NAME,_e as Paginator,pt as PagingError,rt as PersistenceKeys,mt as PreparedStatementKeys,gt as QueryClause,dt as QueryError,We as RamAdapter,Qe as RamFlavour,Ve as RamPaginator,ze as RamStatement,Ct as Repository,Ne as Sequence,Se as SequenceModel,pe as Serial,ke as Service,Ye as Statement,de as UUID,ot as UnsupportedError,Xe as VERSION,Lt as cacheModelForPopulate,Ht as column,Be as create,Rt as createOrUpdate,Zt as createdAt,Jt as createdBy,Xt as createdByOnCreateUpdate,He as createdByOnRamCreateUpdate,Pe as del,Tt as generateInjectableNameForRepository,ne as generated,jt as getPopulateKey,Qt as index,ie as manyToMany,se as manyToOne,ye as migration,oe as noValidateOn,ae as noValidateOnCreate,le as noValidateOnCreateUpdate,ce as noValidateOnUpdate,re as oneToMany,Pt as oneToManyOnCreate,kt as oneToManyOnDelete,It as oneToManyOnUpdate,ee as oneToOne,Bt as oneToOneOnCreate,Dt as oneToOneOnDelete,$t as oneToOneOnUpdate,Oe as pk,Ee as pkDec,Ae as pkOnCreate,Ft as populate,ge as prefixMethod,St as prepared,Nt as query,$e as read,he as relation,Ce as repository,Ut as repositoryFromTypeMetadata,Ie as service,zt as table,Wt as unique,Vt as uniqueOnCreateUpdate,De as update,te as updatedAt,Kt as updatedBy};
2
2
  //# sourceMappingURL=core.js.map