@decaf-ts/core 0.7.17 → 0.7.19
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/README.md +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/query/MethodQueryBuilder.js +2 -2
- package/lib/esm/query/MethodQueryBuilder.js.map +1 -1
- package/lib/esm/ram/RamAdapter.d.ts +1 -1
- package/lib/esm/ram/RamAdapter.js +4 -4
- package/lib/esm/ram/RamAdapter.js.map +1 -1
- package/lib/esm/utils/Services.d.ts +10 -4
- package/lib/esm/utils/Services.js +39 -3
- package/lib/esm/utils/Services.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/query/MethodQueryBuilder.cjs +2 -2
- package/lib/query/MethodQueryBuilder.js.map +1 -1
- package/lib/ram/RamAdapter.cjs +3 -3
- package/lib/ram/RamAdapter.d.ts +1 -1
- package/lib/ram/RamAdapter.js.map +1 -1
- package/lib/utils/Services.cjs +39 -3
- package/lib/utils/Services.d.ts +10 -4
- package/lib/utils/Services.js.map +1 -1
- package/package.json +1 -1
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 a,InternalError as o,Context as c,OperationKeys as l,Repository as h,wrapMethodWithContext as d,enforceDBDecorators as u,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 _,prefixMethod as T,BaseError as R}from"@decaf-ts/db-decorators";import{LoggedClass as P,Logging as $,final as B,isClass as D,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 Y,model as q}from"@decaf-ts/decorator-validation";import{Decoration as Q,DefaultFlavour as z,Metadata as H,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({},a,{allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1});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 o("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 o("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=dt.logCtx(s,this.updateObservers);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(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 at extends o{constructor(t){super(t,at.name,500)}}class ot extends o{constructor(t,e=ot.name){super(t,e,500)}}class ct extends ot{constructor(t){super(t,ct.name)}}class lt extends P{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 o("No context provided");const r=t.pop();if(!(r instanceof c))throw new o("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=Q.flavourResolver.bind(Q);Q.flavourResolver=t=>{try{const e=ht(t);if(e&&e!==z)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof H.registeredFlavour?H.registeredFlavour(r):void 0;if(s&&s!==z)return s;const i=dt._currentFlavour;if(i){const t=dt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return z}};class dt extends lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!dt._baseRepository)throw new o("This should be overridden when necessary. Otherwise it will be replaced lazily");return dt._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new o("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 dt._cache)throw new o(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);dt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),dt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),dt._currentFlavour=this.alias)}Dispatch(){return new dt._baseDispatch}ObserverHandler(){return new it}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new dt._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)?[]:H.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 o(`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:a}=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 d=t[rt.METADATA],u=Object.keys(h).reduce((r,s)=>(s===l||(r[s]=t[k.columnName(e,s)]),r),h);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in u)throw new o(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);u[t]=e})),d&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${d}`),Object.defineProperty(u,rt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),u}async createAll(t,e,r,...s){if(e.length!==r.length)throw new o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),a=k.tableName(t);return i.debug(`Creating ${e.length} entries ${a} 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 o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),a=k.tableName(t);return i.debug(`Updating ${e.length} entries ${a} table`),Promise.all(e.map((e,s)=>this.update(t,e,r[s],...n)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=dt.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 o("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 o("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=dt.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 H.flavourOf(t)}static get currentFlavour(){if(!dt._currentFlavour)throw new o("No persistence flavour set. Please initialize your adapter");return dt._currentFlavour}static get current(){return dt.get(this.currentFlavour)}static get(t){if(!t)return dt.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new o(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return H.flavouredAs(t)}catch(t){throw new o(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 H.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof nt&&(e=[t],t=this.migrations());const{ctx:r}=dt.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 ot(t)}}}i([B(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],dt.prototype,"shutdownProxies",null),i([B(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],dt.prototype,"context",null),i([B(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],dt.prototype,"observe",null),i([B(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],dt.prototype,"unObserve",null),i([B(),n("design:type",Object),n("design:paramtypes",[])],dt.prototype,"client",null);class ut extends o{constructor(t){super(t,ut.name,500)}}class pt extends o{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 ut(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:a,limit:o,offset:c}=this.extractOrderLimitOffset(r,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:a,limit:o,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:a}=this.parseFieldAndOperator(t),o=a?At[a]:At.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=o(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,a;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]||(a=s[2]),{orderBy:i,limit:n,offset:a}}}function St(){return Q.for(rt.STATEMENT).define({decorator:()=>(t,e,r)=>V(W(H.key(rt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function Nt(t={}){return Q.for(rt.QUERY).define({decorator:t=>(e,r,s)=>{const i=Ot.getFieldsFromMethodName(r);return V(W(H.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:a,orderBy:o,limit:c,offset:l}=Ot.build(e.name,...s);let h=r.select(i);n&&(h=h.where(n));const{allowLimit:d,allowOffset:u,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(o||[])[0],allowed:p},{key:"limit",value:c,allowed:d},{key:"offset",value:l,allowed:u}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new ut(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 o("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=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1},t&&(this._adapter=t),e&&(Ct.register(e,this,this.adapter.alias),t)&&H.get(e,X.FLAVOUR)===z&&J(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(t=>{const e=t.name;d(this,this[e+"Prefix"],t,this[e+"Suffix"])})}logCtx(t,e){return dt.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 u(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:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,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)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[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 a=[];if(n.type?(n.name||(n.name=k.sequenceName(t[0],"pk")),a=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):a=t.map((t,e)=>{if(void 0===t[this.pk])throw new o("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?a[e]:""+t[this.pk]),s||await u(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 u(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,u(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:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${k.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,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 o("No value for the Id is defined under the property "+this.pk);const a=await this.read(n,...r.args);if(t=k.merge(a,t,this.class),s||await u(this,r.context,t,l.UPDATE,l.ON,a),!i){const e=await Promise.resolve(t.hasErrors(a,...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 o("missing id on update operation");return e}),a=await this.readAll(n,...r.args);if(t=t.map((t,e)=>k.merge(a[e],t,this.class)),s||await Promise.all(t.map((t,e)=>u(this,r.context,t,l.UPDATE,l.ON,a[e]))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(a[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 u(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=>u(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(this._overrides).select(t).from(this.class)}async query(t,e,r=wt.ASC,s,i,...n){const a=await nt.args(rt.QUERY,this.class,n,this.adapter,this._overrides||{}),{ctx:o}=this.logCtx(a.args,this.query),c=[e,r],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(o)}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:a}=this.logCtx(i.args,this.paginateBy);return n.verbose(`paginating ${k.tableName(this.class)} with page size ${r}`),this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(r,...a)}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 a=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...n);if(!a.length)throw new f("No results found");return a[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 ut("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:H.constr(t)===H.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 o("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 o("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=>dt._baseSequence.parseValue(k.sequenceFor(this.class).type,t)):dt._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||H.flavourOf(t)||dt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ct)return s;const n=e||H.flavourOf(t)||s&&H.get(s,rt.ADAPTER)||dt.currentFlavour,a=n?dt.get(n):void 0;if(!a)throw new o("No registered persistence adapter found flavour "+n);return s=s||a.repository(),new s(a,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 o("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 o(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ct?t.constructor:t,s=H.get(r,e?H.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 H.get(r,e?H.key(rt.QUERY,e):rt.QUERY)}}function _t(t,e){if(!(e||(e=Q.flavourResolver(t instanceof k?t.constructor:t))&&e!==z))throw new o("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([B(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],Ct.prototype,"observe",null),i([B(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ct.prototype,"unObserve",null),dt&&(dt._baseRepository=Ct);class Tt 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 a=rt.ADAPTER,o=r||H.get(n,a);try{let t=o;try{o&&dt.get(o)}catch{const e=dt.current;e&&e.flavour===o&&(t=e.alias)}if(i=Ct.forModel(n,t),i instanceof Ct)return i;const r=o||H.get(i.constructor,a)||H.get(n,a);e.register(i,_t(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,o);if("function"==typeof e){const t=o?dt.get(o):dt.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 o("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 Pt(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=D(e.class)?e.class:e.class();if(!n)throw new o("Could not find model "+e.class);const a=Ct.forModel(n,this.adapter.alias),c=await a.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),a=k.pk(n);await Lt(t,s,r,n[a],n),s[r]=n[a]}async function Bt(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 a;a=i instanceof k?await n.delete(s[r][n.pk]):await n.delete(s[r]),await Lt(t,s,r,a[n.pk],a)}async function Dt(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 o(`Invalid operation. All elements of property ${r} must match the same type.`);const a=new Set([...i]);if("object"!==n){const e=Ut(s,r,this.adapter.alias);for(const i of a){const n=await e.read(i);await Lt(t,s,r,i,n)}return void(s[r]=[...a])}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 Dt.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 o(`Invalid operation. All elements of property ${r} must match the same type.`);const a="object"===n,c=a?Ct.forModel(i[0],this.adapter.alias):Ut(s,r,this.adapter.alias),l=new Set([...a?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 a=await(async(t,e,r,s,i)=>{let n,a;const c=[];for(const l of s){n=jt(e.constructor.name,r,l);try{a=await t.get(n)}catch(t){const s=Ut(e,r,i);if(!s)throw new o("Could not find repo");a=await s.read(l)}c.push(a)}return c})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?a:a[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=H.get(t instanceof k?t.constructor:t,H.key(M.REFLECT,e,M.LIST))?.clazz;if(!r)throw new o("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=H.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 Yt extends Gt{constructor(t,e=Yt.name){super(t,e,403)}}class qt extends o{constructor(t){super(t,qt.name,503)}}function Qt(t){return Q.for(rt.TABLE).define({decorator:t=>e=>K(rt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function zt(t){return Q.for(rt.COLUMN).define({decorator:t=>(e,r)=>Z(H.key(rt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Ht(t,e,r){return Q.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(H.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 Q.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 Q.for(rt.CREATED_BY).define({decorator:()=>(t,e)=>V(x(Xt),Z(rt.CREATED_BY,e),ne())(t,e),args:[]}).apply()}function Kt(){return Q.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 Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),G([t,String,Number,BigInt]),x(Pt,a),A($t,a),E(Bt,a),O(Ft,a))},args:[t,e,r,s,i]}).apply()}function re(t,e=xt,r=!0,s,i){const n=rt.ONE_TO_MANY;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),Y([t,String,Number,BigInt]),x(Dt,a),A(It,a),E(kt,a),O(Ft,a))},args:[t,e,r,s,i]}).apply()}function se(t,e=xt,r=!0,s,i){const n=rt.MANY_TO_ONE;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),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 Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),Y([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ne(){return(t,e)=>Z(H.key(rt.GENERATED,e),!0)(t,e)}function ae(...t){return(e,r)=>{const s=H.get(e,H.key(rt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return V(K(H.key(rt.NO_VALIDATE,r),i))(e,r)}}function oe(){return ae(l.CREATE)}function ce(){return ae(l.UPDATE)}function le(){return ae(l.UPDATE,l.CREATE)}function he(t,e){return Q.for(rt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(Z(t,e)(r,s),Z(H.key(rt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}Q.for(N.TIMESTAMP).extend(ne()).apply(),Q.for(N.COMPOSED).extend(ne()).apply(),H.validationExceptions=((t,e)=>{const r=H.get(t,rt.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t),i=k.nestedRelations(t);return[...new Set([...s,...i])]}).bind(H),H.migrationsFor=(t=>{if(!(t=t??dt.current))throw new o("Could not get adapter for migrations");return H.innerGet(Symbol.for(rt.MIGRATION),t.alias).map(t=>t.class)}).bind(H),H.relations=((t,e)=>{const r=H.get(t,rt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new o("No relations metadata found for property "+e);return r[e]}}).bind(H),k.relations=(t,e)=>H.relations(t instanceof k?t.constructor:t,e)||[],k.nestedRelations=(t,e)=>{e?.length||(e=k.relations(t));let r=[];const s=H.get(t,rt.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&k.relations(i.class)){const s=k.relations(i.class),n=s.map(e=>`${t}.${e}`);e=[...e,...s,...n],r=k.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]},H.generated=((t,e)=>!!H.get("function"!=typeof t?t.constructor:t,H.key(rt.GENERATED,e))).bind(H),H.createdBy=(t=>{const e=H.get("function"!=typeof t?t.constructor:t,rt.CREATED_BY);if(!e)throw new o("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(H),H.updatedBy=(t=>{const e=H.get("function"!=typeof t?t.constructor:t,rt.UPDATED_BY);if(!e)throw new o("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(H),k.tableName=t=>{if(!(t instanceof k?k.get(t.constructor.name):t))throw new o("Unable to find model "+t);return H.get(t instanceof k?t.constructor:t,rt.TABLE)||(t instanceof k?t.constructor.name:t.name)},k.columnName=(t,e)=>H.get(t instanceof k?t.constructor:t,H.key(rt.COLUMN,e))||e,k.sequenceName=(t,...e)=>[k.tableName(t),...e].join("_"),k.sequenceFor=(t,e)=>{if(e)throw new at("not currently supported");const r=k.pkProps(t instanceof k?t.constructor:t);if(!r)throw new o("No sequence options defined for model. did you use the @pk decorator?");return r},k.indexes=t=>{const e=H.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=()=>H.innerGet(Symbol.for(rt.SERVICE)),e.repositories=()=>H.innerGet(Symbol.for(N.REPOSITORY));class de 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 o(`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),[a,o]=s,c=await t.apply(r,n);return this.updateObservers(a,(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),o,c,...n.slice(s.length)).then(()=>{i.verbose(`Observer refresh dispatched by ${e} for ${a}`),i.debug("pks: "+o)}).catch(t=>i.error(`Failed to dispatch observer refresh for ${e} on ${a}: ${t}`)),c}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof dt))throw new at("Only Adapters can be observed by dispatch");this.adapter=t,this.models=dt.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 at("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:a}=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,...a)}catch(t){throw new o("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}dt&&(dt._baseDispatch=de);class ue{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 ue._instance||(ue._instance=new ue),ue._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 P{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=H.get(this.constructor,rt.MIGRATION);if(!t)throw new o("No migration metadata for "+this.constructor.name);const e=t.flavour;return dt.get(e)}async enforceRules(t,e,r){const s=H.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 dt?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 Q.for(rt.MIGRATION).define({decorator:(t,e)=>r=>{const s=H.innerGet(Symbol.for(rt.MIGRATION),t)||[];return H.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 o(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,c;n=s,a=r,c=await i.next(t),Reflect.set(n,a,c)}function Ee(t,e){return(r,s)=>{switch(tt()(r,s),t.type){case void 0:{const e=H.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=[Ht([wt.ASC,wt.DSC]),L(),_(),Z(H.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),Q.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(),Ht(),n("design:type",Object)],Se.prototype,"current",void 0),Se=i([Qt("??sequence"),q(),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 o("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new o(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new o(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let a;const c=e||i;if(c%i!==0)throw new o("Value to increment does not consider the incrementBy setting: "+i);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:a=this.parse(t)+c;break;case BigInt.name:a=this.parse(t)+BigInt(c);break;case String.name:a=this.parse(t);break;case"serial":a=pe.instance.generate(t);break;case"uuid":a=ue.instance.generate(t);break;default:throw new o("Should never happen")}let l;try{l=await this.repo.update(new Se({id:n,current:a}),r)}catch(i){if(!(i instanceof f))throw i;try{l=await this.repo.create(new Se({id:n,current:a}),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),a=this.parse(this.options.incrementBy),c=await this.increment(n,this.parse(t)*a,s),h=[];for(let e=1;t>=e;e++)h.push(n+a*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new at(`type ${this.options.type} is currently not suppported for this adapter`);const d="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(h[h.length-1]!==c&&"String"!==d)throw new o("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 at(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Ce(t,e){return(i,n)=>n?r(H.constr(t))(i,n):(H.set(N.REPOSITORY,H.key(e||dt.currentFlavour,k.tableName(t)),i),K(N.REPOSITORY,i.name)(t),e=e||H.get(i.constructor,rt.ADAPTER),Ct.register(H.constr(t),i,e),s(H.constr(t),{callback:e=>(Object.defineProperty(e,N.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}dt._baseSequence=Ne;class _e extends o{constructor(t){super(t,_e.name,500)}}class Te extends P{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,ge(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${mt.FIND_BY}|${mt.LIST_BY}`,"gi"))}async pagePrefix(t,...e){return[t,...(await nt.args(rt.QUERY,this.clazz,e,this.adapter)).args]}pagePrepared(t,...e){const r=Ct.forModel(this.clazz,this.adapter.alias),s=this.query,{method:i,args:n,params:a}=s,o=RegExp(`^${mt.FIND_BY}|${mt.LIST_BY}`,"gi");if(!i.match(o))throw new at(`Method ${i} is not supported for pagination`);o.lastIndex=0;const c=i.replace(o,mt.PAGE_BY);return r.statement(c,...n,t,Object.assign({},a,{limit:this.size}),...e)}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}async page(t=1,...e){const{ctxArgs:r}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return this.pagePrepared(t,...r);throw new at("Raw support not available without subclassing this")}}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}=H.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 Pe=()=>Re(l.CREATE),$e=()=>Re(l.READ),Be=()=>Re(l.UPDATE),De=()=>Re(l.DELETE);function Ie(t){return t="string"==typeof t?t:H.Symbol(t).toString(),(e,i,n)=>{H.set(rt.SERVICE,t,e);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else a.push(s(t,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return a.push(K(rt.SERVICE,t)),V(...a)(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 o("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 a=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?a.for(e):a,ctxArgs:[...t,n]}}static get(t){if(!t)throw new o("No name provided");const r=e.get(t);if(r)return r;throw new o("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 o("Config not initialized");return this._config}get client(){if(!this._client)throw new o("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([B(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],je.prototype,"boot",null),i([B(),n("design:type",Object),n("design:paramtypes",[])],je.prototype,"config",null),i([B(),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 o("Class not initialized");return this.clazz}constructor(t){super(),this.clazz=t,this.repo=Ct.forModel(t)}static getService(t){if(!t)throw new o("No name provided");const e=Le(t);try{const t=ke.get(e);if(t)return t}catch(t){}throw new o("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 a=class extends s{constructor(){super(t)}};return a=i([Ie(e),n("design:paramtypes",[])],a),new a}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new o("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);const a=t.pop();a instanceof nt||(t=[...t,await n()]);const c=this?a.logger.for(this).for(e):a.logger.clear().for(this).for(e);return{ctx:a,log:e?c.for(e):c,ctxArgs:[...t,a]}}}var Me,Ue,Ge,Ye;i([Pe(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"create",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"createAll",null),i([De(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"delete",null),i([De(),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([Be(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"update",null),i([Be(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Fe.prototype,"updateAll",null);class qe extends lt{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{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.overrides||{},this.fromSelector);r=[...r,t]}const{ctx:s,ctxArgs:i}=dt.logCtx(r,t.name),n=s.get("forcePrepareSimpleQueries"),a=s.get("forcePrepareComplexQueries");return(n&&this.isSimpleQuery()||a)&&await this.prepare(s),i},t.name)})}get log(){return this.adapter.log.for(qe)}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 ut("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){try{if(this.prepared)return this.executePrepared(...t);const e=this.build();return await this.raw(e,...t)}catch(t){throw new ut(t)}}async executePrepared(...t){const e=Ct.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new at("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(!this.selectSelector)return i;const n=k.pk(this.fromSelector),a=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(a):a(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,a=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);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;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 ut("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 a={class:this.fromSelector,method:mt.LIST_BY,args:[s],params:n};return e&&(a.method=mt.FIND_BY,a.args=[e,this.whereCondition.comparison],a.params=n),a}async prepare(t){if(t=t||await this.adapter.context(rt.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){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[0]),r.direction=this.orderBySelector[1]),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,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new ut(t)}}toString(){return this.adapter.flavour+" statement"}}i([B(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],qe.prototype,"select",null),i([B(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Me="undefined"!=typeof S&&S)?Me:Object]),n("design:returntype",Object)],qe.prototype,"distinct",null),i([B(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ue="undefined"!=typeof S&&S)?Ue:Object]),n("design:returntype",Object)],qe.prototype,"max",null),i([B(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ge="undefined"!=typeof S&&S)?Ge:Object]),n("design:returntype",Object)],qe.prototype,"min",null),i([B(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ye="undefined"!=typeof S&&S)?Ye:Object]),n("design:returntype",Object)],qe.prototype,"count",null),i([B(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],qe.prototype,"from",null),i([B(),n("design:type",Function),n("design:paramtypes",[vt]),n("design:returntype",Object)],qe.prototype,"where",null),i([B(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],qe.prototype,"orderBy",null),i([B(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],qe.prototype,"groupBy",null),i([B(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],qe.prototype,"limit",null),i([B(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],qe.prototype,"offset",null),i([B(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],qe.prototype,"execute",null);class Qe extends qe{constructor(t,e){super(t,e)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new o("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=H.getPropDesignTypes(t.constructor,s);if(!n)throw new ut("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 ut("Sorting not supported for not date classes");default:throw new ut("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 ut("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 o("Invalid operator for standard comparisons: "+s)}else{if(s===ft.NOT)throw new o("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 o("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function ze(t,e,r,s){const i=t.get("UUID");if(!i)throw new at("This adapter does not support user identification");s[r]=i}const He="ram";class Ve extends Te{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{ctx:r,ctxArgs:s}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return this.pagePrepared(t,...s);const i=this.prepare(this.statement);let n;if(this._recordCount&&this._totalPages)t=this.validatePage(t),i.skip=(t-1)*this.size,n=await this.adapter.raw(i,!0,...e,r);else if(this._totalPages=this._recordCount=0,n=await this.adapter.raw({...i,limit:void 0},!1,r),this._recordCount=n.count||n.data.length,this._recordCount>0){const t=i?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}return this._currentPage=t,n.data||n}}class We extends dt{constructor(t={},e){super(t,He,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=!0,r){r.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:s,sort:i,limit:n,skip:a,from:c}=t;let{select:l}=t;const h=this.tableFor(c);if(!h)throw new o(`Table ${c} not found in RamAdapter`);const d=k.pk(c),u=H.get(c,H.key(N.ID,d));let p=Array.from(h.entries()).map(([t,e])=>this.revert(e,c,Ne.parseValue(u.type,t),void 0,r));p=s?p.filter(s):p;const g=p.length;return i&&(p=p.sort(i)),a&&(p=p.slice(a)),n&&(p=p.slice(0,n)),l&&(l=Array.isArray(l)?l:[l],p=p.map(t=>Object.entries(t).reduce((t,[e,r])=>(l.includes(e)&&(t[e]=r),t),{}))),e?p:{data:p,count:g}}parseError(t){return t instanceof R?t:new o(t)}Statement(t){return new Qe(this,t)}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;Q.flavouredAs(He).for(t).define(x(ze),Z(t,{})).apply(),Q.flavouredAs(He).for(e).define(b(ze),Z(e,{})).apply()}getClient(){return new Map}}We.decoration(),e.setRegistry(new Tt);const Xe="##VERSION##",Je="##PACKAGE##";H.registerLibrary(Je,Xe);export{fe as AbsMigration,dt as Adapter,Gt as AuthorizationError,me as BaseModel,xe as BigIntSequence,bt as Cascade,je as ClientBasedService,vt as Condition,qt as ConnectionError,nt as Context,lt as ContextualLoggedClass,st as DefaultAdapterFlags,xt as DefaultCascade,be as DefaultSequenceOptions,de as Dispatch,Yt as ForbiddenError,yt as GroupOperator,Tt as InjectablesRegistry,Ot as MethodQueryBuilder,ot as MigrationError,ct as MigrationRuleError,Fe as ModelService,we as NoneSequenceOptions,ve as NumericSequence,_e as ObserverError,it as ObserverHandler,ft as Operator,At as OperatorsMap,wt as OrderDirection,Je as PACKAGE_NAME,Te as Paginator,pt as PagingError,rt as PersistenceKeys,mt as PreparedStatementKeys,gt as QueryClause,ut as QueryError,We as RamAdapter,He as RamFlavour,Ve as RamPaginator,Qe as RamStatement,Ct as Repository,Ne as Sequence,Se as SequenceModel,pe as Serial,ke as Service,qe as Statement,ue as UUID,at as UnsupportedError,Xe as VERSION,Lt as cacheModelForPopulate,zt as column,Pe as create,Rt as createOrUpdate,Zt as createdAt,Jt as createdBy,Xt as createdByOnCreateUpdate,ze as createdByOnRamCreateUpdate,De as del,_t as generateInjectableNameForRepository,ne as generated,jt as getPopulateKey,Ht as index,ie as manyToMany,se as manyToOne,ye as migration,ae as noValidateOn,oe as noValidateOnCreate,le as noValidateOnCreateUpdate,ce as noValidateOnUpdate,re as oneToMany,Dt as oneToManyOnCreate,kt as oneToManyOnDelete,It as oneToManyOnUpdate,ee as oneToOne,Pt as oneToOneOnCreate,Bt 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,Qt as table,Wt as unique,Vt as uniqueOnCreateUpdate,Be 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 a,InternalError as o,Context as c,OperationKeys as l,Repository as h,wrapMethodWithContext as d,enforceDBDecorators as u,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 _,prefixMethod as T,BaseError as B}from"@decaf-ts/db-decorators";import{LoggedClass as R,Logging as P,final as $,isClass as D,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 Y,model as q}from"@decaf-ts/decorator-validation";import{Decoration as Q,DefaultFlavour as z,Metadata as H,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({},a,{allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1});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 o("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 o("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=dt.logCtx(s,this.updateObservers);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(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 at extends o{constructor(t){super(t,at.name,500)}}class ot extends o{constructor(t,e=ot.name){super(t,e,500)}}class ct extends ot{constructor(t){super(t,ct.name)}}class lt extends R{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 o("No context provided");const r=t.pop();if(!(r instanceof c))throw new o("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=Q.flavourResolver.bind(Q);Q.flavourResolver=t=>{try{const e=ht(t);if(e&&e!==z)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof H.registeredFlavour?H.registeredFlavour(r):void 0;if(s&&s!==z)return s;const i=dt._currentFlavour;if(i){const t=dt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return z}};class dt extends lt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!dt._baseRepository)throw new o("This should be overridden when necessary. Otherwise it will be replaced lazily");return dt._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new o("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 dt._cache)throw new o(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);dt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),dt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),dt._currentFlavour=this.alias)}Dispatch(){return new dt._baseDispatch}ObserverHandler(){return new it}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new dt._baseSequence(t,this)}async flags(t,e,r,...s){let i=r.logger||P.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)?[]:H.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 o(`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:a}=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 d=t[rt.METADATA],u=Object.keys(h).reduce((r,s)=>(s===l||(r[s]=t[k.columnName(e,s)]),r),h);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in u)throw new o(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);u[t]=e})),d&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${d}`),Object.defineProperty(u,rt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),u}async createAll(t,e,r,...s){if(e.length!==r.length)throw new o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),a=k.tableName(t);return i.debug(`Creating ${e.length} entries ${a} 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 o("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),a=k.tableName(t);return i.debug(`Updating ${e.length} entries ${a} table`),Promise.all(e.map((e,s)=>this.update(t,e,r[s],...n)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=dt.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 o("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 o("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=dt.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 H.flavourOf(t)}static get currentFlavour(){if(!dt._currentFlavour)throw new o("No persistence flavour set. Please initialize your adapter");return dt._currentFlavour}static get current(){return dt.get(this.currentFlavour)}static get(t){if(!t)return dt.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new o(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return H.flavouredAs(t)}catch(t){throw new o(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 H.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof nt&&(e=[t],t=this.migrations());const{ctx:r}=dt.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 ot(t)}}}i([$(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],dt.prototype,"shutdownProxies",null),i([$(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],dt.prototype,"context",null),i([$(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],dt.prototype,"observe",null),i([$(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],dt.prototype,"unObserve",null),i([$(),n("design:type",Object),n("design:paramtypes",[])],dt.prototype,"client",null);class ut extends o{constructor(t){super(t,ut.name,500)}}class pt extends o{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 ut(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:a,limit:o,offset:c}=this.extractOrderLimitOffset(r,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:a,limit:o,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{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(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:a}=this.parseFieldAndOperator(t),o=a?At[a]:At.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=o(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,a;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]||(a=s[2]),{orderBy:i,limit:n,offset:a}}}function St(){return Q.for(rt.STATEMENT).define({decorator:()=>(t,e,r)=>V(W(H.key(rt.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function Nt(t={}){return Q.for(rt.QUERY).define({decorator:t=>(e,r,s)=>{const i=Ot.getFieldsFromMethodName(r);return V(W(H.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:a,orderBy:o,limit:c,offset:l}=Ot.build(e.name,...s);let h=r.select(i);n&&(h=h.where(n));const{allowLimit:d,allowOffset:u,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(o||[])[0],allowed:p},{key:"limit",value:c,allowed:d},{key:"offset",value:l,allowed:u}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new ut(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 o("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=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1},t&&(this._adapter=t),e&&(Ct.register(e,this,this.adapter.alias),t)&&H.get(e,X.FLAVOUR)===z&&J(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(t=>{const e=t.name;d(this,this[e+"Prefix"],t,this[e+"Suffix"])})}logCtx(t,e){return dt.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 u(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:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,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)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[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 a=[];if(n.type?(n.name||(n.name=k.sequenceName(t[0],"pk")),a=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):a=t.map((t,e)=>{if(void 0===t[this.pk])throw new o("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?a[e]:""+t[this.pk]),s||await u(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 u(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,u(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:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${k.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,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 o("No value for the Id is defined under the property "+this.pk);const a=await this.read(n,...r.args);if(t=k.merge(a,t,this.class),s||await u(this,r.context,t,l.UPDATE,l.ON,a),!i){const e=await Promise.resolve(t.hasErrors(a,...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 o("missing id on update operation");return e}),a=await this.readAll(n,...r.args);if(t=t.map((t,e)=>k.merge(a[e],t,this.class)),s||await Promise.all(t.map((t,e)=>u(this,r.context,t,l.UPDATE,l.ON,a[e]))),!i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(a[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 u(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=>u(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(this._overrides).select(t).from(this.class)}async query(t,e,r=wt.ASC,s,i,...n){const a=await nt.args(rt.QUERY,this.class,n,this.adapter,this._overrides||{}),{ctx:o}=this.logCtx(a.args,this.query),c=[e,r],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.execute(o)}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:a}=this.logCtx(i.args,this.paginateBy);return n.verbose(`paginating ${k.tableName(this.class)} with page size ${r}`),this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(r,...a)}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 a=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...n);if(!a.length)throw new f("No results found");return a[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 ut("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:H.constr(t)===H.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 o("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 o("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=>dt._baseSequence.parseValue(k.sequenceFor(this.class).type,t)):dt._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||H.flavourOf(t)||dt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof Ct)return s;const n=e||H.flavourOf(t)||s&&H.get(s,rt.ADAPTER)||dt.currentFlavour,a=n?dt.get(n):void 0;if(!a)throw new o("No registered persistence adapter found flavour "+n);return s=s||a.repository(),new s(a,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 o("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 o(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof Ct?t.constructor:t,s=H.get(r,e?H.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 H.get(r,e?H.key(rt.QUERY,e):rt.QUERY)}}function _t(t,e){if(!(e||(e=Q.flavourResolver(t instanceof k?t.constructor:t))&&e!==z))throw new o("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([$(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],Ct.prototype,"observe",null),i([$(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Ct.prototype,"unObserve",null),dt&&(dt._baseRepository=Ct);class Tt extends t{get log(){return this.logger||(this.logger=P.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 a=rt.ADAPTER,o=r||H.get(n,a);try{let t=o;try{o&&dt.get(o)}catch{const e=dt.current;e&&e.flavour===o&&(t=e.alias)}if(i=Ct.forModel(n,t),i instanceof Ct)return i;const r=o||H.get(i.constructor,a)||H.get(n,a);e.register(i,_t(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,o);if("function"==typeof e){const t=o?dt.get(o):dt.current;if(!t)return;return new e(t,n)}}}return i}}async function Bt(t,e,r,s){if(!s){const e=k.get(t.constructor.name);if(!e)throw new o("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 Rt(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=D(e.class)?e.class:e.class();if(!n)throw new o("Could not find model "+e.class);const a=Ct.forModel(n,this.adapter.alias),c=await a.create(i),l=k.pk(c);await Lt(t,s,r,c[l],c),s[r]=c[l]}async function Pt(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 Bt(s[r],t,this.adapter.alias),a=k.pk(n);await Lt(t,s,r,n[a],n),s[r]=n[a]}async function $t(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 a;a=i instanceof k?await n.delete(s[r][n.pk]):await n.delete(s[r]),await Lt(t,s,r,a[n.pk],a)}async function Dt(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 o(`Invalid operation. All elements of property ${r} must match the same type.`);const a=new Set([...i]);if("object"!==n){const e=Ut(s,r,this.adapter.alias);for(const i of a){const n=await e.read(i);await Lt(t,s,r,i,n)}return void(s[r]=[...a])}const c=k.pk(i[0]),l=new Set;for(const e of i){const i=await Bt(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 Dt.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 o(`Invalid operation. All elements of property ${r} must match the same type.`);const a="object"===n,c=a?Ct.forModel(i[0],this.adapter.alias):Ut(s,r,this.adapter.alias),l=new Set([...a?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 a=await(async(t,e,r,s,i)=>{let n,a;const c=[];for(const l of s){n=jt(e.constructor.name,r,l);try{a=await t.get(n)}catch(t){const s=Ut(e,r,i);if(!s)throw new o("Could not find repo");a=await s.read(l)}c.push(a)}return c})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?a:a[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=H.get(t instanceof k?t.constructor:t,H.key(M.REFLECT,e,M.LIST))?.clazz;if(!r)throw new o("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=H.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 Yt extends Gt{constructor(t,e=Yt.name){super(t,e,403)}}class qt extends o{constructor(t){super(t,qt.name,503)}}function Qt(t){return Q.for(rt.TABLE).define({decorator:t=>e=>K(rt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function zt(t){return Q.for(rt.COLUMN).define({decorator:t=>(e,r)=>Z(H.key(rt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Ht(t,e,r){return Q.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(H.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 Q.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 Q.for(rt.CREATED_BY).define({decorator:()=>(t,e)=>V(x(Xt),Z(rt.CREATED_BY,e),ne())(t,e),args:[]}).apply()}function Kt(){return Q.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 Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),G([t,String,Number,BigInt]),x(Rt,a),A(Pt,a),E($t,a),O(Ft,a))},args:[t,e,r,s,i]}).apply()}function re(t,e=xt,r=!0,s,i){const n=rt.ONE_TO_MANY;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),Y([t,String,Number,BigInt]),x(Dt,a),A(It,a),E(kt,a),O(Ft,a))},args:[t,e,r,s,i]}).apply()}function se(t,e=xt,r=!0,s,i){const n=rt.MANY_TO_ONE;return Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),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 Q.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};return s&&(a.joinTable=s),i&&(a.name=i),V(tt(),he(n,a),Y([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ne(){return(t,e)=>Z(H.key(rt.GENERATED,e),!0)(t,e)}function ae(...t){return(e,r)=>{const s=H.get(e,H.key(rt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return V(K(H.key(rt.NO_VALIDATE,r),i))(e,r)}}function oe(){return ae(l.CREATE)}function ce(){return ae(l.UPDATE)}function le(){return ae(l.UPDATE,l.CREATE)}function he(t,e){return Q.for(rt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(Z(t,e)(r,s),Z(H.key(rt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}Q.for(N.TIMESTAMP).extend(ne()).apply(),Q.for(N.COMPOSED).extend(ne()).apply(),H.validationExceptions=((t,e)=>{const r=H.get(t,rt.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t),i=k.nestedRelations(t);return[...new Set([...s,...i])]}).bind(H),H.migrationsFor=(t=>{if(!(t=t??dt.current))throw new o("Could not get adapter for migrations");return H.innerGet(Symbol.for(rt.MIGRATION),t.alias).map(t=>t.class)}).bind(H),H.relations=((t,e)=>{const r=H.get(t,rt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new o("No relations metadata found for property "+e);return r[e]}}).bind(H),k.relations=(t,e)=>H.relations(t instanceof k?t.constructor:t,e)||[],k.nestedRelations=(t,e)=>{e?.length||(e=k.relations(t));let r=[];const s=H.get(t,rt.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&k.relations(i.class)){const s=k.relations(i.class),n=s.map(e=>`${t}.${e}`);e=[...e,...s,...n],r=k.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]},H.generated=((t,e)=>!!H.get("function"!=typeof t?t.constructor:t,H.key(rt.GENERATED,e))).bind(H),H.createdBy=(t=>{const e=H.get("function"!=typeof t?t.constructor:t,rt.CREATED_BY);if(!e)throw new o("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(H),H.updatedBy=(t=>{const e=H.get("function"!=typeof t?t.constructor:t,rt.UPDATED_BY);if(!e)throw new o("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(H),k.tableName=t=>{if(!(t instanceof k?k.get(t.constructor.name):t))throw new o("Unable to find model "+t);return H.get(t instanceof k?t.constructor:t,rt.TABLE)||(t instanceof k?t.constructor.name:t.name)},k.columnName=(t,e)=>H.get(t instanceof k?t.constructor:t,H.key(rt.COLUMN,e))||e,k.sequenceName=(t,...e)=>[k.tableName(t),...e].join("_"),k.sequenceFor=(t,e)=>{if(e)throw new at("not currently supported");const r=k.pkProps(t instanceof k?t.constructor:t);if(!r)throw new o("No sequence options defined for model. did you use the @pk decorator?");return r},k.indexes=t=>{const e=H.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=()=>H.innerGet(Symbol.for(rt.SERVICE)),e.repositories=()=>H.innerGet(Symbol.for(N.REPOSITORY));class de 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 o(`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),[a,o]=s,c=await t.apply(r,n);return this.updateObservers(a,(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),o,c,...n.slice(s.length)).then(()=>{i.verbose(`Observer refresh dispatched by ${e} for ${a}`),i.debug("pks: "+o)}).catch(t=>i.error(`Failed to dispatch observer refresh for ${e} on ${a}: ${t}`)),c}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof dt))throw new at("Only Adapters can be observed by dispatch");this.adapter=t,this.models=dt.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 at("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:a}=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,...a)}catch(t){throw new o("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}dt&&(dt._baseDispatch=de);class ue{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 ue._instance||(ue._instance=new ue),ue._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 R{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=H.get(this.constructor,rt.MIGRATION);if(!t)throw new o("No migration metadata for "+this.constructor.name);const e=t.flavour;return dt.get(e)}async enforceRules(t,e,r){const s=H.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 dt?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 Q.for(rt.MIGRATION).define({decorator:(t,e)=>r=>{const s=H.innerGet(Symbol.for(rt.MIGRATION),t)||[];return H.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 o(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,c;n=s,a=r,c=await i.next(t),Reflect.set(n,a,c)}function Ee(t,e){return(r,s)=>{switch(tt()(r,s),t.type){case void 0:{const e=H.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=[Ht([wt.ASC,wt.DSC]),L(),_(),Z(H.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),Q.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(),Ht(),n("design:type",Object)],Se.prototype,"current",void 0),Se=i([Qt("??sequence"),q(),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 o("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new o(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new o(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let a;const c=e||i;if(c%i!==0)throw new o("Value to increment does not consider the incrementBy setting: "+i);switch("function"==typeof s&&s?.name?s.name:s){case Number.name:a=this.parse(t)+c;break;case BigInt.name:a=this.parse(t)+BigInt(c);break;case String.name:a=this.parse(t);break;case"serial":a=pe.instance.generate(t);break;case"uuid":a=ue.instance.generate(t);break;default:throw new o("Should never happen")}let l;try{l=await this.repo.update(new Se({id:n,current:a}),r)}catch(i){if(!(i instanceof f))throw i;try{l=await this.repo.create(new Se({id:n,current:a}),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),a=this.parse(this.options.incrementBy),c=await this.increment(n,this.parse(t)*a,s),h=[];for(let e=1;t>=e;e++)h.push(n+a*this.parse(e));if("uuid"===this.options.type||"serial"===this.options.type)throw new at(`type ${this.options.type} is currently not suppported for this adapter`);const d="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type;if(h[h.length-1]!==c&&"String"!==d)throw new o("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 at(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function Ce(t,e){return(i,n)=>n?r(H.constr(t))(i,n):(H.set(N.REPOSITORY,H.key(e||dt.currentFlavour,k.tableName(t)),i),K(N.REPOSITORY,i.name)(t),e=e||H.get(i.constructor,rt.ADAPTER),Ct.register(H.constr(t),i,e),s(H.constr(t),{callback:e=>(Object.defineProperty(e,N.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}dt._baseSequence=Ne;class _e extends o{constructor(t){super(t,_e.name,500)}}class Te extends R{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,ge(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${mt.FIND_BY}|${mt.LIST_BY}`,"gi"))}async pagePrefix(t,...e){return[t,...(await nt.args(rt.QUERY,this.clazz,e,this.adapter)).args]}pagePrepared(t,...e){const r=Ct.forModel(this.clazz,this.adapter.alias),s=this.query,{method:i,args:n,params:a}=s,o=RegExp(`^${mt.FIND_BY}|${mt.LIST_BY}`,"gi");if(!i.match(o))throw new at(`Method ${i} is not supported for pagination`);o.lastIndex=0;const c=i.replace(o,mt.PAGE_BY);return r.statement(c,...n,t,Object.assign({},a,{limit:this.size}),...e)}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}async page(t=1,...e){const{ctxArgs:r}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return this.pagePrepared(t,...r);throw new at("Raw support not available without subclassing this")}}function Be(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}=H.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 Re=()=>Be(l.CREATE),Pe=()=>Be(l.READ),$e=()=>Be(l.UPDATE),De=()=>Be(l.DELETE);function Ie(t){return t="string"==typeof t?t:H.Symbol(t).toString(),(e,i,n)=>{H.set(rt.SERVICE,t,e);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else a.push(s(t,{callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return a.push(K(rt.SERVICE,t)),V(...a)(e,i,n)}}class ke{constructor(t){this.name=t,this.Context=nt}async flags(t,e,...r){let s=e.logger||P.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 o("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 a=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?a.for(e):a,ctxArgs:[...t,n]}}static get(t){if(!t)throw new o("No name provided");const r=e.get(t);if(r)return r;throw new o("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:P.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 o("Config not initialized");return this._config}get client(){if(!this._client)throw new o("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([$(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],je.prototype,"boot",null),i([$(),n("design:type",Object),n("design:paramtypes",[])],je.prototype,"config",null),i([$(),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 o("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=Ct.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new o("No name provided");const e=Le(t);try{const t=ke.get(e);if(t)return t}catch(t){}throw new o("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 listBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.listBy,!0);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=await this.logCtx(s,this.paginateBy,!0);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.findOneBy,!0);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=await this.logCtx(r,this.findBy,!0);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=await this.logCtx(e,this.statement,!0);return this.repo.statement(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 a=class extends s{constructor(){super(t)}};return a=i([Ie(e),n("design:paramtypes",[])],a),new a}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new o("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);const a=t.pop();a instanceof nt||(t=[...t,await n()]);const c=this?a.logger.for(this).for(e):a.logger.clear().for(this).for(e);return{ctx:a,log:e?c.for(e):c,ctxArgs:[...t,a]}}}var Me,Ue,Ge,Ye;i([Re(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"create",null),i([Re(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"createAll",null),i([De(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"delete",null),i([De(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"deleteAll",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"read",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Fe.prototype,"readAll",null),i([Pe(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Fe.prototype,"query",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Fe.prototype,"update",null),i([$e(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Fe.prototype,"updateAll",null);class qe extends lt{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{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.overrides||{},this.fromSelector);r=[...r,t]}const{ctx:s,ctxArgs:i}=dt.logCtx(r,t.name),n=s.get("forcePrepareSimpleQueries"),a=s.get("forcePrepareComplexQueries");return(n&&this.isSimpleQuery()||a)&&await this.prepare(s),i},t.name)})}get log(){return this.adapter.log.for(qe)}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 ut("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){try{if(this.prepared)return this.executePrepared(...t);const e=this.build();return await this.raw(e,...t)}catch(t){throw new ut(t)}}async executePrepared(...t){const e=Ct.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new at("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(!this.selectSelector)return i;const n=k.pk(this.fromSelector),a=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(a):a(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,a=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);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;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 ut("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 a={class:this.fromSelector,method:mt.LIST_BY,args:[s],params:n};return e&&(a.method=mt.FIND_BY,a.args=[e,this.whereCondition.comparison],a.params=n),a}async prepare(t){if(t=t||await this.adapter.context(rt.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){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[0]),r.direction=this.orderBySelector[1]),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,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new ut(t)}}toString(){return this.adapter.flavour+" statement"}}i([$(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],qe.prototype,"select",null),i([$(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Me="undefined"!=typeof S&&S)?Me:Object]),n("design:returntype",Object)],qe.prototype,"distinct",null),i([$(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ue="undefined"!=typeof S&&S)?Ue:Object]),n("design:returntype",Object)],qe.prototype,"max",null),i([$(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ge="undefined"!=typeof S&&S)?Ge:Object]),n("design:returntype",Object)],qe.prototype,"min",null),i([$(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ye="undefined"!=typeof S&&S)?Ye:Object]),n("design:returntype",Object)],qe.prototype,"count",null),i([$(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],qe.prototype,"from",null),i([$(),n("design:type",Function),n("design:paramtypes",[vt]),n("design:returntype",Object)],qe.prototype,"where",null),i([$(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],qe.prototype,"orderBy",null),i([$(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],qe.prototype,"groupBy",null),i([$(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],qe.prototype,"limit",null),i([$(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],qe.prototype,"offset",null),i([$(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],qe.prototype,"execute",null);class Qe extends qe{constructor(t,e){super(t,e)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new o("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=H.getPropDesignTypes(t.constructor,s);if(!n)throw new ut("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 ut("Sorting not supported for not date classes");default:throw new ut("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 ut("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 o("Invalid operator for standard comparisons: "+s)}else{if(s===ft.NOT)throw new o("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 o("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function ze(t,e,r,s){const i=t.get("UUID");if(!i)throw new at("This adapter does not support user identification");s[r]=i}const He="ram";class Ve extends Te{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{ctx:r,ctxArgs:s}=this.adapter.logCtx(e,this.page);if(this.isPreparedStatement())return this.pagePrepared(t,...s);const i=this.prepare(this.statement);let n;if(this._recordCount&&this._totalPages)t=this.validatePage(t),i.skip=(t-1)*this.size,n=await this.adapter.raw(i,!0,...e,r);else if(this._totalPages=this._recordCount=0,n=await this.adapter.raw({...i,limit:void 0},!1,r),this._recordCount=n.count||n.data.length,this._recordCount>0){const t=i?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}return this._currentPage=t,n.data||n}}class We extends dt{constructor(t={},e){super(t,He,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}`),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 await this.lock.acquire(),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}`),!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 await this.lock.acquire(),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}`),!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}`);await this.lock.acquire();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=!0,r){r.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:s,sort:i,limit:n,skip:a,from:c}=t;let{select:l}=t;const h=this.tableFor(c);if(!h)throw new o(`Table ${c} not found in RamAdapter`);const d=k.pk(c),u=H.get(c,H.key(N.ID,d));let p=Array.from(h.entries()).map(([t,e])=>this.revert(e,c,Ne.parseValue(u.type,t),void 0,r));p=s?p.filter(s):p;const g=p.length;return i&&(p=p.sort(i)),a&&(p=p.slice(a)),n&&(p=p.slice(0,n)),l&&(l=Array.isArray(l)?l:[l],p=p.map(t=>Object.entries(t).reduce((t,[e,r])=>(l.includes(e)&&(t[e]=r),t),{}))),e?p:{data:p,count:g}}parseError(t){return t instanceof B?t:new o(t)}Statement(t){return new Qe(this,t)}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;Q.flavouredAs(He).for(t).define(x(ze),Z(t,{})).apply(),Q.flavouredAs(He).for(e).define(b(ze),Z(e,{})).apply()}getClient(){return new Map}}We.decoration(),e.setRegistry(new Tt);const Xe="##VERSION##",Je="##PACKAGE##";H.registerLibrary(Je,Xe);export{fe as AbsMigration,dt as Adapter,Gt as AuthorizationError,me as BaseModel,xe as BigIntSequence,bt as Cascade,je as ClientBasedService,vt as Condition,qt as ConnectionError,nt as Context,lt as ContextualLoggedClass,st as DefaultAdapterFlags,xt as DefaultCascade,be as DefaultSequenceOptions,de as Dispatch,Yt as ForbiddenError,yt as GroupOperator,Tt as InjectablesRegistry,Ot as MethodQueryBuilder,ot as MigrationError,ct as MigrationRuleError,Fe as ModelService,we as NoneSequenceOptions,ve as NumericSequence,_e as ObserverError,it as ObserverHandler,ft as Operator,At as OperatorsMap,wt as OrderDirection,Je as PACKAGE_NAME,Te as Paginator,pt as PagingError,rt as PersistenceKeys,mt as PreparedStatementKeys,gt as QueryClause,ut as QueryError,We as RamAdapter,He as RamFlavour,Ve as RamPaginator,Qe as RamStatement,Ct as Repository,Ne as Sequence,Se as SequenceModel,pe as Serial,ke as Service,qe as Statement,ue as UUID,at as UnsupportedError,Xe as VERSION,Lt as cacheModelForPopulate,zt as column,Re as create,Bt as createOrUpdate,Zt as createdAt,Jt as createdBy,Xt as createdByOnCreateUpdate,ze as createdByOnRamCreateUpdate,De as del,_t as generateInjectableNameForRepository,ne as generated,jt as getPopulateKey,Ht as index,ie as manyToMany,se as manyToOne,ye as migration,ae as noValidateOn,oe as noValidateOnCreate,le as noValidateOnCreateUpdate,ce as noValidateOnUpdate,re as oneToMany,Dt as oneToManyOnCreate,kt as oneToManyOnDelete,It as oneToManyOnUpdate,ee as oneToOne,Rt as oneToOneOnCreate,$t as oneToOneOnDelete,Pt as oneToOneOnUpdate,Oe as pk,Ee as pkDec,Ae as pkOnCreate,Ft as populate,ge as prefixMethod,St as prepared,Nt as query,Pe as read,he as relation,Ce as repository,Ut as repositoryFromTypeMetadata,Ie as service,Qt as table,Wt as unique,Vt as uniqueOnCreateUpdate,$e as update,te as updatedAt,Kt as updatedBy};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|