@decaf-ts/core 0.7.70 → 0.7.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{InjectableRegistryImp as e,Injectables as t,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,InternalError as l,Context as d,ValidationError as u,Repository as p,wrapMethodWithContext as h,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as b,BadRequestError as w,ConflictError as v,onCreateUpdate as x,timestamp as A,onCreate as E,generated as O,onUpdate as N,onDelete as C,afterAny as T,DBKeys as _,readonly as P,SerializationError as $,prefixMethod as B}from"@decaf-ts/db-decorators";import{LoggedClass as D,Logging as R,final as I,toCamelCase as L}from"@decaf-ts/logging";import{Model as k,hashObj as F,required as j,sf as U,ValidationKeys as Y,async as M,type as q,list as G,option as z,model as H}from"@decaf-ts/decorator-validation";import{Lock as Q,MultiLock as V}from"@decaf-ts/transactional-decorators";import{Metadata as W,Decoration as J,DefaultFlavour as X,apply as Z,methodMetadata as K,DecorationKeys as ee,uses as te,metadata as re,propMetadata as se,prop as ie,description as ne}from"@decaf-ts/decoration";var oe,ae,ce,le,de;(e=>{e.FIND_BY="findBy",e.SELECT="Select",e.AND="And",e.OR="Or",e.GROUP_BY="GroupBy",e.ORDER_BY="OrderBy",e.THEN="Then",e.THEN_BY="ThenBy"})(oe||(oe={})),(e=>{e.EQUAL="EQUAL",e.DIFFERENT="DIFFERENT",e.BIGGER="BIGGER",e.BIGGER_EQ="BIGGER_EQ",e.SMALLER="SMALLER",e.SMALLER_EQ="SMALLER_EQ",e.NOT="NOT",e.IN="IN",e.REGEXP="REGEXP"})(ae||(ae={})),(e=>{e.AND="AND",e.OR="OR"})(ce||(ce={})),(e=>{e.LIST_BY="listBy",e.FIND_BY="findBy",e.FIND_ONE_BY="findOneBy",e.PAGE_BY="paginateBy"})(le||(le={})),(e=>{e.PERSISTENCE="persistence",e.INDEX="index",e.UNIQUE="unique",e.ADAPTER="adapter",e.INJECTABLE="decaf_{0}_adapter_for_{1}",e.SERVICE="service",e.TABLE="table",e.COLUMN="column",e.METADATA="__metadata",e.OWNERSHIP="ownership",e.CREATED_BY="ownership.created-by",e.UPDATED_BY="ownership.updated-by",e.RELATIONS="__relations",e.RELATION="relation",e.ONE_TO_ONE="relation.one-to-one",e.ONE_TO_MANY="relation.one-to-many",e.MANY_TO_ONE="relation.many-to-one",e.MANY_TO_MANY="relation.many-to-many",e.POPULATE="populate",e.NO_VALIDATE="no-validate",e.MIGRATION="migration",e.STATEMENT="statement",e.QUERY="query",e.UUID="uuid",e.INITIALIZATION="initialization",e.SHUTDOWN="shutdown",e.BY_KEY="by-key"})(de||(de={}));const ue=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),pe=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],he=[a.READ,c.READ_ALL],ge=[de.STATEMENT,le.FIND_ONE_BY],fe=[de.QUERY,le.PAGE_BY,le.LIST_BY,le.FIND_BY],ye=[le.PAGE_BY];class me{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new l("Observer already registered");this.observers.push({observer:e,filter:t})}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new l("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...s){const{log:i,ctxArgs:n}=De.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:o}=s;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${s.observer.toString()}: ${e}`),!1}}).map(s=>{s.observer.refresh(e,t,r,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class be extends Q{constructor(){super()}}class we extends d{constructor(e){super(e)}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.cache.get(t),e),{})}}class ve extends D{logCtx(e,t,r=!1,s){return ve.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,s){const i=e.context?t.clear().for(e):t.for(e);return s?i.for(s):i}static logCtx(e,t,r=!1,...s){const i=(e,t,r)=>{const s=t.log||R.get();return t.log=e.context?s.clear().for(e):s.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let n=s.pop();const o=n instanceof we;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new l("No context provided");if(o&&!r){if(!n)throw new l("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},e)}return async function(...r){if(!this)throw new l("No contextual provided");if(!this.context)throw new l("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(t=>i(this,{log:t.logger,ctx:t,ctxArgs:[...s,t]},e))}}class xe extends ve{constructor(){super(),this._Context=we}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let s=r.pop();return s instanceof we||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(t):new this.Context(s).accumulate(t)}}class Ae extends l{constructor(e){super(e,Ae.name,500)}}class Ee extends l{constructor(e,t=Ee.name){super(e,t,500)}}class Oe extends Ee{constructor(e){super(e,Oe.name)}}function Se(e){if(!e)throw new l("No name provided");return"string"==typeof e?e.replaceAll(".","-"):W.Symbol(W.constr(e)).toString().replaceAll(".","-")}function Ne(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function Ce(e,t){const{handler:r,args:s}=W.get(e,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,t)??!1)}async function Te(e){return e.then(e=>e.default||e)}function _e(e,t,r,s){const i=async function(...e){let s;try{s=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof Oe)return;throw e}return Promise.resolve(t.apply(this,s))}.bind(e),n=s||t.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=i}class Pe{generate(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})}static get instance(){return Pe._instance||(Pe._instance=new Pe),Pe._instance}}class $e{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return $e._instance||($e._instance=new $e),$e._instance}}const Be=J.flavourResolver.bind(J);J.flavourResolver=e=>{try{const t=Be(e);if(t&&t!==X)return t;const r="function"==typeof e?e:e?.constructor,s=r&&"function"==typeof W.registeredFlavour?W.registeredFlavour(r):void 0;if(s&&s!==X)return s;const i=De._currentFlavour;if(i){const e=De._cache?.[i];return e?.flavour?e.flavour:i}}catch(e){return X}};class De extends xe{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!De._baseRepository)throw new l("This should be overridden when necessary. Otherwise it will be replaced lazily");return De._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new l("No proxy found for "+e);if(e)try{await this.proxies[e].shutdown(),delete this.proxies[e]}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`)}else for(const e in this.proxies){try{await this.proxies[e].shutdown()}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`);continue}delete this.proxies[e]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.alias in De._cache)throw new l(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);De._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),De._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),De._currentFlavour=this.alias)}Dispatch(){return new De._baseDispatch}ObserverHandler(){return new me}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new De._baseSequence(e,this,t)}async flags(e,t,r,...s){if("string"==typeof t)throw new l("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(t)?t.length?t[0]:void 0:t,n=i?k.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${e}-${Pe.instance.generate()}`;const o=r.logger||R.for(this);return Object.assign({},r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:pe.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?W.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:o})}get Context(){return we}async context(e,t,r,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>k.tableName(e)):k.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof we||(s.push(i),i=void 0),t=i?Object.assign({},t,i.toOverrides()):t;const n=await this.flags("string"==typeof e?e:e.name,r,t,...s,i);if(i){if(!(i instanceof this.Context))return(new this.Context).accumulate({...i.cache,...n,parentContext:i});const t=i.get("operation"),s=i.get("affectedTables");return t!==e||r!==s?(new this.Context).accumulate({...i.cache,...n,parentContext:i}):i.accumulate(n)}return(new this.Context).accumulate({...ue,...n})}prepare(e,...t){const{log:r}=this.logCtx(t,this.prepare),s=e.segregate(),i=Object.entries(s.model).reduce((t,[r,s])=>{if(void 0===s)return t;const i=k.columnName(e.constructor,r);if(this.isReserved(i))throw new l(`Property name ${i} is reserved`);return t[i]=s,t},{});return e[de.METADATA]&&(r.silly("Passing along persistence metadata for "+e[de.METADATA]),Object.defineProperty(i,de.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:e[de.METADATA]})),{record:i,id:e[k.pk(e.constructor)],transient:s.transient}}revert(e,t,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a={};a[k.pk(t)]=r;const c=new t(a);n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const d=e[de.METADATA],u=Object.keys(c).reduce((r,s)=>(r[s]=e[k.columnName(t,s)],r),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in u)throw new l(`Transient property ${e} already exists on model ${c.constructor.name}. should be impossible`);u[e]=t})),d&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${d}`),Object.defineProperty(u,de.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),u}async createAll(e,t,r,...s){const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll);if(!t||!r)throw new u("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new u("Ids and models must have the same length");const o=k.tableName(e);return i.debug(`Creating ${t.length} entries ${o} table`),Ne(t.map((t,s)=>()=>this.create(e,t,r[s],...n)))}async readAll(e,t,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=k.tableName(e);return s.debug(`Reading ${t.length} entries ${n} table`),Ne(t.map(t=>()=>this.read(e,t,...i)))}async updateAll(e,t,r,...s){const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new l("Ids and models must have the same length");const o=k.tableName(e);return i.debug(`Updating ${t.length} entries ${o} table`),Ne(t.map((t,s)=>()=>this.update(e,t,r[s],...n)))}async deleteAll(e,t,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${t.length} entries from ${e} table`),Ne(t.map(t=>()=>this.delete(e,t,...i)))}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(e,t);const r=this.log.for(this.observe);r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");await this.observerHandler.updateObservers(e,t,r,...s)}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(e){return W.flavourOf(e)}static get currentFlavour(){if(!De._currentFlavour)throw new l("No persistence flavour set. Please initialize your adapter");return De._currentFlavour}static get current(){return De.get(this.currentFlavour)}static get(e){if(!e)return De.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new l(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return W.flavouredAs(e).filter(k.isModel)}catch(e){throw new l(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${F(e)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(t,r,i)=>{if("_config"===r){const s=Reflect.get(t,r,i);return Object.assign({},s,e)}return"_client"===r?s:Reflect.get(t,r,i)},set:(e,t,r,i)=>"_client"===t?(s=r,!0):Reflect.set(e,t,r,i)});return this.proxies[r]=i,i}migrations(){return W.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,s){return super.logCtx(e,t,r,s)}}i([I(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],De.prototype,"shutdownProxies",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,we]),n("design:returntype",Promise)],De.prototype,"context",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],De.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],De.prototype,"unObserve",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],De.prototype,"client",null);class Re extends l{constructor(e){super(e,Re.name,500)}}class Ie extends l{constructor(e){super(e,Ie.name,500)}}class Le extends k{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||r?(this.attr1=e,this.operator=t,this.comparison=r):k.fromModel(this,e)}and(e){return Le.and(this,e)}or(e){return Le.or(this,e)}not(e){return new Le(this,ae.NOT,e)}hasErrors(...e){const t=()=>{const e=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Le)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ae).indexOf(this.operator))return{operator:{condition:e}}}if(this.attr1 instanceof Le){if(!(this.comparison instanceof Le)&&this.operator!==ae.NOT)return{comparison:{condition:e}};if(-1===Object.values(ce).indexOf(this.operator)&&this.operator!==ae.NOT)return{operator:{condition:e}}}},r=super.hasErrors(...e);return this.isAsync()?(async()=>await Promise.resolve(r)??t())():r??t()}static and(e,t){return Le.group(e,ce.AND,t)}static or(e,t){return Le.group(e,ce.OR,t)}static group(e,t,r){return new Le(e,t,r)}static attribute(e){return(new Le.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(e){return this.setOp(ae.EQUAL,e)}dif(e){return this.setOp(ae.DIFFERENT,e)}gt(e){return this.setOp(ae.BIGGER,e)}lt(e){return this.setOp(ae.SMALLER,e)}gte(e){return this.setOp(ae.BIGGER_EQ,e)}lte(e){return this.setOp(ae.SMALLER_EQ,e)}in(e){return this.setOp(ae.IN,e)}regexp(e){return this.setOp(ae.REGEXP,RegExp(e).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new Le(this.attr1,this.operator,this.comparison)}catch(e){throw new Re(e)}}}}static builder(){return new Le.Builder}static from(e){return new Le(e)}}var ke,Fe;i([j(),n("design:type",Object)],Le.prototype,"attr1",void 0),i([j(),n("design:type",String)],Le.prototype,"operator",void 0),i([j(),n("design:type",Object)],Le.prototype,"comparison",void 0),(e=>{e.ASC="asc",e.DSC="desc"})(ke||(ke={})),(e=>{e.CASCADE="cascade",e.NONE="none"})(Fe||(Fe={}));const je={update:Fe.CASCADE,delete:Fe.NONE},Ue={Equals:(e,t)=>Le.attribute(e).eq(t),Diff:(e,t)=>Le.attribute(e).dif(t),LessThan:(e,t)=>Le.attribute(e).lt(t),LessThanEqual:(e,t)=>Le.attribute(e).lte(t),GreaterThan:(e,t)=>Le.attribute(e).gt(t),GreaterThanEqual:(e,t)=>Le.attribute(e).gte(t),In:(e,t)=>Le.attribute(e).in(t),Matches:(e,t)=>Le.attribute(e).regexp(t)},Ye=e=>e.charAt(0).toLowerCase()+e.slice(1);class Me extends D{static get log(){return this._logger||(this._logger=R.for(Me.name)),this._logger}static build(e,...t){if(!e.startsWith(oe.FIND_BY))throw Error("Unsupported method "+e);const r=this.extractCore(e),s=this.extractSelect(e),i=this.extractGroupBy(e),n=this.buildWhere(r,t),{orderBy:o,limit:a,offset:c}=this.extractOrderLimitOffset(e,t);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(e){const t=e.substring(oe.FIND_BY.length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?t.substring(0,r.index):t}static getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")})}static extractSelect(e){const t=e.indexOf(oe.SELECT);if(-1===t)return;const r=e.substring(t+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(Ye).filter(Boolean)}static extractGroupBy(e){const t=e.indexOf(oe.GROUP_BY);if(-1!==t)return e.substring(t+oe.GROUP_BY.length).split(oe.ORDER_BY)[0].split(oe.THEN_BY).map(Ye).filter(Boolean)}static buildWhere(e,t){if(!e&&0===t.length)return;const r=(e.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=e.match(/And|Or/g)||[];let i;if(r.forEach((e,r)=>{const{field:n,operator:o}=this.parseFieldAndOperator(e),a=o?Ue[o]:Ue.Equals;if(!a)throw Error("Unsupported operator "+o);const c=t[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===oe.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(e){for(const t of Object.keys(Ue))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:Ye(r),operator:t}}return{field:Ye(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(e,t){const r=Me.log.for(this.getProperlyOrderByOrThrow);if(t||e){if(t&&!e)throw new Re("Expected OrderBy clause, but no sortable field was found in method name.");if(t||!e){if(!Object.values(ke).includes(t))throw new Re(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(ke).join(", ")}.`);return[[e,t]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t){const r=this.extractCore(e).split(/And|Or/).length,s=t.slice(r)??[];let i,n,o;if(s.at(-1)instanceof d&&s.pop(),s.length>=1){const t=s[0],r=this.extractOrderByField(e);i=this.getProperlyOrderByOrThrow(r,t)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function qe(){return J.for(de.STATEMENT).define({decorator:()=>(e,t,r)=>Z(K(W.key(de.STATEMENT,t),!0))(e,t,r),args:[]}).apply()}function Ge(e={}){return J.for(de.QUERY).define({decorator:e=>(t,r,s)=>{const i=Me.getFieldsFromMethodName(r);return Z(K(W.key(de.QUERY,r),{...e,fields:i}),qe(),(e=>(t,r,s)=>{s.value=new Proxy(s.value,{apply(t,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=Me.build(t.name,...s);let d=r.select(i);n&&(d=d.where(n));const{allowLimit:u,allowOffset:p,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},f=[{key:"orderBy",value:(a||[])[0],allowed:h},{key:"limit",value:c,allowed:u},{key:"offset",value:l,allowed:p}];for(const e of f)if(void 0!==e.value){if(!e.allowed&&g)throw new Re(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(d=d[e.key](e.value))}return d.execute()}})})(e))(t,r,s)},args:[e]}).apply()}function ze(e){return Xe(e,[a.CREATE,c.CREATE_ALL])}function He(e){return Xe(e,[a.UPDATE,c.UPDATE_ALL])}function Qe(e){return Xe(e,[a.DELETE,c.DELETE_ALL])}function Ve(e){return Xe(e,pe)}function We(e){return Xe(e,Object.values(a))}function Je(e){return Xe(e,Object.values(c))}function Xe(e,t){return(r,s,i,...n)=>{if("string"==typeof e)throw new l("clazz cannot be string. This should be impossible");const{log:o}=ve.prototype.logCtx(n,Xe);return o.silly(`filtering ${s} event for${r?" "+(k.tableName(r)||r):""} ${i}`),("string"==typeof r?r===k.tableName(e)||r===e.constructor.name:W.constr(e)===W.constr(r))&&t.includes(s)}}const Ze={onlyOnCreate:ze,onlyOnUpdate:He,onlyOnDelete:Qe,onlyOnTransactional:Ve,onlyOnSingle:We,onlyOnBulk:Je};function Ke(e){const t=Object.assign({},Ze);return Object.entries(t).forEach(([r,s])=>{t[r]=s(e.class)}),t}class et extends p{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 l("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=k.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return Ke(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(et.register(t,this,this.adapter.alias),e)&&W.get(t,ee.FLAVOUR)===X&&te(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;h(s,s[t+"Prefix"],e,s[t+"Suffix"])}),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,s){const i=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},s||{},this._overrides||{}));function n(e){return e.ctxArgs.shift(),e}return i instanceof Promise?i.then(n):n(i)}override(e){return new Proxy(this,{get:(t,r,s)=>{const i=Reflect.get(t,r,s);return"_overrides"!==r?i:Object.assign({},i,e)}})}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(e,...t):Reflect.get(r,s,i)})}ObserverHandler(){return new me}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),e=new this.class(e),n||await f(this,r,e,a.CREATE,a.ON),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new u(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);s.debug(`Creating new ${this.class.name} in table ${k.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(e,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r)),o=n.map(e=>e.id);let a=n.map(e=>e.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((e,t)=>this.adapter.revert(e,this.class,o[t],r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!e.length)return[e,...s];const d=k.sequenceFor(e[0]);let p=[];if(k.generatedBySequence(this.class)?(d.name||(d.name=k.sequenceName(e[0],"pk")),p=await(await this.adapter.Sequence(d)).range(e.length,...s)):k.generated(this.class,this.pk)||(p=e.map((e,t)=>{if(void 0===e[this.pk])throw new l("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),d.type&&(e[this.pk]="String"!==d.type||d.generated?p[t]:""+e[this.pk]),n||await f(this,r,e,a.CREATE,a.ON),e))),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=y(s);if(n)throw new u(n)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=e,n||await f(this,r,o,a.READ,a.ON),[e,...s]}async read(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.read);s.debug(`reading ${this.class.name} from table ${k.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,f(this,r,t,a.READ,a.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}async update(e,...t){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(t,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(e,i);return s.debug(`updating ${this.class.name} in table ${k.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const c=e[this.pk];if(!c)throw new l("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(c,r),r.get("mergeForUpdate")&&(e=k.merge(d,e,this.class))),n||await f(this,r,e,a.UPDATE,a.ON,d),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new u(s.toString())}return[e,...s,d]}async updateAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.updateAll);s.verbose(`Updating ${e.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),...i)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const d=e.map(e=>{const t=e[this.pk];if(!t)throw new l("missing id on update operation");return t});let p;if(r.get("applyUpdateValidation")&&(p=await this.readAll(d,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>k.merge(p[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>f(this,r,e,a.UPDATE,a.ON,p?p[t]:void 0))),!o){const t=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(p[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const n=y(s);if(n)throw new u(n)}return[e,...s,p]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await f(this,r,t,a.DELETE,a.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.delete);s.debug(`deleting new ${this.class.name} in table ${k.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>f(this,r,e,a.DELETE,a.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);return s.debug(`deleting ${e.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(e,t,r=ke.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,de.QUERY,!0)).for(this.query),a=[t,r],c=this.select().where(e).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}async listBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${k.tableName(this.class)} by ${e} ${t}`),this.select().orderBy([e,t]).execute(...i)}async paginateBy(e,t,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new Re("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:d}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);let u;if(c.verbose(`paginating ${k.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>t===ke.ASC?this.attr(k.pk(this.class)).gt(o):this.attr(k.pk(this.class)).lt(o))()).orderBy([e,t]).paginate(a,...d);else{if(!n)throw new Re("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([e,t]).paginate(a,...d)}const p=await u.page(i,o,...d);return u.serialize(p)}async findOneBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${k.tableName(this.class)} with ${e} ${t}`);const n=await this.select().where(this.attr(e).eq(t)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${k.tableName(this.class)} with ${e} ${t}`),this.select().where(this.attr(e).eq(t)).execute(...i)}async statement(e,...t){if(!et.statements(this,e))throw new Re("Invalid prepared statement requested "+e);const{log:r,ctxArgs:s}=(await this.logCtx(t,de.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+e),this[e](...s)}attr(e){return Le.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=k.tableName(this.class);this.adapter.observe(this,(e,t,r,...i)=>"string"==typeof e?e===s:W.constr(e)===W.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString())}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.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(e,t,r,...s){if(!this.observerHandler)throw new l("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(e,t,Array.isArray(r)?r.map(e=>De._baseSequence.parseValue(k.sequenceFor(this.class).type,e)):De._baseSequence.parseValue(k.sequenceFor(this.class).type,r),...n)}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}static forModel(e,t,...r){let s;const i=t||W.flavourOf(e)||De.currentFlavour;try{s=this.get(e,i)}catch(e){s=void 0}if(s instanceof et)return s;const n=t||W.flavourOf(e)||s&&W.get(s,de.ADAPTER)||De.currentFlavour,o=n?De.get(n):void 0;if(!o)throw new l("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,e,...r)}static get(e,t){const r=k.tableName(e);let s=r;if(t&&(s=[r,t].join(b)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new l("Could not find repository registered under "+r)}static register(e,t,r){let s=k.tableName(e);if(r&&(s=[s,r].join(b)),s in this._cache&&this._cache[s]instanceof et)throw new l(s+" already has a registered instance");this._cache[s]=t}static statements(e,t){const r=e instanceof et?e.constructor:e,s=W.get(r,t?W.key(de.STATEMENT,t):de.STATEMENT);return(t?s:Object.keys(s))||!1}static queries(e,t){const r=e instanceof et?e.constructor:e;return W.get(r,t?W.key(de.QUERY,t):de.QUERY)}}function tt(e,t){if(!(t||(t=J.flavourResolver(e instanceof k?e.constructor:e))&&t!==X))throw new l("Could not retrieve flavour from model "+(e instanceof k?e.constructor.name:e.name));return U(de.INJECTABLE,t,k.tableName(e))}i([qe(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],et.prototype,"listBy",null),i([qe(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],et.prototype,"paginateBy",null),i([qe(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],et.prototype,"findOneBy",null),i([qe(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],et.prototype,"findBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],et.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],et.prototype,"unObserve",null),De&&(De._baseRepository=et);class rt extends e{get log(){return this.logger||(this.logger=R.for(this)),this.logger}constructor(){super()}get(e,r){const s=this.log.for(this.get);let i;try{i=super.get(e)}catch{}if(!i){let n;if("function"==typeof e?n=k.get(e.name)||e:"symbol"!=typeof e&&"string"!=typeof e||(n=k.get(e.toString())),!n)return;const o=de.ADAPTER,a=r||W.get(n,o);try{let e=a;try{a&&De.get(a)}catch{const t=De.current;t&&t.flavour===a&&(e=t.alias)}if(i=et.forModel(n,e),i instanceof et)return i;const r=a||W.get(i.constructor,o)||W.get(n,o);t.register(i,tt(n,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=et.get(n,a);if("function"==typeof t){const e=a?De.get(a):De.current;if(!e)return;return new t(e,n)}}}return i}}var st,it,nt,ot,at;async function ct(e,t,r,s){const i=t.logger.for(ct);if(!s){const t=k.get(e.constructor.name);if(!t)throw new l("Could not find model "+e.constructor.name);s=et.forModel(t,r),i.info("Retrieved "+s.toString())}let n;if(void 0===e[k.pk(s.class)])i.info(`No pk found in ${k.tableName(s.class)} - creating`),n=await s.create(e,t);else{i.info(`pk found in ${k.tableName(s.class)} - attempting update`);try{n=await s.update(e,t),i.info("Updated "+k.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;i.info("update Failed - creating new "+k.tableName(s.class)),n=await s.create(e,t)}i.info("After create update: "+n)}return n}async function lt(e,t,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const t=wt(s,r,this.adapter.alias),n=await t.read(i,e);return await yt(e,s,r,i,n),void(s[r]=i)}const n="function"!=typeof t.class||t.class.name?t.class:t.class();if(!n)throw new l("Could not find model "+t.class);const o=et.forModel(n,this.adapter.alias),a=await o.create(i,e),c=k.pk(a);await yt(e,s,r,a[c],a),s[r]=a[c]}async function dt(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Fe.CASCADE)return;if("object"!=typeof i){const t=wt(s,r,this.adapter.alias),n=await t.read(i,e);return await yt(e,s,r,i,n),void(s[r]=i)}const n=await ct(s[r],e,this.adapter.alias),o=k.pk(n);await yt(e,s,r,n[o],n),s[r]=n[o]}async function ut(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Fe.CASCADE)return;const n=wt(s,r,this.adapter.alias);let o;o=i instanceof k?await n.delete(s[r][n.pk],e):await n.delete(s[r],e),await yt(e,s,r,o[n.pk],o)}async function pt(e,t,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o=e.logger.for(pt),a=new Set([...i]);if("object"!==n){const t=wt(s,r,this.adapter.alias),i=await t.readAll([...a.values()],e);for(let t=0;t<i.length;t++){const s=i[t];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await yt(e,s,r,[...a.values()][t],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=k.pk(i[0].constructor),d=new Set;for(const t of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(t));const i=await ct(t,e,this.adapter.alias);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await yt(e,s,r,i[c],i),o.info("Creating or updating one-to-many model: "+JSON.stringify(t)),d.add(i[c])}s[r]=[...d]}async function ht(e,t,r,s){const{cascade:i}=t;if(i.update===Fe.CASCADE)return pt.call(this,e,t,r,s)}async function gt(e,t,r,s){if(t.cascade.delete!==Fe.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof t.class||t.class.name?t.class:t.class(),a="object"===n,c=a?et.forModel(o,this.adapter.alias):wt(s,r,this.adapter.alias),d=[...new Set([...a?i.map(e=>e[c.pk]):i]).values()];let u,p;try{u=await c.deleteAll(d,e)}catch(t){throw e.logger.error("Failed to delete all records",t),t}for(let t=0;t<u.length;t++){p=u[t];try{await yt(e,s,r,d[t],p)}catch(i){throw e.logger.error(`Failed to cache record ${d[t]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=d}function ft(e,t,r){return[de.POPULATE,e,t,r].join(".")}async function yt(e,t,r,s,i){const n=ft(t.constructor.name,r,s),o=e.get("cacheForPopulate")||{};return o[n]=i,e.accumulate({cacheForPopulate:o})}async function mt(e,t,r,s){if(!t.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,r,s,i,n)=>{let o,a;const c=[],d=t.get("cacheForPopulate")||{};for(const t of i){o=ft(r.constructor.name,s,t);try{if(a=d[o],!a)throw Error("Not found in cache")}catch(i){const o=wt(r,s,n);if(!o)throw new l("Could not find repo");a=await o.read(t,e)}c.push(a)}return c})(e,s,r,n?i:[i],this.adapter.alias);s[r]=n?o:o[0]}(e=>{e.PENDING="pending",e.RUNNING="running",e.FAILED="failed",e.SUCCEEDED="succeeded",e.CANCELED="canceled",e.WAITING_RETRY="waiting_retry"})(st||(st={})),(e=>{e.EXPONENTIAL="exponential",e.FIXED="fixed"})(it||(it={})),(e=>{e.NONE="none",e.FULL="full"})(nt||(nt={})),(e=>{e.STATUS="status",e.LOG="log",e.PROGRESS="progress"})(ot||(ot={})),(e=>{e.ATOMIC="atomic",e.COMPOSITE="composite"})(at||(at={}));const bt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function wt(e,t,r){if(!e)throw Error("No model was provided to get repository");let s;if(Array.isArray(e[t])||e[t]instanceof Set){const r=W.get(e instanceof k?e.constructor:e,W.key(Y.REFLECT,t,Y.LIST))?.clazz;if(!r)throw new l("Failed to find types decorators for property "+t);s=(Array.isArray(r)?[...r]:[r]).map(e=>"function"!=typeof e||e.name?e:e())}else s=W.getPropDesignTypes(e instanceof k?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!bt.includes((""+e.name).toLowerCase()));return et.forModel(i,r)}class vt extends w{constructor(e,t=vt.name,r=401){super(e,t,r)}}class xt extends vt{constructor(e,t=xt.name){super(e,t,403)}}class At extends l{constructor(e){super(e,At.name,503)}}function Et(e){return J.for(de.TABLE).define({decorator:e=>t=>re(de.TABLE,e||t.name.toLowerCase())(t),args:[e]}).apply()}function Ot(e){return J.for(de.COLUMN).define({decorator:e=>(t,r)=>se(W.key(de.COLUMN,r),e||r)(t,r),args:[e]}).apply()}function St(e,t,r){return J.for(de.INDEX).define({decorator:(e,t,r)=>(s,i)=>("string"==typeof e&&(r=e,e=void 0,t=void 0),"string"==typeof t&&(r=t,t=void 0),!t&&e&&e.find(e=>![ke.ASC,ke.DSC].includes(e))&&(t=e,e=void 0),se(W.key(`${de.INDEX}${t&&t?.length?"."+t.join("."):""}`,i),{directions:e,compositions:t,name:r})(s,i)),args:[e,t,r]}).apply()}async function Nt(e,t,r,s){if(s[r]&&(await this.select().where(Le.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 Ct(){const e=de.UNIQUE;return J.for(e).define(M(),x(Nt),se(e,{})).apply()}async function Tt(e,t,r,s){throw new vt("This adapter does not support user identification")}function _t(){return J.for(de.CREATED_BY).define({decorator:()=>(e,t)=>Z(E(Tt),se(de.CREATED_BY,t),O(de.CREATED_BY))(e,t),args:[]}).apply()}function Pt(){return J.for(de.UPDATED_BY).define({decorator:()=>(e,t)=>Z(N(Tt),se(de.UPDATED_BY,t),O(de.UPDATED_BY))(e,t),args:[]}).apply()}function $t(){return A([a.CREATE])}function Bt(){return A()}function Dt(e){const t="function"==typeof e&&e.name?e:e(),r=k.pk(t);return W.allowedTypes(t,r)||[]}function Rt(e,t=je,r=!0,s,i){const n=de.ONE_TO_ONE;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),q([e,...a]),E(lt,o),N(dt,o),C(ut,o),T(mt,o)];return Z(...c)},args:[e,t,r,s,i]}).apply()}function It(e,t=je,r=!0,s,i){const n=de.ONE_TO_MANY;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),G([e,...a]),E(pt,o),N(ht,o),C(gt,o),T(mt,o)];return Z(...c)},args:[e,t,r,s,i]}).apply()}function Lt(e,t=je,r=!0,s,i){const n=de.MANY_TO_ONE;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),q([e,...a])];return Z(...c)},args:[e,t,r,s,i]}).apply()}function kt(e,t=je,r=!0,s,i){const n=de.MANY_TO_MANY;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),G([e,...a])];return Z(...c)},args:[e,t,r,s,i]}).apply()}function Ft(...e){return(t,r)=>{const s=W.get(t,W.key(de.NO_VALIDATE,r))||[],i=[...new Set([...s,...e])];return Z(re(W.key(de.NO_VALIDATE,r),i))(t,r)}}function jt(){return Ft(a.CREATE)}function Ut(){return Ft(a.UPDATE)}function Yt(){return Ft(a.UPDATE,a.CREATE)}function Mt(e,t){return J.for(de.RELATIONS).define({decorator:(e,t)=>(r,s)=>(se(e,t)(r,s),se(W.key(de.RELATIONS,s),Object.assign({},t,{key:e}))(r,s)),args:[e,t]}).apply()}class qt extends k{constructor(e){super(e)}}i([Ot(),$t(),ne("timestamp of creation"),n("design:type",Date)],qt.prototype,"createdAt",void 0),i([Ot(),Bt(),ne("timestamp of last update"),n("design:type",Date)],qt.prototype,"updatedAt",void 0);let Gt=class extends qt{constructor(e){super(e),this.strategy=it.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=nt.FULL}};i([j(),q(String),z(it),ne("the backoff strategy"),n("design:type",String)],Gt.prototype,"strategy",void 0),i([j(),ne("base interval between attempts"),n("design:type",Number)],Gt.prototype,"baseMs",void 0),i([j(),ne("max interval"),n("design:type",Number)],Gt.prototype,"maxMs",void 0),i([q(String),z(nt),ne("optional jitter strategy"),n("design:type",String)],Gt.prototype,"jitter",void 0),Gt=i([H(),n("design:paramtypes",[Object])],Gt),W.tasks=(()=>W.innerGet(Symbol.for("tasks"))).bind(W),W.taskFor=(e=>{const t=W.tasks();return t?t[e]:void 0}).bind(W),W.validationExceptions=((e,t)=>{const r=W.get(e,de.NO_VALIDATE)||[],s=Object.entries(r).filter(([,e])=>e.includes(t)).map(([e])=>e);let i=[];return t!==a.CREATE&&t!==a.UPDATE||(i=k.nestedRelations(e)),[...new Set([...s,...i])]}).bind(W),W.migrationsFor=(e=>{if(!(e=e??De.current))throw new l("Could not get adapter for migrations");return W.innerGet(Symbol.for(de.MIGRATION),e.alias).map(e=>e.class)}).bind(W),W.migrations=(()=>{const e=W.innerGet(Symbol.for([de.MIGRATION,de.BY_KEY].join("-")));return Object.values(e).flat().map(e=>[e.class.name,e.class])}).bind(W),W.relations=((e,t)=>{const r=W.get(e,de.RELATIONS);if(r){if(!t)return Object.keys(r);if(!r[t])throw new l("No relations metadata found for property "+t);return r[t]}}).bind(W),k.relations=(e,t)=>W.relations(e instanceof k?e.constructor:e,t)||[],k.nestedRelations=((e,t=[])=>{let r=[];const s=W.get(e,de.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...t])];for(const e in s){const i=s[e];if(i?.class&&k.relations(i.class)){const s=k.relations(i.class).map(t=>`${e}.${t}`);t=[...t,...s],r=k.nestedRelations(i.class,t)}}return[...new Set([...t,...r])]}).bind(k),k.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!k.sequenceFor(r).generated}).bind(k),W.createdBy=(e=>{const t=W.get("function"!=typeof e?e.constructor:e,de.CREATED_BY);if(!t)throw new l("No createdBy metadata found for model. did you use @createdBy()?");return t}).bind(W),W.updatedBy=(e=>{const t=W.get("function"!=typeof e?e.constructor:e,de.UPDATED_BY);if(!t)throw new l("No updatedBy metadata found for model. did you use @updatedBy()?");return t}).bind(W),k.tableName=e=>{if(!(e instanceof k?k.get(e.constructor.name):e))throw new l("Unable to find model "+e);return W.get(e instanceof k?e.constructor:e,de.TABLE)||(e instanceof k?e.constructor.name:e.name)},k.columnName=(e,t)=>W.get(e instanceof k?e.constructor:e,W.key(de.COLUMN,t))||t,k.sequenceName=(e,...t)=>[k.tableName(e),...t].join("_"),k.sequenceFor=(e,t)=>{if(t)throw new Ae("not currently supported");const r=k.pkProps(e instanceof k?e.constructor:e);if(!r)throw new l("No sequence options defined for model. did you use the @pk decorator?");return r},k.indexes=e=>{const t=W.get(e instanceof k?e.constructor:e,de.INDEX);return Object.keys(t||{}).reduce((e,r)=>(e[r]={[de.INDEX]:t[r]},e),{})},t.services=()=>W.innerGet(Symbol.for(de.SERVICE)),t.repositories=()=>W.innerGet(Symbol.for(_.REPOSITORY));class zt extends ve{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new l("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...e){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:t}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.initialize);t.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(e=>{if(!r[e])throw new l(`Method ${e} not found in ${r.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(r,e),s=r;for(;!t&&s!==Object.prototype;)s=Object.getPrototypeOf(s),t=Object.getOwnPropertyDescriptor(s,e);function i(e){switch(e){case c.CREATE_ALL:return a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return e}}t&&t.writable?r[e]=new Proxy(r[e],{apply:async(t,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),t),[c,l,d]=s,u=await t.call(r,c,l,d,...o),p=[c,i(e),l];return a.get("observeFullResult")&&p.push(u),this.updateObservers(...p,...o).catch(t=>n.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof De))throw new Ae("Only Adapters can be observed by dispatch");this.adapter=e,this.models=De.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}unObserve(e){if(this.adapter!==e)throw new Ae("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){if(!e)throw new l("Model must be provided for observer update");const i=e&&"string"==typeof e?e:k.tableName(e),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...o)}catch(e){throw new l("Failed to refresh dispatch: "+e)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Ht(e,t,r,s){if(e.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=t;i&&"function"==typeof i&&(i=i(s,...n||[],e)),s[r]=Pe.instance.generate(i)}function Qt(e=!1,t,...r){"function"==typeof e&&(t=e,e=!1);const s=de.UUID;return J.for(s).define({decorator:(e,t,...r)=>{const s={update:e,seed:t,args:r},i=[j(),O(de.UUID),E(Ht,s,{priority:56})];return e&&i.push(N(Ht,s,{priority:56})),e||i.push(P()),Z(...i)},args:[e,t,...r]}).apply()}De&&(De._baseDispatch=zt);class Vt extends k{constructor(e){super(e)}}i([$t(),n("design:type",Date)],Vt.prototype,"createdAt",void 0),i([Bt(),n("design:type",Date)],Vt.prototype,"updatedAt",void 0);const Wt={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Jt=Wt,Xt={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Zt=Object.assign({},Xt,{type:"BigInt"});async function Kt(e,t,r,s){if(!t.type||!t.generated||s[r])return;let i;t.name||(t.name=k.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new l(`Failed to instantiate Sequence ${t.name}: ${e}`)}var n,o,a;n=s,o=r,a=await i.next(e),Reflect.set(n,o,a)}function er(e,t){return(r,s)=>{if(ie()(r,s),!e.type){const t=W.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(t?.name||t))throw Error("Incorrrect option type");e.type=t}switch(e.type){case String.name||String.name.toLowerCase():case String:e.generated=void 0!==e.generated&&e.generated,e.type=String;break;case Number.name||String.name.toLowerCase():case Number:e.generated=void 0===e.generated||e.generated,e.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:e.type=BigInt,e.generated=void 0===e.generated||e.generated;break;case"uuid":case"serial":e.generated=!0;break;default:throw Error("Unsupported type")}void 0===e.generated&&(e.generated=!0);const i=[St([ke.ASC,ke.DSC]),j(),P(),se(W.key(_.ID,s),e),E(Kt,e,t)];return e.generated&&i.push(O()),Z(...i)(r,s)}}function tr(e){const t=Object.assign({},Jt);return delete t.generated,e=Object.assign({},t,e),J.for(_.ID).define({decorator:er,args:[e,{priority:60}]}).apply()}let rr=class extends Vt{constructor(e){super(e)}};i([tr({type:String,generated:!1}),n("design:type",String)],rr.prototype,"id",void 0),i([j(),St(),n("design:type",Object)],rr.prototype,"current",void 0),rr=i([Et("??sequence"),H(),n("design:paramtypes",[Object])],rr);class sr extends ve{static{this.lock=new V}constructor(e,t,r={}){super(),this.options=e,this.adapter=t,this.repo=et.forModel(rr,t.alias).override(r)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.READ,!0),{name:s,startWith:i}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof m){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new l("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new l(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new l(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(e,t){const{log:r,ctx:s}=this.adapter.logCtx([t],this.increment),{type:i,incrementBy:n,name:o}=this.options;if(!o)throw new l("Sequence name is required");return sr.lock.execute(async()=>{const t=e||n;if(t%n!==0)throw new l("Value to increment does not consider the incrementBy setting: "+n);const a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),d=async e=>{try{return await this.repo.update(new rr({id:o,current:e}),s)}catch(t){if(t instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${e}`),this.repo.create(new rr({id:o,current:e}),s);throw t}};if("uuid"===a)for(;;){const e=await Promise.resolve(Pe.instance.generate(c));try{const t=await d(e);return r.debug(`Sequence uuid increment ${o} current=${c} next=${e}`),t.current}catch(e){if(e instanceof v)continue;throw e}}const u=await(async e=>{switch(a){case Number.name:return this.parse(e)+t;case BigInt.name:return this.parse(e)+BigInt(t);case String.name:return this.parse(e);case"serial":return await Promise.resolve($e.instance.generate(e));default:throw new l("Should never happen")}})(c),p=await d(u);return r.debug(`Sequence.increment ${o} current=${c} next=${u}`),p.current},o)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ae(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*n,r);let c=[];for(let t=0;e-1>=t;t++)c.push(o-n*this.parse(t));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new l("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return sr.parseValue(this.options.type,e)}logCtx(e,t,r=!1){const s=this.adapter.logCtx([rr,...e],t,r);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return k.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new Ae(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function ir(e,t){return(i,n)=>n?r(W.constr(e))(i,n):(W.set(_.REPOSITORY,W.key(t||De.currentFlavour,k.tableName(e)),i),re(_.REPOSITORY,i.name)(e),t=t||W.get(i.constructor,de.ADAPTER),et.register(e,i,t),s(W.constr(e),{callback:t=>(Object.defineProperty(t,_.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(i))}De._baseSequence=sr;class nr extends l{constructor(e){super(e,nr.name,500)}}function or(e,t){return()=>e.unObserve(t)}class ar extends D{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(e,t,r,s){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=s,_e(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const e=this.query;return e.method&&e.method.match(RegExp(`${le.FIND_BY}|${le.LIST_BY}`,"gi"))}async pagePrefix(e,...t){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...t],le.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[e,...r]}async pagePrepared(e,t,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!t||t instanceof we?[t,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${e} page${t?" - bookmark "+t:""}`),!t||t instanceof we||(this._bookmark=t);const n=et.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,d=RegExp(`^${le.FIND_BY}|${le.LIST_BY}`,"gi");if(!a.match(d))throw new Ae(`Method ${a} is not supported for pagination`);d.lastIndex=0;const u=a.replace(d,le.PAGE_BY),p=[u,...c];let h={limit:this.size,offset:e,bookmark:this._bookmark};u!==le.PAGE_BY||p.length>2?h={direction:l.direction,limit:this.size,offset:e,bookmark:this._bookmark}:p.push(l.direction),p.push(h);const g=await n.statement(...p,...i);return this.apply(g)}async next(...e){return this.page(this.current+1,...e)}async previous(...e){return this.page(this.current-1,...e)}validatePage(e){if(1>e||!Number.isInteger(e))throw new Ie("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new Ie(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:s}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...s);throw new Ae("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new $(e)}}apply(e){const t="string"==typeof e?ar.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total,this._recordCount=t.count,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new $(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var cr,lr,dr,ur;class pr extends ve{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{B(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...t],e.name===this.paginate.name?le.PAGE_BY:de.QUERY,!0,this.overrides||{})).for(e);s.shift();const n=r.get("forcePrepareSimpleQueries"),o=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${o}`),(n&&this.isSimpleQuery()||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(pr)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}count(e){return this.countSelector=e,this}from(e){if(this.fromSelector="string"==typeof e?k.get(e):e,!this.fromSelector)throw new Re("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e){return this.orderBySelector=e,this}groupBy(e){return this.groupBySelector=e,this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctxArgs:r}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();return t.silly("executing raw statement"),await this.raw(s,...r)}catch(e){throw new Re(e)}}async executePrepared(...e){const t=et.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return t.statement(r,...s,i,...e)}async raw(e,...t){const{ctx:r,ctxArgs:s}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new Ae("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(e,!0,...s);if(!this.selectSelector)return i;const n=k.pk(this.fromSelector),o=function(e){const t=e[n];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(e,t){let{attr1:r,operator:s,comparison:i}=e;const n={};switch(s){case ce.AND:case ce.OR:{let e=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,t);e=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof Le){const e=this.prepareCondition(i,t);o=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${o}`;break}case ae.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case ae.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case ae.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case ae.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case ae.BIGGER_EQ:n.method=r+" bigger than equal";break;case ae.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case ae.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case ae.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Re("Unsupported operator "+s)}return n}squash(e){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let t;if(this.whereCondition){if(this.whereCondition.comparison instanceof Le)return;t=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:t?[t,ke.DSC]:[k.pk(this.fromSelector),ke.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:le.LIST_BY,args:[s],params:n};return t&&(o.method=le.FIND_BY,o.args=[t,this.whereCondition.comparison],o.params=n),o}async prepare(e){if(e=e||await this.adapter.context(de.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],r={},s={class:this.fromSelector,args:t,params:r},i=[oe.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);i.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&i.push(oe.SELECT,this.selectSelector.join(` ${oe.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(oe.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(oe.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=L(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new Re(e)}}toString(){return this.adapter.flavour+" statement"}}i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"select",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(cr="undefined"!=typeof S&&S)?cr:Object]),n("design:returntype",Object)],pr.prototype,"distinct",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(lr="undefined"!=typeof S&&S)?lr:Object]),n("design:returntype",Object)],pr.prototype,"max",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(dr="undefined"!=typeof S&&S)?dr:Object]),n("design:returntype",Object)],pr.prototype,"min",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ur="undefined"!=typeof S&&S)?ur:Object]),n("design:returntype",Object)],pr.prototype,"count",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"from",null),i([I(),n("design:type",Function),n("design:paramtypes",[Le]),n("design:returntype",Object)],pr.prototype,"where",null),i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"orderBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"groupBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"limit",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"offset",null),i([I(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],pr.prototype,"execute",null);class hr extends ve{constructor(e){super(),this.name=e,this.observers=[],this.Context=we}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new me,writable:!1});const r=this.log.for(this.observe);this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString()))}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("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(e,t,r,...n)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${Pe.instance.generate()}`;const s=t.logger||R.for(this);return s.setConfig({correlationId:t.correlationId}),Object.assign({},ue,t,{args:r,timestamp:new Date,operation:e,logger:s})}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let s=r.pop();void 0===s||s instanceof we||(r.push(s),s=void 0);const i=await this.flags("string"==typeof e?e:e.name,t,...r);return s?new this.Context(s).accumulate({...i,parentContext:s}):(new this.Context).accumulate(i)}logCtx(e,t,r=!1,s){return ve.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new l("No name provided");const r=Se(e),s=t.get(r);if(s)return s;throw new l("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...e){let r=e.pop();void 0===r||r instanceof we||(e.push(r),r=void 0);const s=await hr.prototype.flags(de.INITIALIZATION,{},...e);r=r?new we(r).accumulate({...s,parentContext:r}):(new we).accumulate(s),e=[...e,r];const{log:i,ctxArgs:n}=hr.prototype.logCtx(e,this.boot),o=t.services();for(const[e,r]of Object.entries(o))try{i.verbose(`Booting ${r.name} service...`);const s=t.get(r);if(!s)throw new l("Failed to resolve injectable for "+e);s instanceof gr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new l(`Failed to boot ${e} service:${t}`)}}}i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],hr.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],hr.prototype,"unObserve",null);class gr extends hr{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=await this.logCtx(e,this.boot,!0);t.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 l("Config not initialized");return this._config}get client(){if(!this._client)throw new l("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info(`Shutting down ${this.name} service...`)}}function fr(e){return function(t,r,s){const i=s.value;return s.value=function(...t){const r=this.class;if(r&&Ce(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,t)},s}}i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],gr.prototype,"boot",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"config",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"client",null);const yr=()=>fr(a.CREATE),mr=()=>fr(a.READ),br=()=>fr(a.UPDATE),wr=()=>fr(a.DELETE);function vr(e){return(t,i,n)=>{n||i?(ie()(t,i),e=e||W.type(t.constructor,i)):e=e||t,e=Se(e);const o=[];if(n&&"number"==typeof n.value)o.push(r(e));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(e))}else W.set(de.SERVICE,e,t),o.push(s(e,{singleton:!0,callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return Z(...o)(t,i,n)}}const xr=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Ar extends hr{get class(){if(!this.clazz)throw new l("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=et.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new l("No name provided");const t=xr(e);try{const e=hr.get(t);if(e)return e}catch(e){}throw new l("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(e,...t):Reflect.get(r,s,i)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(e,...t){const{ctxArgs:r}=(await this.logCtx(t,de.QUERY,!0)).for(this.query),s=this.repo?.[e];if("function"!=typeof s)throw new l(`Method "${e}" is not implemented`);return s.apply(this.repo,r)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(e,t,...s)}async paginateBy(e,t,r,...s){const{ctxArgs:i}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(e,t,r,...i)}async findOneBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(e,t,...s)}async findBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(e,t,...s)}async statement(e,...t){const{ctxArgs:r}=(await this.logCtx(t,de.STATEMENT,!0)).for(this.statement);return this.repo.statement(e,...r)}static forModel(e,t){let r;t=xr(t||e);try{r=Ar.get(t)}catch(e){r=void 0}if(r instanceof Ar)return r;const s=this;let o=class extends s{constructor(){super(e)}};return o=i([vr(t),n("design:paramtypes",[])],o),new o}refresh(e,t,r,...s){return this.repo.refresh(e,t,r,...s)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...s){return this.repo.updateObservers(e,t,r,...s)}logCtx(e,t,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}}i([yr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"create",null),i([yr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ar.prototype,"createAll",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"delete",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ar.prototype,"deleteAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"read",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ar.prototype,"readAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Ar.prototype,"query",null),i([br(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"update",null),i([br(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Ar.prototype,"updateAll",null);class Er extends gr{constructor(){super()}async initialize(...e){const t=e.shift();if(!t||!Array.isArray(t)||t instanceof we||!t.every(e=>Array.isArray(e)))throw new l("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.initialize),i=t.map(([e,t,...s])=>{try{r.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const i=new e(t,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(t){throw new l(`Failed to initialize ${e.name}: ${t}`)}});for(const e of i)try{await e.initialize(...s)}catch(t){throw new l(`Failed to initialize ${e.toString()}: ${t}`)}return{client:i,config:t}}}t.setRegistry(new rt);const Or="##VERSION##",Sr="##PACKAGE##";W.registerLibrary(Sr,Or);export{xe as AbsContextual,De as Adapter,vt as AuthorizationError,Vt as BaseModel,Zt as BigIntSequence,Fe as Cascade,gr as ClientBasedService,Le as Condition,At as ConnectionError,we as Context,be as ContextLock,ve as ContextualLoggedClass,ue as DefaultAdapterFlags,je as DefaultCascade,Ze as DefaultRepositoryFilters,Jt as DefaultSequenceOptions,zt as Dispatch,xt as ForbiddenError,ce as GroupOperator,rt as InjectablesRegistry,Me as MethodQueryBuilder,Ee as MigrationError,Oe as MigrationRuleError,Ar as ModelService,fe as MultipleSelectOperationKeys,he as NonTransactionOperationKeys,Wt as NoneSequenceOptions,Xt as NumericSequence,nr as ObserverError,me as ObserverHandler,ae as Operator,Ue as OperatorsMap,ke as OrderDirection,Sr as PACKAGE_NAME,ye as PaginationOperationKeys,ar as Paginator,Ie as PagingError,de as PersistenceKeys,Er as PersistenceService,le as PreparedStatementKeys,oe as QueryClause,Re as QueryError,et as Repository,ge as SelectOperationKeys,sr as Sequence,rr as SequenceModel,$e as Serial,hr as Service,pr as Statement,pe as TransactionOperationKeys,Pe as UUID,Ae as UnsupportedError,Or as VERSION,yt as cacheModelForPopulate,Ot as column,yr as create,ct as createOrUpdate,$t as createdAt,_t as createdBy,Tt as createdByOnCreateUpdate,wr as del,tt as generateInjectableNameForRepository,Ke as getFilters,Dt as getPkTypes,ft as getPopulateKey,St as index,Se as injectableServiceKey,Ce as isOperationBlocked,kt as manyToMany,Lt as manyToOne,Ft as noValidateOn,jt as noValidateOnCreate,Yt as noValidateOnCreateUpdate,Ut as noValidateOnUpdate,Te as normalizeImport,It as oneToMany,pt as oneToManyOnCreate,gt as oneToManyOnDelete,ht as oneToManyOnUpdate,Rt as oneToOne,lt as oneToOneOnCreate,ut as oneToOneOnDelete,dt as oneToOneOnUpdate,Je as onlyOnBulk,ze as onlyOnCreate,Qe as onlyOnDelete,Xe as onlyOnFilter,We as onlyOnSingle,Ve as onlyOnTransactional,He as onlyOnUpdate,tr as pk,er as pkDec,Kt as pkOnCreate,mt as populate,_e as prefixMethod,qe as prepared,Ne as promiseSequence,Ge as query,mr as read,Mt as relation,ir as repository,wt as repositoryFromTypeMetadata,vr as service,Et as table,or as unRegistration,Ct as unique,Nt as uniqueOnCreateUpdate,br as update,Bt as updatedAt,Pt as updatedBy,Qt as uuid,Ht as uuidCreateUpdateHandler};
1
+ import{InjectableRegistryImp as e,Injectables as t,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,InternalError as l,Context as d,ValidationError as u,Repository as p,wrapMethodWithContext as h,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as b,BadRequestError as w,ConflictError as v,onCreateUpdate as x,timestamp as A,onCreate as E,generated as O,onUpdate as N,onDelete as C,afterAny as T,DBKeys as _,readonly as P,SerializationError as $,prefixMethod as B}from"@decaf-ts/db-decorators";import{LoggedClass as D,Logging as R,final as I,toCamelCase as L}from"@decaf-ts/logging";import{Model as k,hashObj as F,required as j,sf as U,ValidationKeys as Y,async as M,type as q,list as G,option as z,model as H}from"@decaf-ts/decorator-validation";import{Lock as Q,MultiLock as V}from"@decaf-ts/transactional-decorators";import{Metadata as W,Decoration as J,DefaultFlavour as X,apply as Z,methodMetadata as K,DecorationKeys as ee,uses as te,metadata as re,propMetadata as se,prop as ie,description as ne}from"@decaf-ts/decoration";var oe,ae,ce,le,de;(e=>{e.FIND_BY="findBy",e.SELECT="Select",e.AND="And",e.OR="Or",e.GROUP_BY="GroupBy",e.ORDER_BY="OrderBy",e.THEN="Then",e.THEN_BY="ThenBy"})(oe||(oe={})),(e=>{e.EQUAL="EQUAL",e.DIFFERENT="DIFFERENT",e.BIGGER="BIGGER",e.BIGGER_EQ="BIGGER_EQ",e.SMALLER="SMALLER",e.SMALLER_EQ="SMALLER_EQ",e.NOT="NOT",e.IN="IN",e.REGEXP="REGEXP"})(ae||(ae={})),(e=>{e.AND="AND",e.OR="OR"})(ce||(ce={})),(e=>{e.LIST_BY="listBy",e.FIND_BY="findBy",e.FIND_ONE_BY="findOneBy",e.PAGE_BY="paginateBy"})(le||(le={})),(e=>{e.PERSISTENCE="persistence",e.INDEX="index",e.UNIQUE="unique",e.ADAPTER="adapter",e.INJECTABLE="decaf_{0}_adapter_for_{1}",e.SERVICE="service",e.TABLE="table",e.COLUMN="column",e.METADATA="__metadata",e.OWNERSHIP="ownership",e.CREATED_BY="ownership.created-by",e.UPDATED_BY="ownership.updated-by",e.RELATIONS="__relations",e.RELATION="relation",e.ONE_TO_ONE="relation.one-to-one",e.ONE_TO_MANY="relation.one-to-many",e.MANY_TO_ONE="relation.many-to-one",e.MANY_TO_MANY="relation.many-to-many",e.POPULATE="populate",e.NO_VALIDATE="no-validate",e.MIGRATION="migration",e.STATEMENT="statement",e.QUERY="query",e.UUID="uuid",e.INITIALIZATION="initialization",e.SHUTDOWN="shutdown",e.BY_KEY="by-key"})(de||(de={}));const ue=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),pe=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],he=[a.READ,c.READ_ALL],ge=[de.STATEMENT,le.FIND_ONE_BY],fe=[de.QUERY,le.PAGE_BY,le.LIST_BY,le.FIND_BY],ye=[le.PAGE_BY];class me{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new l("Observer already registered");this.observers.push({observer:e,filter:t})}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new l("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...s){const{log:i,ctxArgs:n}=De.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:o}=s;if(!o)return!0;try{return o(e,t,r,...n)}catch(e){return i.error(`Failed to filter observer ${s.observer.toString()}: ${e}`),!1}}).map(s=>{s.observer.refresh(e,t,r,...n)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class be extends Q{constructor(){super()}}class we extends d{constructor(e){super(e)}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.cache.get(t),e),{})}}class ve extends D{logCtx(e,t,r=!1,s){return ve.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,s){const i=e.context?t.clear().for(e):t.for(e);return s?i.for(s):i}static logCtx(e,t,r=!1,...s){const i=(e,t,r)=>{const s=t.log||R.get();return t.log=e.context?s.clear().for(e):s.for(e),"string"==typeof r?t.for=e=>Object.assign(t,{log:t.log.for(e)}):t.log=t.log.for(r),t};let n=s.pop();const o=n instanceof we;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new l("No context provided");if(o&&!r){if(!n)throw new l("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},e)}return async function(...r){if(!this)throw new l("No contextual provided");if(!this.context)throw new l("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(t=>i(this,{log:t.logger,ctx:t,ctxArgs:[...s,t]},e))}}class xe extends ve{constructor(){super(),this._Context=we}get Context(){return this._Context}async context(e,t,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof e?e:e.name} operation with flag overrides: ${Object.keys(t)}`);let s=r.pop();return s instanceof we||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(t):new this.Context(s).accumulate(t)}}class Ae extends l{constructor(e){super(e,Ae.name,500)}}class Ee extends l{constructor(e,t=Ee.name){super(e,t,500)}}class Oe extends Ee{constructor(e){super(e,Oe.name)}}function Se(e){if(!e)throw new l("No name provided");return"string"==typeof e?e.replaceAll(".","-"):W.Symbol(W.constr(e)).toString().replaceAll(".","-")}function Ne(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function Ce(e,t){const{handler:r,args:s}=W.get(e,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,t)??!1)}async function Te(e){return e.then(e=>e.default||e)}function _e(e,t,r,s){const i=async function(...e){let s;try{s=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof Oe)return;throw e}return Promise.resolve(t.apply(this,s))}.bind(e),n=s||t.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),e[n]=i}class Pe{generate(e){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})}static get instance(){return Pe._instance||(Pe._instance=new Pe),Pe._instance}}class $e{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return $e._instance||($e._instance=new $e),$e._instance}}const Be=J.flavourResolver.bind(J);J.flavourResolver=e=>{try{const t=Be(e);if(t&&t!==X)return t;const r="function"==typeof e?e:e?.constructor,s=r&&"function"==typeof W.registeredFlavour?W.registeredFlavour(r):void 0;if(s&&s!==X)return s;const i=De._currentFlavour;if(i){const e=De._cache?.[i];return e?.flavour?e.flavour:i}}catch(e){return X}};class De extends xe{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!De._baseRepository)throw new l("This should be overridden when necessary. Otherwise it will be replaced lazily");return De._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new l("No proxy found for "+e);if(e)try{await this.proxies[e].shutdown(),delete this.proxies[e]}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`)}else for(const e in this.proxies){try{await this.proxies[e].shutdown()}catch(t){this.log.error(`Failed to shutdown proxied adapter ${e}: ${t}`);continue}delete this.proxies[e]}}}async shutdown(){await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(e,t,r){if(super(),this._config=e,this.flavour=t,this._alias=r,this.alias in De._cache)throw new l(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);De._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),De._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),De._currentFlavour=this.alias)}Dispatch(){return new De._baseDispatch}ObserverHandler(){return new me}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new De._baseSequence(e,this,t)}async flags(e,t,r,...s){if("string"==typeof t)throw new l("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(t)?t.length?t[0]:void 0:t,n=i?k.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${e}-${Pe.instance.generate()}`;const o=r.logger||R.for(this);return Object.assign({},r,{affectedTables:t?[...new Set([...(Array.isArray(t)?t:[t]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:pe.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?W.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:o})}get Context(){return we}async context(e,t,r,...s){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>k.tableName(e)):k.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof we||(s.push(i),i=void 0),t=i?Object.assign({},t,i.toOverrides()):t;const n=await this.flags("string"==typeof e?e:e.name,r,t,...s,i);if(i){if(!(i instanceof this.Context))return(new this.Context).accumulate({...i.cache,...n,parentContext:i});const t=i.get("operation"),s=i.get("affectedTables");return t!==e||r!==s?(new this.Context).accumulate({...i.cache,...n,parentContext:i}):i.accumulate(n)}return(new this.Context).accumulate({...ue,...n})}prepare(e,...t){const{log:r}=this.logCtx(t,this.prepare),s=e.segregate(),i=Object.entries(s.model).reduce((t,[r,s])=>{if(void 0===s)return t;const i=k.columnName(e.constructor,r);if(this.isReserved(i))throw new l(`Property name ${i} is reserved`);return t[i]=s,t},{});return e[de.METADATA]&&(r.silly("Passing along persistence metadata for "+e[de.METADATA]),Object.defineProperty(i,de.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:e[de.METADATA]})),{record:i,id:e[k.pk(e.constructor)],transient:s.transient}}revert(e,t,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a={};a[k.pk(t)]=r;const c=new t(a);n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const d=e[de.METADATA],u=Object.keys(c).reduce((r,s)=>(r[s]=e[k.columnName(t,s)],r),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([e,t])=>{if(e in u)throw new l(`Transient property ${e} already exists on model ${c.constructor.name}. should be impossible`);u[e]=t})),d&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${d}`),Object.defineProperty(u,de.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:d})),u}async createAll(e,t,r,...s){const{log:i,ctxArgs:n}=this.logCtx(s,this.createAll);if(!t||!r)throw new u("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new u("Ids and models must have the same length");const o=k.tableName(e);return i.debug(`Creating ${t.length} entries ${o} table`),Ne(t.map((t,s)=>()=>this.create(e,t,r[s],...n)))}async readAll(e,t,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.readAll),n=k.tableName(e);return s.debug(`Reading ${t.length} entries ${n} table`),Ne(t.map(t=>()=>this.read(e,t,...i)))}async updateAll(e,t,r,...s){const{log:i,ctxArgs:n}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new l("Ids and models must have the same length");const o=k.tableName(e);return i.debug(`Updating ${t.length} entries ${o} table`),Ne(t.map((t,s)=>()=>this.update(e,t,r[s],...n)))}async deleteAll(e,t,...r){const{log:s,ctxArgs:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${t.length} entries from ${e} table`),Ne(t.map(t=>()=>this.delete(e,t,...i)))}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(e,t);const r=this.log.for(this.observe);r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this))}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).debug(`Observer ${e.toString()} removed`)}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");await this.observerHandler.updateObservers(e,t,r,...s)}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(e){return W.flavourOf(e)}static get currentFlavour(){if(!De._currentFlavour)throw new l("No persistence flavour set. Please initialize your adapter");return De._currentFlavour}static get current(){return De.get(this.currentFlavour)}static get(e){if(!e)return De.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new l(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return W.flavouredAs(e).filter(k.isModel)}catch(e){throw new l(e)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(e,...t){this.proxies||(this.proxies={});const r=`${this.alias} - ${F(e)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(t,r,i)=>{if("_config"===r){const s=Reflect.get(t,r,i);return Object.assign({},s,e)}return"_client"===r?s:Reflect.get(t,r,i)},set:(e,t,r,i)=>"_client"===t?(s=r,!0):Reflect.set(e,t,r,i)});return this.proxies[r]=i,i}migrations(){return W.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,s){return super.logCtx(e,t,r,s)}}i([I(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],De.prototype,"shutdownProxies",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,we]),n("design:returntype",Promise)],De.prototype,"context",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],De.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],De.prototype,"unObserve",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],De.prototype,"client",null);class Re extends l{constructor(e){super(e,Re.name,500)}}class Ie extends l{constructor(e){super(e,Ie.name,500)}}class Le extends k{constructor(e,t,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,t||r?(this.attr1=e,this.operator=t,this.comparison=r):k.fromModel(this,e)}and(e){return Le.and(this,e)}or(e){return Le.or(this,e)}not(e){return new Le(this,ae.NOT,e)}hasErrors(...e){const t=()=>{const e=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Le)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(ae).indexOf(this.operator))return{operator:{condition:e}}}if(this.attr1 instanceof Le){if(!(this.comparison instanceof Le)&&this.operator!==ae.NOT)return{comparison:{condition:e}};if(-1===Object.values(ce).indexOf(this.operator)&&this.operator!==ae.NOT)return{operator:{condition:e}}}},r=super.hasErrors(...e);return this.isAsync()?(async()=>await Promise.resolve(r)??t())():r??t()}static and(e,t){return Le.group(e,ce.AND,t)}static or(e,t){return Le.group(e,ce.OR,t)}static group(e,t,r){return new Le(e,t,r)}static attribute(e){return(new Le.Builder).attribute(e)}static attr(e){return this.attribute(e)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(e){return this.attr1=e,this}attr(e){return this.attribute(e)}eq(e){return this.setOp(ae.EQUAL,e)}dif(e){return this.setOp(ae.DIFFERENT,e)}gt(e){return this.setOp(ae.BIGGER,e)}lt(e){return this.setOp(ae.SMALLER,e)}gte(e){return this.setOp(ae.BIGGER_EQ,e)}lte(e){return this.setOp(ae.SMALLER_EQ,e)}in(e){return this.setOp(ae.IN,e)}regexp(e){return this.setOp(ae.REGEXP,RegExp(e).source)}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new Le(this.attr1,this.operator,this.comparison)}catch(e){throw new Re(e)}}}}static builder(){return new Le.Builder}static from(e){return new Le(e)}}var ke,Fe;i([j(),n("design:type",Object)],Le.prototype,"attr1",void 0),i([j(),n("design:type",String)],Le.prototype,"operator",void 0),i([j(),n("design:type",Object)],Le.prototype,"comparison",void 0),(e=>{e.ASC="asc",e.DSC="desc"})(ke||(ke={})),(e=>{e.CASCADE="cascade",e.NONE="none"})(Fe||(Fe={}));const je={update:Fe.CASCADE,delete:Fe.NONE},Ue={Equals:(e,t)=>Le.attribute(e).eq(t),Diff:(e,t)=>Le.attribute(e).dif(t),LessThan:(e,t)=>Le.attribute(e).lt(t),LessThanEqual:(e,t)=>Le.attribute(e).lte(t),GreaterThan:(e,t)=>Le.attribute(e).gt(t),GreaterThanEqual:(e,t)=>Le.attribute(e).gte(t),In:(e,t)=>Le.attribute(e).in(t),Matches:(e,t)=>Le.attribute(e).regexp(t)},Ye=e=>e.charAt(0).toLowerCase()+e.slice(1);class Me extends D{static get log(){return this._logger||(this._logger=R.for(Me.name)),this._logger}static build(e,...t){if(!e.startsWith(oe.FIND_BY))throw Error("Unsupported method "+e);const r=this.extractCore(e),s=this.extractSelect(e),i=this.extractGroupBy(e),n=this.buildWhere(r,t),{orderBy:o,limit:a,offset:c}=this.extractOrderLimitOffset(e,t);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(e){const t=e.substring(oe.FIND_BY.length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?t.substring(0,r.index):t}static getFieldsFromMethodName(e){return(this.extractCore(e).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")})}static extractSelect(e){const t=e.indexOf(oe.SELECT);if(-1===t)return;const r=e.substring(t+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(Ye).filter(Boolean)}static extractGroupBy(e){const t=e.indexOf(oe.GROUP_BY);if(-1!==t)return e.substring(t+oe.GROUP_BY.length).split(oe.ORDER_BY)[0].split(oe.THEN_BY).map(Ye).filter(Boolean)}static buildWhere(e,t){if(!e&&0===t.length)return;const r=(e.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=e.match(/And|Or/g)||[];let i;if(r.forEach((e,r)=>{const{field:n,operator:o}=this.parseFieldAndOperator(e),a=o?Ue[o]:Ue.Equals;if(!a)throw Error("Unsupported operator "+o);const c=t[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===oe.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(e){for(const t of Object.keys(Ue))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:Ye(r),operator:t}}return{field:Ye(e)}}static extractOrderByField(e){const t=e.match(/OrderBy(.+)$/);if(!t)return;const r=t[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(e,t){const r=Me.log.for(this.getProperlyOrderByOrThrow);if(t||e){if(t&&!e)throw new Re("Expected OrderBy clause, but no sortable field was found in method name.");if(t||!e){if(!Object.values(ke).includes(t))throw new Re(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(ke).join(", ")}.`);return[[e,t]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t){const r=this.extractCore(e).split(/And|Or/).length,s=t.slice(r)??[];let i,n,o;if(s.at(-1)instanceof d&&s.pop(),s.length>=1){const t=s[0],r=this.extractOrderByField(e);i=this.getProperlyOrderByOrThrow(r,t)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function qe(){return J.for(de.STATEMENT).define({decorator:()=>(e,t,r)=>Z(K(W.key(de.STATEMENT,t),!0))(e,t,r),args:[]}).apply()}function Ge(e={}){return J.for(de.QUERY).define({decorator:e=>(t,r,s)=>{const i=Me.getFieldsFromMethodName(r);return Z(K(W.key(de.QUERY,r),{...e,fields:i}),qe(),(e=>(t,r,s)=>{s.value=new Proxy(s.value,{apply(t,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=Me.build(t.name,...s);let d=r.select(i);n&&(d=d.where(n));const{allowLimit:u,allowOffset:p,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},f=[{key:"orderBy",value:(a||[])[0],allowed:h},{key:"limit",value:c,allowed:u},{key:"offset",value:l,allowed:p}];for(const e of f)if(void 0!==e.value){if(!e.allowed&&g)throw new Re(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(d=d[e.key](e.value))}return d.execute()}})})(e))(t,r,s)},args:[e]}).apply()}function ze(e){return Xe(e,[a.CREATE,c.CREATE_ALL])}function He(e){return Xe(e,[a.UPDATE,c.UPDATE_ALL])}function Qe(e){return Xe(e,[a.DELETE,c.DELETE_ALL])}function Ve(e){return Xe(e,pe)}function We(e){return Xe(e,Object.values(a))}function Je(e){return Xe(e,Object.values(c))}function Xe(e,t){return(r,s,i,...n)=>{if("string"==typeof e)throw new l("clazz cannot be string. This should be impossible");const{log:o}=ve.prototype.logCtx(n,Xe);return o.silly(`filtering ${s} event for${r?" "+(k.tableName(r)||r):""} ${i}`),("string"==typeof r?r===k.tableName(e)||r===e.constructor.name:W.constr(e)===W.constr(r))&&t.includes(s)}}const Ze={onlyOnCreate:ze,onlyOnUpdate:He,onlyOnDelete:Qe,onlyOnTransactional:Ve,onlyOnSingle:We,onlyOnBulk:Je};function Ke(e){const t=Object.assign({},Ze);return Object.entries(t).forEach(([r,s])=>{t[r]=s(e.class)}),t}class et extends p{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 l("No adapter found for this repository. did you use the @uses decorator or pass it in the constructor?");return this._adapter}get tableName(){return this._tableName||(this._tableName=k.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return Ke(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(et.register(t,this,this.adapter.alias),e)&&W.get(t,ee.FLAVOUR)===X&&te(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;h(s,s[t+"Prefix"],e,s[t+"Suffix"])}),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,s){const i=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},s||{},this._overrides||{}));function n(e){return e.ctxArgs.shift(),e}return i instanceof Promise?i.then(n):n(i)}override(e){return new Proxy(this,{get:(t,r,s)=>{const i=Reflect.get(t,r,s);return"_overrides"!==r?i:Object.assign({},i,e)}})}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(e,...t):Reflect.get(r,s,i)})}ObserverHandler(){return new me}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),e=new this.class(e),n||await f(this,r,e,a.CREATE,a.ON),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new u(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);s.debug(`Creating new ${this.class.name} in table ${k.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(e,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.createAll);s.debug(`Creating ${e.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r)),o=n.map(e=>e.id);let a=n.map(e=>e.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((e,t)=>this.adapter.revert(e,this.class,o[t],r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!e.length)return[e,...s];const d=k.sequenceFor(e[0]);let p=[];if(k.generatedBySequence(this.class)?(d.name||(d.name=k.sequenceName(e[0],"pk")),p=await(await this.adapter.Sequence(d)).range(e.length,...s)):k.generated(this.class,this.pk)||(p=e.map((e,t)=>{if(void 0===e[this.pk])throw new l("Primary key is not defined for model in position "+t);return e[this.pk]})),e=await Promise.all(e.map(async(e,t)=>(e=new this.class(e),d.type&&(e[this.pk]="String"!==d.type||d.generated?p[t]:""+e[this.pk]),n||await f(this,r,e,a.CREATE,a.ON),e))),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),n=y(s);if(n)throw new u(n)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=e,n||await f(this,r,o,a.READ,a.ON),[e,...s]}async read(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.read);s.debug(`reading ${this.class.name} from table ${k.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,f(this,r,t,a.READ,a.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.readAll);return s.debug(`reading ${e.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}async update(e,...t){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(t,this.update);let{record:n,id:o,transient:a}=this.adapter.prepare(e,i);return s.debug(`updating ${this.class.name} in table ${k.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);const c=e[this.pk];if(!c)throw new l("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(c,r),r.get("mergeForUpdate")&&(e=k.merge(d,e,this.class))),n||await f(this,r,e,a.UPDATE,a.ON,d),!o){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new u(s.toString())}return[e,...s,d]}async updateAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.updateAll);s.verbose(`Updating ${e.length} new ${this.class.name} in table ${k.tableName(this.class)}`);const n=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,n.map(e=>e.id),n.map(e=>e.record),...i)).map((e,t)=>this.adapter.revert(e,this.class,n[t].id,r.get("rebuildWithTransient")?n[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const d=e.map(e=>{const t=e[this.pk];if(!t)throw new l("missing id on update operation");return t});let p;if(r.get("applyUpdateValidation")&&(p=await this.readAll(d,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>k.merge(p[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>f(this,r,e,a.UPDATE,a.ON,p?p[t]:void 0))),!o){const t=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(p[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const n=y(s);if(n)throw new u(n)}return[e,...s,p]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.read(e,...s);await f(this,r,t,a.DELETE,a.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.delete);s.debug(`deleting new ${this.class.name} in table ${k.tableName(this.class)} with pk ${e}`);const n=await this.adapter.delete(this.class,e,...i);return this.adapter.revert(n,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>f(this,r,e,a.DELETE,a.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(t,this.create);return s.debug(`deleting ${e.length} ${this.class.name} in table ${k.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...i)).map((t,s)=>this.adapter.revert(t,this.class,e[s],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}async query(e,t,r=ke.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,de.QUERY,!0)).for(this.query),a=[t,r],c=this.select().where(e).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}async listBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${k.tableName(this.class)} by ${e} ${t}`),this.select().orderBy([e,t]).execute(...i)}async paginateBy(e,t,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:o,limit:a}=r;if(!n&&!o)throw new Re("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:d}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);let u;if(c.verbose(`paginating ${k.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>t===ke.ASC?this.attr(k.pk(this.class)).gt(o):this.attr(k.pk(this.class)).lt(o))()).orderBy([e,t]).paginate(a,...d);else{if(!n)throw new Re("PaginateBy needs a page or a bookmark");u=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([e,t]).paginate(a,...d)}const p=await u.page(i,o,...d);return u.serialize(p)}async findOneBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${k.tableName(this.class)} with ${e} ${t}`);const n=await this.select().where(this.attr(e).eq(t)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(e,t,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${k.tableName(this.class)} with ${e} ${t}`),this.select().where(this.attr(e).eq(t)).execute(...i)}async statement(e,...t){if(!et.statements(this,e))throw new Re("Invalid prepared statement requested "+e);const{log:r,ctxArgs:s}=(await this.logCtx(t,de.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+e),this[e](...s)}attr(e){return Le.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=k.tableName(this.class);this.adapter.observe(this,(e,t,r,...i)=>"string"==typeof e?e===s:W.constr(e)===W.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString())}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(e),this.log.for(this.unObserve).verbose(`Observer ${e.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(e,t,r,...s){if(!this.observerHandler)throw new l("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(e,t,Array.isArray(r)?r.map(e=>De._baseSequence.parseValue(k.sequenceFor(this.class).type,e)):De._baseSequence.parseValue(k.sequenceFor(this.class).type,r),...n)}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}static forModel(e,t,...r){let s;const i=t||W.flavourOf(e)||De.currentFlavour;try{s=this.get(e,i)}catch(e){s=void 0}if(s instanceof et)return s;const n=t||W.flavourOf(e)||s&&W.get(s,de.ADAPTER)||De.currentFlavour,o=n?De.get(n):void 0;if(!o)throw new l("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,e,...r)}static get(e,t){const r=k.tableName(e);let s=r;if(t&&(s=[r,t].join(b)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new l("Could not find repository registered under "+r)}static register(e,t,r){let s=k.tableName(e);if(r&&(s=[s,r].join(b)),s in this._cache&&this._cache[s]instanceof et)throw new l(s+" already has a registered instance");this._cache[s]=t}static statements(e,t){const r=e instanceof et?e.constructor:e,s=W.get(r,t?W.key(de.STATEMENT,t):de.STATEMENT);return(t?s:Object.keys(s))||!1}static queries(e,t){const r=e instanceof et?e.constructor:e;return W.get(r,t?W.key(de.QUERY,t):de.QUERY)}}function tt(e,t){if(!(t||(t=J.flavourResolver(e instanceof k?e.constructor:e))&&t!==X))throw new l("Could not retrieve flavour from model "+(e instanceof k?e.constructor.name:e.name));return U(de.INJECTABLE,t,k.tableName(e))}i([qe(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],et.prototype,"listBy",null),i([qe(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],et.prototype,"paginateBy",null),i([qe(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],et.prototype,"findOneBy",null),i([qe(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],et.prototype,"findBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],et.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],et.prototype,"unObserve",null),De&&(De._baseRepository=et);class rt extends e{get log(){return this.logger||(this.logger=R.for(this)),this.logger}constructor(){super()}get(e,r){const s=this.log.for(this.get);let i;try{i=super.get(e)}catch{}if(!i){let n;if("function"==typeof e?n=k.get(e.name)||e:"symbol"!=typeof e&&"string"!=typeof e||(n=k.get(e.toString())),!n)return;const o=de.ADAPTER,a=r||W.get(n,o);try{let e=a;try{a&&De.get(a)}catch{const t=De.current;t&&t.flavour===a&&(e=t.alias)}if(i=et.forModel(n,e),i instanceof et)return i;const r=a||W.get(i.constructor,o)||W.get(n,o);t.register(i,tt(n,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=et.get(n,a);if("function"==typeof t){const e=a?De.get(a):De.current;if(!e)return;return new t(e,n)}}}return i}}var st,it,nt,ot,at;async function ct(e,t,r,s){const i=t.logger.for(ct);if(!s){const t=k.get(e.constructor.name);if(!t)throw new l("Could not find model "+e.constructor.name);s=et.forModel(t,r),i.info("Retrieved "+s.toString())}let n;if(void 0===e[k.pk(s.class)])i.info(`No pk found in ${k.tableName(s.class)} - creating`),n=await s.create(e,t);else{i.info(`pk found in ${k.tableName(s.class)} - attempting update`);try{n=await s.update(e,t),i.info("Updated "+k.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;i.info("update Failed - creating new "+k.tableName(s.class)),n=await s.create(e,t)}i.info("After create update: "+n)}return n}async function lt(e,t,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const t=wt(s,r,this.adapter.alias),n=await t.read(i,e);return await yt(e,s,r,i,n),void(s[r]=i)}const n="function"!=typeof t.class||t.class.name?t.class:t.class();if(!n)throw new l("Could not find model "+t.class);const o=et.forModel(n,this.adapter.alias),a=await o.create(i,e),c=k.pk(a);await yt(e,s,r,a[c],a),s[r]=a[c]}async function dt(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Fe.CASCADE)return;if("object"!=typeof i){const t=wt(s,r,this.adapter.alias),n=await t.read(i,e);return await yt(e,s,r,i,n),void(s[r]=i)}const n=await ct(s[r],e,this.adapter.alias),o=k.pk(n);await yt(e,s,r,n[o],n),s[r]=n[o]}async function ut(e,t,r,s){const i=s[r];if(!i)return;if(t.cascade.update!==Fe.CASCADE)return;const n=wt(s,r,this.adapter.alias);let o;o=i instanceof k?await n.delete(s[r][n.pk],e):await n.delete(s[r],e),await yt(e,s,r,o[n.pk],o)}async function pt(e,t,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o=e.logger.for(pt),a=new Set([...i]);if("object"!==n){const t=wt(s,r,this.adapter.alias),i=await t.readAll([...a.values()],e);for(let t=0;t<i.length;t++){const s=i[t];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await yt(e,s,r,[...a.values()][t],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=k.pk(i[0].constructor),d=new Set;for(const t of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(t));const i=await ct(t,e,this.adapter.alias);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await yt(e,s,r,i[c],i),o.info("Creating or updating one-to-many model: "+JSON.stringify(t)),d.add(i[c])}s[r]=[...d]}async function ht(e,t,r,s){const{cascade:i}=t;if(i.update===Fe.CASCADE)return pt.call(this,e,t,r,s)}async function gt(e,t,r,s){if(t.cascade.delete!==Fe.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(e=>typeof e===n))throw new l(`Invalid operation. All elements of property ${r} must match the same type.`);const o="function"!=typeof t.class||t.class.name?t.class:t.class(),a="object"===n,c=a?et.forModel(o,this.adapter.alias):wt(s,r,this.adapter.alias),d=[...new Set([...a?i.map(e=>e[c.pk]):i]).values()];let u,p;try{u=await c.deleteAll(d,e)}catch(t){throw e.logger.error("Failed to delete all records",t),t}for(let t=0;t<u.length;t++){p=u[t];try{await yt(e,s,r,d[t],p)}catch(i){throw e.logger.error(`Failed to cache record ${d[t]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=d}function ft(e,t,r){return[de.POPULATE,e,t,r].join(".")}async function yt(e,t,r,s,i){const n=ft(t.constructor.name,r,s),o=e.get("cacheForPopulate")||{};return o[n]=i,e.accumulate({cacheForPopulate:o})}async function mt(e,t,r,s){if(!t.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(t,r,s,i,n)=>{let o,a;const c=[],d=t.get("cacheForPopulate")||{};for(const t of i){o=ft(r.constructor.name,s,t);try{if(a=d[o],!a)throw Error("Not found in cache")}catch(i){const o=wt(r,s,n);if(!o)throw new l("Could not find repo");a=await o.read(t,e)}c.push(a)}return c})(e,s,r,n?i:[i],this.adapter.alias);s[r]=n?o:o[0]}(e=>{e.PENDING="pending",e.RUNNING="running",e.FAILED="failed",e.SUCCEEDED="succeeded",e.CANCELED="canceled",e.WAITING_RETRY="waiting_retry"})(st||(st={})),(e=>{e.EXPONENTIAL="exponential",e.FIXED="fixed"})(it||(it={})),(e=>{e.NONE="none",e.FULL="full"})(nt||(nt={})),(e=>{e.STATUS="status",e.LOG="log",e.PROGRESS="progress"})(ot||(ot={})),(e=>{e.ATOMIC="atomic",e.COMPOSITE="composite"})(at||(at={}));const bt=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function wt(e,t,r){if(!e)throw Error("No model was provided to get repository");let s;if(Array.isArray(e[t])||e[t]instanceof Set){const r=W.get(e instanceof k?e.constructor:e,W.key(Y.REFLECT,t,Y.LIST))?.clazz;if(!r)throw new l("Failed to find types decorators for property "+t);s=(Array.isArray(r)?[...r]:[r]).map(e=>"function"!=typeof e||e.name?e:e())}else s=W.getPropDesignTypes(e instanceof k?e.constructor:e,t)?.designTypes;const i=s?.find(e=>!bt.includes((""+e.name).toLowerCase()));return et.forModel(i,r)}class vt extends w{constructor(e,t=vt.name,r=401){super(e,t,r)}}class xt extends vt{constructor(e,t=xt.name){super(e,t,403)}}class At extends l{constructor(e){super(e,At.name,503)}}function Et(e){return J.for(de.TABLE).define({decorator:e=>t=>re(de.TABLE,e||t.name.toLowerCase())(t),args:[e]}).apply()}function Ot(e){return J.for(de.COLUMN).define({decorator:e=>(t,r)=>se(W.key(de.COLUMN,r),e||r)(t,r),args:[e]}).apply()}function St(e,t,r){return J.for(de.INDEX).define({decorator:(e,t,r)=>(s,i)=>("string"==typeof e&&(r=e,e=void 0,t=void 0),"string"==typeof t&&(r=t,t=void 0),!t&&e&&e.find(e=>![ke.ASC,ke.DSC].includes(e))&&(t=e,e=void 0),se(W.key(`${de.INDEX}${t&&t?.length?"."+t.join("."):""}`,i),{directions:e,compositions:t,name:r})(s,i)),args:[e,t,r]}).apply()}async function Nt(e,t,r,s){if(s[r]&&(await this.select().where(Le.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 Ct(){const e=de.UNIQUE;return J.for(e).define(M(),x(Nt),se(e,{})).apply()}async function Tt(e,t,r,s){throw new vt("This adapter does not support user identification")}function _t(){return J.for(de.CREATED_BY).define({decorator:()=>(e,t)=>Z(E(Tt),se(de.CREATED_BY,t),O(de.CREATED_BY))(e,t),args:[]}).apply()}function Pt(){return J.for(de.UPDATED_BY).define({decorator:()=>(e,t)=>Z(N(Tt),se(de.UPDATED_BY,t),O(de.UPDATED_BY))(e,t),args:[]}).apply()}function $t(){return A([a.CREATE])}function Bt(){return A()}function Dt(e){const t="function"==typeof e&&e.name?e:e(),r=k.pk(t);return W.allowedTypes(t,r)||[]}function Rt(e,t=je,r=!0,s,i){const n=de.ONE_TO_ONE;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),q([e,...a]),E(lt,o),N(dt,o),C(ut,o),T(mt,o)];return Z(...c)},args:[e,t,r,s,i]}).apply()}function It(e,t=je,r=!0,s,i){const n=de.ONE_TO_MANY;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),G([e,...a]),E(pt,o),N(ht,o),C(gt,o),T(mt,o)];return Z(...c)},args:[e,t,r,s,i]}).apply()}function Lt(e,t=je,r=!0,s,i){const n=de.MANY_TO_ONE;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),q([e,...a])];return Z(...c)},args:[e,t,r,s,i]}).apply()}function kt(e,t=je,r=!0,s,i){const n=de.MANY_TO_MANY;return J.for(n).define({decorator:(e,t,r,s,i)=>{const o={class:e,cascade:t,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=Dt(e),c=[ie(),Mt(n,o),G([e,...a])];return Z(...c)},args:[e,t,r,s,i]}).apply()}function Ft(...e){return(t,r)=>{const s=W.get(t,W.key(de.NO_VALIDATE,r))||[],i=[...new Set([...s,...e])];return Z(re(W.key(de.NO_VALIDATE,r),i))(t,r)}}function jt(){return Ft(a.CREATE)}function Ut(){return Ft(a.UPDATE)}function Yt(){return Ft(a.UPDATE,a.CREATE)}function Mt(e,t){return J.for(de.RELATIONS).define({decorator:(e,t)=>(r,s)=>(se(e,t)(r,s),se(W.key(de.RELATIONS,s),Object.assign({},t,{key:e}))(r,s)),args:[e,t]}).apply()}class qt extends k{constructor(e){super(e)}}i([Ot(),$t(),ne("timestamp of creation"),n("design:type",Date)],qt.prototype,"createdAt",void 0),i([Ot(),Bt(),ne("timestamp of last update"),n("design:type",Date)],qt.prototype,"updatedAt",void 0);let Gt=class extends qt{constructor(e){super(e),this.strategy=it.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=nt.FULL}};i([j(),q(String),z(it),ne("the backoff strategy"),n("design:type",String)],Gt.prototype,"strategy",void 0),i([j(),ne("base interval between attempts"),n("design:type",Number)],Gt.prototype,"baseMs",void 0),i([j(),ne("max interval"),n("design:type",Number)],Gt.prototype,"maxMs",void 0),i([q(String),z(nt),ne("optional jitter strategy"),n("design:type",String)],Gt.prototype,"jitter",void 0),Gt=i([H(),n("design:paramtypes",[Object])],Gt),W.tasks=(()=>W.innerGet(Symbol.for("tasks"))).bind(W),W.taskFor=(e=>{const t=W.tasks();return t?t[e]:void 0}).bind(W),W.validationExceptions=((e,t)=>{const r=W.get(e,de.NO_VALIDATE)||[],s=Object.entries(r).filter(([,e])=>e.includes(t)).map(([e])=>e);let i=[];return t!==a.CREATE&&t!==a.UPDATE||(i=k.nestedRelations(e)),[...new Set([...s,...i])]}).bind(W),W.migrationsFor=(e=>{if(!(e=e??De.current))throw new l("Could not get adapter for migrations");return W.innerGet(Symbol.for(de.MIGRATION),e.alias).map(e=>e.class)}).bind(W),W.migrations=(()=>{const e=W.innerGet(Symbol.for([de.MIGRATION,de.BY_KEY].join("-")));return Object.values(e).flat().map(e=>[e.class.name,e.class])}).bind(W),W.relations=((e,t)=>{const r=W.get(e,de.RELATIONS);if(r){if(!t)return Object.keys(r);if(!r[t])throw new l("No relations metadata found for property "+t);return r[t]}}).bind(W),k.relations=(e,t)=>W.relations(e instanceof k?e.constructor:e,t)||[],k.nestedRelations=((e,t=[])=>{let r=[];const s=W.get(e,de.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...t])];for(const e in s){const i=s[e];if(i?.class&&k.relations(i.class)){const s=k.relations(i.class).map(t=>`${e}.${t}`);t=[...t,...s],r=k.nestedRelations(i.class,t)}}return[...new Set([...t,...r])]}).bind(k),k.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!k.sequenceFor(r).generated}).bind(k),W.createdBy=(e=>{const t=W.get("function"!=typeof e?e.constructor:e,de.CREATED_BY);if(!t)throw new l("No createdBy metadata found for model. did you use @createdBy()?");return t}).bind(W),W.updatedBy=(e=>{const t=W.get("function"!=typeof e?e.constructor:e,de.UPDATED_BY);if(!t)throw new l("No updatedBy metadata found for model. did you use @updatedBy()?");return t}).bind(W),k.tableName=e=>{if(!(e instanceof k?k.get(e.constructor.name):e))throw new l("Unable to find model "+e);return W.get(e instanceof k?e.constructor:e,de.TABLE)||(e instanceof k?e.constructor.name:e.name)},k.columnName=(e,t)=>W.get(e instanceof k?e.constructor:e,W.key(de.COLUMN,t))||t,k.sequenceName=(e,...t)=>[k.tableName(e),...t].join("_"),k.sequenceFor=(e,t)=>{if(t)throw new Ae("not currently supported");const r=k.pkProps(e instanceof k?e.constructor:e);if(!r)throw new l("No sequence options defined for model. did you use the @pk decorator?");return r},k.indexes=e=>{const t=W.get(e instanceof k?e.constructor:e,de.INDEX);return Object.keys(t||{}).reduce((e,r)=>(e[r]={[de.INDEX]:t[r]},e),{})},t.services=()=>W.innerGet(Symbol.for(de.SERVICE)),t.repositories=()=>W.innerGet(Symbol.for(_.REPOSITORY));class zt extends ve{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new l("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...e){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:t}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.initialize);t.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(e=>{if(!r[e])throw new l(`Method ${e} not found in ${r.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(r,e),s=r;for(;!t&&s!==Object.prototype;)s=Object.getPrototypeOf(s),t=Object.getOwnPropertyDescriptor(s,e);function i(e){switch(e){case c.CREATE_ALL:return a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return e}}t&&t.writable?r[e]=new Proxy(r[e],{apply:async(t,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),t),[c,l,d]=s,u=await t.call(r,c,l,d,...o),p=[c,i(e),l];return a.get("observeFullResult")&&p.push(u),this.updateObservers(...p,...o).catch(t=>n.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof De))throw new Ae("Only Adapters can be observed by dispatch");this.adapter=e,this.models=De.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`))}unObserve(e){if(this.adapter!==e)throw new Ae("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(e,t,r,...s){if(!e)throw new l("Model must be provided for observer update");const i=e&&"string"==typeof e?e:k.tableName(e),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...o)}catch(e){throw new l("Failed to refresh dispatch: "+e)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Ht(e,t,r,s){if(e.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=t;i&&"function"==typeof i&&(i=i(s,...n||[],e)),s[r]=await Pe.instance.generate(i)}function Qt(e=!1,t,...r){"function"==typeof e&&(t=e,e=!1);const s=de.UUID;return J.for(s).define({decorator:(e,t,...r)=>{const s={update:e,seed:t,args:r},i=[j(),O(de.UUID),E(Ht,s,{priority:56})];return e&&i.push(N(Ht,s,{priority:56})),e||i.push(P()),Z(...i)},args:[e,t,...r]}).apply()}De&&(De._baseDispatch=zt);class Vt extends k{constructor(e){super(e)}}i([$t(),n("design:type",Date)],Vt.prototype,"createdAt",void 0),i([Bt(),n("design:type",Date)],Vt.prototype,"updatedAt",void 0);const Wt={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Jt=Wt,Xt={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},Zt=Object.assign({},Xt,{type:"BigInt"});async function Kt(e,t,r,s){if(!t.type||!t.generated||s[r])return;let i;t.name||(t.name=k.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new l(`Failed to instantiate Sequence ${t.name}: ${e}`)}var n,o,a;n=s,o=r,a=await i.next(e),Reflect.set(n,o,a)}function er(e,t){return(r,s)=>{if(ie()(r,s),!e.type){const t=W.type(r.constructor,s);if(![Number.name,String.name,BigInt.name].includes(t?.name||t))throw Error("Incorrrect option type");e.type=t}switch(e.type){case String.name||String.name.toLowerCase():case String:e.generated=void 0!==e.generated&&e.generated,e.type=String;break;case Number.name||String.name.toLowerCase():case Number:e.generated=void 0===e.generated||e.generated,e.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:e.type=BigInt,e.generated=void 0===e.generated||e.generated;break;case"uuid":case"serial":e.generated=!0;break;default:throw Error("Unsupported type")}void 0===e.generated&&(e.generated=!0);const i=[St([ke.ASC,ke.DSC]),j(),P(),se(W.key(_.ID,s),e),E(Kt,e,t)];return e.generated&&i.push(O()),Z(...i)(r,s)}}function tr(e){const t=Object.assign({},Jt);return delete t.generated,e=Object.assign({},t,e),J.for(_.ID).define({decorator:er,args:[e,{priority:60}]}).apply()}let rr=class extends Vt{constructor(e){super(e)}};i([tr({type:String,generated:!1}),n("design:type",String)],rr.prototype,"id",void 0),i([j(),St(),n("design:type",Object)],rr.prototype,"current",void 0),rr=i([Et("??sequence"),H(),n("design:paramtypes",[Object])],rr);class sr extends ve{static{this.lock=new V}constructor(e,t,r={}){super(),this.options=e,this.adapter=t,this.repo=et.forModel(rr,t.alias).override(r)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.READ,!0),{name:s,startWith:i}=this.options;try{const e=await this.repo.read(s,r);return this.parse(e.current)}catch(e){if(e instanceof m){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new l("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new l(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new l(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(e,t){const{log:r,ctx:s}=this.adapter.logCtx([t],this.increment),{type:i,incrementBy:n,name:o}=this.options;if(!o)throw new l("Sequence name is required");return sr.lock.execute(async()=>{const t=e||n;if(t%n!==0)throw new l("Value to increment does not consider the incrementBy setting: "+n);const a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),d=async e=>{try{return await this.repo.update(new rr({id:o,current:e}),s)}catch(t){if(t instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${e}`),this.repo.create(new rr({id:o,current:e}),s);throw t}};if("uuid"===a)for(;;){const e=await Promise.resolve(Pe.instance.generate(c));try{const t=await d(e);return r.debug(`Sequence uuid increment ${o} current=${c} next=${e}`),t.current}catch(e){if(e instanceof v)continue;throw e}}const u=await(async e=>{switch(a){case Number.name:return this.parse(e)+t;case BigInt.name:return this.parse(e)+BigInt(t);case String.name:return this.parse(e);case"serial":return await Promise.resolve($e.instance.generate(e));default:throw new l("Should never happen")}})(c),p=await d(u);return r.debug(`Sequence.increment ${o} current=${c} next=${u}`),p.current},o)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.UPDATE,!0)).for(this.next);return this.increment(void 0,t)}async range(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Ae(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(e)*n,r);let c=[];for(let t=0;e-1>=t;t++)c.push(o-n*this.parse(t));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new l("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return sr.parseValue(this.options.type,e)}logCtx(e,t,r=!1){const s=this.adapter.logCtx([rr,...e],t,r);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return k.sequenceName(e,"pk")}static parseValue(e,t){switch("function"==typeof e&&e?.name?e.name:e){case Number.name||Number.name.toLowerCase():return"string"==typeof t?parseInt(t):"number"==typeof t?t:BigInt(t);case BigInt.name||BigInt.name.toLowerCase():return BigInt(t);case String.name||String.name.toLowerCase():return t.toString();case void 0:case"uuid":case"serial":return t;default:throw new Ae(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function ir(e,t){return(i,n)=>n?r(W.constr(e))(i,n):(W.set(_.REPOSITORY,W.key(t||De.currentFlavour,k.tableName(e)),i),re(_.REPOSITORY,i.name)(e),t=t||W.get(i.constructor,de.ADAPTER),et.register(e,i,t),s(W.constr(e),{callback:t=>(Object.defineProperty(t,_.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:e}),t)})(i))}De._baseSequence=sr;class nr extends l{constructor(e){super(e,nr.name,500)}}function or(e,t){return()=>e.unObserve(t)}class ar extends D{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(e,t,r,s){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=s,_e(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const e=this.query;return e.method&&e.method.match(RegExp(`${le.FIND_BY}|${le.LIST_BY}`,"gi"))}async pagePrefix(e,...t){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...t],le.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[e,...r]}async pagePrepared(e,t,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!t||t instanceof we?[t,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${e} page${t?" - bookmark "+t:""}`),!t||t instanceof we||(this._bookmark=t);const n=et.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,d=RegExp(`^${le.FIND_BY}|${le.LIST_BY}`,"gi");if(!a.match(d))throw new Ae(`Method ${a} is not supported for pagination`);d.lastIndex=0;const u=a.replace(d,le.PAGE_BY),p=[u,...c];let h={limit:this.size,offset:e,bookmark:this._bookmark};u!==le.PAGE_BY||p.length>2?h={direction:l.direction,limit:this.size,offset:e,bookmark:this._bookmark}:p.push(l.direction),p.push(h);const g=await n.statement(...p,...i);return this.apply(g)}async next(...e){return this.page(this.current+1,...e)}async previous(...e){return this.page(this.current-1,...e)}validatePage(e){if(1>e||!Number.isInteger(e))throw new Ie("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new Ie(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:s}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...s);throw new Ae("Raw support not available without subclassing this")}serialize(e,t=!1){const r={data:e,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return t?JSON.stringify(r):r}catch(e){throw new $(e)}}apply(e){const t="string"==typeof e?ar.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total,this._recordCount=t.count,this._bookmark=t.bookmark,t.data}static deserialize(e){try{return JSON.parse(e)}catch(e){throw new $(e)}}static isSerializedPage(e){return e&&"object"==typeof e&&Array.isArray(e.data)&&"number"==typeof e.total&&"number"==typeof e.current&&"number"==typeof e.count}}var cr,lr,dr,ur;class pr extends ve{constructor(e,t){super(),this.adapter=e,this.overrides=t,[this.execute,this.paginate].forEach(e=>{B(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...t],e.name===this.paginate.name?le.PAGE_BY:de.QUERY,!0,this.overrides||{})).for(e);s.shift();const n=r.get("forcePrepareSimpleQueries"),o=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${o}`),(n&&this.isSimpleQuery()||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(pr)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}count(e){return this.countSelector=e,this}from(e){if(this.fromSelector="string"==typeof e?k.get(e):e,!this.fromSelector)throw new Re("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e){return this.orderBySelector=e,this}groupBy(e){return this.groupBySelector=e,this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctxArgs:r}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();return t.silly("executing raw statement"),await this.raw(s,...r)}catch(e){throw new Re(e)}}async executePrepared(...e){const t=et.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return t.statement(r,...s,i,...e)}async raw(e,...t){const{ctx:r,ctxArgs:s}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new Ae("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(e,!0,...s);if(!this.selectSelector)return i;const n=k.pk(this.fromSelector),o=function(e){const t=e[n];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(i)?i.map(o):o(i)}prepareCondition(e,t){let{attr1:r,operator:s,comparison:i}=e;const n={};switch(s){case ce.AND:case ce.OR:{let e=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,t);e=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof Le){const e=this.prepareCondition(i,t);o=e.method,n.args=[...n.args||[],...e.args||[]]}n.method=`${e} ${s.toLowerCase()} ${o}`;break}case ae.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case ae.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case ae.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case ae.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case ae.BIGGER_EQ:n.method=r+" bigger than equal";break;case ae.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case ae.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case ae.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Re("Unsupported operator "+s)}return n}squash(e){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let t;if(this.whereCondition){if(this.whereCondition.comparison instanceof Le)return;t=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:t?[t,ke.DSC]:[k.pk(this.fromSelector),ke.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:le.LIST_BY,args:[s],params:n};return t&&(o.method=le.FIND_BY,o.args=[t,this.whereCondition.comparison],o.params=n),o}async prepare(e){if(e=e||await this.adapter.context(de.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&e.get("forcePrepareSimpleQueries")){const t=this.squash(e);if(t)return this.prepared=t,this}const t=[],r={},s={class:this.fromSelector,args:t,params:r},i=[oe.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,e);i.push(r.method),r.args&&r.args.length&&t.push(...r.args)}return this.selectSelector&&i.push(oe.SELECT,this.selectSelector.join(` ${oe.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(oe.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(oe.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=L(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new Re(e)}}toString(){return this.adapter.flavour+" statement"}}i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"select",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(cr="undefined"!=typeof S&&S)?cr:Object]),n("design:returntype",Object)],pr.prototype,"distinct",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(lr="undefined"!=typeof S&&S)?lr:Object]),n("design:returntype",Object)],pr.prototype,"max",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(dr="undefined"!=typeof S&&S)?dr:Object]),n("design:returntype",Object)],pr.prototype,"min",null),i([I(),n("design:type",Function),n("design:paramtypes",["function"==typeof(ur="undefined"!=typeof S&&S)?ur:Object]),n("design:returntype",Object)],pr.prototype,"count",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"from",null),i([I(),n("design:type",Function),n("design:paramtypes",[Le]),n("design:returntype",Object)],pr.prototype,"where",null),i([I(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],pr.prototype,"orderBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],pr.prototype,"groupBy",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"limit",null),i([I(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],pr.prototype,"offset",null),i([I(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],pr.prototype,"execute",null);class hr extends ve{constructor(e){super(),this.name=e,this.observers=[],this.Context=we}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new me,writable:!1});const r=this.log.for(this.observe);this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString()))}unObserve(e){if(!this.observerHandler)throw new l("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(e);const t=this.log.for(this.unObserve);t.verbose(`Observer ${e.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,t.verbose("No longer being observed"))}async updateObservers(e,t,r,...s){if(!this.observerHandler)throw new l("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(e,t,r,...n)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${Pe.instance.generate()}`;const s=t.logger||R.for(this);return s.setConfig({correlationId:t.correlationId}),Object.assign({},ue,t,{args:r,timestamp:new Date,operation:e,logger:s})}async refresh(e,t,r,...s){return this.updateObservers(e,t,r,...s)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let s=r.pop();void 0===s||s instanceof we||(r.push(s),s=void 0);const i=await this.flags("string"==typeof e?e:e.name,t,...r);return s?new this.Context(s).accumulate({...i,parentContext:s}):(new this.Context).accumulate(i)}logCtx(e,t,r=!1,s){return ve.logCtx.call(this,t,s||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new l("No name provided");const r=Se(e),s=t.get(r);if(s)return s;throw new l("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...e){let r=e.pop();void 0===r||r instanceof we||(e.push(r),r=void 0);const s=await hr.prototype.flags(de.INITIALIZATION,{},...e);r=r?new we(r).accumulate({...s,parentContext:r}):(new we).accumulate(s),e=[...e,r];const{log:i,ctxArgs:n}=hr.prototype.logCtx(e,this.boot),o=t.services();for(const[e,r]of Object.entries(o))try{i.verbose(`Booting ${r.name} service...`);const s=t.get(r);if(!s)throw new l("Failed to resolve injectable for "+e);s instanceof gr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new l(`Failed to boot ${e} service:${t}`)}}}i([I(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",void 0)],hr.prototype,"observe",null),i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],hr.prototype,"unObserve",null);class gr extends hr{constructor(){super()}async boot(...e){const{log:t,ctxArgs:r}=await this.logCtx(e,this.boot,!0);t.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 l("Config not initialized");return this._config}get client(){if(!this._client)throw new l("Client not initialized");return this._client}async shutdown(...e){const{log:t}=await this.logCtx(e,this.shutdown,!0);t.info(`Shutting down ${this.name} service...`)}}function fr(e){return function(t,r,s){const i=s.value;return s.value=function(...t){const r=this.class;if(r&&Ce(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,t)},s}}i([I(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],gr.prototype,"boot",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"config",null),i([I(),n("design:type",Object),n("design:paramtypes",[])],gr.prototype,"client",null);const yr=()=>fr(a.CREATE),mr=()=>fr(a.READ),br=()=>fr(a.UPDATE),wr=()=>fr(a.DELETE);function vr(e){return(t,i,n)=>{n||i?(ie()(t,i),e=e||W.type(t.constructor,i)):e=e||t,e=Se(e);const o=[];if(n&&"number"==typeof n.value)o.push(r(e));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(e))}else W.set(de.SERVICE,e,t),o.push(s(e,{singleton:!0,callback:t=>Object.defineProperty(t,"name",{enumerable:!0,configurable:!1,writable:!1,value:e})}));return Z(...o)(t,i,n)}}const xr=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Ar extends hr{get class(){if(!this.clazz)throw new l("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=et.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new l("No name provided");const t=xr(e);try{const e=hr.get(t);if(e)return e}catch(e){}throw new l("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(e,...t):Reflect.get(r,s,i)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(e,...t){const{ctxArgs:r}=(await this.logCtx(t,de.QUERY,!0)).for(this.query),s=this.repo?.[e];if("function"!=typeof s)throw new l(`Method "${e}" is not implemented`);return s.apply(this.repo,r)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(e,t,...s)}async paginateBy(e,t,r,...s){const{ctxArgs:i}=(await this.logCtx(s,le.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(e,t,r,...i)}async findOneBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(e,t,...s)}async findBy(e,t,...r){const{ctxArgs:s}=(await this.logCtx(r,le.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(e,t,...s)}async statement(e,...t){const{ctxArgs:r}=(await this.logCtx(t,de.STATEMENT,!0)).for(this.statement);return this.repo.statement(e,...r)}static forModel(e,t){let r;t=xr(t||e);try{r=Ar.get(t)}catch(e){r=void 0}if(r instanceof Ar)return r;const s=this;let o=class extends s{constructor(){super(e)}};return o=i([vr(t),n("design:paramtypes",[])],o),new o}refresh(e,t,r,...s){return this.repo.refresh(e,t,r,...s)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...s){return this.repo.updateObservers(e,t,r,...s)}logCtx(e,t,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}}i([yr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"create",null),i([yr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ar.prototype,"createAll",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"delete",null),i([wr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ar.prototype,"deleteAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"read",null),i([mr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Ar.prototype,"readAll",null),i([mr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Ar.prototype,"query",null),i([br(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Ar.prototype,"update",null),i([br(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Ar.prototype,"updateAll",null);class Er extends gr{constructor(){super()}async initialize(...e){const t=e.shift();if(!t||!Array.isArray(t)||t instanceof we||!t.every(e=>Array.isArray(e)))throw new l("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(e,de.INITIALIZATION,!0)).for(this.initialize),i=t.map(([e,t,...s])=>{try{r.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const i=new e(t,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(t){throw new l(`Failed to initialize ${e.name}: ${t}`)}});for(const e of i)try{await e.initialize(...s)}catch(t){throw new l(`Failed to initialize ${e.toString()}: ${t}`)}return{client:i,config:t}}}t.setRegistry(new rt);const Or="##VERSION##",Sr="##PACKAGE##";W.registerLibrary(Sr,Or);export{xe as AbsContextual,De as Adapter,vt as AuthorizationError,Vt as BaseModel,Zt as BigIntSequence,Fe as Cascade,gr as ClientBasedService,Le as Condition,At as ConnectionError,we as Context,be as ContextLock,ve as ContextualLoggedClass,ue as DefaultAdapterFlags,je as DefaultCascade,Ze as DefaultRepositoryFilters,Jt as DefaultSequenceOptions,zt as Dispatch,xt as ForbiddenError,ce as GroupOperator,rt as InjectablesRegistry,Me as MethodQueryBuilder,Ee as MigrationError,Oe as MigrationRuleError,Ar as ModelService,fe as MultipleSelectOperationKeys,he as NonTransactionOperationKeys,Wt as NoneSequenceOptions,Xt as NumericSequence,nr as ObserverError,me as ObserverHandler,ae as Operator,Ue as OperatorsMap,ke as OrderDirection,Sr as PACKAGE_NAME,ye as PaginationOperationKeys,ar as Paginator,Ie as PagingError,de as PersistenceKeys,Er as PersistenceService,le as PreparedStatementKeys,oe as QueryClause,Re as QueryError,et as Repository,ge as SelectOperationKeys,sr as Sequence,rr as SequenceModel,$e as Serial,hr as Service,pr as Statement,pe as TransactionOperationKeys,Pe as UUID,Ae as UnsupportedError,Or as VERSION,yt as cacheModelForPopulate,Ot as column,yr as create,ct as createOrUpdate,$t as createdAt,_t as createdBy,Tt as createdByOnCreateUpdate,wr as del,tt as generateInjectableNameForRepository,Ke as getFilters,Dt as getPkTypes,ft as getPopulateKey,St as index,Se as injectableServiceKey,Ce as isOperationBlocked,kt as manyToMany,Lt as manyToOne,Ft as noValidateOn,jt as noValidateOnCreate,Yt as noValidateOnCreateUpdate,Ut as noValidateOnUpdate,Te as normalizeImport,It as oneToMany,pt as oneToManyOnCreate,gt as oneToManyOnDelete,ht as oneToManyOnUpdate,Rt as oneToOne,lt as oneToOneOnCreate,ut as oneToOneOnDelete,dt as oneToOneOnUpdate,Je as onlyOnBulk,ze as onlyOnCreate,Qe as onlyOnDelete,Xe as onlyOnFilter,We as onlyOnSingle,Ve as onlyOnTransactional,He as onlyOnUpdate,tr as pk,er as pkDec,Kt as pkOnCreate,mt as populate,_e as prefixMethod,qe as prepared,Ne as promiseSequence,Ge as query,mr as read,Mt as relation,ir as repository,wt as repositoryFromTypeMetadata,vr as service,Et as table,or as unRegistration,Ct as unique,Nt as uniqueOnCreateUpdate,br as update,Bt as updatedAt,Pt as updatedBy,Qt as uuid,Ht as uuidCreateUpdateHandler};
2
2
  //# sourceMappingURL=core.js.map