@decaf-ts/core 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +6 -1
  2. package/dist/core.cjs +1 -1
  3. package/dist/core.cjs.map +1 -1
  4. package/dist/core.js +1 -1
  5. package/dist/core.js.map +1 -1
  6. package/lib/esm/identity/decorators.js +1 -1
  7. package/lib/esm/identity/decorators.js.map +1 -1
  8. package/lib/esm/index.d.ts +1 -1
  9. package/lib/esm/index.js +1 -1
  10. package/lib/{ram/model/RamSequenceModel.d.ts → esm/model/SequenceModel.d.ts} +3 -3
  11. package/lib/esm/{ram/model/RamSequenceModel.js → model/SequenceModel.js} +12 -11
  12. package/lib/esm/model/SequenceModel.js.map +1 -0
  13. package/lib/esm/model/decorators.d.ts +1 -1
  14. package/lib/esm/model/decorators.js +1 -1
  15. package/lib/esm/model/decorators.js.map +1 -1
  16. package/lib/esm/model/index.d.ts +1 -0
  17. package/lib/esm/model/index.js +1 -0
  18. package/lib/esm/model/index.js.map +1 -1
  19. package/lib/esm/persistence/Adapter.d.ts +3 -2
  20. package/lib/esm/persistence/Adapter.js +9 -0
  21. package/lib/esm/persistence/Adapter.js.map +1 -1
  22. package/lib/esm/persistence/Sequence.d.ts +33 -17
  23. package/lib/esm/persistence/Sequence.js +126 -0
  24. package/lib/esm/persistence/Sequence.js.map +1 -1
  25. package/lib/esm/persistence/generators.d.ts +14 -0
  26. package/lib/esm/persistence/generators.js +31 -0
  27. package/lib/esm/persistence/generators.js.map +1 -0
  28. package/lib/esm/persistence/index.d.ts +1 -0
  29. package/lib/esm/persistence/index.js +1 -0
  30. package/lib/esm/persistence/index.js.map +1 -1
  31. package/lib/esm/ram/RamAdapter.d.ts +1 -10
  32. package/lib/esm/ram/RamAdapter.js +0 -11
  33. package/lib/esm/ram/RamAdapter.js.map +1 -1
  34. package/lib/esm/ram/index.d.ts +0 -2
  35. package/lib/esm/ram/index.js +0 -2
  36. package/lib/esm/ram/index.js.map +1 -1
  37. package/lib/esm/repository/Repository.d.ts +1 -1
  38. package/lib/esm/repository/Repository.js +3 -4
  39. package/lib/esm/repository/Repository.js.map +1 -1
  40. package/lib/esm/repository/decorators.js +2 -2
  41. package/lib/esm/repository/decorators.js.map +1 -1
  42. package/lib/esm/repository/injectables.js +3 -1
  43. package/lib/esm/repository/injectables.js.map +1 -1
  44. package/lib/esm/utils/Services.d.ts +47 -7
  45. package/lib/esm/utils/Services.js +150 -13
  46. package/lib/esm/utils/Services.js.map +1 -1
  47. package/lib/esm/utils/decorators.d.ts +2 -1
  48. package/lib/esm/utils/decorators.js +7 -3
  49. package/lib/esm/utils/decorators.js.map +1 -1
  50. package/lib/identity/decorators.cjs +2 -2
  51. package/lib/identity/decorators.js.map +1 -1
  52. package/lib/index.cjs +1 -1
  53. package/lib/index.d.ts +1 -1
  54. package/lib/{ram/model/RamSequenceModel.cjs → model/SequenceModel.cjs} +14 -13
  55. package/lib/{esm/ram/model/RamSequenceModel.d.ts → model/SequenceModel.d.ts} +3 -3
  56. package/lib/model/SequenceModel.js.map +1 -0
  57. package/lib/model/decorators.cjs +2 -2
  58. package/lib/model/decorators.d.ts +1 -1
  59. package/lib/model/decorators.js.map +1 -1
  60. package/lib/model/index.cjs +1 -0
  61. package/lib/model/index.d.ts +1 -0
  62. package/lib/model/index.js.map +1 -1
  63. package/lib/persistence/Adapter.cjs +9 -0
  64. package/lib/persistence/Adapter.d.ts +3 -2
  65. package/lib/persistence/Adapter.js.map +1 -1
  66. package/lib/persistence/Sequence.cjs +126 -0
  67. package/lib/persistence/Sequence.d.ts +33 -17
  68. package/lib/persistence/Sequence.js.map +1 -1
  69. package/lib/persistence/generators.cjs +36 -0
  70. package/lib/persistence/generators.d.ts +14 -0
  71. package/lib/persistence/generators.js.map +1 -0
  72. package/lib/persistence/index.cjs +1 -0
  73. package/lib/persistence/index.d.ts +1 -0
  74. package/lib/persistence/index.js.map +1 -1
  75. package/lib/ram/RamAdapter.cjs +0 -11
  76. package/lib/ram/RamAdapter.d.ts +1 -10
  77. package/lib/ram/RamAdapter.js.map +1 -1
  78. package/lib/ram/index.cjs +0 -2
  79. package/lib/ram/index.d.ts +0 -2
  80. package/lib/ram/index.js.map +1 -1
  81. package/lib/repository/Repository.cjs +3 -4
  82. package/lib/repository/Repository.d.ts +1 -1
  83. package/lib/repository/Repository.js.map +1 -1
  84. package/lib/repository/decorators.cjs +1 -1
  85. package/lib/repository/decorators.js.map +1 -1
  86. package/lib/repository/injectables.cjs +3 -1
  87. package/lib/repository/injectables.js.map +1 -1
  88. package/lib/utils/Services.cjs +151 -13
  89. package/lib/utils/Services.d.ts +47 -7
  90. package/lib/utils/Services.js.map +1 -1
  91. package/lib/utils/decorators.cjs +7 -3
  92. package/lib/utils/decorators.d.ts +2 -1
  93. package/lib/utils/decorators.js.map +1 -1
  94. package/package.json +1 -1
  95. package/lib/esm/ram/RamSequence.d.ts +0 -68
  96. package/lib/esm/ram/RamSequence.js +0 -141
  97. package/lib/esm/ram/RamSequence.js.map +0 -1
  98. package/lib/esm/ram/model/RamSequenceModel.js.map +0 -1
  99. package/lib/esm/ram/model/index.d.ts +0 -1
  100. package/lib/esm/ram/model/index.js +0 -2
  101. package/lib/esm/ram/model/index.js.map +0 -1
  102. package/lib/ram/RamSequence.cjs +0 -145
  103. package/lib/ram/RamSequence.d.ts +0 -68
  104. package/lib/ram/RamSequence.js.map +0 -1
  105. package/lib/ram/model/RamSequenceModel.js.map +0 -1
  106. package/lib/ram/model/index.cjs +0 -18
  107. package/lib/ram/model/index.d.ts +0 -1
  108. package/lib/ram/model/index.js.map +0 -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{InternalError as a,Context as o,DefaultRepositoryFlags as c,OperationKeys as l,Repository as h,wrapMethodWithContext as u,enforceDBDecorators as d,ValidationError as p,reduceErrorsToPrint as g,DefaultSeparator as f,BulkCrudOperationKeys as y,DBKeys as w,NotFoundError as b,BadRequestError as m,ConflictError as v,onCreateUpdate as A,timestamp as O,onCreate as E,onUpdate as x,onDelete as N,afterAny as T,readonly as _,BaseError as R}from"@decaf-ts/db-decorators";import{Model as $,hashObj as C,required as D,sf as P,ModelKeys as I,ValidationKeys as B,async as j,type as L,list as k,model as F}from"@decaf-ts/decorator-validation";import{LoggedClass as M,Logging as U,final as G,isClass as H}from"@decaf-ts/logging";import{Decoration as q,DefaultFlavour as z,Metadata as Y,DecorationKeys as V,uses as Q,metadata as W,propMetadata as X,apply as J,prop as Z}from"@decaf-ts/decoration";import{Lock as K}from"@decaf-ts/transactional-decorators";var tt;(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"})(tt||(tt={}));class et{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new a("Observer already registered");this.observers.push({observer:t,filter:e})}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new a("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=ot.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 rt extends a{constructor(t){super(t,rt.name,500)}}class st extends a{constructor(t,e=st.name){super(t,e,500)}}class it extends st{constructor(t){super(t,it.name)}}class nt extends M{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return nt.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new a("No context provided");const r=t.pop();if(!(r instanceof o))throw new a("No context provided");if(t.filter(t=>t instanceof o).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 at=q.flavourResolver.bind(q);q.flavourResolver=t=>{try{const e=at(t);if(e&&e!==z)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof Y.registeredFlavour?Y.registeredFlavour(r):void 0;if(s&&s!==z)return s;const i=ot._currentFlavour;if(i){const t=ot._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return z}};class ot extends nt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!ot._baseRepository)throw new a("This should be overridden when necessary. Otherwise it will be replaced lazily");return ot._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new a("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.Context=o,this.alias in ot._cache)throw new a(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);ot._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),ot._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),ot._currentFlavour=this.alias)}Dispatch(){return new ot._baseDispatch}ObserverHandler(){return new et}isReserved(t){return!t}async initialize(...t){}async flags(t,e,r,...s){let i=r.logger||U.for(this.toString());return r.correlationId&&(i=i.for({correlationId:r.correlationId})),Object.assign({},c,r,{affectedTables:(Array.isArray(e)?e:[e]).map($.tableName),writeOperation:t!==l.READ,timestamp:new Date,operation:t,ignoredValidationProperties:Array.isArray(e)?[]:Y.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=$.columnName(t.constructor,r);if(this.isReserved(i))throw new a(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[tt.METADATA]&&(r.silly("Passing along persistence metadata for "+t[tt.METADATA]),Object.defineProperty(i,tt.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[tt.METADATA]})),{record:i,id:t[$.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),c={},l=$.pk(e);c[l]=r;const h=new e(c);n.silly(`Rebuilding model ${h.constructor.name} id ${r}`);const u=t[tt.METADATA],d=Object.keys(h).reduce((r,s)=>(s===l||(r[s]=t[$.columnName(e,s)]),r),h);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in d)throw new a(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);d[t]=e})),u&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${u}`),Object.defineProperty(d,tt.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),d}async createAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),o=$.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Promise.all(e.map((e,s)=>this.create(t,e,r[s],...n)))}async readAll(t,e,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=$.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Promise.all(e.map(e=>this.read(t,e,...i)))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),o=$.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Promise.all(e.map((e,s)=>this.update(t,e,r[s],...n)))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=ot.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map(e=>this.delete(t,e,...i)))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);r.verbose("Registering new observer "+t.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=ot.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 Y.flavourOf(t)}static get currentFlavour(){if(!ot._currentFlavour)throw new a("No persistence flavour set. Please initialize your adapter");return ot._currentFlavour}static get current(){return ot.get(this.currentFlavour)}static get(t){if(!t)return ot.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new a(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return Y.flavouredAs(t)}catch(t){throw new a(t)}}static decoration(){}static logCtx(t,e){return super.logCtx(t,e)}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${C(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 Y.migrationsFor(this)}async getQueryRunner(){return this}async migrate(t=this.migrations(),...e){t instanceof o&&(e=[t],t=this.migrations());const{ctx:r}=ot.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 st(t)}}}var ct,lt;i([G(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],ot.prototype,"shutdownProxies",null),i([G(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],ot.prototype,"context",null),i([G(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],ot.prototype,"observe",null),i([G(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ot.prototype,"unObserve",null),i([G(),n("design:type",Object),n("design:paramtypes",[])],ot.prototype,"client",null),(t=>{t.ASC="asc",t.DSC="desc"})(ct||(ct={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(lt||(lt={}));const ht={update:lt.CASCADE,delete:lt.NONE};class ut extends nt{constructor(t,e){super(),this.options=t,this.adapter=e}parse(t){return ut.parseValue(this.options.type,t)}static pk(t){return $.sequenceName(t,"pk")}static parseValue(t,e){switch(t){case"Number":return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case"BigInt":return BigInt(e);case void 0:case"String":return e;default:throw new rt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}var dt,pt;(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"})(dt||(dt={})),(t=>{t.AND="AND",t.OR="OR"})(pt||(pt={}));class gt extends a{constructor(t){super(t,gt.name,500)}}class ft extends a{constructor(t){super(t,ft.name,500)}}class yt extends ${constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,this.attr1=t,this.operator=e,this.comparison=r}and(t){return yt.and(this,t)}or(t){return yt.or(this,t)}not(t){return new yt(this,dt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof yt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(dt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof yt){if(!(this.comparison instanceof yt)&&this.operator!==dt.NOT)return{comparison:{condition:t}};if(-1===Object.values(pt).indexOf(this.operator)&&this.operator!==dt.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 yt.group(t,pt.AND,e)}static or(t,e){return yt.group(t,pt.OR,e)}static group(t,e,r){return new yt(t,e,r)}static attribute(t){return(new yt.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(dt.EQUAL,t)}dif(t){return this.setOp(dt.DIFFERENT,t)}gt(t){return this.setOp(dt.BIGGER,t)}lt(t){return this.setOp(dt.SMALLER,t)}gte(t){return this.setOp(dt.BIGGER_EQ,t)}lte(t){return this.setOp(dt.SMALLER_EQ,t)}in(t){return this.setOp(dt.IN,t)}regexp(t){return this.setOp(dt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new yt(this.attr1,this.operator,this.comparison)}catch(t){throw new gt(t)}}}}static builder(){return new yt.Builder}}i([D(),n("design:type",Object)],yt.prototype,"attr1",void 0),i([D(),n("design:type",String)],yt.prototype,"operator",void 0),i([D(),n("design:type",Object)],yt.prototype,"comparison",void 0);class wt extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=$.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],t&&(this._adapter=t),e&&(wt.register(e,this,this.adapter.alias),t)&&Y.get(e,V.FLAVOUR)===z&&Q(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach(t=>{const e=t.name;u(this,this[e+"Prefix"],t,this[e+"Suffix"])})}logCtx(t,e){return ot.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 et}async createPrefix(t,...e){const r=await o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation");if(t=new this.class(t),s&&await d(this,r.context,t,l.CREATE,l.ON),i){const e=await Promise.resolve(t.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${$.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 ${$.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 o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const n=$.sequenceFor(t[0]);let c=[];if(n.type?(n.name||(n.name=ut.pk(t[0])),c=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):c=t.map((t,e)=>{if(void 0===t[this.pk])throw new a("Primary key is not defined for model in position "+e);return t[this.pk]}),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),n.type&&(t[this.pk]="String"!==n.type||n.generated?c[e]:""+t[this.pk]),s&&await d(this,r.context,t,l.CREATE,l.ON),t))),i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async readPrefix(t,...e){const r=await o.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await d(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${$.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 o.args(l.READ,this.class,e,this.adapter,this._overrides||{});return await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,d(this,r.context,e,l.READ,l.ON)})),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${$.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 ${$.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 o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation"),n=t[this.pk];if(!n)throw new a("No value for the Id is defined under the property "+this.pk);const c=await this.read(n,...r.args);if(t=$.merge(c,t,this.class),s&&await d(this,r.context,t,l.UPDATE,l.ON,c),i){const e=await Promise.resolve(t.hasErrors(c,...$.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${$.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 o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation"),n=t.map(t=>{const e=t[this.pk];if(!e)throw new a("missing id on update operation");return e}),c=await this.readAll(n,...r.args);if(t=t.map((t,e)=>$.merge(c[e],t,this.class)),s&&await Promise.all(t.map((t,e)=>d(this,r.context,t,l.UPDATE,l.ON,c[e]))),i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(c[r],t,...e)))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async deletePrefix(t,...e){const r=await o.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await d(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${$.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 o.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.readAll(t,...r.args);return await Promise.all(s.map(async t=>d(this,r.context,t,l.DELETE,l.ON))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${$.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement().select(t).from(this.class)}async query(t,e,r=ct.ASC,s,i){const n=[e,r],a=this.select().where(t).orderBy(n);return s&&a.limit(s),i&&a.offset(i),a.execute()}attr(t){return yt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=$.tableName(this.class);this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:Y.constr(t)===Y.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString())}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>ut.parseValue($.sequenceFor(this.class).type,t)):ut.parseValue($.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||Y.flavourOf(t)||ot.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof wt)return s;const n=e||Y.flavourOf(t)||s&&Y.get(s,tt.ADAPTER)||ot.currentFlavour,o=n?ot.get(n):void 0;if(!o)throw new a("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=$.tableName(t);let s=r;if(e&&(s=[r,e].join(f)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a("Could not find repository registered under "+r)}static register(t,e,r){let s=$.tableName(t);if(r&&(s=[s,r].join(f)),s in this._cache&&this._cache[s]instanceof wt)throw new a(s+" already has a registered instance");this._cache[s]=e}}function bt(t,e){if(!(e||(e=q.flavourResolver(t instanceof $?t.constructor:t))&&e!==z))throw new a("Could not retrieve flavour from model "+(t instanceof $?t.constructor.name:t.name));return P(tt.INJECTABLE,e,$.tableName(t))}i([G(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],wt.prototype,"observe",null),i([G(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],wt.prototype,"unObserve",null),ot&&(ot._baseRepository=wt);class mt extends t{get log(){return this.logger||(this.logger=U.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=t:"symbol"!=typeof t&&"string"!=typeof t||(n=$.get(t.toString())),!n)return;const a=tt.ADAPTER,o=r||Y.get(n,a);try{let t=o;try{o&&ot.get(o)}catch{const e=ot.current;e&&e.flavour===o&&(t=e.alias)}if(i=wt.forModel(n,t),i instanceof wt)return i;const r=o||Y.get(i.constructor,a)||Y.get(n,a);e.register(i,bt(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=wt.get(n,o);if("function"==typeof e){const t=o?ot.get(o):ot.current;if(!t)return;return new e(t,n)}}}return i}}class vt extends nt{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,y.CREATE_ALL,y.UPDATE_ALL,y.DELETE_ALL].forEach(e=>{if(!t[e])throw new a(`Method ${e} not found in ${t.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(t,e),s=t;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,e);r&&r.writable?t[e]=new Proxy(t[e],{apply:async(t,r,s)=>{const{log:i,ctxArgs:n}=r.logCtx(s,t),[a,o]=s,c=await t.apply(r,n);return this.updateObservers(a,(t=>{switch(t){case y.CREATE_ALL:return l.CREATE;case y.UPDATE_ALL:return l.UPDATE;case y.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 ot))throw new rt("Only Adapters can be observed by dispatch");this.adapter=t,this.models=ot.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 rt("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:$.tableName(t),{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`Dispatching ${e} from table ${i} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new a("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}function At(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 it)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}ot&&(ot._baseDispatch=vt);class Ot extends M{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach(t=>{const e=t.name;At(this,t,this.prefix(e))})}get adapter(){const t=Y.get(this.constructor,tt.MIGRATION);if(!t)throw new a("No migration metadata for "+this.constructor.name);const e=t.flavour;return ot.get(e)}async enforceRules(t,e,r){const s=Y.get(this.constructor,tt.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 ot?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await o.args("migration",$,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new it("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function Et(t,e){return q.for(tt.MIGRATION).define({decorator:(t,e)=>r=>{const s=Y.innerGet(Symbol.for(tt.MIGRATION),t)||[];return Y.set(tt.MIGRATION,t,[...s,{class:r}]),W(tt.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}function xt(t,e){return(i,n)=>n?r(t[I.ANCHOR]||t)(i,n):(Y.set(w.REPOSITORY,Y.key(e||ot.currentFlavour,$.tableName(t)),i),W(w.REPOSITORY,i.name)(t),e=e||Y.get(i.constructor,tt.ADAPTER),wt.register(Y.constr(t),i,e),s(Y.constr(t),{callback:e=>(Object.defineProperty(e,w.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}Y.validationExceptions=((t,e)=>{const r=Y.get(t,tt.NO_VALIDATE);return r?Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t):[]}).bind(Y),$.shouldValidateNestedHandler=((t,e)=>{const r=Y.get(t.constructor);if(!r)return!1;const s=r[tt.RELATIONS],i=r[tt.RELATION];if(Array.isArray(s)&&s?.includes(e)){const r=Object.keys(i)[0],s=$.isPropertyModel(t,e);return i[r]?.class!==s}return!0}).bind($),Y.migrationsFor=(t=>{if(!(t=t??ot.current))throw new a("Could not get adapter for migrations");return Y.innerGet(Symbol.for(tt.MIGRATION),t.alias).map(t=>t.class)}).bind(Y),Y.relations=((t,e)=>{const r=Y.get(t,tt.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new a("No relations metadata found for property "+e);return r[e]}}).bind(Y),$.relations=(t,e)=>Y.relations(t instanceof $?t.constructor:t,e)||[],$.tableName=t=>{if(!(t instanceof $?$.get(t.constructor.name):t))throw new a("Unable to find model "+t);return Y.get(t instanceof $?t.constructor:t,tt.TABLE)||(t instanceof $?t.constructor.name:t.name)},$.columnName=(t,e)=>Y.get(t instanceof $?t.constructor:t,Y.key(tt.COLUMN,e))||e,$.sequenceName=(t,...e)=>[$.tableName(t),...e].join("_"),$.sequenceFor=(t,e)=>{if(e)throw new rt("not currently supported");const r=$.pkProps(t instanceof $?t.constructor:t);if(!r)throw new a("No sequence options defined for model. did you use the @pk decorator?");return r},$.indexes=t=>{const e=Y.get(t instanceof $?t.constructor:t,tt.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[tt.INDEX]:e[r]},t),{})},e.services=()=>Y.innerGet(Symbol.for(tt.SERVICE)),e.repositories=()=>Y.innerGet(Symbol.for(w.REPOSITORY));class Nt extends a{constructor(t){super(t,Nt.name,500)}}const Tt={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},_t=Tt,St={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Rt=Object.assign({},St,{type:"BigInt"});async function $t(t,e,r,s){if(!s){const e=$.get(t.constructor.name);if(!e)throw new a("Could not find model "+t.constructor.name);s=wt.forModel(e,r)}if(void 0===t[$.pk(s.class)])return s.create(t,e);try{return s.update(t,e)}catch(r){if(!(r instanceof b))throw r;return s.create(t,e)}}async function Ct(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 kt(t,s,r,i,n),void(s[r]=i)}const n=H(e.class)?e.class:e.class();if(!n)throw new a("Could not find model "+e.class);const o=wt.forModel(n,this.adapter.alias),c=await o.create(i),l=$.pk(c);await kt(t,s,r,c[l],c),s[r]=c[l]}async function Dt(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==lt.CASCADE)return;if("object"!=typeof i){const e=Ut(s,r,this.adapter.alias),n=await e.read(i);return await kt(t,s,r,i,n),void(s[r]=i)}const n=await $t(s[r],t,this.adapter.alias),a=$.pk(n);await kt(t,s,r,n[a],n),s[r]=n[a]}async function Pt(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==lt.CASCADE)return;const n=Ut(s,r,this.adapter.alias);let a;a=i instanceof $?await n.delete(s[r][n.pk]):await n.delete(s[r]),await kt(t,s,r,a[n.pk],a)}async function It(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o=new Set([...i]);if("object"!==n){const e=Ut(s,r,this.adapter.alias);for(const i of o){const n=await e.read(i);await kt(t,s,r,i,n)}return void(s[r]=[...o])}const c=$.pk(i[0]),l=new Set;for(const e of i){const i=await $t(e,t,this.adapter.alias);await kt(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function Bt(t,e,r,s){const{cascade:i}=e;if(i.update===lt.CASCADE)return It.call(this,t,e,r,s)}async function jt(t,e,r,s){if(e.cascade.delete!==lt.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o="object"===n,c=o?wt.forModel(i[0],this.adapter.alias):Ut(s,r,this.adapter.alias),l=new Set([...o?i.map(t=>t[c.pk]):i]);for(const e of l.values()){const i=await c.delete(e);await kt(t,s,r,e,i)}s[r]=[...l]}function Lt(t,e,r){return[tt.POPULATE,t,e,r].join(".")}async function kt(t,e,r,s,i){const n=Lt(e.constructor.name,r,s);return t.accumulate({[n]:i})}async function Ft(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,e,r,s,i)=>{let n,o;const c=[];for(const l of s){n=Lt(e.constructor.name,r,l);try{o=await t.get(n)}catch(t){const s=Ut(e,r,i);if(!s)throw new a("Could not find repo");o=await s.read(l)}c.push(o)}return c})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?o:o[0]}const Mt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Ut(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=Y.get(t instanceof $?t.constructor:t,Y.key(B.REFLECT,e,B.LIST))?.clazz;if(!r)throw new a("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map(t=>"function"!=typeof t||t.name?t:t())}else s=Y.getPropDesignTypes(t instanceof $?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Mt.includes((""+t.name).toLowerCase()));return wt.forModel(i,r)}class Gt extends m{constructor(t,e=Gt.name,r=401){super(t,e,r)}}class Ht extends Gt{constructor(t,e=Ht.name){super(t,e,403)}}class qt extends a{constructor(t){super(t,qt.name,503)}}class zt extends nt{constructor(t){super(),this.name=t}static get(t){if(!t)throw new a("No name provided");const r=e.get(t);if(r)return r;throw new a("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(){const t=U.for(this.boot),r=e.services();for(const[e,s]of Object.entries(r))try{const t=new s.data;t instanceof Yt&&await t.boot()}catch(r){t.error(`Failed to boot ${e} service`,r)}}}class Yt extends zt{constructor(){super()}async boot(){const{config:t,client:e}=await this.initialize();this._config=t,this._client=e}get config(){if(!this._config)throw new a("Config not initialized");return this._config}get client(){if(!this._client)throw new a("Client not initialized");return this._client}async shutdown(){}}function Vt(t){return q.for(tt.TABLE).define({decorator:t=>e=>W(tt.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Qt(t){return q.for(tt.COLUMN).define({decorator:t=>(e,r)=>X(Y.key(tt.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Wt(t,e,r){return q.for(tt.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=>![ct.ASC,ct.DSC].includes(t))&&(e=t,t=void 0),X(Y.key(`${tt.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Xt(t,e,r,s){if(s[r]&&(await this.select().where(yt.attribute(r).eq(s[r])).execute()).length)throw new v(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Jt(){const t=tt.UNIQUE;return q.for(t).define(j(),A(Xt),X(t,{})).apply()}async function Zt(t,e,r,s){throw new Gt("This adapter does not support user identification")}function Kt(){const t=tt.CREATED_BY;return q.for(t).define({decorator:()=>J(E(Zt),X(t,{})),args:[]}).apply()}function te(){const t=tt.UPDATED_BY;return q.for(t).define({decorator:()=>J(x(Zt),X(t,{})),args:[]}).apply()}function ee(){return O([l.CREATE])}function re(){return O()}function se(t,e=ht,r=!0,s,i){const n=tt.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),J(Z(),ue(n,a),L([t,String,Number,BigInt]),E(Ct,a),x(Dt,a),N(Pt,a),T(Ft,a))},args:[t,e,r,s,i]}).apply()}function ie(t,e=ht,r=!0,s,i){const n=tt.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),J(Z(),ue(n,a),k([t,String,Number,BigInt]),E(It,a),x(Bt,a),N(jt,a),T(Ft,a))},args:[t,e,r,s,i]}).apply()}function ne(t,e=ht,r=!0,s,i){const n=tt.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),J(Z(),ue(n,a),L([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function ae(t,e=ht,r=!0,s,i){const n=tt.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),J(Z(),ue(n,a),k([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function oe(...t){return(e,r)=>{const s=Y.get(e,Y.key(tt.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return J(W(Y.key(tt.NO_VALIDATE,r),i))(e,r)}}function ce(){return oe(l.CREATE)}function le(){return oe(l.UPDATE)}function he(){return oe(l.UPDATE,l.CREATE)}function ue(t,e){return q.for(tt.RELATIONS).define({decorator:(t,e)=>(r,s)=>(X(t,e)(r,s),X(Y.key(tt.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}async function de(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=$.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e)}catch(t){throw new a(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,o,c;n=s,o=r,c=await i.next(t),Reflect.set(n,o,c)}function pe(t=_t){t=Object.assign({},_t,t,{generated:!(!t.type||void 0!==t.generated)||t.generated||_t.generated});const e=w.ID;return q.for(e).define({decorator:(t,e)=>(r,s)=>J(Wt([ct.ASC,ct.DSC]),D(),_(),X(Y.key(w.ID,s),t),E(de,t,e))(r,s),args:[t,{priority:60}]}).apply()}i([G(),n("design:type",Function),n("design:paramtypes",[]),n("design:returntype",Promise)],Yt.prototype,"boot",null),i([G(),n("design:type",Object),n("design:paramtypes",[])],Yt.prototype,"config",null),i([G(),n("design:type",Object),n("design:paramtypes",[])],Yt.prototype,"client",null);class ge extends ${constructor(t){super(t)}}i([ee(),n("design:type",Date)],ge.prototype,"createdAt",void 0),i([re(),n("design:type",Date)],ge.prototype,"updatedAt",void 0);class fe extends M{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new ft("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new ft(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}}var ye,we,be,me,ve;class Ae extends nt{constructor(t){super(),this.adapter=t}get log(){return this.adapter.log.for(Ae)}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?$.get(t):t,!this.fromSelector)throw new gt("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){let e=t;if((!e.length||!(e[e.length-1]instanceof o))&&this.fromSelector){const t=await this.adapter.context(l.READ,{},this.fromSelector);e=[...e,t]}const{ctx:r}=ot.logCtx(e,this.toString());try{const t=this.build();return await this.raw(t,r)}catch(t){throw new a(t)}}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw),i=await this.adapter.raw(t,...s);if(!this.selectSelector)return i;const n=$.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)}toString(){return this.adapter.flavour+" statement"}}i([G(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ae.prototype,"select",null),i([G(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ye="undefined"!=typeof S&&S)?ye:Object]),n("design:returntype",Object)],Ae.prototype,"distinct",null),i([G(),n("design:type",Function),n("design:paramtypes",["function"==typeof(we="undefined"!=typeof S&&S)?we:Object]),n("design:returntype",Object)],Ae.prototype,"max",null),i([G(),n("design:type",Function),n("design:paramtypes",["function"==typeof(be="undefined"!=typeof S&&S)?be:Object]),n("design:returntype",Object)],Ae.prototype,"min",null),i([G(),n("design:type",Function),n("design:paramtypes",["function"==typeof(me="undefined"!=typeof S&&S)?me:Object]),n("design:returntype",Object)],Ae.prototype,"count",null),i([G(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ae.prototype,"from",null),i([G(),n("design:type",Function),n("design:paramtypes",[yt]),n("design:returntype",Object)],Ae.prototype,"where",null),i([G(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ae.prototype,"orderBy",null),i([G(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ae.prototype,"groupBy",null),i([G(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ae.prototype,"limit",null),i([G(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ae.prototype,"offset",null),i([G(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Ae.prototype,"execute",null),(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"})(ve||(ve={}));const Oe={Equals:(t,e)=>yt.attribute(t).eq(e),Diff:(t,e)=>yt.attribute(t).dif(e),LessThan:(t,e)=>yt.attribute(t).lt(e),LessThanEqual:(t,e)=>yt.attribute(t).lte(e),GreaterThan:(t,e)=>yt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>yt.attribute(t).gte(e),Between:(t,e,r)=>yt.attribute(t).gte(e).and(yt.attribute(t).lte(r)),In:(t,e)=>yt.attribute(t).in(e),Matches:(t,e)=>yt.attribute(t).regexp(e)},Ee=t=>t.charAt(0).toLowerCase()+t.slice(1);class xe{static build(t,...e){if(!t.startsWith(ve.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(ve.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static extractSelect(t){const e=t.indexOf(ve.SELECT);if(-1===e)return;const r=t.substring(e+ve.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(ve.AND).map(Ee).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(ve.GROUP_BY);if(-1!==e)return t.substring(e+ve.GROUP_BY.length).split(ve.ORDER_BY)[0].split(ve.THEN_BY).map(Ee).filter(Boolean)}static buildWhere(t,e){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?Oe[a]:Oe.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]===ve.AND?i.and(l):i.or(l)}),!i)throw Error("No conditions found in method name");return i}static parseFieldAndOperator(t){for(const e of Object.keys(Oe))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:Ee(r),operator:e}}return{field:Ee(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 Ne(t={}){return(e,r,s)=>{const i=r.toString();s.value=function(...e){const{select:r,where:s,groupBy:n,orderBy:a,limit:o,offset:c}=xe.build(i,...e);let l=this.select(r);s&&(l=l.where(s));const{allowLimit:h,allowOffset:u,allowOrderBy:d,throws:p}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},g=[{key:"orderBy",value:(a||[])[0],allowed:d},{key:"limit",value:o,allowed:h},{key:"offset",value:c,allowed:u}];for(const t of g)if(void 0!==t.value){if(!t.allowed&&p)throw new gt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(l=l[t.key](t.value))}return l.execute()}}}class Te extends fe{constructor(t,e,r,s){super(t,e,r,s)}prepare(t){const e=Object.assign({},t);return e.limit=this.size,e}async page(t=1,...e){const r=await o.args(l.READ,this.clazz,e,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=t.length,this._recordCount>0){const t=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const i=await this.adapter.raw(s,await this.adapter.context(l.READ,{},this.clazz));return this._currentPage=t,i}}class _e extends Ae{constructor(t){super(t)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new a("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=Y.getPropDesignTypes(t.constructor,s);if(!n)throw new gt("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 gt("Sorting not supported for not date classes");default:throw new gt("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}async paginate(t){try{const e=this.build();return new Te(this.adapter,e,t,this.fromSelector)}catch(t){throw new a(t)}}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:i}=t;if(-1===[pt.AND,pt.OR,dt.NOT].indexOf(s))switch(s){case dt.BIGGER:return e[r]>i;case dt.BIGGER_EQ:return e[r]>=i;case dt.DIFFERENT:return e[r]!==i;case dt.EQUAL:return e[r]===i;case dt.REGEXP:if("string"!=typeof e[r])throw new gt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(i,"g"));case dt.SMALLER:return e[r]<i;case dt.SMALLER_EQ:return e[r]<=i;default:throw new a("Invalid operator for standard comparisons: "+s)}else{if(s===dt.NOT)throw new a("Not implemented");{const t=this.parseCondition(r),n=this.parseCondition(i);switch(s){case pt.AND:return t.where(e)&&n.where(e);case pt.OR:return t.where(e)||n.where(e);default:throw new a("Invalid operator for And/Or comparisons: "+s)}}}}}}}let Se=class extends ge{constructor(t){super(t)}};i([pe(),n("design:type",String)],Se.prototype,"id",void 0),i([D(),Wt(),n("design:type",Object)],Se.prototype,"current",void 0),Se=i([Vt("__RamSequence"),F(),n("design:paramtypes",[Object])],Se);class Re extends ut{constructor(t,e){super(t,e),this.repo=wt.forModel(Se,e.alias)}async current(...t){const e=(await o.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 b){if(void 0===s)throw new a("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new a(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new a(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let o;const c=e||i;if(c%i!==0)throw new a("Value to increment does not consider the incrementBy setting: "+i);switch(s){case"Number":o=this.parse(t)+c;break;case"BigInt":o=this.parse(t)+BigInt(c);break;case"String":o=this.parse(t);break;default:throw new a("Should never happen")}let l;const h=this.repo.override({ignoredValidationProperties:["updatedAt"]});try{l=await h.update(new Se({id:n,current:o}),r)}catch(t){if(!(t instanceof b))throw t;l=await h.create(new Se({id:n,current:o}),r)}return l.current}async next(...t){const e=await o.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 o.args(l.UPDATE,Se,e,this.adapter),{context:s,args:i}=r,n=await this.current(...i),c=this.parse(this.options.incrementBy),h=await this.increment(n,this.parse(t)*c,s),u=[];for(let e=1;t>=e;e++)u.push(n+c*this.parse(e));if(u[u.length-1]!==h&&"String"!==this.options.type)throw new a("Miscalculation of range");return u}}async function $e(t,e,r,s){const i=t.get("UUID");if(!i)throw new rt("This adapter does not support user identification");s[r]=i}const Ce="ram";class De extends ot{constructor(t={},e){super(t,Ce,e),this.Context=o,this.indexes={},this.lock=new K}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[$.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=$.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 v(`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=$.tableName(t);if(!this.client.has(s))throw new b(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new b(`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=$.tableName(t);if(i.debug(`updating record in table ${n} with id ${e}`),await this.lock.acquire(),!this.client.has(n))throw new b(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new b(`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=$.tableName(t);if(s.debug(`deleting record from table ${i} with pk ${e}`),await this.lock.acquire(),!this.client.has(i))throw new b(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new b(`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=$.get(t));const e=$.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e){e.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:r,sort:s,limit:i,skip:n,from:o}=t;let{select:c}=t;const l=this.tableFor(o);if(!l)throw new a(`Table ${o} not found in RamAdapter`);const h=$.pk(o),u=Y.get(o,Y.key(w.ID,h));let d=Array.from(l.entries()).map(([t,r])=>this.revert(r,o,ut.parseValue(u.type,t),void 0,e));return d=r?d.filter(r):d,s&&(d=d.sort(s)),n&&(d=d.slice(n)),i&&(d=d.slice(0,i)),c&&(c=Array.isArray(c)?c:[c],d=d.map(t=>Object.entries(t).reduce((t,[e,r])=>(c.includes(e)&&(t[e]=r),t),{}))),d}parseError(t){return t instanceof R?t:new a(t)}Statement(){return new _e(this)}async Sequence(t){return new Re(t,this)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${C(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=tt.CREATED_BY,e=tt.UPDATED_BY;q.flavouredAs(Ce).for(t).define(E($e),X(t,{})).apply(),q.flavouredAs(Ce).for(e).define(A($e),X(e,{})).apply()}getClient(){return new Map}}De.decoration(),e.setRegistry(new mt);const Pe="##VERSION##",Ie="##PACKAGE##";Y.registerLibrary(Ie,Pe);export{Ot as AbsMigration,ot as Adapter,Gt as AuthorizationError,ge as BaseModel,Rt as BigIntSequence,lt as Cascade,Yt as ClientBasedService,yt as Condition,qt as ConnectionError,nt as ContextualLoggedClass,ht as DefaultCascade,_t as DefaultSequenceOptions,vt as Dispatch,Ht as ForbiddenError,pt as GroupOperator,mt as InjectablesRegistry,xe as MethodQueryBuilder,st as MigrationError,it as MigrationRuleError,Tt as NoneSequenceOptions,St as NumericSequence,Nt as ObserverError,et as ObserverHandler,dt as Operator,Oe as OperatorsMap,ct as OrderDirection,Ie as PACKAGE_NAME,fe as Paginator,ft as PagingError,tt as PersistenceKeys,ve as QueryClause,gt as QueryError,De as RamAdapter,Ce as RamFlavour,Te as RamPaginator,Re as RamSequence,Se as RamSequenceModel,_e as RamStatement,wt as Repository,ut as Sequence,zt as Service,Ae as Statement,rt as UnsupportedError,Pe as VERSION,kt as cacheModelForPopulate,Qt as column,$t as createOrUpdate,ee as createdAt,Kt as createdBy,Zt as createdByOnCreateUpdate,$e as createdByOnRamCreateUpdate,bt as generateInjectableNameForRepository,Lt as getPopulateKey,Wt as index,ae as manyToMany,ne as manyToOne,Et as migration,oe as noValidateOn,ce as noValidateOnCreate,he as noValidateOnCreateUpdate,le as noValidateOnUpdate,ie as oneToMany,It as oneToManyOnCreate,jt as oneToManyOnDelete,Bt as oneToManyOnUpdate,se as oneToOne,Ct as oneToOneOnCreate,Pt as oneToOneOnDelete,Dt as oneToOneOnUpdate,pe as pk,de as pkOnCreate,Ft as populate,At as prefixMethod,Ne as query,ue as relation,xt as repository,Ut as repositoryFromTypeMetadata,Vt as table,Jt as unique,Xt as uniqueOnCreateUpdate,re as updatedAt,te 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{InternalError as a,Context as o,DefaultRepositoryFlags as c,OperationKeys as l,Repository as h,wrapMethodWithContext as u,enforceDBDecorators as d,ValidationError as p,reduceErrorsToPrint as g,DefaultSeparator as f,BulkCrudOperationKeys as y,NotFoundError as w,BadRequestError as b,ConflictError as m,onCreateUpdate as v,timestamp as x,onCreate as A,onUpdate as O,onDelete as E,afterAny as N,DBKeys as _,readonly as T,BaseError as C}from"@decaf-ts/db-decorators";import{Model as $,hashObj as R,required as D,sf as P,ValidationKeys as I,async as j,type as B,list as L,model as k}from"@decaf-ts/decorator-validation";import{LoggedClass as F,Logging as M,final as U,isClass as G}from"@decaf-ts/logging";import{Decoration as q,DefaultFlavour as z,Metadata as H,DecorationKeys as Y,uses as V,metadata as Q,propMetadata as W,apply as X,prop as J}from"@decaf-ts/decoration";import{Lock as Z}from"@decaf-ts/transactional-decorators";var K;(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"})(K||(K={}));class tt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map((t=>t.observer)).indexOf(t))throw new a("Observer already registered");this.observers.push({observer:t,filter:e})}unObserve(t){const e=this.observers.map((t=>t.observer)).indexOf(t);if(-1===e)throw new a("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=at.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 et extends a{constructor(t){super(t,et.name,500)}}class rt extends a{constructor(t,e=rt.name){super(t,e,500)}}class st extends rt{constructor(t){super(t,st.name)}}class it extends F{logFor(t,...e){return t.logger.for(this)}logCtx(t,e){return it.logCtx.call(this,t,e)}static logCtx(t,e){if(1>t.length)throw new a("No context provided");const r=t.pop();if(!(r instanceof o))throw new a("No context provided");if(t.filter((t=>t instanceof o)).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 nt=q.flavourResolver.bind(q);q.flavourResolver=t=>{try{const e=nt(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=at._currentFlavour;if(i){const t=at._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return z}};class at extends it{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!at._baseRepository)throw new a("This should be overridden when necessary. Otherwise it will be replaced lazily");return at._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new a("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.Context=o,this.alias in at._cache)throw new a(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);at._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),at._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),at._currentFlavour=this.alias)}Dispatch(){return new at._baseDispatch}ObserverHandler(){return new tt}isReserved(t){return!t}async initialize(...t){}async Sequence(t){return new at._baseSequence(t,this)}async flags(t,e,r,...s){let i=r.logger||M.for(this.toString());return r.correlationId&&(i=i.for({correlationId:r.correlationId})),Object.assign({},c,r,{affectedTables:(Array.isArray(e)?e:[e]).map($.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=$.columnName(t.constructor,r);if(this.isReserved(i))throw new a(`Property name ${i} is reserved`);return e[i]=s,e}),{});return t[K.METADATA]&&(r.silly("Passing along persistence metadata for "+t[K.METADATA]),Object.defineProperty(i,K.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[K.METADATA]})),{record:i,id:t[$.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),c={},l=$.pk(e);c[l]=r;const h=new e(c);n.silly(`Rebuilding model ${h.constructor.name} id ${r}`);const u=t[K.METADATA],d=Object.keys(h).reduce(((r,s)=>(s===l||(r[s]=t[$.columnName(e,s)]),r)),h);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach((([t,e])=>{if(t in d)throw new a(`Transient property ${t} already exists on model ${h.constructor.name}. should be impossible`);d[t]=e}))),u&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${h.constructor.name} id ${r}: ${u}`),Object.defineProperty(d,K.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:u})),d}async createAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll),o=$.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Promise.all(e.map(((e,s)=>this.create(t,e,r[s],...n))))}async readAll(t,e,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=$.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Promise.all(e.map((e=>this.read(t,e,...i))))}async updateAll(t,e,r,...s){if(e.length!==r.length)throw new a("Ids and models must have the same length");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll),o=$.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Promise.all(e.map(((e,s)=>this.update(t,e,r[s],...n))))}async deleteAll(t,e,...r){const{log:s,ctxArgs:i}=at.logCtx(r,this.deleteAll);return s.verbose(`Deleting ${e.length} entries from ${t} table`),Promise.all(e.map((e=>this.delete(t,e,...i))))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);r.verbose("Registering new observer "+t.toString()),this.dispatch||(r.info("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(t){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=at.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(!at._currentFlavour)throw new a("No persistence flavour set. Please initialize your adapter");return at._currentFlavour}static get current(){return at.get(this.currentFlavour)}static get(t){if(!t)return at.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new a(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return H.flavouredAs(t)}catch(t){throw new a(t)}}static decoration(){}static logCtx(t,e){return super.logCtx(t,e)}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${R(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 o&&(e=[t],t=this.migrations());const{ctx:r}=at.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 rt(t)}}}var ot,ct;i([U(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],at.prototype,"shutdownProxies",null),i([U(),n("design:type",Function),n("design:paramtypes",[String,Object,Object,Object]),n("design:returntype",Promise)],at.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],at.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],at.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],at.prototype,"client",null),(t=>{t.ASC="asc",t.DSC="desc"})(ot||(ot={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(ct||(ct={}));const lt={update:ct.CASCADE,delete:ct.NONE};var ht,ut;(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"})(ht||(ht={})),(t=>{t.AND="AND",t.OR="OR"})(ut||(ut={}));class dt extends a{constructor(t){super(t,dt.name,500)}}class pt extends a{constructor(t){super(t,pt.name,500)}}class gt extends ${constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,this.attr1=t,this.operator=e,this.comparison=r}and(t){return gt.and(this,t)}or(t){return gt.or(this,t)}not(t){return new gt(this,ht.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof gt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ht).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof gt){if(!(this.comparison instanceof gt)&&this.operator!==ht.NOT)return{comparison:{condition:t}};if(-1===Object.values(ut).indexOf(this.operator)&&this.operator!==ht.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 gt.group(t,ut.AND,e)}static or(t,e){return gt.group(t,ut.OR,e)}static group(t,e,r){return new gt(t,e,r)}static attribute(t){return(new gt.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(ht.EQUAL,t)}dif(t){return this.setOp(ht.DIFFERENT,t)}gt(t){return this.setOp(ht.BIGGER,t)}lt(t){return this.setOp(ht.SMALLER,t)}gte(t){return this.setOp(ht.BIGGER_EQ,t)}lte(t){return this.setOp(ht.SMALLER_EQ,t)}in(t){return this.setOp(ht.IN,t)}regexp(t){return this.setOp(ht.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new gt(this.attr1,this.operator,this.comparison)}catch(t){throw new dt(t)}}}}static builder(){return new gt.Builder}}i([D(),n("design:type",Object)],gt.prototype,"attr1",void 0),i([D(),n("design:type",String)],gt.prototype,"operator",void 0),i([D(),n("design:type",Object)],gt.prototype,"comparison",void 0);class ft extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=$.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}constructor(t,e,...r){super(e),this.observers=[],t&&(this._adapter=t),e&&(ft.register(e,this,this.adapter.alias),t)&&H.get(e,Y.FLAVOUR)===z&&V(t.flavour)(e),[this.createAll,this.readAll,this.updateAll,this.deleteAll].forEach((t=>{const e=t.name;u(this,this[e+"Prefix"],t,this[e+"Suffix"])}))}logCtx(t,e){return at.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 tt}async createPrefix(t,...e){const r=await o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation");if(t=new this.class(t),s&&await d(this,r.context,t,l.CREATE,l.ON),i){const e=await Promise.resolve(t.hasErrors(...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${$.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 ${$.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 o.args(l.CREATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation");if(!t.length)return[t,...r.args];const n=$.sequenceFor(t[0]);let c=[];if(n.type?(n.name||(n.name=$.sequenceName(t[0],"pk")),c=await(await this.adapter.Sequence(n)).range(t.length,...r.args)):c=t.map(((t,e)=>{if(void 0===t[this.pk])throw new a("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map((async(t,e)=>(t=new this.class(t),n.type&&(t[this.pk]="String"!==n.type||n.generated?c[e]:""+t[this.pk]),s&&await d(this,r.context,t,l.CREATE,l.ON),t)))),i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map((t=>Promise.resolve(t.hasErrors(...e))))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async readPrefix(t,...e){const r=await o.args(l.READ,this.class,e,this.adapter,this._overrides||{}),s=new this.class;return s[this.pk]=t,await d(this,r.context,s,l.READ,l.ON),[t,...r.args]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${$.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 o.args(l.READ,this.class,e,this.adapter,this._overrides||{});return await Promise.all(t.map((async t=>{const e=new this.class;return e[this.pk]=t,d(this,r.context,e,l.READ,l.ON)}))),[t,...r.args]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${$.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 ${$.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 o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation"),n=t[this.pk];if(!n)throw new a("No value for the Id is defined under the property "+this.pk);const c=await this.read(n,...r.args);if(t=$.merge(c,t,this.class),s&&await d(this,r.context,t,l.UPDATE,l.ON,c),i){const e=await Promise.resolve(t.hasErrors(c,...$.relations(this.class),...r.context.get("ignoredValidationProperties")||[]));if(e)throw new p(e.toString())}return[t,...r.args]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.debug(`Updating ${t.length} new ${this.class.name} in table ${$.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 o.args(l.UPDATE,this.class,e,this.adapter,this._overrides||{}),s=!1!==r.context.get("ignoreHandlers"),i=!r.context.get("ignoreValidation"),n=t.map((t=>{const e=t[this.pk];if(!e)throw new a("missing id on update operation");return e})),c=await this.readAll(n,...r.args);if(t=t.map(((t,e)=>$.merge(c[e],t,this.class))),s&&await Promise.all(t.map(((t,e)=>d(this,r.context,t,l.UPDATE,l.ON,c[e])))),i){const e=r.context.get("ignoredValidationProperties")||[],s=await Promise.all(t.map(((t,r)=>Promise.resolve(t.hasErrors(c[r],t,...e))))),i=g(s);if(i)throw new p(i)}return[t,...r.args]}async deletePrefix(t,...e){const r=await o.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.read(t,...r.args);return await d(this,r.context,s,l.DELETE,l.ON),[t,...r.args]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${$.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 o.args(l.DELETE,this.class,e,this.adapter,this._overrides||{}),s=await this.readAll(t,...r.args);return await Promise.all(s.map((async t=>d(this,r.context,t,l.DELETE,l.ON)))),[t,...r.args]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${$.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map(((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r)))}select(t){return this.adapter.Statement().select(t).from(this.class)}async query(t,e,r=ot.ASC,s,i){const n=[e,r],a=this.select().where(t).orderBy(n);return s&&a.limit(s),i&&a.offset(i),a.execute()}attr(t){return gt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=$.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 a("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new a("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map((t=>at._baseSequence.parseValue($.sequenceFor(this.class).type,t))):at._baseSequence.parseValue($.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)||at.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof ft)return s;const n=e||H.flavourOf(t)||s&&H.get(s,K.ADAPTER)||at.currentFlavour,o=n?at.get(n):void 0;if(!o)throw new a("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=$.tableName(t);let s=r;if(e&&(s=[r,e].join(f)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a("Could not find repository registered under "+r)}static register(t,e,r){let s=$.tableName(t);if(r&&(s=[s,r].join(f)),s in this._cache&&this._cache[s]instanceof ft)throw new a(s+" already has a registered instance");this._cache[s]=e}}function yt(t,e){if(!(e||(e=q.flavourResolver(t instanceof $?t.constructor:t))&&e!==z))throw new a("Could not retrieve flavour from model "+(t instanceof $?t.constructor.name:t.name));return P(K.INJECTABLE,e,$.tableName(t))}i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],ft.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ft.prototype,"unObserve",null),at&&(at._baseRepository=ft);class wt extends t{get log(){return this.logger||(this.logger=M.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=$.get(t.toString())||t:"symbol"!=typeof t&&"string"!=typeof t||(n=$.get(t.toString())),!n)return;const a=K.ADAPTER,o=r||H.get(n,a);try{let t=o;try{o&&at.get(o)}catch{const e=at.current;e&&e.flavour===o&&(t=e.alias)}if(i=ft.forModel(n,t),i instanceof ft)return i;const r=o||H.get(i.constructor,a)||H.get(n,a);e.register(i,yt(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=ft.get(n,o);if("function"==typeof e){const t=o?at.get(o):at.current;if(!t)return;return new e(t,n)}}}return i}}class bt extends it{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,y.CREATE_ALL,y.UPDATE_ALL,y.DELETE_ALL].forEach((e=>{if(!t[e])throw new a(`Method ${e} not found in ${t.alias} adapter to bind Observables Dispatch`);let r=Object.getOwnPropertyDescriptor(t,e),s=t;for(;!r&&s!==Object.prototype;)s=Object.getPrototypeOf(s),r=Object.getOwnPropertyDescriptor(s,e);r&&r.writable?t[e]=new Proxy(t[e],{apply:async(t,r,s)=>{const{log:i,ctxArgs:n}=r.logCtx(s,t),[a,o]=s,c=await t.apply(r,n);return this.updateObservers(a,(t=>{switch(t){case y.CREATE_ALL:return l.CREATE;case y.UPDATE_ALL:return l.UPDATE;case y.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 at))throw new et("Only Adapters can be observed by dispatch");this.adapter=t,this.models=at.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 et("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:$.tableName(t),{log:n,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`Dispatching ${e} from table ${i} for ${e} with id: ${JSON.stringify(r)}`),await this.adapter.refresh(t,e,r,...o)}catch(t){throw new a("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}}at&&(at._baseDispatch=bt);class mt{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 mt._instance||(mt._instance=new mt),mt._instance}}class vt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return vt._instance||(vt._instance=new vt),vt._instance}}function xt(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 st)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 At extends F{constructor(){super(),this.transaction=!0,[this.up,this.down].forEach((t=>{const e=t.name;xt(this,t,this.prefix(e))}))}get adapter(){const t=H.get(this.constructor,K.MIGRATION);if(!t)throw new a("No migration metadata for "+this.constructor.name);const e=t.flavour;return at.get(e)}async enforceRules(t,e,r){const s=H.get(this.constructor,K.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 at?r=this.getQueryRunner(e.client):(r=e,e=this.adapter);const s=await o.args("migration",$,[t],e);if(!await this.enforceRules(r,e,s.context))throw s.context.logger.verbose(`Skipping migration ${this.constructor.name} due to rules`),new st("Migration skipped for rule enforcement");return[r,e,s.context]}.bind(this)}}function Ot(t,e){return q.for(K.MIGRATION).define({decorator:(t,e)=>r=>{const s=H.innerGet(Symbol.for(K.MIGRATION),t)||[];return H.set(K.MIGRATION,t,[...s,{class:r}]),Q(K.MIGRATION,{flavour:t,rules:e})(r)},args:[t,e]}).apply()}async function Et(t,e,r,s){if(!s){const e=$.get(t.constructor.name);if(!e)throw new a("Could not find model "+t.constructor.name);s=ft.forModel(e,r)}if(void 0===t[$.pk(s.class)])return s.create(t,e);try{return s.update(t,e)}catch(r){if(!(r instanceof w))throw r;return s.create(t,e)}}async function Nt(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=jt(s,r,this.adapter.alias),n=await e.read(i);return await Dt(t,s,r,i,n),void(s[r]=i)}const n=G(e.class)?e.class:e.class();if(!n)throw new a("Could not find model "+e.class);const o=ft.forModel(n,this.adapter.alias),c=await o.create(i),l=$.pk(c);await Dt(t,s,r,c[l],c),s[r]=c[l]}async function St(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==ct.CASCADE)return;if("object"!=typeof i){const e=jt(s,r,this.adapter.alias),n=await e.read(i);return await Dt(t,s,r,i,n),void(s[r]=i)}const n=await Et(s[r],t,this.adapter.alias),a=$.pk(n);await Dt(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!==ct.CASCADE)return;const n=jt(s,r,this.adapter.alias);let a;a=i instanceof $?await n.delete(s[r][n.pk]):await n.delete(s[r]),await Dt(t,s,r,a[n.pk],a)}async function Tt(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o=new Set([...i]);if("object"!==n){const e=jt(s,r,this.adapter.alias);for(const i of o){const n=await e.read(i);await Dt(t,s,r,i,n)}return void(s[r]=[...o])}const c=$.pk(i[0]),l=new Set;for(const e of i){const i=await Et(e,t,this.adapter.alias);await Dt(t,s,r,i[c],i),l.add(i[c])}s[r]=[...l]}async function Ct(t,e,r,s){const{cascade:i}=e;if(i.update===ct.CASCADE)return Tt.call(this,t,e,r,s)}async function $t(t,e,r,s){if(e.cascade.delete!==ct.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every((t=>typeof t===n)))throw new a(`Invalid operation. All elements of property ${r} must match the same type.`);const o="object"===n,c=o?ft.forModel(i[0],this.adapter.alias):jt(s,r,this.adapter.alias),l=new Set([...o?i.map((t=>t[c.pk])):i]);for(const e of l.values()){const i=await c.delete(e);await Dt(t,s,r,e,i)}s[r]=[...l]}function Rt(t,e,r){return[K.POPULATE,t,e,r].join(".")}async function Dt(t,e,r,s,i){const n=Rt(e.constructor.name,r,s);return t.accumulate({[n]:i})}async function Pt(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,e,r,s,i)=>{let n,o;const c=[];for(const l of s){n=Rt(e.constructor.name,r,l);try{o=await t.get(n)}catch(t){const s=jt(e,r,i);if(!s)throw new a("Could not find repo");o=await s.read(l)}c.push(o)}return c})(t,s,r,n?i:[i],this.adapter.alias);s[r]=n?o:o[0]}const It=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function jt(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 $?t.constructor:t,H.key(I.REFLECT,e,I.LIST))?.clazz;if(!r)throw new a("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map((t=>"function"!=typeof t||t.name?t:t()))}else s=H.getPropDesignTypes(t instanceof $?t.constructor:t,e)?.designTypes;const i=s?.find((t=>!It.includes((""+t.name).toLowerCase())));return ft.forModel(i,r)}class Bt extends b{constructor(t,e=Bt.name,r=401){super(t,e,r)}}class Lt extends Bt{constructor(t,e=Lt.name){super(t,e,403)}}class kt extends a{constructor(t){super(t,kt.name,503)}}function Ft(t){return q.for(K.TABLE).define({decorator:t=>e=>Q(K.TABLE,t||e.name.toLowerCase())(e),args:[t]}).apply()}function Mt(t){return q.for(K.COLUMN).define({decorator:t=>(e,r)=>W(H.key(K.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Ut(t,e,r){return q.for(K.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=>![ot.ASC,ot.DSC].includes(t)))&&(e=t,t=void 0),W(H.key(`${K.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Gt(t,e,r,s){if(s[r]&&(await this.select().where(gt.attribute(r).eq(s[r])).execute()).length)throw new m(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function qt(){const t=K.UNIQUE;return q.for(t).define(j(),v(Gt),W(t,{})).apply()}async function zt(t,e,r,s){throw new Bt("This adapter does not support user identification")}function Ht(){const t=K.CREATED_BY;return q.for(t).define({decorator:()=>X(A(zt),W(t,{})),args:[]}).apply()}function Yt(){const t=K.UPDATED_BY;return q.for(t).define({decorator:()=>X(O(zt),W(t,{})),args:[]}).apply()}function Vt(){return x([l.CREATE])}function Qt(){return x()}function Wt(t,e=lt,r=!0,s,i){const n=K.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),X(J(),se(n,a),B([t,String,Number,BigInt]),A(Nt,a),O(St,a),E(_t,a),N(Pt,a))},args:[t,e,r,s,i]}).apply()}function Xt(t,e=lt,r=!0,s,i){const n=K.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),X(J(),se(n,a),L([t,String,Number,BigInt]),A(Tt,a),O(Ct,a),E($t,a),N(Pt,a))},args:[t,e,r,s,i]}).apply()}function Jt(t,e=lt,r=!0,s,i){const n=K.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),X(J(),se(n,a),B([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function Zt(t,e=lt,r=!0,s,i){const n=K.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),X(J(),se(n,a),L([t,String,Number,BigInt]))},args:[t,e,r,s,i]}).apply()}function Kt(...t){return(e,r)=>{const s=H.get(e,H.key(K.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return X(Q(H.key(K.NO_VALIDATE,r),i))(e,r)}}function te(){return Kt(l.CREATE)}function ee(){return Kt(l.UPDATE)}function re(){return Kt(l.UPDATE,l.CREATE)}function se(t,e){return q.for(K.RELATIONS).define({decorator:(t,e)=>(r,s)=>(W(t,e)(r,s),W(H.key(K.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class ie extends ${constructor(t){super(t)}}i([Vt(),n("design:type",Date)],ie.prototype,"createdAt",void 0),i([Qt(),n("design:type",Date)],ie.prototype,"updatedAt",void 0);const ne={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},ae=ne,oe={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},ce=Object.assign({},oe,{type:"BigInt"});async function le(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=$.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e)}catch(t){throw new a(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,o,c;n=s,o=r,c=await i.next(t),Reflect.set(n,o,c)}function he(t=ae){t=Object.assign({},ae,t,{generated:!(!t.type||void 0!==t.generated)||t.generated||ae.generated});const e=_.ID;return q.for(e).define({decorator:(t,e)=>(r,s)=>X(Ut([ot.ASC,ot.DSC]),D(),T(),W(H.key(_.ID,s),t),A(le,t,e))(r,s),args:[t,{priority:60}]}).apply()}let ue=class extends ie{constructor(t){super(t)}};i([he({type:"String",generated:!1}),n("design:type",String)],ue.prototype,"id",void 0),i([D(),Ut(),n("design:type",Object)],ue.prototype,"current",void 0),ue=i([Ft("??sequence"),k(),n("design:paramtypes",[Object])],ue);class de extends it{constructor(t,e){super(),this.options=t,this.adapter=e,this.repo=ft.forModel(ue,e.alias)}async current(...t){const e=(await o.args(l.READ,ue,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 w){if(void 0===s)throw new a("Starting value is not defined for a non existing sequence");try{return this.parse(s)}catch(t){throw new a(`Failed to parse initial value for sequence ${s}: ${t}`)}}throw new a(`Failed to retrieve current value for sequence ${r}: ${t}`)}}async increment(t,e,r){const{type:s,incrementBy:i,name:n}=this.options;let o;const c=e||i;if(c%i!=0)throw new a("Value to increment does not consider the incrementBy setting: "+i);switch(s){case"Number":o=this.parse(t)+c;break;case"BigInt":o=this.parse(t)+BigInt(c);break;case"String":o=this.parse(t);break;case"serial":o=vt.instance.generate(t);break;case"uuid":o=mt.instance.generate(t);break;default:throw new a("Should never happen")}let l;try{l=await this.repo.update(new ue({id:n,current:o}),r)}catch(i){if(!(i instanceof w))throw i;try{l=await this.repo.create(new ue({id:n,current:o}),r)}catch(i){if(!(i instanceof m)||"uuid"!==s)throw i;return this.increment(t,e,r)}}return l.current}async next(...t){const e=await o.args(l.UPDATE,ue,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 o.args(l.UPDATE,ue,e,this.adapter),{context:s,args:i}=r,n=await this.current(...i),c=this.parse(this.options.incrementBy),h=await this.increment(n,this.parse(t)*c,s),u=[];for(let e=1;t>=e;e++)u.push(n+c*this.parse(e));if(u[u.length-1]!==h&&"String"!==this.options.type)throw new a("Miscalculation of range");return u}parse(t){return de.parseValue(this.options.type,t)}static pk(t){return $.sequenceName(t,"pk")}static parseValue(t,e){switch(t){case"Number":return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case"BigInt":return BigInt(e);case void 0:case"String":case"uuid":case"serial":return e;default:throw new et(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function pe(t,e){return(i,n)=>n?r(H.constr(t))(i,n):(H.set(_.REPOSITORY,H.key(e||at.currentFlavour,$.tableName(t)),i),Q(_.REPOSITORY,i.name)(t),e=e||H.get(i.constructor,K.ADAPTER),ft.register(H.constr(t),i,e),s(H.constr(t),{callback:e=>(Object.defineProperty(e,_.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}at._baseSequence=de,H.validationExceptions=((t,e)=>{const r=H.get(t,K.NO_VALIDATE);return r?Object.entries(r).filter((([,t])=>t.includes(e))).map((([t])=>t)):[]}).bind(H),$.shouldValidateNestedHandler=((t,e)=>{const r=H.get(t.constructor);if(!r)return!1;const s=r[K.RELATIONS],i=r[K.RELATION];if(Array.isArray(s)&&s?.includes(e)){const r=Object.keys(i)[0],s=$.isPropertyModel(t,e);return i[r]?.class!==s}return!0}).bind($),H.migrationsFor=(t=>{if(!(t=t??at.current))throw new a("Could not get adapter for migrations");return H.innerGet(Symbol.for(K.MIGRATION),t.alias).map((t=>t.class))}).bind(H),H.relations=((t,e)=>{const r=H.get(t,K.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new a("No relations metadata found for property "+e);return r[e]}}).bind(H),$.relations=(t,e)=>H.relations(t instanceof $?t.constructor:t,e)||[],$.tableName=t=>{if(!(t instanceof $?$.get(t.constructor.name):t))throw new a("Unable to find model "+t);return H.get(t instanceof $?t.constructor:t,K.TABLE)||(t instanceof $?t.constructor.name:t.name)},$.columnName=(t,e)=>H.get(t instanceof $?t.constructor:t,H.key(K.COLUMN,e))||e,$.sequenceName=(t,...e)=>[$.tableName(t),...e].join("_"),$.sequenceFor=(t,e)=>{if(e)throw new et("not currently supported");const r=$.pkProps(t instanceof $?t.constructor:t);if(!r)throw new a("No sequence options defined for model. did you use the @pk decorator?");return r},$.indexes=t=>{const e=H.get(t instanceof $?t.constructor:t,K.INDEX);return Object.keys(e||{}).reduce(((t,r)=>(t[r]={[K.INDEX]:e[r]},t)),{})},e.services=()=>H.innerGet(Symbol.for(K.SERVICE)),e.repositories=()=>H.innerGet(Symbol.for(_.REPOSITORY));class ge extends a{constructor(t){super(t,ge.name,500)}}class fe extends F{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new pt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new pt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}}class ye{constructor(t){this.name=t,this.Context=o}async flags(t,e,...r){let s=e.logger||M.for(this.toString());return e.correlationId&&(s=s.for({correlationId:e.correlationId})),Object.assign({},c,e,{timestamp:new Date,operation:t,logger:s})}async context(t,e,...r){const s=await this.flags(t,e,...r);return(new this.Context).accumulate(s)}async logCtx(t,e,r=!1){return await ye.logCtx.bind(this)(t,e,r)}static async logCtx(t,e,r=!1,...s){const i=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,{})}.bind(this);1>t.length&&(t=[await i()]);const n=t.pop();n instanceof o||(t=[...t,await i()]);const c=this?n.logger.for(this).for(e):n.logger.clear().for(this).for(e);return{ctx:n,log:e?c.for(e):c,ctxArgs:[...t,n]}}static get(t){if(!t)throw new a("No name provided");const r=e.get(t);if(r)return r;throw new a("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){const r={context:async t=>(new o).accumulate(Object.assign({},c,{timestamp:new Date,operation:t,logger:M.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 we&&await t.boot(...i)}catch(e){s.error(`Failed to boot ${t} service`,e)}}}class we extends ye{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=await this.logCtx(t,this.boot,!0);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new a("Config not initialized");return this._config}get client(){if(!this._client)throw new a("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],we.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],we.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],we.prototype,"client",null);class be extends ye{get class(){if(!this.clazz)throw new a("Class not initialized");return this.clazz}constructor(t){super(),this.clazz=t,this.repo=ft.forModel(t)}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 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 be.logCtx.bind(this.repo.adapter)(t,e,r,{},this.class)}static async logCtx(t,e,r=!1,s={},i){const n=async function(){if(!r)throw new a("No context provided");return this.context("string"==typeof e?e:e.name,s,i)}.bind(this);1>t.length&&(t=[await n()]);const c=t.pop();c instanceof o||(t=[...t,await n()]);const l=this?c.logger.for(this).for(e):c.logger.clear().for(this).for(e);return{ctx:c,log:e?l.for(e):l,ctxArgs:[...t,c]}}}var me,ve,xe,Ae,Oe;class Ee extends it{constructor(t){super(),this.adapter=t}get log(){return this.adapter.log.for(Ee)}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?$.get(t):t,!this.fromSelector)throw new dt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){let e=t;if((!e.length||!(e[e.length-1]instanceof o))&&this.fromSelector){const t=await this.adapter.context(l.READ,{},this.fromSelector);e=[...e,t]}const{ctx:r}=at.logCtx(e,this.toString());try{const t=this.build();return await this.raw(t,r)}catch(t){throw new a(t)}}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw),i=await this.adapter.raw(t,...s);if(!this.selectSelector)return i;const n=$.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)}toString(){return this.adapter.flavour+" statement"}}i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ee.prototype,"select",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(me="undefined"!=typeof S&&S)?me:Object]),n("design:returntype",Object)],Ee.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ve="undefined"!=typeof S&&S)?ve:Object]),n("design:returntype",Object)],Ee.prototype,"max",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(xe="undefined"!=typeof S&&S)?xe:Object]),n("design:returntype",Object)],Ee.prototype,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ae="undefined"!=typeof S&&S)?Ae:Object]),n("design:returntype",Object)],Ee.prototype,"count",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ee.prototype,"from",null),i([U(),n("design:type",Function),n("design:paramtypes",[gt]),n("design:returntype",Object)],Ee.prototype,"where",null),i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Ee.prototype,"orderBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Ee.prototype,"groupBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ee.prototype,"limit",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Ee.prototype,"offset",null),i([U(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Ee.prototype,"execute",null),(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"})(Oe||(Oe={}));const Ne={Equals:(t,e)=>gt.attribute(t).eq(e),Diff:(t,e)=>gt.attribute(t).dif(e),LessThan:(t,e)=>gt.attribute(t).lt(e),LessThanEqual:(t,e)=>gt.attribute(t).lte(e),GreaterThan:(t,e)=>gt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>gt.attribute(t).gte(e),Between:(t,e,r)=>gt.attribute(t).gte(e).and(gt.attribute(t).lte(r)),In:(t,e)=>gt.attribute(t).in(e),Matches:(t,e)=>gt.attribute(t).regexp(e)},Se=t=>t.charAt(0).toLowerCase()+t.slice(1);class _e{static build(t,...e){if(!t.startsWith(Oe.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(Oe.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static extractSelect(t){const e=t.indexOf(Oe.SELECT);if(-1===e)return;const r=t.substring(e+Oe.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(Oe.AND).map(Se).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(Oe.GROUP_BY);if(-1!==e)return t.substring(e+Oe.GROUP_BY.length).split(Oe.ORDER_BY)[0].split(Oe.THEN_BY).map(Se).filter(Boolean)}static buildWhere(t,e){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?Ne[a]:Ne.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]===Oe.AND?i.and(l):i.or(l)})),!i)throw Error("No conditions found in method name");return i}static parseFieldAndOperator(t){for(const e of Object.keys(Ne))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:Se(r),operator:e}}return{field:Se(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 Te(t={}){return(e,r,s)=>{const i=r.toString();s.value=function(...e){const{select:r,where:s,groupBy:n,orderBy:a,limit:o,offset:c}=_e.build(i,...e);let l=this.select(r);s&&(l=l.where(s));const{allowLimit:h,allowOffset:u,allowOrderBy:d,throws:p}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},g=[{key:"orderBy",value:(a||[])[0],allowed:d},{key:"limit",value:o,allowed:h},{key:"offset",value:c,allowed:u}];for(const t of g)if(void 0!==t.value){if(!t.allowed&&p)throw new dt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(l=l[t.key](t.value))}return l.execute()}}}class Ce extends fe{constructor(t,e,r,s){super(t,e,r,s)}prepare(t){const e=Object.assign({},t);return e.limit=this.size,e}async page(t=1,...e){const r=await o.args(l.READ,this.clazz,e,this.adapter),s=this.prepare(this.statement);if(!this._recordCount||!this._totalPages){this._totalPages=this._recordCount=0;const t=await this.adapter.raw({...s,limit:void 0},r.context)||[];if(this._recordCount=t.length,this._recordCount>0){const t=s?.limit||this.size;this._totalPages=Math.ceil(this._recordCount/t)}}t=this.validatePage(t),s.skip=(t-1)*this.size;const i=await this.adapter.raw(s,await this.adapter.context(l.READ,{},this.clazz));return this._currentPage=t,i}}class $e extends Ee{constructor(t){super(t)}getSort(){return(t,e)=>{if(!this.orderBySelector)throw new a("orderBySelector not set. Should be impossible");const r=this.orderBySelector,[s,i]=r,{designType:n}=H.getPropDesignTypes(t.constructor,s);if(!n)throw new dt("type not compatible with sorting: "+n);switch(n.name){case"string":case"String":return("asc"===i?1:-1)*t[s].localeCompare(e[s]);case"number":case"Number":return("asc"===i?1:-1)*(t[s]-e[s]);case"object":case"Object":if(t[s]instanceof Date&&e[s]instanceof Date)return("asc"===i?1:-1)*(t[s].valueOf()-e[s].valueOf());throw new dt("Sorting not supported for not date classes");default:throw new dt("sorting not supported for type "+n)}}}build(){const t={select:this.selectSelector,from:this.fromSelector,where:this.whereCondition?this.parseCondition(this.whereCondition).where:t=>!0,limit:this.limitSelector,skip:this.offsetSelector};return this.orderBySelector&&(t.sort=this.getSort()),t}async paginate(t){try{const e=this.build();return new Ce(this.adapter,e,t,this.fromSelector)}catch(t){throw new a(t)}}parseCondition(t){return{where:e=>{const{attr1:r,operator:s,comparison:i}=t;if(-1===[ut.AND,ut.OR,ht.NOT].indexOf(s))switch(s){case ht.BIGGER:return e[r]>i;case ht.BIGGER_EQ:return e[r]>=i;case ht.DIFFERENT:return e[r]!==i;case ht.EQUAL:return e[r]===i;case ht.REGEXP:if("string"!=typeof e[r])throw new dt("Invalid regexp comparison on a non string attribute: "+e[r]);return!!e[r].match(RegExp(i,"g"));case ht.SMALLER:return e[r]<i;case ht.SMALLER_EQ:return e[r]<=i;default:throw new a("Invalid operator for standard comparisons: "+s)}else{if(s===ht.NOT)throw new a("Not implemented");{const t=this.parseCondition(r),n=this.parseCondition(i);switch(s){case ut.AND:return t.where(e)&&n.where(e);case ut.OR:return t.where(e)||n.where(e);default:throw new a("Invalid operator for And/Or comparisons: "+s)}}}}}}}async function Re(t,e,r,s){const i=t.get("UUID");if(!i)throw new et("This adapter does not support user identification");s[r]=i}const De="ram";class Pe extends at{constructor(t={},e){super(t,De,e),this.Context=o,this.indexes={},this.lock=new Z}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[$.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=$.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 m(`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=$.tableName(t);if(!this.client.has(s))throw new w(`Table ${s} not found`);if(!this.client.get(s)?.has(e))throw new w(`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=$.tableName(t);if(i.debug(`updating record in table ${n} with id ${e}`),await this.lock.acquire(),!this.client.has(n))throw new w(`Table ${n} not found`);if(!this.client.get(n)?.has(e))throw new w(`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=$.tableName(t);if(s.debug(`deleting record from table ${i} with pk ${e}`),await this.lock.acquire(),!this.client.has(i))throw new w(`Table ${i} not found`);if(!this.client.get(i)?.has(e))throw new w(`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=$.get(t));const e=$.tableName(t);return this.client.has(e)||this.client.set(e,new Map),this.client.get(e)}async raw(t,e){e.logger.for(this.raw).debug("performing raw query: "+JSON.stringify(t));const{where:r,sort:s,limit:i,skip:n,from:o}=t;let{select:c}=t;const l=this.tableFor(o);if(!l)throw new a(`Table ${o} not found in RamAdapter`);const h=$.pk(o),u=H.get(o,H.key(_.ID,h));let d=Array.from(l.entries()).map((([t,r])=>this.revert(r,o,de.parseValue(u.type,t),void 0,e)));return d=r?d.filter(r):d,s&&(d=d.sort(s)),n&&(d=d.slice(n)),i&&(d=d.slice(0,i)),c&&(c=Array.isArray(c)?c:[c],d=d.map((t=>Object.entries(t).reduce(((t,[e,r])=>(c.includes(e)&&(t[e]=r),t)),{})))),d}parseError(t){return t instanceof C?t:new a(t)}Statement(){return new $e(this)}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${R(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=K.CREATED_BY,e=K.UPDATED_BY;q.flavouredAs(De).for(t).define(A(Re),W(t,{})).apply(),q.flavouredAs(De).for(e).define(v(Re),W(e,{})).apply()}getClient(){return new Map}}Pe.decoration(),e.setRegistry(new wt);const Ie="##VERSION##",je="##PACKAGE##";H.registerLibrary(je,Ie);export{At as AbsMigration,at as Adapter,Bt as AuthorizationError,ie as BaseModel,ce as BigIntSequence,ct as Cascade,we as ClientBasedService,gt as Condition,kt as ConnectionError,it as ContextualLoggedClass,lt as DefaultCascade,ae as DefaultSequenceOptions,bt as Dispatch,Lt as ForbiddenError,ut as GroupOperator,wt as InjectablesRegistry,_e as MethodQueryBuilder,rt as MigrationError,st as MigrationRuleError,be as ModelService,ne as NoneSequenceOptions,oe as NumericSequence,ge as ObserverError,tt as ObserverHandler,ht as Operator,Ne as OperatorsMap,ot as OrderDirection,je as PACKAGE_NAME,fe as Paginator,pt as PagingError,K as PersistenceKeys,Oe as QueryClause,dt as QueryError,Pe as RamAdapter,De as RamFlavour,Ce as RamPaginator,$e as RamStatement,ft as Repository,de as Sequence,ue as SequenceModel,vt as Serial,ye as Service,Ee as Statement,mt as UUID,et as UnsupportedError,Ie as VERSION,Dt as cacheModelForPopulate,Mt as column,Et as createOrUpdate,Vt as createdAt,Ht as createdBy,zt as createdByOnCreateUpdate,Re as createdByOnRamCreateUpdate,yt as generateInjectableNameForRepository,Rt as getPopulateKey,Ut as index,Zt as manyToMany,Jt as manyToOne,Ot as migration,Kt as noValidateOn,te as noValidateOnCreate,re as noValidateOnCreateUpdate,ee as noValidateOnUpdate,Xt as oneToMany,Tt as oneToManyOnCreate,$t as oneToManyOnDelete,Ct as oneToManyOnUpdate,Wt as oneToOne,Nt as oneToOneOnCreate,_t as oneToOneOnDelete,St as oneToOneOnUpdate,he as pk,le as pkOnCreate,Pt as populate,xt as prefixMethod,Te as query,se as relation,pe as repository,jt as repositoryFromTypeMetadata,Ft as table,qt as unique,Gt as uniqueOnCreateUpdate,Qt as updatedAt,Yt as updatedBy};
2
2
  //# sourceMappingURL=core.js.map