@decaf-ts/core 0.8.27 → 0.8.29
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.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/lib/esm/index.d.ts +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/persistence/Dispatch.d.ts +1 -1
- package/lib/esm/persistence/Dispatch.js +4 -2
- package/lib/esm/persistence/Dispatch.js.map +1 -1
- package/lib/esm/repository/Repository.js +1 -1
- package/lib/esm/repository/Repository.js.map +1 -1
- package/lib/esm/services/ModelService.js +1 -1
- package/lib/esm/services/ModelService.js.map +1 -1
- package/lib/index.cjs +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/persistence/Dispatch.cjs +3 -1
- package/lib/persistence/Dispatch.d.ts +1 -1
- package/lib/persistence/Dispatch.js.map +1 -1
- package/lib/repository/Repository.cjs +1 -1
- package/lib/repository/Repository.js.map +1 -1
- package/lib/services/ModelService.cjs +1 -1
- package/lib/services/ModelService.js.map +1 -1
- package/package.json +1 -1
package/dist/core.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e,t,r,a,s,i,o,n){"use strict";var c,d,l,u,p;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.PAGE_BY="pageBy",c.COUNT_BY="countBy",c.SUM_BY="sumBy",c.AVG_BY="avgBy",c.MIN_BY="minBy",c.MAX_BY="maxBy",c.DISTINCT_BY="distinctBy",c.GROUP_BY_PREFIX="groupBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(d=e.Operator||(e.Operator={})).EQUAL="EQUAL",d.DIFFERENT="DIFFERENT",d.BIGGER="BIGGER",d.BIGGER_EQ="BIGGER_EQ",d.SMALLER="SMALLER",d.SMALLER_EQ="SMALLER_EQ",d.BETWEEN="BETWEEN",d.NOT="NOT",d.IN="IN",d.REGEXP="REGEXP",d.GROUP_BY="group-by",d.COUNT="count",d.SUM="sum",d.MAX="v_max",d.MIN="v_min",d.DISTINCT="distinct",d.VIEW="view",e.GroupOperator=void 0,(l=e.GroupOperator||(e.GroupOperator={})).AND="AND",l.OR="OR",e.PreparedStatementKeys=void 0,(u=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",u.FIND_BY="findBy",u.FIND_ONE_BY="findOneBy",u.PAGE_BY="paginateBy",u.COUNT_OF="countOf",u.MAX_OF="maxOf",u.MIN_OF="minOf",u.AVG_OF="avgOf",u.SUM_OF="sumOf",u.DISTINCT_OF="distinctOf",u.GROUP_OF="groupOf",e.PersistenceKeys=void 0,(p=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",p.INDEX="index",p.UNIQUE="unique",p.ADAPTER="adapter",p.INJECTABLE="decaf_{0}_adapter_for_{1}",p.SERVICE="service",p.TABLE="table",p.COLUMN="column",p.METADATA="__metadata",p.OWNERSHIP="ownership",p.CREATED_BY="ownership.created-by",p.UPDATED_BY="ownership.updated-by",p.RELATIONS="__relations",p.RELATION="relation",p.ONE_TO_ONE="relation.one-to-one",p.ONE_TO_MANY="relation.one-to-many",p.MANY_TO_ONE="relation.many-to-one",p.MANY_TO_MANY="relation.many-to-many",p.POPULATE="populate",p.NO_VALIDATE="no-validate",p.MIGRATION="migration",p.STATEMENT="statement",p.QUERY="query",p.UUID="uuid",p.TAG_FOR_DELETION="tag_for_deletion",p.INITIALIZATION="initialization",p.SHUTDOWN="shutdown",p.BY_KEY="by-key",p.AUTH="auth",p.AUTH_ROLE="auth-role",p.DECAF_ROUTE="DecafRoute";const h=Object.assign({},{ignoreDevSafeGuards:!1}),g=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),y=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],f=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],m=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],_=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY],w=[e.PreparedStatementKeys.PAGE_BY];class b extends o.Lock{constructor(){super()}}class E extends a.Context{constructor(e){super(e)}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new a.InternalError(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t),this.accumulate({pending:r})}getFromChildren(e){const t=this.getOrUndefined(e);if(t)return t;const r=this.getOrUndefined("childContexts");return r&&r.length?r.map(t=>t.getFromChildren(e)).flat().reduce((e,t)=>Object.assign(e,t),{}):void 0}pending(){return this.getFromChildren("pending")}getOrUndefined(e){try{return this.get(e)}catch(e){return}}override(e){return new Proxy(this,{get:(t,r,s)=>"get"===r?new Proxy(t.get,{apply:(t,r,i)=>{const o=i[0];if(!o)throw new a.InternalError("Invalid property access to overridden context: "+o);return o in e?e[o]:Reflect.apply(t,s,i)}}):Reflect.get(t,r,s)})}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.get(t),e),{})}accumulate(e){return super.accumulate(e)}}class v extends s.LoggedClass{logCtx(e,t,r=!1,a){return v.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...i){const o=(e,t,r)=>{const a=t.log||s.Logging.get();return t.log=e.context?a.clear().for(e):a.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=i.pop();const c=n instanceof E;if(n&&!c&&(i.push(n),n=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!n)throw new a.InternalError("Missing context. should be impossible");return o(this,{log:n.logger,ctx:n,ctxArgs:[...i,n]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...i,n].filter(Boolean)).then(t=>o(this,{log:t.logger,ctx:t,ctxArgs:[...i,t]},e))}}class O extends v{constructor(){super(),this._Context=E}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 a=r.pop();return a instanceof E||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class T{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");return this.observers.push({observer:e,filter:t}),()=>this.unObserve(e)}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:i}=v.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:o}=a;if(!o)return!0;try{return o(e,t,r,...i)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>{a.observer.refresh(e,t,r,...i)}))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class x extends a.InternalError{constructor(e){super(e,x.name,500)}}class k extends a.InternalError{constructor(e,t=k.name){super(e,t,500)}}class A extends k{constructor(e){super(e,A.name)}}function C(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):n.Metadata.Symbol(n.Metadata.constr(e)).toString().replaceAll(".","-")}function M(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function D(e,t){const{handler:r,args:s}=n.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)}function P(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof A)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),i=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),e[i]=s}class B{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 B._instance||(B._instance=new B),B._instance}}class I{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return I._instance||(I._instance=new I),I._instance}}const N=n.Decoration.flavourResolver.bind(n.Decoration);n.Decoration.flavourResolver=e=>{try{const t=N(e);if(t&&t!==n.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof n.Metadata.registeredFlavour?n.Metadata.registeredFlavour(r):void 0;if(a&&a!==n.DefaultFlavour)return a;const s=R._currentFlavour;if(s){const e=R._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return n.DefaultFlavour}};class R extends O{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!R._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return R._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new a.InternalError("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(...t){(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.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 R._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);R._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),R._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),R._currentFlavour=this.alias)}Dispatch(){return new R._baseDispatch}ObserverHandler(){return new T}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new R._baseSequence(e,this,t)}async flags(e,t,r,...o){if("string"==typeof t)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(t)?t.length?t[0]:void 0:t,d=c?i.Model.tableName(c)+" - ":"";r.correlationId=r.correlationId||`${d}${e}-${B.instance.generate()}`;const l=r.logger||s.Logging.for(this);return Object.assign({},g,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:o,writeOperation:y.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?n.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:l})}get Context(){return E}async context(e,t,r,...a){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>i.Model.tableName(e)):i.Model.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let s=a.pop();void 0===s||s instanceof E||(a.push(s),s=void 0),t=s?Object.assign({},s.toOverrides(),t):t;const o=await this.flags("string"==typeof e?e:e.name,r,t,...[...a,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}const t=s.get("operation"),a=s.getOrUndefined("affectedTables");if(t!==e||r&&r!==a){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}return s.accumulate(o)}return(new this.Context).accumulate({...o})}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),o=t.segregate(),n=Object.entries(o.model).reduce((e,[r,s])=>{if(void 0===s)return e;const o=i.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(n,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:n,id:t[i.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,s,o,...n){const{log:c,ctx:d}=this.logCtx(n,this.revert),l=i.Model.pk(r),u=new r;u[l]=s,c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==l).reduce((e,a)=>(e[a]=t[i.Model.columnName(r,a)],e),u);return d.get("rebuildWithTransient")&&o&&(c.verbose("re-adding transient properties: "+Object.keys(o).join(", ")),Object.entries(o).forEach(([e,t])=>{if(e in h&&void 0!==h[e])throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${s}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:p})),h}async createAll(e,t,r,...s){const{log:o,ctx:n}=this.logCtx(s,this.createAll);if(!t||!r)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new a.ValidationError("Ids and models must have the same length");const c=i.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),M(t.map((t,a)=>()=>this.create(e,t,r[a],...s,n.override({noEmitSingle:!0}))))}async readAll(e,t,...r){const{log:a,ctx:s}=this.logCtx(r,this.readAll),o=i.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),M(t.map(t=>()=>this.read(e,t,...r,s.override({noEmitSingle:!0}))))}async updateAll(e,t,r,...s){const{log:o,ctx:n}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const c=i.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),M(t.map((t,a)=>()=>this.update(e,t,r[a],...s,n.override({noEmitSingle:!0}))))}async deleteAll(e,t,...r){const{log:a,ctx:s}=this.logCtx(r,this.deleteAll);return a.debug(`Deleting ${t.length} entries from ${e} table`),M(t.map(t=>()=>this.delete(e,t,...r,s.override({noEmitSingle:!0}))))}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);return r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const a=Array.isArray(r),s=!i.get("noEmitSingle"),n=!i.get("noEmitBulk");(a&&n||!a&&s)&&await this.observerHandler.updateObservers(e,t,r,...o)}}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return n.Metadata.flavourOf(e)}static get currentFlavour(){if(!R._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return R._currentFlavour}static get current(){return R.get(this.currentFlavour)}static get(e){if(!e)return R.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return n.Metadata.flavouredAs(e).filter(i.Model.isModel)}catch(e){throw new a.InternalError(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} - ${i.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=s,s}migrations(){return n.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],R.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,E]),r.__metadata("design:returntype",Promise)],R.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],R.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],R.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],R.prototype,"client",null);class L extends a.InternalError{constructor(e){super(e,L.name,500)}}class $ extends a.InternalError{constructor(e){super(e,$.name,500)}}class F extends i.Model{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):i.Model.fromModel(this,e)}and(e){return F.and(this,e)}or(e){return F.or(this,e)}not(t){return new F(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof F)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===e.Operator.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof F){if(!(this.comparison instanceof F)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return F.group(t,e.GroupOperator.AND,r)}static or(t,r){return F.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new F(e,t,r)}static attribute(e){return(new F.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(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}between(t,r){return this.setOp(e.Operator.BETWEEN,[t,r])}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new F(this.attr1,this.operator,this.comparison)}catch(e){throw new L(e)}}}}static builder(){return new F.Builder}static from(e){return new F(e)}}var j,U;r.__decorate([i.required(),r.__metadata("design:type",Object)],F.prototype,"attr1",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],F.prototype,"operator",void 0),r.__decorate([i.required(),r.__metadata("design:type",Object)],F.prototype,"comparison",void 0),e.OrderDirection=void 0,(j=e.OrderDirection||(e.OrderDirection={})).ASC="asc",j.DSC="desc",e.Cascade=void 0,(U=e.Cascade||(e.Cascade={})).CASCADE="cascade",U.NONE="none";const q={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},Y={Equals:(e,t)=>F.attribute(e).eq(t),Diff:(e,t)=>F.attribute(e).dif(t),LessThan:(e,t)=>F.attribute(e).lt(t),LessThanEqual:(e,t)=>F.attribute(e).lte(t),GreaterThan:(e,t)=>F.attribute(e).gt(t),GreaterThanEqual:(e,t)=>F.attribute(e).gte(t),In:(e,t)=>F.attribute(e).in(t),Matches:(e,t)=>F.attribute(e).regexp(t)},G=e=>e.charAt(0).toLowerCase()+e.slice(1);class z extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(z.name)),this._logger}static{this.prefixMap={[e.QueryClause.FIND_BY]:"find",[e.QueryClause.PAGE_BY]:"page",[e.QueryClause.COUNT_BY]:"count",[e.QueryClause.SUM_BY]:"sum",[e.QueryClause.AVG_BY]:"avg",[e.QueryClause.MIN_BY]:"min",[e.QueryClause.MAX_BY]:"max",[e.QueryClause.DISTINCT_BY]:"distinct",[e.QueryClause.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(e){for(const[t,r]of Object.entries(this.prefixMap))if(e.startsWith(t))return{action:r,prefix:t}}static build(e,...t){const r=this.getActionFromMethodName(e);if(!r)throw Error("Unsupported method "+e);const{action:a,prefix:s}=r;let i;["count","sum","avg","min","max","distinct","group"].includes(a)&&(i=this.extractAggregationSelector(e,s));const o=this.extractCore(e,s),n=this.extractSelect(e),c=this.extractGroupBy(e),d=this.buildWhere(o,t),{orderBy:l,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,o);return{action:a,select:n,selector:i,where:d,groupBy:c,orderBy:l,limit:u,offset:p}}static extractAggregationSelector(e,t){const r=e.substring(t.length),a=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),s=a?r.substring(0,a.index):r;return s?G(s):void 0}static extractCore(t,r=e.QueryClause.FIND_BY){const a=t.substring(r.length);if(r!==e.QueryClause.FIND_BY&&r!==e.QueryClause.PAGE_BY){const e=a.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!e)return"";if("And"===e[0]||"Or"===e[0]){const t=a.substring(e.index+e[0].length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return r?t.substring(0,r.index):t}return""}const s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?a.substring(0,s.index):a}static getFieldsFromMethodName(t){const r=this.getActionFromMethodName(t),a=r?.prefix||e.QueryClause.FIND_BY,s=this.extractCore(t,a);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(e=>e.length>0).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")}):[]}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(G).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(G).filter(Boolean);const a=this.getActionFromMethodName(t);if("group"===a?.action){const r=t.substring(a.prefix.length),s=r.indexOf(e.QueryClause.THEN_BY);if(-1===s)return;const i=r.substring(s+e.QueryClause.THEN_BY.length).split(e.QueryClause.THEN_BY),o=[];for(const e of i){const t=e.match(/(OrderBy|Limit|Offset|Select)/),r=t?e.substring(0,t.index):e;r&&o.push(G(r))}return o.length>0?o:void 0}}static buildWhere(t,r){if(!t)return;const a=t.split(/OrderBy|GroupBy/)[0]||"";if(!a)return;const s=a.split(/And|Or/).filter(e=>e.length>0);if(0===s.length)return;const i=t.match(/And|Or/g)||[];let o;return s.forEach((t,a)=>{const{field:s,operator:n}=this.parseFieldAndOperator(t),c=n?Y[n]:Y.Equals;if(!c)throw Error("Unsupported operator "+n);const d=r[a];if(void 0===d)throw Error("Invalid value for field "+s);const l=c(s,d);o=0===a?l:i[a-1]===e.QueryClause.AND?o.and(l):o.or(l)}),o}static parseFieldAndOperator(e){for(const t of Object.keys(Y))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:G(r),operator:t}}return{field:G(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(t,r){const a=z.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new L("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new L(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t,r){const s=r??this.extractCore(e),i=s?s.split(/And|Or/).filter(e=>e.length>0).length:0,o=t.slice(i)??[];let n,c,d;if(o.at(-1)instanceof a.Context&&o.pop(),o.length>=1){const t=o[0],r=this.extractOrderByField(e);n=this.getProperlyOrderByOrThrow(r,t)}return 2>o.length||"number"!=typeof o[1]||(c=o[1]),3>o.length||"number"!=typeof o[2]||(d=o[2]),{orderBy:n,limit:c,offset:d}}}function H(){return n.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>n.apply(n.methodMetadata(n.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function Q(e,t,r){return(a,s)=>{const i=r?.name||((e,t,r)=>{const a=(n.Metadata.get(e.constructor,t)||{})[r]||{};return Object.keys(a).length+1+""})(a,e,s),o=n.Metadata.key(e,s,i),c={...r||{},kind:t,attribute:s};return n.propMetadata(o,c)(a,s)}}function V(e){return te(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function W(e){return te(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function J(e){return te(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function X(e){return te(e,y)}function Z(e){return te(e,Object.values(a.OperationKeys))}function ee(e){return te(e,Object.values(a.BulkCrudOperationKeys))}function te(e,t){return(r,s,o,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:d}=v.prototype.logCtx(c,te);return d.silly(`filtering ${s} event for${r?" "+(i.Model.tableName(r)||r):""} ${o}`),("string"==typeof r?r===i.Model.tableName(e)||r===e.constructor.name:n.Metadata.constr(e)===n.Metadata.constr(r))&&t.includes(s)}}const re={onlyOnCreate:V,onlyOnUpdate:W,onlyOnDelete:J,onlyOnTransactional:X,onlyOnSingle:Z,onlyOnBulk:ee};function ae(e){const t=Object.assign({},re);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var se,ie,oe,ne,ce,de,le,ue,pe,he,ge;class ye extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("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=i.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ae(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(ye.register(t,this,this.adapter.alias),e)&&n.Metadata.get(t,n.DecorationKeys.FLAVOUR)===n.DefaultFlavour&&n.uses(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(s,s[t+"Prefix"],e,s[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,a){const s=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},a||{},this._overrides||{}));function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new T}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.createPrefix),o=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${o}, validationSetting: ${n}`),e=new this.class(e),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!n){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${i.Model.tableName(this.class)}`);let{record:o,id:n,transient:c}=this.adapter.prepare(e,r);return o=await this.adapter.create(this.class,n,o,...s),this.adapter.revert(o,this.class,n,c,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${i.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r)),n=o.map(e=>e.id);let c=o.map(e=>e.record);return c=await this.adapter.createAll(this.class,n,c,...s),c.map((e,t)=>this.adapter.revert(e,this.class,n[t],r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(o.silly(`handlerSetting: ${n}, validationSetting: ${c}`),!e.length)return[e,...s];const d=i.Model.sequenceFor(e[0]);let l=[];if(i.Model.generatedBySequence(this.class)?(d.name||(d.name=i.Model.sequenceName(e[0],"pk")),l=await(await this.adapter.Sequence(d)).range(e.length,...s)):i.Model.generated(this.class,this.pk)||(l=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("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?l[t]:""+e[this.pk]),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.readPrefix),o=r.get("ignoreHandlers");i.silly("handlerSetting: "+o);const n=new this.class;return n[this.pk]=e,o||await a.enforceDBDecorators(this,r,n,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${i.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAllPrefix),o=r.get("ignoreHandlers");return i.silly("handlerSetting: "+o),o||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:o,id:n,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${i.Model.tableName(this.class)} with id ${n}`),o=await this.adapter.update(this.class,n,o,...r),this.adapter.revert(o,this.class,n,c,s)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${n}, validationSetting: ${c}`);const d=e[this.pk];if(!d)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(d,r),r.get("mergeForUpdate")&&(e=i.Model.merge(l,e,this.class))),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,l),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(l,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,l]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.verbose(`Updating ${e.length} new ${this.class.name} in table ${i.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,o.map(e=>e.id),o.map(e=>e.record),...s)).map((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${n}, ignoredValidation: ${c}`);const d=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let l;if(r.get("applyUpdateValidation")&&(l=await this.readAll(d,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>i.Model.merge(l[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,l?l[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let s;o.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(l[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s,l]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),o=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+o),!o){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${i.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAllPrefix),o=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+o),!o){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}count(e){return this.adapter.Statement(this._overrides).count(e).from(this.class)}min(e){return this.adapter.Statement(this._overrides).min(e).from(this.class)}max(e){return this.adapter.Statement(this._overrides).max(e).from(this.class)}sum(e){return this.adapter.Statement(this._overrides).sum(e).from(this.class)}avg(e){return this.adapter.Statement(this._overrides).avg(e).from(this.class)}distinct(e){return this.adapter.Statement(this._overrides).distinct(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,i,...o){const{ctxArgs:n}=(await this.logCtx(o,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],d=this.select().where(t).orderBy(c);return s&&d.limit(s),i&&d.offset(i),d.execute(...n)}async listBy(t,r,...a){const{log:s,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${i.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...o)}async paginateBy(t,r,a={offset:1,limit:10},...s){const o=a.offset||1,{offset:n,bookmark:c,limit:d}=a;if(!n&&!c)throw new L("PaginateBy needs a page or a bookmark");const{log:l,ctx:u,ctxArgs:p}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let h;if(l.verbose(`paginating ${i.Model.tableName(this.class)} with page size ${d}`),c&&u.get("paginateByBookmark"))h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>r===e.OrderDirection.ASC?this.attr(i.Model.pk(this.class)).gt(c):this.attr(i.Model.pk(this.class)).lt(c))()).orderBy([t,r]).paginate(d,...p);else{if(!n)throw new L("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(d,...p)}const g=await h.page(o,c,...p);return h.serialize(g)}async findOneBy(t,r,...s){const{log:o,ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);o.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`);const c=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...n);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,r,...a){const{log:s,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...o)}async countOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);return a.verbose(`counting ${i.Model.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return a.verbose(`finding max of ${t} in ${i.Model.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return a.verbose(`finding min of ${t} in ${i.Model.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return a.verbose(`calculating average of ${t} in ${i.Model.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return a.verbose(`calculating sum of ${t} in ${i.Model.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return a.verbose(`finding distinct values of ${t} in ${i.Model.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return a.verbose(`grouping ${i.Model.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...r){if(!ye.statements(this,t))throw new L("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}attr(e){return F.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=i.Model.tableName(this.class);return this.adapter.observe(this,(e,t,r,...s)=>"string"==typeof e?e===a:n.Metadata.constr(e)===n.Metadata.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:n}=this.logCtx(s,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>R._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,e)):R._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,r),...n)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let i;const o=r||n.Metadata.flavourOf(t)||R.currentFlavour;try{i=this.get(t,o)}catch(e){i=void 0}if(i instanceof ye)return i;const c=r||n.Metadata.flavourOf(t)||i&&n.Metadata.get(i,e.PersistenceKeys.ADAPTER)||R.currentFlavour,d=c?R.get(c):void 0;if(!d)throw new a.InternalError("No registered persistence adapter found flavour "+c);return i=i||d.repository(),new i(d,t,...s)}static get(e,t){const r=i.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=i.Model.tableName(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof ye)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof ye?t.constructor:t,s=n.Metadata.get(a,r?n.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof ye?t.constructor:t;return n.Metadata.get(a,r?n.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function fe(t,r){if(!(r||(r=n.Decoration.flavourResolver(t instanceof i.Model?t.constructor:t))&&r!==n.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof i.Model?t.constructor.name:t.name));return i.sf(e.PersistenceKeys.INJECTABLE,r,i.Model.tableName(t))}r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"listBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"paginateBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"findOneBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"findBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"countOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(se="undefined"!=typeof K&&K)?se:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"maxOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ie="undefined"!=typeof K&&K)?ie:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"minOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(oe="undefined"!=typeof K&&K)?oe:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"avgOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ne="undefined"!=typeof K&&K)?ne:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"sumOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ce="undefined"!=typeof K&&K)?ce:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"distinctOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(de="undefined"!=typeof K&&K)?de:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"groupOf",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],ye.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],ye.prototype,"unObserve",null),R&&(R._baseRepository=ye);class me extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let o;try{o=super.get(r)}catch{}if(!o){let c;if("function"==typeof r?c=i.Model.get(r.name)||r:"symbol"!=typeof r&&"string"!=typeof r||(c=i.Model.get(r.toString())),!c)return;const d=e.PersistenceKeys.ADAPTER,l=a||n.Metadata.get(c,d);try{let e=l;try{l&&R.get(l)}catch{const t=R.current;t&&t.flavour===l&&(e=t.alias)}if(o=ye.forModel(c,e),o instanceof ye)return o;const r=l||n.Metadata.get(o.constructor,d)||n.Metadata.get(c,d);t.Injectables.register(o,fe(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ye.get(c,l);if("function"==typeof t){const e=l?R.get(l):R.current;if(!e)return;return new t(e,c)}}}return o}}e.TaskStatus=void 0,(le=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",le.SCHEDULED="scheduled",le.RUNNING="running",le.FAILED="failed",le.SUCCEEDED="succeeded",le.CANCELED="canceled",le.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(ue=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",ue.FIXED="fixed",e.JitterStrategy=void 0,(pe=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",pe.FULL="full",e.TaskEventType=void 0,(he=e.TaskEventType||(e.TaskEventType={})).STATUS="status",he.LOG="log",he.PROGRESS="progress",he.ALL="all",e.TaskType=void 0,(ge=e.TaskType||(e.TaskType={})).ATOMIC="atomic",ge.COMPOSITE="composite";const _e="tasks",we={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};n.Metadata.tasks=(()=>n.Metadata.innerGet(Symbol.for(_e))).bind(n.Metadata),n.Metadata.taskFor=(e=>{const t=n.Metadata.tasks();return t?t[e]:void 0}).bind(n.Metadata),n.Metadata.validationExceptions=((t,r)=>{const s=n.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],o=Object.entries(s).filter(([,e])=>e.includes(r)).map(([e])=>e);let c=[];return r!==a.OperationKeys.CREATE&&r!==a.OperationKeys.UPDATE||(c=i.Model.nestedRelations(t)),[...new Set([...o,...c])]}).bind(n.Metadata),n.Metadata.migrationsFor=(t=>{if(!(t=t??R.current))throw new a.InternalError("Could not get adapter for migrations");return n.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(n.Metadata),n.Metadata.migrations=(()=>{const t=n.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(t).flat().map(e=>[e.class.name,e.class])}).bind(n.Metadata),n.Metadata.relations=((t,r)=>{const s=n.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(n.Metadata),i.Model.relations=(e,t)=>n.Metadata.relations(e instanceof i.Model?e.constructor:e,t)||[],i.Model.nestedRelations=((t,r=[])=>{let a=[];const s=n.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...r])];for(const e in s){const t=s[e];if(t?.class&&i.Model.relations(t.class)){const s=i.Model.relations(t.class).map(t=>`${e}.${t}`);r=[...r,...s],a=i.Model.nestedRelations(t.class,r)}}return[...new Set([...r,...a])]}).bind(i.Model),i.Model.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!i.Model.sequenceFor(r).generated}).bind(i.Model),i.Model.fromTable=(t=>{const r=n.Metadata.innerGet(Symbol.for(e.PersistenceKeys.TABLE));if(!r||!r[t]||!i.Model.get(r[t].name))throw new a.InternalError("No table metadata found for model. did you use @table()?");return i.Model.get(r[t].name)}).bind(i.Model),n.Metadata.createdBy=(t=>{const r=n.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(n.Metadata),n.Metadata.updatedBy=(t=>{const r=n.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(n.Metadata),i.Model.tableName=t=>{if(!(t instanceof i.Model?i.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return n.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof i.Model?t.constructor.name:t.name)},i.Model.columnName=(t,r)=>n.Metadata.get(t instanceof i.Model?t.constructor:t,n.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,i.Model.sequenceName=(e,...t)=>[i.Model.tableName(e),...t].join("_"),i.Model.sequenceFor=(e,t)=>{if(t)throw new x("not currently supported");const r=i.Model.pkProps(e instanceof i.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},i.Model.indexes=t=>{const r=n.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t),{})},t.Injectables.services=()=>n.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>n.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class be extends v{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`);const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function i(e){switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}}t&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:o,ctx:n}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,d,l]=a,u=await t.call(r,c,d,l,...o),p=[c,i(e),d];return n.get("observeFullResult")&&p.push(u),this.updateObservers(...p,...o).catch(t=>s.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${d}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof R))throw new x("Only Adapters can be observed by dispatch");return this.adapter=e,this.models=R.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(this.adapter!==e)throw new x("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 a.InternalError("Model must be provided for observer update");const o=e&&"string"==typeof e?e:i.Model.tableName(e),{log:n,ctxArgs:c,ctx:d}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${o}: ${r}${d.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${o}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Ee(e,t,r,a){if(e.get("allowGenerationOverride")&&void 0!==a[r])return;let{seed:s,args:i}=t;s&&"function"==typeof s&&(s=s(a,...i||[],e)),a[r]=await B.instance.generate(s)}function ve(t=!1,r,...s){"function"==typeof t&&(r=t,t=!1);const o=e.PersistenceKeys.UUID;return n.Decoration.for(o).define({decorator:(t,r,...s)=>{const o={update:t,seed:r,args:s},c=[i.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Ee,o,{priority:54})];return t&&c.push(a.onUpdate(Ee,o,{priority:54})),t||c.push(a.readonly()),n.apply(...c)},args:[t,r,...s]}).apply()}async function Se(e,t,r,s,o){const n=t.logger.for(Se);if(!s){const t=i.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=ye.forModel(t,r),n.info("Retrieved "+s.toString())}let c;if(s=o?s.override(o):s,void 0===e[i.Model.pk(s.class)])n.info(`No pk found in ${i.Model.tableName(s.class)} - creating`),c=await s.create(e,t);else{n.info(`pk found in ${i.Model.tableName(s.class)} - attempting update`);try{c=await s.update(e,t),n.info("Updated "+i.Model.tableName(s.class))}catch(r){if(!(r instanceof a.NotFoundError))throw r;n.info("update Failed - creating new "+i.Model.tableName(s.class)),c=await s.create(e,t)}n.info("After create update: "+c)}return c}async function Oe(e,t,r,s){const o=s[r];if(!o)return;if("object"!=typeof o){const t=Ne(s,r,this.adapter.alias),a=await t.read(o,e);return await De(e,s,r,o,a),void(s[r]=o)}const n="function"!=typeof t.class||t.class.name?t.class:t.class();if(!n)throw new a.InternalError("Could not find model "+t.class);const c=ye.forModel(n,this.adapter.alias),d=await c.override(this._overrides).create(o,e),l=i.Model.pk(d);await De(e,s,r,d[l],d),s[r]=d[l]}async function Te(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=Ne(s,a,this.adapter.alias),r=await e.override(this._overrides).read(o,t);return await De(t,s,a,o,r),void(s[a]=o)}const n=await Se(s[a],t,this.adapter.alias,void 0,this._overrides),c=i.Model.pk(n);await De(t,s,a,n[c],n),s[a]=n[c]}async function xe(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const n=Ne(s,a,this.adapter.alias);let c;c=o instanceof i.Model?await n.delete(s[a][n.pk],t):await n.delete(s[a],t),await De(t,s,a,c[n.pk],c)}async function ke(e,t,r,s){const o=s[r];if(!o||!o.length)return;const n=typeof o[0];if(!o.every(e=>typeof e===n))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=e.logger.for(ke),d=new Set([...o]);if("object"!==n){const t=Ne(s,r,this.adapter.alias),a=await t.readAll([...d.values()],e);for(let t=0;t<a.length;t++){const s=a[t];c.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await De(e,s,r,[...d.values()][t],a)}return s[r]=[...d],void c.info("SET ONE TO MANY IDS: "+s[r])}const l=i.Model.pk(o[0].constructor),u=new Set;for(const t of o){c.info("Creating or updating one-to-many model: "+JSON.stringify(t));const a=await Se(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(a)} under ${a[l]}`),await De(e,s,r,a[l],a),c.info("Creating or updating one-to-many model: "+JSON.stringify(t)),u.add(a[l])}s[r]=[...u]}async function Ae(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return ke.call(this,t,r,a,s)}async function Ce(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=i[s];if(!o||!o.length)return;const n=typeof o[0];if(!o.every(e=>typeof e===n))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),d="object"===n,l=d?ye.forModel(c,this.adapter.alias):Ne(i,s,this.adapter.alias),u=[...new Set([...d?o.map(e=>e[l.pk]):o]).values()];let p,h;try{p=await l.deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await De(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u}function Me(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function De(e,t,r,a,s){const i=Me(t.constructor.name,r,a),o=e.get("cacheForPopulate")||{};return o[i]=s,e.accumulate({cacheForPopulate:o})}async function Pe(e,t,r,s){if(!t.populate)return;const i=s[r],o=Array.isArray(i);if(void 0===i||o&&0===i.length)return;const n=await(async(t,r,s,i)=>{let o,n;const c=[],d=t.get("cacheForPopulate")||{};for(const t of i){o=Me(r.constructor.name,s,t);try{if(n=d[o],!n)throw Error("Not found in cache")}catch(i){const o=Ne(r,s);if(!o)throw new a.InternalError("Could not find repo");n=await o.read(t,e)}c.push(n)}return c})(e,s,r,o?i:[i]);s[r]=o?n:n[0]}async function Be(t,r,s,o,n){if(r.cascade.update!==e.Cascade.CASCADE)return;const c=o[s];if(void 0===c||Array.isArray(c)&&0===c.length)return;if(!n)throw new a.InternalError("No way to compare old model. do you have updateValidation and mergeModels enabled?");function d(e){return Array.isArray(e)?e.map(d):"object"!=typeof e?e:e[i.Model.pk(e)]}const l=d(o[s]),u=d(n[s]);if(void 0===u||i.isEqual(l,u))return;if(Array.isArray(l)!==Array.isArray(u))throw new a.InternalError("Cannot cascade update for different array types");const p=(Array.isArray(l)?l:[l]).filter(Boolean),h=(Array.isArray(u)?u:[u]).filter(Boolean).filter(e=>!p.includes(e)),g=Ne(o,s);if(!g)throw new a.InternalError("Could not find repo");try{const e=await g.deleteAll(h,t);t.logger.debug(`Deleted ${e.length} entries from table ${i.Model.tableName(g.class)} due to cascade rules with `)}catch(e){throw new a.InternalError("Error deleting cascade entries: "+e)}}R&&(R._baseDispatch=be);const Ie=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Ne(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=n.Metadata.get(e instanceof i.Model?e.constructor:e,n.Metadata.key(i.ValidationKeys.REFLECT,t,i.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("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=n.Metadata.getPropDesignTypes(e instanceof i.Model?e.constructor:e,t)?.designTypes;const o=s?.find(e=>!Ie.includes((""+e.name).toLowerCase()));return ye.forModel(o,r)}class Re extends a.BadRequestError{constructor(e,t=Re.name,r=401){super(e,t,r)}}class Le extends Re{constructor(e,t=Le.name){super(e,t,403)}}class $e extends a.InternalError{constructor(e){super(e,$e.name,503)}}function Ke(t){return n.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>(n.Metadata.set(e.PersistenceKeys.TABLE,t||r.name.toLowerCase(),r),n.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r)),args:[t]}).apply()}function Fe(t){return n.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>n.propMetadata(n.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}function je(t,r,a){return n.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,i)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(r=t,t=void 0),n.propMetadata(n.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,i),{directions:t,compositions:r,name:a})(s,i)),args:[t,r,a]}).apply()}async function Ue(e,t,r,s){if(s[r]&&(await this.select().where(F.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function qe(e,t,r,a){throw new Re("This adapter does not support user identification")}function Ye(){return n.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>n.apply(a.onCreate(qe),n.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply()}function Ge(){return n.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>n.apply(a.onUpdate(qe),n.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),args:[]}).apply()}function ze(){return a.timestamp([a.OperationKeys.CREATE])}function He(){return a.timestamp()}function Qe(e){const t="function"==typeof e&&e.name?e:e(),r=i.Model.pk(t);return n.Metadata.allowedTypes(t,r)||[]}function Ve(...t){return(r,a)=>{const s=n.Metadata.get(r,n.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],i=[...new Set([...s,...t])];return n.apply(n.metadata(n.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),i))(r,a)}}function We(t,r){return n.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(n.propMetadata(t,r)(a,s),n.propMetadata(n.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class Je extends i.Model{constructor(e){super(e)}}r.__decorate([ze(),r.__metadata("design:type",Date)],Je.prototype,"createdAt",void 0),r.__decorate([He(),r.__metadata("design:type",Date)],Je.prototype,"updatedAt",void 0);const Xe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ze=Xe,et={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},tt=Object.assign({},et,{type:"BigInt"});async function rt(e,t,r,s){if(!t.type||!t.generated||s[r])return;let o;t.name||(t.name=i.Model.sequenceName(s,"pk"));try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var n,c,d;n=s,c=r,d=await o.next(e),Reflect.set(n,c,d)}function at(t,r){return(s,o)=>{if(n.prop()(s,o),!t.type){const e=n.Metadata.type(s.constructor,o);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e}switch(t.type){case String.name||String.name.toLowerCase():case String:t.generated=void 0!==t.generated&&t.generated,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=void 0===t.generated||t.generated,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=void 0===t.generated||t.generated;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const c=[n.prop(),je([e.OrderDirection.ASC,e.OrderDirection.DSC]),i.required(),a.readonly(),n.propMetadata(n.Metadata.key(a.DBKeys.ID,o),t),a.onCreate(rt,t,r)];return t.generated&&c.push(a.generated()),n.apply(...c)(s,o)}}function st(e){const t=Object.assign({},Ze);return delete t.generated,e=Object.assign({},t,e),n.Decoration.for(a.DBKeys.ID).define({decorator:at,args:[e,{priority:60}]}).apply()}e.SequenceModel=class extends Je{constructor(e){super(e)}},r.__decorate([st({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([i.required(),je(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([Ke("??sequence"),i.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class it extends v{static{this.lock=new o.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ye.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.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 a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r){const{log:s,ctx:i}=this.adapter.logCtx([r],this.increment),{type:o,incrementBy:n,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return it.lock.execute(async()=>{const r=t||n;if(r%n!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+n);const d="function"==typeof o&&o?.name?o.name:o,l=await this.current(i),u=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),i)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${l} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===d)for(;;){const e=await Promise.resolve(B.instance.generate(l));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${l} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(d){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return await Promise.resolve(I.instance.generate(e));default:throw new a.InternalError("Should never happen")}})(l),h=await u(p);return s.debug(`Sequence.increment ${c} current=${l} next=${p}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.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.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new x(`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,o=this.parse(this.options.incrementBy),n=await this.increment(this.parse(e)*o,r);let c=[];for(let t=0;e-1>=t;t++)c.push(n-o*this.parse(t));if(c=c.reverse(),c[c.length-1]!==n&&"String"!==i)throw new a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return it.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return i.Model.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 x(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function ot(r,s){return(o,c)=>c?t.inject(n.Metadata.constr(r))(o,c):(n.Metadata.set(a.DBKeys.REPOSITORY,n.Metadata.key(s||R.currentFlavour,i.Model.tableName(r)),o),n.metadata(a.DBKeys.REPOSITORY,o.name)(r),s=s||n.Metadata.get(o.constructor,e.PersistenceKeys.ADAPTER),ye.register(r,o,s),t.injectable(n.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(o))}R._baseSequence=it;class nt extends a.InternalError{constructor(e){super(e,nt.name,500)}}class ct extends s.LoggedClass{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,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,P(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:i}=this.adapter.logCtx(!r||r instanceof E?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof E||(this._bookmark=r);const o=ye.forModel(this.clazz,this.adapter.alias),n=this.query,{method:c,args:d,params:l}=n,u=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!c.match(u))throw new x(`Method ${c} is not supported for pagination`);u.lastIndex=0;const p=c.replace(u,e.PreparedStatementKeys.PAGE_BY),h=[p,...d];let g={limit:this.size,offset:t,bookmark:this._bookmark};p!==e.PreparedStatementKeys.PAGE_BY||h.length>2?g={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(g);const y=await o.statement(...h,...i);return this.apply(y)}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 $("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new $(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new x("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 a.SerializationError(e)}}apply(e){const t="string"==typeof e?ct.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 a.SerializationError(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 dt,lt,ut,pt,ht,gt,yt;class ft extends v{constructor(e,t){super(),this.adapter=e,this.overrides=t,this._inCountMode=!1,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const o=a.get("forcePrepareSimpleQueries"),n=a.get("forcePrepareComplexQueries");i.silly(`statement force simple ${o}, forceComplex: ${n}`);const c=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(o&&(this.isSimpleQuery()||c)||n)&&(i.silly(`squashing ${n?"complex":"simple"} query to prepared statement`),await this.prepare(a),i.silly(`squashed ${n?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(ft)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!e)throw new L("distinct() requires a selector when not chained after count()");return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}sum(e){return this.sumSelector=e,this}avg(e){return this.avgSelector=e,this}count(e){return this.countSelector=e??null,this._inCountMode=!0,this}from(e){if(this.fromSelector="string"==typeof e?i.Model.get(e):e,!this.fromSelector)throw new L("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e,t){return this.orderBySelectors=[this.normalizeOrderCriterion(e,t)],this}thenBy(e,t){if(Array.isArray(e)||void 0!==t){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new L("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new L("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(e),this}normalizeOrderCriterion(e,t){if(Array.isArray(e)){const[t,r]=e;return[t,this.normalizeOrderDirection(r)]}return[e,this.normalizeOrderDirection(t)]}normalizeOrderDirection(t){if(!t)throw new L("orderBy direction is required when specifying the attribute separately.");const r=(t+"").toLowerCase();if(r===e.OrderDirection.ASC)return e.OrderDirection.ASC;if(r===e.OrderDirection.DSC)return e.OrderDirection.DSC;throw new L(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new L("groupBy must be called before orderBy.");return this.groupBySelectors=[e],this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctx:r,ctxArgs:a}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();t.silly("executing raw statement");const o=await this.raw(s,...a);if(this.hasAggregation())return o;if(!this.selectSelector){const e=i.Model.pk(this.fromSelector),t=function(t){const a=t[e];return this.adapter.revert(t,this.fromSelector,a,void 0,r)}.bind(this);return this.groupBySelectors?.length?this.revertGroupedResults(o,t):Array.isArray(o)?o.map(t):t(o)}return o}catch(e){throw new L(e)}}revertGroupedResults(e,t){return Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.entries(e).reduce((e,[r,a])=>(e[r]=this.revertGroupedResults(a,t),e),{}):e}async executePrepared(...e){const t=ye.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new x("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(this.hasAggregation())return s;if(!this.selectSelector)return s;const o=i.Model.pk(this.fromSelector),n=function(e){const t=e[o];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(s)?s.map(n):n(s)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:i}=t;const o={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=i;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,o.args=[...o.args||[],...t.args||[]]}if(i instanceof F){const e=this.prepareCondition(i,r);t=e.method,o.args=[...o.args||[],...e.args||[]]}o.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:o.method=a,o.args=[...o.args||[],i];break;case e.Operator.DIFFERENT:o.method=a+" diff",o.args=[...o.args||[],i];break;case e.Operator.REGEXP:o.method=a+" matches",o.args=[...o.args||[],i];break;case e.Operator.BIGGER:o.method=a+" bigger",o.args=[...o.args||[],i];break;case e.Operator.BIGGER_EQ:o.method=a+" bigger than equal";break;case e.Operator.SMALLER:o.method=a+" less",o.args=[...o.args||[],i];break;case e.Operator.SMALLER_EQ:o.method=a+" less than equal",o.args=[...o.args||[],i];break;case e.Operator.IN:o.method=a+" in",o.args=[...o.args||[],i];break;default:throw new L("Unsupported operator "+s)}return o}squash(t){if(this.whereCondition&&this.whereCondition.comparison instanceof F)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:e.PreparedStatementKeys.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let r;this.whereCondition&&(r=this.whereCondition.attr1);const a=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,e.OrderDirection.DSC]:[i.Model.pk(this.fromSelector),e.OrderDirection.DSC],[s,o]=a,n={direction:o};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const c={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[s],params:n};return r&&(c.method=e.PreparedStatementKeys.FIND_BY,c.args=[r,this.whereCondition.comparison],c.params=n),c}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},i={class:this.fromSelector,args:r,params:a};let o,n=e.QueryClause.FIND_BY;void 0!==this.countSelector?(n=e.QueryClause.COUNT_BY,o=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=e.QueryClause.SUM_BY,o=this.sumSelector):this.avgSelector?(n=e.QueryClause.AVG_BY,o=this.avgSelector):this.minSelector?(n=e.QueryClause.MIN_BY,o=this.minSelector):this.maxSelector?(n=e.QueryClause.MAX_BY,o=this.maxSelector):this.distinctSelector?(n=e.QueryClause.DISTINCT_BY,o=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=e.QueryClause.GROUP_BY_PREFIX,o=this.groupBySelectors[0]);const c=[n];if(o&&c.push(o),this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);c.push(e.method),e.args&&e.args.length&&r.push(...e.args)}if(this.selectSelector&&c.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...r]=this.orderBySelectors;c.push(e.QueryClause.ORDER_BY,t[0]),a.direction=t[1],r.length&&(a.order=this.orderBySelectors.map(([e,t])=>[e,t]),r.forEach(([t])=>{c.push(e.QueryClause.THEN_BY,t)}))}if(this.groupBySelectors?.length&&n!==e.QueryClause.GROUP_BY_PREFIX){const[t,...r]=this.groupBySelectors;c.push(e.QueryClause.GROUP_BY,t),r.forEach(t=>c.push(e.QueryClause.THEN_BY,t))}else this.groupBySelectors?.length&&n===e.QueryClause.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>c.push(e.QueryClause.THEN_BY,t));return this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),i.method=s.toCamelCase(c.join(" ")),i.params=a,this.prepared=i,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelectors&&this.groupBySelectors.length||void 0!==this.countSelector||this.countDistinctSelector||this.maxSelector||this.minSelector||this.sumSelector||this.avgSelector||this.distinctSelector)}hasAggregation(){return void 0!==this.countSelector||void 0!==this.countDistinctSelector||void 0!==this.maxSelector||void 0!==this.minSelector||void 0!==this.sumSelector||void 0!==this.avgSelector||void 0!==this.distinctSelector||(this.groupBySelectors?.length||0)>0}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new L(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],ft.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(dt="undefined"!=typeof S&&S)?dt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(lt="undefined"!=typeof S&&S)?lt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ut="undefined"!=typeof S&&S)?ut:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(pt="undefined"!=typeof S&&S)?pt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"sum",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ht="undefined"!=typeof S&&S)?ht:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"avg",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(gt="undefined"!=typeof S&&S)?gt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],ft.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[F]),r.__metadata("design:returntype",Object)],ft.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],ft.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],ft.prototype,"thenBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(yt="undefined"!=typeof Key&&Key)?yt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],ft.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],ft.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],ft.prototype,"execute",null);class mt extends v{constructor(e){super(),this.name=e,this.observers=[],this.Context=E}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new T,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString())),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:o}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...o)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${B.instance.generate()}`;const a=t.logger||s.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},h,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof E||(r.push(a),a=void 0),t=a?Object.assign({},a.toOverrides(),t):t;const s=await this.flags("string"==typeof e?e:e.name,t,...[...r,a].filter(Boolean));if(a){if(!(a instanceof this.Context)){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}if(a.get("operation")!==e){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}return a.accumulate(s)}return(new this.Context).accumulate({...s})}logCtx(e,t,r=!1,a){return v.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const r=C(e),s=t.Injectables.get(r);if(s)return s;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...r){let s=r.pop();void 0===s||s instanceof E||(r.push(s),s=void 0);const i=await mt.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new E(s).accumulate({...i,parentContext:s}):(new E).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=mt.prototype.logCtx(r,this.boot),c=t.Injectables.services();for(const[e,r]of Object.entries(c))try{o.verbose(`Booting ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);s instanceof _t&&(o.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new a.InternalError(`Failed to boot ${e} service:${t}`)}}static async shutdown(...r){let s=r.pop();void 0===s||s instanceof E||(r.push(s),s=void 0);const i=await mt.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...r);s=s?new E(s).accumulate({...i,parentContext:s}):(new E).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=mt.prototype.logCtx(r,this.shutdown),c=t.Injectables.services();for(const[e,r]of Object.entries(c).reverse())try{o.verbose(`Shutting down ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);if(s instanceof _t){o.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(e){o.error(`Failed to gracefully shutdown ${r.name} service`,e)}}}catch(t){throw new a.InternalError(`Failed to Shutdown services ${e}: ${t}`)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],mt.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],mt.prototype,"unObserve",null);class _t extends mt{constructor(){super()}async boot(...t){const{log:r,ctxArgs:a}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.boot);r.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...a);this._config=s,this._client=i}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("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 wt(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&D(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],_t.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],_t.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],_t.prototype,"client",null);const bt=()=>wt(a.OperationKeys.CREATE),Et=()=>wt(a.OperationKeys.READ),vt=()=>wt(a.OperationKeys.UPDATE),St=()=>wt(a.OperationKeys.DELETE);function Ot(r){return(a,s,i)=>{i||s?(n.prop()(a,s),r=r||n.Metadata.type(a.constructor,s)):r=r||a,r=C(r);const o=[];if(i&&"number"==typeof i.value)o.push(t.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");o.push(t.inject(r))}else n.Metadata.set(e.PersistenceKeys.SERVICE,r,a),o.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return n.apply(...o)(a,s,i)}}const Tt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class xt extends mt{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ye.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=Tt(e);try{const e=mt.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"repo"===a?r.repo.for(e,...t):Reflect.get(r,a,s)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let a;t=Tt(t||e);try{a=xt.get(t)}catch(e){a=void 0}if(a instanceof xt)return a;const s=this;let i=class extends s{constructor(){super(e)}};return i=r.__decorate([Ot(t),r.__metadata("design:paramtypes",[])],i),new i}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"create",null),r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"createAll",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"delete",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"deleteAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"read",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"readAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],xt.prototype,"query",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"update",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],xt.prototype,"updateAll",null),e.TaskBackoffModel=class extends i.Model{constructor(t){super(t),this.strategy=e.BackoffStrategy.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=e.JitterStrategy.FULL}},r.__decorate([i.required(),i.type(String),i.option(e.BackoffStrategy),n.description("the backoff strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),r.__decorate([i.required(),n.description("base interval between attempts"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),r.__decorate([i.required(),n.description("max interval"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),r.__decorate([i.type(String),i.option(e.JitterStrategy),n.description("optional jitter strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"jitter",void 0),e.TaskBackoffModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskBackoffModel),e.TaskErrorModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),n.description("The error message"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),r.__decorate([n.prop(),n.description("The error stack"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),r.__decorate([n.prop(),n.description("The error code"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),r.__decorate([n.prop(),n.description("The error details"),r.__metadata("design:type",Object)],e.TaskErrorModel.prototype,"details",void 0),e.TaskErrorModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskErrorModel),e.TaskEventModel=class extends i.Model{constructor(e){super(e),this.ts=new Date}},r.__decorate([a.composed(["taskId","classification","uuid"],":"),st(),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),r.__decorate([a.readonly(),i.required(),a.transient(),ve(!1),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"uuid",void 0),r.__decorate([a.readonly(),i.required(),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"taskId",void 0),r.__decorate([i.date(),i.required(),r.__metadata("design:type",Date)],e.TaskEventModel.prototype,"ts",void 0),r.__decorate([a.readonly(),i.required(),i.option(e.TaskEventType),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"classification",void 0),r.__decorate([n.prop(),a.readonly(),r.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=r.__decorate([Ke("task_event"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class kt extends i.JSONSerializer{constructor(){super()}preSerialize(e,...t){if(null===e||"object"!=typeof e)return e;const r=Object.assign({},e);if(e instanceof F)return r[i.ModelKeys.ANCHOR]="??condition",r;if(i.Model.isModel(e)){let t;try{t=n.Metadata.modelName(e.constructor)}catch(e){t=void 0}t&&(r[i.ModelKeys.ANCHOR]=t)}return r}deserialize(e,...t){const r=JSON.parse(e),a=r[i.ModelKeys.ANCHOR];return a?"??condition"===a?F.from(r):i.Model.build(r,a):r}serialize(e,...t){return JSON.stringify(this.preSerialize(e))}}e.TaskLogEntryModel=class extends i.Model{constructor(e){super(e),this.ts=new Date}},r.__decorate([i.date(),i.required(),r.__metadata("design:type",Date)],e.TaskLogEntryModel.prototype,"ts",void 0),r.__decorate([i.required(),i.option(s.LogLevel),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"level",void 0),r.__decorate([i.required(),n.prop(),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),r.__decorate([n.prop(),r.__metadata("design:type",Object)],e.TaskLogEntryModel.prototype,"meta",void 0),e.TaskLogEntryModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskLogEntryModel),e.TaskModel=class extends i.Model{constructor(t){super(t),this.atomicity=e.TaskType.ATOMIC,this.status=e.TaskStatus.PENDING,this.attempt=0,this.logTail=[]}},r.__decorate([st({type:"uuid"}),n.description("the task id"),r.__metadata("design:type",String)],e.TaskModel.prototype,"id",void 0),r.__decorate([i.required(),i.type(String),i.option(e.TaskType),n.description("defines a single or composite task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),r.__decorate([i.required(),n.description("Holds task classification - must match @task()"),r.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),r.__decorate([i.required(),i.type(String),i.option(e.TaskStatus),n.description("Holds the task current status"),r.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),r.__decorate([n.prop(),a.serialize(kt),n.description("Holds task input"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),r.__decorate([n.prop(),a.serialize(kt),n.description("Holds the task output when successfully completed"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the error for failed tasks"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskModel.prototype,"error",void 0),r.__decorate([i.required(),i.min(0),n.description("Holds the current attempt"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),r.__decorate([i.min(1),i.required(),n.description("max attempts for the task"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),r.__decorate([i.required(),a.serialize(),n.description("backoff configuration"),r.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),r.__decorate([i.date(),n.description("Next execution timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),r.__decorate([i.date(),n.description("Task scheduled timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),r.__decorate([n.prop(),n.description("Task lease owner identifier"),r.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),r.__decorate([i.date(),n.description("Task lease expiration timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the various steps definition and inputs - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"steps",void 0),r.__decorate([i.min(0),n.prop(),n.description("Holds the current step - only for type === 'composite'"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the step results - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the task log entries"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),r.__decorate([Fe(),ze(),n.description("timestamp of creation"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),r.__decorate([Fe(),He(),n.description("timestamp of last update"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),r.__decorate([Fe(),Ye(),n.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),r.__decorate([Fe(),Ge(),n.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=r.__decorate([n.description("Holds the current step when applicable"),Ke("tasks"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),n.description("The status of a step"),r.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),r.__decorate([n.prop(),n.description("The result of a successful step"),r.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),r.__decorate([n.prop(),n.description("the error of a failed step"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskStepResultModel.prototype,"error",void 0),e.TaskStepResultModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepResultModel),e.TaskStepSpecModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),n.prop(),n.description("task handler type"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),r.__decorate([n.description("optional task step input"),n.prop(),r.__metadata("design:type",Object)],e.TaskStepSpecModel.prototype,"input",void 0),e.TaskStepSpecModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepSpecModel);class At extends i.Model{constructor(t){super(t),this.baseMs=1e3,this.jitter=e.JitterStrategy.FULL,this.maxMs=6e4,this.strategy=e.BackoffStrategy.EXPONENTIAL,i.Model.fromModel(this,t)}setBaseMs(e){return this.baseMs=e,this}setJitter(e){return this.jitter=e,this}setMaxMs(e){return this.maxMs=e,this}setStrategy(e){return this.strategy=e,this}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskBackoffModel(this)}}r.__decorate([i.required(),i.min(1e3),r.__metadata("design:type",Number)],At.prototype,"baseMs",void 0),r.__decorate([i.required(),i.option(e.JitterStrategy),r.__metadata("design:type",String)],At.prototype,"jitter",void 0),r.__decorate([i.gt("baseMs"),i.min(1e3),i.required(),r.__metadata("design:type",Number)],At.prototype,"maxMs",void 0),r.__decorate([i.required(),i.option(e.BackoffStrategy),r.__metadata("design:type",String)],At.prototype,"strategy",void 0);class Ct extends i.Model{setClassification(e){return this.classification=e,this}setStatus(e){return this.status=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new At,r=this;return t.build=new Proxy(t.build,{apply:(e,t,a)=>(r.backoff=Reflect.apply(e,t,a),r)}),t}setInput(e){return this.input=e,this}setMaxAttempts(e){return this.maxAttempts=e,this}constructor(t){super(t),this.status=e.TaskStatus.PENDING,this.atomicity=e.TaskType.ATOMIC,this.backoff=new e.TaskBackoffModel,this.maxAttempts=1,i.Model.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskModel(this)}}r.__decorate([i.required(),r.__metadata("design:type",String)],Ct.prototype,"classification",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Ct.prototype,"status",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Ct.prototype,"atomicity",void 0),r.__decorate([i.required(),r.__metadata("design:type",e.TaskBackoffModel)],Ct.prototype,"backoff",void 0),r.__decorate([n.prop(),r.__metadata("design:type",Object)],Ct.prototype,"input",void 0),r.__decorate([i.min(1),i.required(),r.__metadata("design:type",Number)],Ct.prototype,"maxAttempts",void 0);class Mt extends Ct{constructor(t){super(t),this.stepResults=[],i.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setSteps(e){return this.steps=e,this}addStep(t,r){this.steps=this.steps||[];const a=new Date;return this.steps.push(new e.TaskStepSpecModel({classification:t,input:r,createdAt:a,updatedAt:a})),this}}r.__decorate([i.list(()=>e.TaskStepSpecModel),r.__metadata("design:type",Array)],Mt.prototype,"steps",void 0);class Dt extends O{get type(){if(!this._type){const e=n.Metadata.get(this.constructor,_e);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new a.InternalError("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),a.wrapMethodWithContext(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(e,...t){const{log:r,ctx:a,ctxArgs:s}=this.logCtx(t,this.runPrefix);return r.info(`Running task ${a.taskId} attempt ${a.attempt}`),[e,...s]}runSuffix(e,t){const{log:r}=this.logCtx([t],this.runPrefix);return r.info(`Concluded task ${t.taskId} attempt ${t.attempt}`),e}}function Pt(e){return n.Decoration.for(_e).define({decorator:e=>t=>{const r={type:e};return n.Metadata.set(_e,e,t),n.metadata(_e,r)(t)},args:[e]}).apply()}e.CleanUpTask=class extends Dt{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof F)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=F.attr("status").eq(e.TaskStatus.SUCCEEDED).and(F.attr("updatedAt").lte(t.successfulExpiry)),i=F.attr("status").eq(e.TaskStatus.FAILED).and(F.attr("updatedAt").lte(t.failedExpiry)),o=F.attr("status").eq(e.TaskStatus.CANCELED).and(F.attr("updatedAt").lte(t.cancelledExpiry));s=r.or(i).or(o)}a.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(r);if(0===i.length)return a.info("No tasks found for cleanup"),[];a.info(`Found ${i.length} tasks to delete`);const o=await this.tasks.deleteAll(i.map(e=>e.id),r);return a.info(`Successfully deleted ${o.length} tasks`),a.debug("deleted tasks:",o),o}catch(e){throw a.error("Error during task cleanup",e),e}}},r.__decorate([ot(e.TaskModel),r.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=r.__decorate([Pt("cleanup-task"),r.__metadata("design:paramtypes",[])],e.CleanUpTask);class Bt{constructor(e,t=150,r=300,a){this.logger=e,this.bufferSize=t,this.maxBufferSize=r,this.pipe=a,this.history=[],this.root=this.logger.root,Object.values(s.LogLevel).forEach(e=>{this[e]=new Proxy(this[e],{apply:(t,r,a)=>{t.apply(r,a),r.push(e,...a)}})})}push(e,t,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([e,t,r])}flush(e){const t=this.history;return this.history=[],e&&t.length?e(t).catch(e=>this.logger.error("Failed to pipe logs",e)).finally(()=>this.history=[]):(this.history=[],t)}benchmark(e){return this.logger.benchmark(e)}clear(){return this.logger=this.logger.clear(),this}debug(e,t){this.logger.debug(e,t)}error(e,t,r){this.logger.error(e,t,r)}for(e,...t){return new Proxy(this,{get:(r,a)=>"logger"===a?Reflect.get(r,a).for(e,...t):Reflect.get(r,a)})}info(e,t){this.logger.info(e,t)}setConfig(e){this.logger.setConfig(e)}silly(e,t){this.logger.silly(e,t)}trace(e,t){this.logger.trace(e,t)}verbose(e,t,r){this.logger.verbose(e,t,r)}warn(e,t){this.logger.warn(e,t)}}function It(t,r={logProgress:!0,logStatus:!0,style:!0}){return async i=>{switch(t=t.for(i.taskId,{style:!1,timestamp:!1,logLevel:!1}),i.classification){case e.TaskEventType.LOG:{const e=i.payload;for(let[a,i,o]of e){r.style||(i=s.style(i),i=i.clear().toString());const e=[i];a===s.LogLevel.verbose&&e.push(1),e.push(o);try{t[a](...e)}catch(e){t.error("Failed to pipe task logs",e)}}break}case e.TaskEventType.PROGRESS:if(r.logProgress){const{currentStep:e,totalSteps:r}=i.payload;t.info(`### STEP ${e}/${r}`)}break;case e.TaskEventType.STATUS:if(r.logStatus){const r=i.payload?.status??i.payload;let o=s.style(r);switch(r){case e.TaskStatus.SUCCEEDED:o=o.green.bold;break;case e.TaskStatus.RUNNING:o=o.blue.bold;break;case e.TaskStatus.PENDING:o=o.yellow;break;case e.TaskStatus.WAITING_RETRY:o=o.yellow.bold;break;case e.TaskStatus.FAILED:o=o.red.bold;break;case e.TaskStatus.CANCELED:o=o.magenta.bold;break;case e.TaskStatus.SCHEDULED:o=o.cyan;break;default:throw new a.InternalError("Received unknown task status: "+i.payload)}t.info("### STATUS "+o)}break;default:throw new a.InternalError("Unknown task event classification: "+i.classification)}}}function Nt(t,r){const a=r.strategy===e.BackoffStrategy.FIXED?r.baseMs:r.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(a,r.maxMs);return r.jitter===e.JitterStrategy.FULL?Math.floor(Math.random()*s):s}function Rt(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Lt(e){return new Promise(t=>setTimeout(t,e))}class $t extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=$t.name,Object.setPrototypeOf(this,$t.prototype)}}class Kt extends E{get taskId(){return this.get("taskId")}get logger(){return super.logger}get pipe(){return this.get("pipe")}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(e,t){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[e]=t,this.cache.put("resultCache",r)}changeState(e,t){throw new $t({status:e,...t})}cancel(t,r){this.changeState(e.TaskStatus.CANCELED,{error:this.toTaskError(t,r)})}retry(t){this.changeState(e.TaskStatus.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,r){const a=t instanceof Date?t:t.build();this.changeState(e.TaskStatus.SCHEDULED,{error:this.toTaskError(r),scheduledTo:a})}toTaskError(t,r){if(t||r)return t instanceof e.TaskErrorModel?t:t instanceof Error?Rt(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}constructor(e){super(e)}}class Ft{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=n.Metadata.tasks();e&&Object.entries(e).forEach(([e,t])=>{let r;try{r=new t}catch(t){throw new a.InternalError(`Failed to initialize handler with key ${e}: ${t}`)}this.register(r)})}register(e){if(this.handlers.has(e.type))throw new a.InternalError("Duplicate task handler: "+e.type);this.handlers.set(e.type,e)}get(e){return this.handlers.get(e)}}class jt extends T{constructor(){super(...arguments),this.listeners=new Set}observe(e,t){return super.observe(e,t)}unObserve(e){super.unObserve(e)}emit(t,r){this.updateObservers(e.TaskEventModel,t.classification,t.id,t,r)}async updateObservers(e,t,r,a,...s){const{log:i,ctxArgs:o}=R.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(a=>{const{filter:s}=a;if(!s)return!0;try{return s(e,t,r,...o)}catch(e){return i.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(e=>{e.observer.refresh(a,...o)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class Ut extends a.BaseError{constructor(e,t,r,a,s,i=500){super(e,r,i),this.taskId=t,this.details=a,this.meta=s}}class qt extends Ut{constructor(e,t,r){super(qt.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class Yt extends Ut{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(Yt.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class Gt extends Ut{constructor(e,t,r){super(Gt.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class zt extends Ut{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(zt.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class Ht{constructor(t,r){this.bus=t,this.task=r,this.resolved=!1,this.unregistration=t.observe(this,(t,r,a,...s)=>a.startsWith(this.task.id)&&(t===e.TaskEventModel||t===i.Model.tableName(e.TaskEventModel))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED,e.TaskStatus.WAITING_RETRY,e.TaskStatus.SCHEDULED])}wait(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED])}attach(e,t={logProgress:!0,logStatus:!0,style:!0}){this.pipe(It(e,t))}logs(t){this.pipe(async r=>{if(r.classification!==e.TaskEventType.LOG)return;const a=r.payload;await t(a)},e.TaskEventType.LOG)}pipe(t,r=e.TaskEventType.ALL){this.pipes=this.pipes||{},this.pipes[r]=this.pipes[r]||new Set,this.pipes[r].add(t)}succeed(e){this.complete()}fail(e){this.complete()}cancel(e){e.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(e.TaskStatus.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(e.TaskStatus.FAILED,t)}onCancel(t){return this.registerStatusHandler(e.TaskStatus.CANCELED,t)}awaitStatusTerminal(t){return new Promise((r,a)=>{const s=[];let i=!1;const o=async t=>{if(!i){(()=>{if(!i){i=!0;for(const e of s)e()}})();try{t.payload?.status===e.TaskStatus.SUCCEEDED?r(this.extractOutput(t)):a(this.extractError(t))}catch(e){a(e)}}};t.forEach(e=>{const t=this.registerStatusHandler(e,o);s.push(t)})})}extractOutput(e){return void 0!==e.payload?.output?e.payload.output:this.task.output}extractError(e){const t=e.payload?.status??this.task.status,r=this.buildMeta(t,e.payload);return this.createTaskControlError(t,e.payload?.error??this.task.error,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.CANCELED,e.TaskStatus.FAILED].includes(t)}async track(t,r){if(!t.payload)return;const a=t.payload.status;this.task.status=a,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),a!==e.TaskStatus.SUCCEEDED?(a===e.TaskStatus.FAILED&&this.fail(),a===e.TaskStatus.CANCELED&&this.cancel(t),a===e.TaskStatus.WAITING_RETRY&&this.retry(),a===e.TaskStatus.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,r){const a=async(e,a)=>{e.payload?.status===t&&await r(e,a)};if(this.pipe(a,e.TaskEventType.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);a(e,this.getTerminalContext())}return()=>{this.pipes?.[e.TaskEventType.STATUS]?.delete(a)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new E),this.terminalContext}buildTerminalEvent(t){const r={status:t};return t===e.TaskStatus.SUCCEEDED&&(r.output=this.task.output),t!==e.TaskStatus.FAILED&&t!==e.TaskStatus.CANCELED||!this.task.error||(r.error=this.task.error),this.task.nextRunAt&&(r.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(r.scheduledTo=this.task.scheduledTo),new e.TaskEventModel({classification:e.TaskEventType.STATUS,taskId:this.task.id,payload:r})}createTaskControlError(t,r,a){switch(t){case e.TaskStatus.FAILED:return new qt(this.task.id,r,a);case e.TaskStatus.CANCELED:return new Gt(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new Yt(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new zt(this.task.id,r,a);default:return new qt(this.task.id,r,a)}}buildMeta(e,t){const r={};if(t?.nextRunAt&&(r.nextRunAt=t.nextRunAt),t?.scheduledTo&&(r.scheduledTo=t.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===e.TaskStatus.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,r){if(!this.pipes)return;const a=this.pipes[e.TaskEventType.ALL]?[...this.pipes[e.TaskEventType.ALL].values()]:[];a.push(...this.pipes[t.classification]?.values()||[]);for(const e of a)try{await e(t,r)}catch(a){r.logger.error(`Failed to trigger pipe ${e.name} for event ${t.classification}. discarding event`,a)}}}class Qt extends O{get Context(){return Kt}get adapter(){return this.config.adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=ye.forModel(e.TaskModel,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=ye.forModel(e.TaskEventModel,this.config.adapter.alias)),this._events}constructor(e){super(),this.config=e,this.lock=new o.Lock,this.running=!1,this.config=Object.assign({},we,e,{bus:e.bus||new jt,registry:e.registry||new Ft})}async push(e,t=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push);i.verbose("pushing task "+e.classification);const o=await this.tasks.create(e,s);return i.info(`${e.classification} task registered under ${o.id}`),t?{task:o,tracker:new Ht(this.bus,o)}:o}schedule(t,r=!1,...a){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=e.TaskStatus.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,r,...a)}}}async track(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.track);s.verbose("tracking task "+e);let i=await this.tasks.read(e,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${e}`),{task:i,tracker:new Ht(this.bus,i)}}async ensureTaskError(t,r){if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t.status)||t.error)return t;let a=t;for(let e=0;6>e;e+=1){await Lt(20);try{const e=await this.tasks.read(a.id,r);if(e.error)return e;a=e}catch{break}}return a}async cancel(t,...r){const{ctx:a}=(await this.logCtx(r,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,a);if(s.status===e.TaskStatus.SUCCEEDED||s.status===e.TaskStatus.FAILED)return s;s.status=e.TaskStatus.CANCELED;const i=new e.TaskErrorModel({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const o=await this.tasks.update(s,a);return await this.emitStatus(a,o,e.TaskStatus.CANCELED,i),o}async isRunning(){await this.lock.acquire();const e=this.running;return this.lock.release(),e}async start(...e){const{ctx:t}=(await this.logCtx(e,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.loop(t))}async stop(...t){const{ctx:r,log:a}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||a.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(F.attr("status").eq(e.TaskStatus.RUNNING)).execute(r),i=r.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((e,t)=>{const o=setTimeout(()=>{a.error(`Graceful shutdown interrupted after ${i} ms...`),e()},i);Promise.allSettled(s.map(({id:e})=>new Promise((t,a)=>{this.track(e,r).then(({tracker:e})=>{e.resolve().then(t)}).catch(a)}))).then(t=>{clearTimeout(o),a.info(`Graceful shutdown completed before expiry. concluded ${t.length} tasks`),e()}).catch(e=>{clearTimeout(o),t(e)})})}async loop(...e){const{ctx:t}=this.logCtx(e,this.loop);for(;await this.isRunning();){const e=await this.claimBatch(t);await Promise.allSettled(e.map(e=>this.executeClaimed(e))),await Lt(e.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=t.timestamp,s=F.attribute("status").eq(e.TaskStatus.PENDING),i=F.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(F.attribute("nextRunAt").lte(a)),o=F.attribute("status").eq(e.TaskStatus.RUNNING).and(F.attribute("leaseExpiry").lte(a)),n=F.attribute("status").eq(e.TaskStatus.SCHEDULED).and(F.attribute("scheduledTo").lte(a)),c=s.or(i).or(o).or(n),d=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+d.length);const l=[];for(const e of d){const r=await this.tryClaim(e,t);if(r&&l.push(r),l.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+l.length),l}async tryClaim(t,r){const a=r.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,r)}catch{}const o=new e.TaskModel({...i,status:e.TaskStatus.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});a.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(o,r)}catch{return null}}async executeClaimed(t){const{ctx:r,log:i}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),o=new Kt(r).accumulate({taskId:t.id,logger:new Bt(i,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{},pipe:async e=>{const[,r]=await this.appendLog(o,t,e);await this.emitLog(o,t.id,r)},flush:async()=>o.logger.flush(o.pipe),progress:async e=>{await this.emitProgress(o,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});await this.emitStatus(o,t,e.TaskStatus.RUNNING);try{let r;if(t.atomicity===e.TaskType.COMPOSITE){r=await this.runComposite(t,o);try{t=await this.tasks.read(t.id,o)}catch{}r?.stepResults&&(t.stepResults=r.stepResults,t.currentStep=r.stepResults.length)}else{const e=this.registry.get(t.classification);if(i.debug(`handler type for ${t.id} is ${e?.constructor?.name??"none"}`),!e)throw new a.InternalError("No task handler registered for type: "+t.classification);r=await e.run(t.input,o),i.verbose("handler finished for "+t.id)}t.status=e.TaskStatus.SUCCEEDED,t.output=r,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,o),o.logger.info(`task ${t.id} success state ${t.status}`),i.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(o,t,e.TaskStatus.SUCCEEDED,r)}catch(r){try{t=await this.tasks.read(t.id,o)}catch{}if(r instanceof $t)return void await this.handleTaskStateChange(r.request,t,o);if(i.error("task execution error",r),t.atomicity===e.TaskType.COMPOSITE){const r=this.normalizeStepResults(t.stepResults);if(t.stepResults=r,null==t.currentStep){const a=r.findIndex(t=>t.status===e.TaskStatus.FAILED);0>a||(t.currentStep=a)}}const a=(t.attempt??0)+1,n=Rt(r);if(a<t.maxAttempts){const r=Nt(a,this.normalizeBackoff(t.backoff)),c=new Date(Date.now()+r);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=c,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,o),i.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await this.emitStatus(o,t,e.TaskStatus.WAITING_RETRY),await o.pipe(s.LogLevel.warn,"Retry scheduled",{nextRunAt:c,delayMs:r,attempt:a})}else t.attempt=a,t.status=e.TaskStatus.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,o),i.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await this.emitStatus(o,t,e.TaskStatus.FAILED,n),await o.pipe(s.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts})}}async handleTaskStateChange(t,r,i){switch(r.leaseOwner=void 0,r.leaseExpiry=void 0,t.status){case e.TaskStatus.CANCELED:{const a=t.error??new e.TaskErrorModel({message:`Task ${r.id} canceled`});return r.status=e.TaskStatus.CANCELED,r.error=a,r.nextRunAt=void 0,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.CANCELED,a),void await i.pipe(s.LogLevel.warn,"Task canceled via context")}case e.TaskStatus.WAITING_RETRY:{const a=(r.attempt??0)+1,o=Nt(a,this.normalizeBackoff(r.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+o),c=t.error??new e.TaskErrorModel({message:`Task ${r.id} requested retry`});return r.status=e.TaskStatus.WAITING_RETRY,r.attempt=a,r.error=c,r.nextRunAt=n,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.WAITING_RETRY,c),void await i.pipe(s.LogLevel.warn,"Retry requested",{nextRunAt:n,delayMs:o,attempt:a})}case e.TaskStatus.SCHEDULED:{if(!t.scheduledTo)throw new a.InternalError("Scheduled state requires a target date");const o=t.error??new e.TaskErrorModel({message:`Task ${r.id} rescheduled`});return r.status=e.TaskStatus.SCHEDULED,r.scheduledTo=t.scheduledTo,r.error=o,r.nextRunAt=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.SCHEDULED,o),void await i.pipe(s.LogLevel.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new a.InternalError("Unsupported task state change requested: "+t.status)}}async runComposite(t,r){const{ctx:a}=(await this.logCtx([r],t.classification,!0)).for(this.runComposite),i=this.normalizeSteps(t.steps);let o=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),c=(e,t)=>{r.cacheResult(e,t),a instanceof Kt&&a!==r&&a.cacheResult(e,t)};for(let r=0;r<n.length;r+=1){const a=n[r];if(a?.status===e.TaskStatus.SUCCEEDED){const e=i[r];if(!e)continue;const s=`${t.id}:step:${r}`;c(e.classification,a.output),c(s,a.output)}}for(;o<i.length;){const a=i[o],d=this.registry.get(a.classification);if(!d)throw Error("No task handler registered for composite step: "+a.classification);await r.pipe([s.LogLevel.info,`Composite step ${o+1}/${i.length}: ${a.classification}`]);try{const s=await d.run(a.input,r),l=o,u=new Date;n[l]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:s,createdAt:u,updatedAt:u});const p=`${t.id}:step:${l}`;c(a.classification,s),c(p,s),o=l+1,t.stepResults=n,t.currentStep=o,t=await this.tasks.update(t),await this.emitProgress(r,t.id,{currentStep:o,totalSteps:i.length,output:s})}catch(r){const a=new Date;throw n[o]=new e.TaskStepResultModel({status:e.TaskStatus.FAILED,error:Rt(r),createdAt:a,updatedAt:a}),t.stepResults=n,t.currentStep=o,t.error=Rt(r),t=await this.tasks.update(t),r}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof e.TaskBackoffModel)return t;let r=t??{};if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskBackoffModel(r)}normalizeSteps(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepSpecModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepSpecModel(r)}):[]}normalizeStepResults(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepResultModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepResultModel(r)}):[]}async appendLog(t,r,a){const s=(Array.isArray(a)&&Array.isArray(a[0])?a:[a]).map(([t,r,a])=>new e.TaskLogEntryModel({level:t,msg:r,meta:a})),i=[...r.logTail??[],...s].slice(-this.config.logTailMax);r.logTail=i;try{return[await this.tasks.update(r,t),s]}catch{return[r,[]]}}async emitStatus(t,r,a,s){t instanceof Kt&&await t.flush();const i={status:a};s&&s instanceof e.TaskErrorModel?i.error=s:s&&(i.output=s),r.nextRunAt&&(i.nextRunAt=r.nextRunAt),r.scheduledTo&&(i.scheduledTo=r.scheduledTo);const o=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,i);this.bus.emit(o,t)}async emitLog(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.LOG,a.map(e=>({ts:e.ts,level:e.level,msg:e.msg,meta:e.meta})));this.bus.emit(s,t)}async emitProgress(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.PROGRESS,a);this.bus.emit(s,t)}async persistEvent(t,r,a,s){const i=new e.TaskEventModel({taskId:r,classification:a,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,r,...a){return this.adapter.context(t,r,e.TaskModel,...a)}}class Vt extends _t{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||r instanceof E)throw new a.InternalError("No/invalid config provided");const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);if(!r.adapter)throw new a.InternalError("No adapter provided");s.info("Initializing Task Engine...");const i=new Qt(r);return s.verbose(i+" initialized"),{client:i,config:r}}async push(e,t=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push),i=await this.client.push(e,t,...s);return await this.client.isRunning()||this.client.start(),i}async track(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.push);return this.client.track(e,...r)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create),s=await this.repo.create(e,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll),s=await this.repo.createAll(e,...r);return await this.client.isRunning()||this.client.start(),s}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){throw new x("Updates to tasks are not available")}async updateAll(e,...t){throw new x("Updates to tasks are not available")}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}async shutdown(...t){const{ctxArgs:r,ctx:a,log:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...r),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(a),s.verbose("gracefully shutdown task runner")}}r.__decorate([ot(e.TaskModel),r.__metadata("design:type",Object)],Vt.prototype,"repo",void 0),r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"create",null),r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"createAll",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"delete",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"deleteAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"read",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"readAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"query",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"update",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"updateAll",null),t.Injectables.setRegistry(new me);const Wt="##VERSION##",Jt="##PACKAGE##";n.Metadata.registerLibrary(Jt,Wt),e.AbsContextual=O,e.Adapter=R,e.AuthorizationError=Re,e.BaseModel=Je,e.BigIntSequence=tt,e.ClientBasedService=_t,e.CompositeTaskBuilder=Mt,e.Condition=F,e.ConnectionError=$e,e.Context=E,e.ContextLock=b,e.ContextualLoggedClass=v,e.DefaultAdapterFlags=g,e.DefaultCascade=q,e.DefaultContextFlags=h,e.DefaultRepositoryFilters=re,e.DefaultSequenceOptions=Ze,e.DefaultTaskEngineConfig=we,e.Dispatch=be,e.ForbiddenError=Le,e.InjectablesRegistry=me,e.MethodQueryBuilder=z,e.MigrationError=k,e.MigrationRuleError=A,e.ModelService=xt,e.MultipleSelectOperationKeys=_,e.NonTransactionOperationKeys=f,e.NoneSequenceOptions=Xe,e.NumericSequence=et,e.ObserverError=nt,e.ObserverHandler=T,e.OperatorsMap=Y,e.PACKAGE_NAME=Jt,e.PaginationOperationKeys=w,e.Paginator=ct,e.PagingError=$,e.PersistenceService=class extends _t{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof E||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s,ctxArgs:i}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),o=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});for(const e of o)try{await e.initialize(...i)}catch(t){throw new a.InternalError(`Failed to initialize ${e.toString()}: ${t}`)}return{client:o,config:r}}},e.QueryError=L,e.Repository=ye,e.SelectOperationKeys=m,e.Sequence=it,e.Serial=I,e.Service=mt,e.Statement=ft,e.TaskBackoffBuilder=At,e.TaskBuilder=Ct,e.TaskCancelError=Gt,e.TaskContext=Kt,e.TaskControlError=Ut,e.TaskEngine=Qt,e.TaskEventBus=jt,e.TaskFailError=qt,e.TaskHandler=Dt,e.TaskHandlerRegistry=Ft,e.TaskIOSerializer=kt,e.TaskLogger=Bt,e.TaskRescheduleError=zt,e.TaskRetryError=Yt,e.TaskService=Vt,e.TaskTracker=Ht,e.TasksKey=_e,e.TransactionOperationKeys=y,e.UUID=B,e.UnsupportedError=x,e.VERSION=Wt,e.applyViewDecorator=Q,e.auth=t=>{const r=e.PersistenceKeys.AUTH;return n.Decoration.for(r).define({decorator:e=>n.metadata(r,e),args:[t]}).apply()},e.cacheModelForPopulate=De,e.cascadeDelete=Be,e.column=Fe,e.computeBackoffMs=Nt,e.create=bt,e.createOrUpdate=Se,e.createdAt=ze,e.createdBy=Ye,e.createdByOnCreateUpdate=qe,e.del=St,e.generateInjectableNameForRepository=fe,e.getFilters=ae,e.getLogPipe=It,e.getPkTypes=Qe,e.getPopulateKey=Me,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=je,e.injectableServiceKey=C,e.isOperationBlocked=D,e.manyToMany=(t,r=q,a=!0,s,o)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return n.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const o={class:e,cascade:t,populate:r};a&&(o.joinTable=a),s&&(o.name=s);const d=Qe(e),l=[n.prop(),We(c,o),i.list([e,...d])];return n.apply(...l)},args:[t,r,a,s,o]}).apply()},e.manyToOne=(t,r=q,a=!0,s,o)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return n.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const o={class:e,cascade:t,populate:r};a&&(o.joinTable=a),s&&(o.name=s);const d=Qe(e),l=[n.prop(),We(c,o),i.type([e,...d])];return n.apply(...l)},args:[t,r,a,s,o]}).apply()},e.noValidateOn=Ve,e.noValidateOnCreate=()=>Ve(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>Ve(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>Ve(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=q,s=!0,o,c)=>{const d=e.PersistenceKeys.ONE_TO_MANY;return n.Decoration.for(d).define({decorator:(e,t,r,s,o)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),o&&(c.name=o);const l=Qe(e),u=[n.prop(),We(d,c),i.list([e,...l]),a.onCreate(ke,c,{priority:70}),a.onUpdate(Ae,c,{priority:70}),a.onDelete(Ce,c,{priority:70}),a.afterUpdate(Be,c,{priority:70}),a.afterAny(Pe,c,{priority:70})];return n.apply(...u)},args:[t,r,s,o,c]}).apply()},e.oneToManyOnCreate=ke,e.oneToManyOnDelete=Ce,e.oneToManyOnUpdate=Ae,e.oneToOne=(t,r=q,s=!0,o,c)=>{const d=e.PersistenceKeys.ONE_TO_ONE;return n.Decoration.for(d).define({decorator:(e,t,r,s,o)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),o&&(c.name=o);const l=Qe(e),u=[n.prop(),We(d,c),i.type([e,...l]),a.onCreate(Oe,c,{priority:70}),a.onUpdate(Te,c,{priority:70}),a.onDelete(xe,c,{priority:70}),a.afterUpdate(Be,c,{priority:70}),a.afterAny(Pe,c,{priority:70})];return n.apply(...u)},args:[t,r,s,o,c]}).apply()},e.oneToOneOnCreate=Oe,e.oneToOneOnDelete=xe,e.oneToOneOnUpdate=Te,e.onlyOnBulk=ee,e.onlyOnCreate=V,e.onlyOnDelete=J,e.onlyOnFilter=te,e.onlyOnSingle=Z,e.onlyOnTransactional=X,e.onlyOnUpdate=W,e.pk=st,e.pkDec=at,e.pkOnCreate=rt,e.populate=Pe,e.prefixMethod=P,e.prepared=H,e.promiseSequence=M,e.query=(t={})=>n.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const i=z.getFieldsFromMethodName(a);return n.apply(n.methodMetadata(n.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:i}),H(),(e=>(t,r,a)=>{a.value=new Proxy(a.value,{apply(t,r,a){const{action:s,select:i,selector:o,where:n,groupBy:c,orderBy:d,limit:l,offset:u}=z.build(t.name,...a),p=r;let h;switch(s){case"find":case"page":h=p.select(i);break;case"count":h=p.count(o);break;case"sum":h=p.sum(o);break;case"avg":h=p.avg(o);break;case"min":h=p.min(o);break;case"max":h=p.max(o);break;case"distinct":h=p.distinct(o);break;case"group":h=p.select(),o&&(h=h.groupBy(o));break;default:throw new L("Unsupported action: "+s)}if(n&&(h=h.where(n)),c&&c.length>0&&"group"!==s){h=h.groupBy(c[0]);for(let e=1;e<c.length;e++)h=h.thenBy(c[e])}else if(c&&c.length>0&&"group"===s)for(const e of c)h=h.thenBy(e);const{allowLimit:g,allowOffset:y,allowOrderBy:f,throws:m}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},_=[{key:"orderBy",value:(d||[])[0],allowed:f},{key:"limit",value:l,allowed:g},{key:"offset",value:u,allowed:y}];for(const e of _)if(void 0!==e.value){if(!e.allowed&&m)throw new L(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(h=h[e.key](e.value))}if("page"===s){const e=a[a.length-1],t="number"==typeof e?e:e?.limit??10;return h.paginate(t)}return h.execute()}})})(t))(r,a,s)},args:[t]}).apply(),e.read=Et,e.relation=We,e.repository=ot,e.repositoryFromTypeMetadata=Ne,e.roles=t=>n.metadata(e.PersistenceKeys.AUTH_ROLE,t),e.route=(t,r)=>{const a=e.PersistenceKeys.DECAF_ROUTE;return n.Decoration.for(a).define({decorator:()=>(e,s,i)=>{const o={path:r,httpMethod:t,handler:i};return n.apply(n.methodMetadata(n.Metadata.key(a,s),o))(e,s,i)},args:[]}).apply()},e.serializeError=Rt,e.service=Ot,e.sleep=Lt,e.table=Ke,e.task=Pt,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return n.Decoration.for(t).define(i.async(),a.onCreateUpdate(Ue),n.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=Ue,e.update=vt,e.updatedAt=He,e.updatedBy=Ge,e.uuid=ve,e.uuidCreateUpdateHandler=Ee,e.view=t=>n.Decoration.for(e.Operator.VIEW).define({decorator:t=>Q(e.Operator.VIEW,"view",t),args:[t]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/transactional-decorators"),require("@decaf-ts/decoration")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/transactional-decorators","@decaf-ts/decoration"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsTransactionalDecorators,e.decafTsDecoration);
|
|
1
|
+
var e,t;e=this,t=function(e,t,r,a,s,i,o,n){"use strict";var c,d,l,u,p;e.QueryClause=void 0,(c=e.QueryClause||(e.QueryClause={})).FIND_BY="findBy",c.PAGE_BY="pageBy",c.COUNT_BY="countBy",c.SUM_BY="sumBy",c.AVG_BY="avgBy",c.MIN_BY="minBy",c.MAX_BY="maxBy",c.DISTINCT_BY="distinctBy",c.GROUP_BY_PREFIX="groupBy",c.SELECT="Select",c.AND="And",c.OR="Or",c.GROUP_BY="GroupBy",c.ORDER_BY="OrderBy",c.THEN="Then",c.THEN_BY="ThenBy",e.Operator=void 0,(d=e.Operator||(e.Operator={})).EQUAL="EQUAL",d.DIFFERENT="DIFFERENT",d.BIGGER="BIGGER",d.BIGGER_EQ="BIGGER_EQ",d.SMALLER="SMALLER",d.SMALLER_EQ="SMALLER_EQ",d.BETWEEN="BETWEEN",d.NOT="NOT",d.IN="IN",d.REGEXP="REGEXP",d.GROUP_BY="group-by",d.COUNT="count",d.SUM="sum",d.MAX="v_max",d.MIN="v_min",d.DISTINCT="distinct",d.VIEW="view",e.GroupOperator=void 0,(l=e.GroupOperator||(e.GroupOperator={})).AND="AND",l.OR="OR",e.PreparedStatementKeys=void 0,(u=e.PreparedStatementKeys||(e.PreparedStatementKeys={})).LIST_BY="listBy",u.FIND_BY="findBy",u.FIND_ONE_BY="findOneBy",u.PAGE_BY="paginateBy",u.COUNT_OF="countOf",u.MAX_OF="maxOf",u.MIN_OF="minOf",u.AVG_OF="avgOf",u.SUM_OF="sumOf",u.DISTINCT_OF="distinctOf",u.GROUP_OF="groupOf",e.PersistenceKeys=void 0,(p=e.PersistenceKeys||(e.PersistenceKeys={})).PERSISTENCE="persistence",p.INDEX="index",p.UNIQUE="unique",p.ADAPTER="adapter",p.INJECTABLE="decaf_{0}_adapter_for_{1}",p.SERVICE="service",p.TABLE="table",p.COLUMN="column",p.METADATA="__metadata",p.OWNERSHIP="ownership",p.CREATED_BY="ownership.created-by",p.UPDATED_BY="ownership.updated-by",p.RELATIONS="__relations",p.RELATION="relation",p.ONE_TO_ONE="relation.one-to-one",p.ONE_TO_MANY="relation.one-to-many",p.MANY_TO_ONE="relation.many-to-one",p.MANY_TO_MANY="relation.many-to-many",p.POPULATE="populate",p.NO_VALIDATE="no-validate",p.MIGRATION="migration",p.STATEMENT="statement",p.QUERY="query",p.UUID="uuid",p.TAG_FOR_DELETION="tag_for_deletion",p.INITIALIZATION="initialization",p.SHUTDOWN="shutdown",p.BY_KEY="by-key",p.AUTH="auth",p.AUTH_ROLE="auth-role",p.DECAF_ROUTE="DecafRoute";const h=Object.assign({},{ignoreDevSafeGuards:!1}),g=Object.assign({},a.DefaultRepositoryFlags,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),y=[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL],f=[a.OperationKeys.READ,a.BulkCrudOperationKeys.READ_ALL],m=[e.PersistenceKeys.STATEMENT,e.PreparedStatementKeys.FIND_ONE_BY],_=[e.PersistenceKeys.QUERY,e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.LIST_BY,e.PreparedStatementKeys.FIND_BY],w=[e.PreparedStatementKeys.PAGE_BY];class b extends o.Lock{constructor(){super()}}class E extends a.Context{constructor(e){super(e)}pushPending(e,t){const r=this.pending()||{};if(r[e]=r[e]||[],r[e].includes(t))throw new a.InternalError(`Trying to push a repeated pending ${e} task: ${t}`);r[e].push(t),this.accumulate({pending:r})}getFromChildren(e){const t=this.getOrUndefined(e);if(t)return t;const r=this.getOrUndefined("childContexts");return r&&r.length?r.map(t=>t.getFromChildren(e)).flat().reduce((e,t)=>Object.assign(e,t),{}):void 0}pending(){return this.getFromChildren("pending")}getOrUndefined(e){try{return this.get(e)}catch(e){return}}override(e){return new Proxy(this,{get:(t,r,s)=>"get"===r?new Proxy(t.get,{apply:(t,r,i)=>{const o=i[0];if(!o)throw new a.InternalError("Invalid property access to overridden context: "+o);return o in e?e[o]:Reflect.apply(t,s,i)}}):Reflect.get(t,r,s)})}toOverrides(){return this.cache.keys().reduce((e,t)=>(e[t]=this.get(t),e),{})}accumulate(e){return super.accumulate(e)}}class v extends s.LoggedClass{logCtx(e,t,r=!1,a){return v.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static logFrom(e,t,r,a){const s=e.context?t.clear().for(e):t.for(e);return a?s.for(a):s}static logCtx(e,t,r=!1,...i){const o=(e,t,r)=>{const a=t.log||s.Logging.get();return t.log=e.context?a.clear().for(e):a.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=i.pop();const c=n instanceof E;if(n&&!c&&(i.push(n),n=void 0),!r&&!c)throw new a.InternalError("No context provided");if(c&&!r){if(!n)throw new a.InternalError("Missing context. should be impossible");return o(this,{log:n.logger,ctx:n,ctxArgs:[...i,n]},e)}return async function(...r){if(!this)throw new a.InternalError("No contextual provided");if(!this.context)throw new a.InternalError("Invalid contextual provided");return this.context("string"==typeof e?e:e.name,t||{},...r)}.call(this,...[...i,n].filter(Boolean)).then(t=>o(this,{log:t.logger,ctx:t,ctxArgs:[...i,t]},e))}}class O extends v{constructor(){super(),this._Context=E}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 a=r.pop();return a instanceof E||(r.push(a),a=void 0),this.flags,!a||a instanceof this.Context?(new this.Context).accumulate(t):new this.Context(a).accumulate(t)}}class T{constructor(){this.observers=[]}count(){return this.observers.length}observe(e,t){if(-1!==this.observers.map(e=>e.observer).indexOf(e))throw new a.InternalError("Observer already registered");return this.observers.push({observer:e,filter:t}),()=>this.unObserve(e)}unObserve(e){const t=this.observers.map(e=>e.observer).indexOf(e);if(-1===t)throw new a.InternalError("Failed to find Observer");this.observers.splice(t,1)}async updateObservers(e,t,r,...a){const{log:s,ctxArgs:i}=v.logCtx(this.updateObservers,void 0,!1,...a);(await Promise.allSettled(this.observers.filter(a=>{const{filter:o}=a;if(!o)return!0;try{return o(e,t,r,...i)}catch(e){return s.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(a=>{a.observer.refresh(e,t,r,...i)}))).forEach((e,t)=>{"rejected"===e.status&&s.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class x extends a.InternalError{constructor(e){super(e,x.name,500)}}class k extends a.InternalError{constructor(e,t=k.name){super(e,t,500)}}class A extends k{constructor(e){super(e,A.name)}}function C(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):n.Metadata.Symbol(n.Metadata.constr(e)).toString().replaceAll(".","-")}function M(e){return e.reduce((e,t)=>e.then(async e=>[...e,await t()]),Promise.resolve([]))}function D(e,t){const{handler:r,args:s}=n.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)}function P(e,t,r,a){const s=async function(...e){let a;try{a=await Promise.resolve(r.call(this,...e))}catch(e){if(e instanceof A)return;throw e}return Promise.resolve(t.apply(this,a))}.bind(e),i=a||t.name;Object.defineProperty(s,"name",{enumerable:!0,configurable:!0,writable:!1,value:i}),e[i]=s}class B{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 B._instance||(B._instance=new B),B._instance}}class I{constructor(){this.count=14}generate(e){return(""+((e=(e?parseInt(e):0)||0)+1)).padStart(this.count,"0")}static get instance(){return I._instance||(I._instance=new I),I._instance}}const N=n.Decoration.flavourResolver.bind(n.Decoration);n.Decoration.flavourResolver=e=>{try{const t=N(e);if(t&&t!==n.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof n.Metadata.registeredFlavour?n.Metadata.registeredFlavour(r):void 0;if(a&&a!==n.DefaultFlavour)return a;const s=R._currentFlavour;if(s){const e=R._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return n.DefaultFlavour}};class R extends O{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!R._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return R._baseRepository}async shutdownProxies(e){if(this.proxies){if(e&&!(e in this.proxies))throw new a.InternalError("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(...t){(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.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 R._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);R._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),R._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),R._currentFlavour=this.alias)}Dispatch(){return new R._baseDispatch}ObserverHandler(){return new T}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new R._baseSequence(e,this,t)}async flags(e,t,r,...o){if("string"==typeof t)throw new a.InternalError("Model must be a constructor or array of constructors or undefined. this should be impossible");const c=Array.isArray(t)?t.length?t[0]:void 0:t,d=c?i.Model.tableName(c)+" - ":"";r.correlationId=r.correlationId||`${d}${e}-${B.instance.generate()}`;const l=r.logger||s.Logging.for(this);return Object.assign({},g,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:o,writeOperation:y.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?n.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:l})}get Context(){return E}async context(e,t,r,...a){this.log.for(this.context).silly(`creating new context for ${e} operation on ${r?Array.isArray(r)?r.map(e=>i.Model.tableName(e)):i.Model.tableName(r):"no"} table ${t&&Object.keys(t)?Object.keys(t).length:"no"} with flag overrides`);let s=a.pop();void 0===s||s instanceof E||(a.push(s),s=void 0),t=s?Object.assign({},s.toOverrides(),t):t;const o=await this.flags("string"==typeof e?e:e.name,r,t,...[...a,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}const t=s.get("operation"),a=s.getOrUndefined("affectedTables");if(t!==e||r&&r!==a){const e=(new this.Context).accumulate({...s.cache,...o,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],e]}),e}return s.accumulate(o)}return(new this.Context).accumulate({...o})}prepare(t,...r){const{log:s}=this.logCtx(r,this.prepare),o=t.segregate(),n=Object.entries(o.model).reduce((e,[r,s])=>{if(void 0===s)return e;const o=i.Model.columnName(t.constructor,r);if(this.isReserved(o))throw new a.InternalError(`Property name ${o} is reserved`);return e[o]=s,e},{});return t[e.PersistenceKeys.METADATA]&&(s.silly("Passing along persistence metadata for "+t[e.PersistenceKeys.METADATA]),Object.defineProperty(n,e.PersistenceKeys.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[e.PersistenceKeys.METADATA]})),{record:n,id:t[i.Model.pk(t.constructor)],transient:o.transient}}revert(t,r,s,o,...n){const{log:c,ctx:d}=this.logCtx(n,this.revert),l=i.Model.pk(r),u=new r;u[l]=s,c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==l).reduce((e,a)=>(e[a]=t[i.Model.columnName(r,a)],e),u);return d.get("rebuildWithTransient")&&o&&(c.verbose("re-adding transient properties: "+Object.keys(o).join(", ")),Object.entries(o).forEach(([e,t])=>{if(e in h&&void 0!==h[e])throw new a.InternalError(`Transient property ${e} already exists on model ${u.constructor.name}. should be impossible`);h[e]=t})),p&&(c.silly(`Passing along ${this.flavour} persistence metadata for ${u.constructor.name} id ${s}: ${p}`),Object.defineProperty(h,e.PersistenceKeys.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:p})),h}async createAll(e,t,r,...s){const{log:o,ctx:n}=this.logCtx(s,this.createAll);if(!t||!r)throw new a.ValidationError("Ids and models cannot be null or undefined");if(t.length!==r.length)throw new a.ValidationError("Ids and models must have the same length");const c=i.Model.tableName(e);return o.debug(`Creating ${t.length} entries ${c} table`),M(t.map((t,a)=>()=>this.create(e,t,r[a],...s,n.override({noEmitSingle:!0}))))}async readAll(e,t,...r){const{log:a,ctx:s}=this.logCtx(r,this.readAll),o=i.Model.tableName(e);return a.debug(`Reading ${t.length} entries ${o} table`),M(t.map(t=>()=>this.read(e,t,...r,s.override({noEmitSingle:!0}))))}async updateAll(e,t,r,...s){const{log:o,ctx:n}=this.logCtx(s,this.updateAll);if(t.length!==r.length)throw new a.InternalError("Ids and models must have the same length");const c=i.Model.tableName(e);return o.debug(`Updating ${t.length} entries ${c} table`),M(t.map((t,a)=>()=>this.update(e,t,r[a],...s,n.override({noEmitSingle:!0}))))}async deleteAll(e,t,...r){const{log:a,ctx:s}=this.logCtx(r,this.deleteAll);return a.debug(`Deleting ${t.length} entries from ${e} table`),M(t.map(t=>()=>this.delete(e,t,...r,s.override({noEmitSingle:!0}))))}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);return r.silly("Registering new observer "+e.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:o}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const a=Array.isArray(r),s=!i.get("noEmitSingle"),n=!i.get("noEmitBulk");(a&&n||!a&&s)&&await this.observerHandler.updateObservers(e,t,r,...o)}}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}toString(){return this.flavour+" adapter"}static flavourOf(e){return n.Metadata.flavourOf(e)}static get currentFlavour(){if(!R._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return R._currentFlavour}static get current(){return R.get(this.currentFlavour)}static get(e){if(!e)return R.get(this._currentFlavour);if(e in this._cache)return this._cache[e];throw new a.InternalError(`No Adapter registered under ${e}.`)}static setCurrent(e){this._currentFlavour=e}static models(e){try{return n.Metadata.flavouredAs(e).filter(i.Model.isModel)}catch(e){throw new a.InternalError(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} - ${i.hashObj(e)}`;if(r in this.proxies)return this.proxies[r];let a;const s=new Proxy(this,{get:(t,r,s)=>{if("_config"===r){const a=Reflect.get(t,r,s);return Object.assign({},a,e)}return"_client"===r?a:Reflect.get(t,r,s)},set:(e,t,r,s)=>"_client"===t?(a=r,!0):Reflect.set(e,t,r,s)});return this.proxies[r]=s,s}migrations(){return n.Metadata.migrationsFor(this)}async getQueryRunner(){return this}logCtx(e,t,r=!1,a){return super.logCtx(e,t,r,a)}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String]),r.__metadata("design:returntype",Promise)],R.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,E]),r.__metadata("design:returntype",Promise)],R.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],R.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],R.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],R.prototype,"client",null);class L extends a.InternalError{constructor(e){super(e,L.name,500)}}class $ extends a.InternalError{constructor(e){super(e,$.name,500)}}class F extends i.Model{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):i.Model.fromModel(this,e)}and(e){return F.and(this,e)}or(e){return F.or(this,e)}not(t){return new F(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof F)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(e.Operator).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===e.Operator.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof F){if(!(this.comparison instanceof F)&&this.operator!==e.Operator.NOT)return{comparison:{condition:t}};if(-1===Object.values(e.GroupOperator).indexOf(this.operator)&&this.operator!==e.Operator.NOT)return{operator:{condition:t}}}},a=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(a)??r())():a??r()}static and(t,r){return F.group(t,e.GroupOperator.AND,r)}static or(t,r){return F.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new F(e,t,r)}static attribute(e){return(new F.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(t){return this.setOp(e.Operator.EQUAL,t)}dif(t){return this.setOp(e.Operator.DIFFERENT,t)}gt(t){return this.setOp(e.Operator.BIGGER,t)}lt(t){return this.setOp(e.Operator.SMALLER,t)}gte(t){return this.setOp(e.Operator.BIGGER_EQ,t)}lte(t){return this.setOp(e.Operator.SMALLER_EQ,t)}in(t){return this.setOp(e.Operator.IN,t)}regexp(t){return this.setOp(e.Operator.REGEXP,RegExp(t).source)}between(t,r){return this.setOp(e.Operator.BETWEEN,[t,r])}setOp(e,t){return this.operator=e,this.comparison=t,this.build()}build(){try{return new F(this.attr1,this.operator,this.comparison)}catch(e){throw new L(e)}}}}static builder(){return new F.Builder}static from(e){return new F(e)}}var j,U;r.__decorate([i.required(),r.__metadata("design:type",Object)],F.prototype,"attr1",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],F.prototype,"operator",void 0),r.__decorate([i.required(),r.__metadata("design:type",Object)],F.prototype,"comparison",void 0),e.OrderDirection=void 0,(j=e.OrderDirection||(e.OrderDirection={})).ASC="asc",j.DSC="desc",e.Cascade=void 0,(U=e.Cascade||(e.Cascade={})).CASCADE="cascade",U.NONE="none";const q={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},Y={Equals:(e,t)=>F.attribute(e).eq(t),Diff:(e,t)=>F.attribute(e).dif(t),LessThan:(e,t)=>F.attribute(e).lt(t),LessThanEqual:(e,t)=>F.attribute(e).lte(t),GreaterThan:(e,t)=>F.attribute(e).gt(t),GreaterThanEqual:(e,t)=>F.attribute(e).gte(t),In:(e,t)=>F.attribute(e).in(t),Matches:(e,t)=>F.attribute(e).regexp(t)},G=e=>e.charAt(0).toLowerCase()+e.slice(1);class z extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(z.name)),this._logger}static{this.prefixMap={[e.QueryClause.FIND_BY]:"find",[e.QueryClause.PAGE_BY]:"page",[e.QueryClause.COUNT_BY]:"count",[e.QueryClause.SUM_BY]:"sum",[e.QueryClause.AVG_BY]:"avg",[e.QueryClause.MIN_BY]:"min",[e.QueryClause.MAX_BY]:"max",[e.QueryClause.DISTINCT_BY]:"distinct",[e.QueryClause.GROUP_BY_PREFIX]:"group"}}static getActionFromMethodName(e){for(const[t,r]of Object.entries(this.prefixMap))if(e.startsWith(t))return{action:r,prefix:t}}static build(e,...t){const r=this.getActionFromMethodName(e);if(!r)throw Error("Unsupported method "+e);const{action:a,prefix:s}=r;let i;["count","sum","avg","min","max","distinct","group"].includes(a)&&(i=this.extractAggregationSelector(e,s));const o=this.extractCore(e,s),n=this.extractSelect(e),c=this.extractGroupBy(e),d=this.buildWhere(o,t),{orderBy:l,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,o);return{action:a,select:n,selector:i,where:d,groupBy:c,orderBy:l,limit:u,offset:p}}static extractAggregationSelector(e,t){const r=e.substring(t.length),a=r.match(/(And|Or|GroupBy|OrderBy|Select|Limit|Offset|ThenBy)/),s=a?r.substring(0,a.index):r;return s?G(s):void 0}static extractCore(t,r=e.QueryClause.FIND_BY){const a=t.substring(r.length);if(r!==e.QueryClause.FIND_BY&&r!==e.QueryClause.PAGE_BY){const e=a.match(/(And|Or|GroupBy|OrderBy|ThenBy|Select|Limit|Offset)/);if(!e)return"";if("And"===e[0]||"Or"===e[0]){const t=a.substring(e.index+e[0].length),r=t.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select|ThenBy)/);return r?t.substring(0,r.index):t}return""}const s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset|Select)/);return s?a.substring(0,s.index):a}static getFieldsFromMethodName(t){const r=this.getActionFromMethodName(t),a=r?.prefix||e.QueryClause.FIND_BY,s=this.extractCore(t,a);return s?(s.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).filter(e=>e.length>0).map(e=>{const{operator:t,field:r}=this.parseFieldAndOperator(e);return r+(t??"")}):[]}static extractSelect(t){const r=t.indexOf(e.QueryClause.SELECT);if(-1===r)return;const a=t.substring(r+e.QueryClause.SELECT.length),s=a.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?a.substring(0,s.index):a).split(e.QueryClause.AND).map(G).filter(Boolean)}static extractGroupBy(t){const r=t.indexOf(e.QueryClause.GROUP_BY);if(-1!==r)return t.substring(r+e.QueryClause.GROUP_BY.length).split(e.QueryClause.ORDER_BY)[0].split(e.QueryClause.THEN_BY).map(G).filter(Boolean);const a=this.getActionFromMethodName(t);if("group"===a?.action){const r=t.substring(a.prefix.length),s=r.indexOf(e.QueryClause.THEN_BY);if(-1===s)return;const i=r.substring(s+e.QueryClause.THEN_BY.length).split(e.QueryClause.THEN_BY),o=[];for(const e of i){const t=e.match(/(OrderBy|Limit|Offset|Select)/),r=t?e.substring(0,t.index):e;r&&o.push(G(r))}return o.length>0?o:void 0}}static buildWhere(t,r){if(!t)return;const a=t.split(/OrderBy|GroupBy/)[0]||"";if(!a)return;const s=a.split(/And|Or/).filter(e=>e.length>0);if(0===s.length)return;const i=t.match(/And|Or/g)||[];let o;return s.forEach((t,a)=>{const{field:s,operator:n}=this.parseFieldAndOperator(t),c=n?Y[n]:Y.Equals;if(!c)throw Error("Unsupported operator "+n);const d=r[a];if(void 0===d)throw Error("Invalid value for field "+s);const l=c(s,d);o=0===a?l:i[a-1]===e.QueryClause.AND?o.and(l):o.or(l)}),o}static parseFieldAndOperator(e){for(const t of Object.keys(Y))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:G(r),operator:t}}return{field:G(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(t,r){const a=z.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new L("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new L(`Invalid OrderBy direction ${r}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`);return[[t,r]]}a.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(e,t,r){const s=r??this.extractCore(e),i=s?s.split(/And|Or/).filter(e=>e.length>0).length:0,o=t.slice(i)??[];let n,c,d;if(o.at(-1)instanceof a.Context&&o.pop(),o.length>=1){const t=o[0],r=this.extractOrderByField(e);n=this.getProperlyOrderByOrThrow(r,t)}return 2>o.length||"number"!=typeof o[1]||(c=o[1]),3>o.length||"number"!=typeof o[2]||(d=o[2]),{orderBy:n,limit:c,offset:d}}}function H(){return n.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>n.apply(n.methodMetadata(n.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function Q(e,t,r){return(a,s)=>{const i=r?.name||((e,t,r)=>{const a=(n.Metadata.get(e.constructor,t)||{})[r]||{};return Object.keys(a).length+1+""})(a,e,s),o=n.Metadata.key(e,s,i),c={...r||{},kind:t,attribute:s};return n.propMetadata(o,c)(a,s)}}function V(e){return te(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function W(e){return te(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function J(e){return te(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function X(e){return te(e,y)}function Z(e){return te(e,Object.values(a.OperationKeys))}function ee(e){return te(e,Object.values(a.BulkCrudOperationKeys))}function te(e,t){return(r,s,o,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:d}=v.prototype.logCtx(c,te);return d.silly(`filtering ${s} event for${r?" "+(i.Model.tableName(r)||r):""} ${o}`),("string"==typeof r?r===i.Model.tableName(e)||r===e.constructor.name:n.Metadata.constr(e)===n.Metadata.constr(r))&&t.includes(s)}}const re={onlyOnCreate:V,onlyOnUpdate:W,onlyOnDelete:J,onlyOnTransactional:X,onlyOnSingle:Z,onlyOnBulk:ee};function ae(e){const t=Object.assign({},re);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var se,ie,oe,ne,ce,de,le,ue,pe,he,ge;class ye extends a.Repository{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new a.InternalError("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=i.Model.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return ae(this)}constructor(e,t,...r){super(t),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},e&&(this._adapter=e),t&&(ye.register(t,this,this.adapter.alias),e)&&n.Metadata.get(t,n.DecorationKeys.FLAVOUR)===n.DefaultFlavour&&n.uses(e.flavour)(t);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(e=>{const t=e.name;a.wrapMethodWithContext(s,s[t+"Prefix"],e,s[t+"Suffix"])}),a.wrapMethodWithContextForUpdate(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(e,t,r=!1,a){const s=this.adapter.logCtx([this.class,...e],t,r,Object.assign({},a||{},this._overrides||{}));function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}override(e){return new Proxy(this,{get:(t,r,a)=>{const s=Reflect.get(t,r,a);return"_overrides"!==r?s:Object.assign({},s,e)}})}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"adapter"===a?this.adapter.for(e,...t):Reflect.get(r,a,s)})}ObserverHandler(){return new T}async createPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.createPrefix),o=r.get("ignoreHandlers"),n=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${o}, validationSetting: ${n}`),e=new this.class(e),o||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),!n){const t=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s]}async create(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);a.debug(`Creating new ${this.class.name} in table ${i.Model.tableName(this.class)}`);let{record:o,id:n,transient:c}=this.adapter.prepare(e,r);return o=await this.adapter.create(this.class,n,o,...s),this.adapter.revert(o,this.class,n,c,r)}async createAll(e,...t){if(!e.length)return e;const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.createAll);a.debug(`Creating ${e.length} new ${this.class.name} in table ${i.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r)),n=o.map(e=>e.id);let c=o.map(e=>e.record);return c=await this.adapter.createAll(this.class,n,c,...s),c.map((e,t)=>this.adapter.revert(e,this.class,n[t],r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async createAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),c=r.get("ignoreValidation");if(o.silly(`handlerSetting: ${n}, validationSetting: ${c}`),!e.length)return[e,...s];const d=i.Model.sequenceFor(e[0]);let l=[];if(i.Model.generatedBySequence(this.class)?(d.name||(d.name=i.Model.sequenceName(e[0],"pk")),l=await(await this.adapter.Sequence(d)).range(e.length,...s)):i.Model.generated(this.class,this.pk)||(l=e.map((e,t)=>{if(void 0===e[this.pk])throw new a.InternalError("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?l[t]:""+e[this.pk]),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.CREATE,a.OperationKeys.ON),e))),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.all(e.map(e=>Promise.resolve(e.hasErrors(...t)))),i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s]}async readPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.readPrefix),o=r.get("ignoreHandlers");i.silly("handlerSetting: "+o);const n=new this.class;return n[this.pk]=e,o||await a.enforceDBDecorators(this,r,n,a.OperationKeys.READ,a.OperationKeys.ON),[e,...s]}async read(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.read);a.debug(`reading ${this.class.name} from table ${i.Model.tableName(this.class)} with pk ${this.pk}`);const o=await this.adapter.read(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async readAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAllPrefix),o=r.get("ignoreHandlers");return i.silly("handlerSetting: "+o),o||await Promise.all(e.map(async e=>{const t=new this.class;return t[this.pk]=e,a.enforceDBDecorators(this,r,t,a.OperationKeys.READ,a.OperationKeys.ON)})),[e,...s]}async readAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.readAll);return a.debug(`reading ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.readAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}async update(e,...t){const{ctxArgs:r,log:a,ctx:s}=this.logCtx(t,this.update);let{record:o,id:n,transient:c}=this.adapter.prepare(e,s);return a.debug(`updating ${this.class.name} in table ${i.Model.tableName(this.class)} with id ${n}`),o=await this.adapter.update(this.class,n,o,...r),this.adapter.revert(o,this.class,n,c,s)}async updatePrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${n}, validationSetting: ${c}`);const d=e[this.pk];if(!d)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(d,r),r.get("mergeForUpdate")&&(e=i.Model.merge(l,e,this.class))),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,l),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(l,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,l]}async updateAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.updateAll);a.verbose(`Updating ${e.length} new ${this.class.name} in table ${i.Model.tableName(this.class)}`);const o=e.map(e=>this.adapter.prepare(e,r));return(await this.adapter.updateAll(this.class,o.map(e=>e.id),o.map(e=>e.record),...s)).map((e,t)=>this.adapter.revert(e,this.class,o[t].id,r.get("rebuildWithTransient")?o[t].transient:void 0,r))}async updateAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:o}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),c=r.get("ignoreValidation");o.silly(`handlerSetting: ${n}, ignoredValidation: ${c}`);const d=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let l;if(r.get("applyUpdateValidation")&&(l=await this.readAll(d,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>i.Model.merge(l[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,l?l[t]:void 0))),!c){const t=r.get("ignoredValidationProperties")||[];let s;o.silly("ignored validation properties: "+t),s=r.get("applyUpdateValidation")?await Promise.all(e.map((e,r)=>Promise.resolve(e.hasErrors(l[r],...t)))):await Promise.resolve(e.map(e=>e.hasErrors(...t)));const i=a.reduceErrorsToPrint(s);if(i)throw new a.ValidationError(i)}return[e,...s,l]}async deletePrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.deletePrefix),o=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+o),!o){const t=await this.read(e,...s);await a.enforceDBDecorators(this,r,t,a.OperationKeys.DELETE,a.OperationKeys.ON)}return[e,...s]}async delete(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.delete);a.debug(`deleting new ${this.class.name} in table ${i.Model.tableName(this.class)} with pk ${e}`);const o=await this.adapter.delete(this.class,e,...s);return this.adapter.revert(o,this.class,e,void 0,r)}async deleteAllPrefix(e,...t){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAllPrefix),o=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+o),!o){const t=await this.readAll(e,...s);await Promise.all(t.map(async e=>a.enforceDBDecorators(this,r,e,a.OperationKeys.DELETE,a.OperationKeys.ON)))}return[e,...s]}async deleteAll(e,...t){const{ctx:r,log:a,ctxArgs:s}=this.logCtx(t,this.create);return a.debug(`deleting ${e.length} ${this.class.name} in table ${i.Model.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,e,...s)).map((t,a)=>this.adapter.revert(t,this.class,e[a],void 0,r))}select(e){return this.adapter.Statement(this._overrides).select(e).from(this.class)}count(e){return this.adapter.Statement(this._overrides).count(e).from(this.class)}min(e){return this.adapter.Statement(this._overrides).min(e).from(this.class)}max(e){return this.adapter.Statement(this._overrides).max(e).from(this.class)}sum(e){return this.adapter.Statement(this._overrides).sum(e).from(this.class)}avg(e){return this.adapter.Statement(this._overrides).avg(e).from(this.class)}distinct(e){return this.adapter.Statement(this._overrides).distinct(e).from(this.class)}async query(t,r,a=e.OrderDirection.ASC,s,i,...o){const{ctxArgs:n}=(await this.logCtx(o,e.PersistenceKeys.QUERY,!0)).for(this.query),c=[r,a],d=this.select().where(t).orderBy(c);return s&&d.limit(s),i&&d.offset(i),d.execute(...n)}async listBy(t,r,...a){const{log:s,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${i.Model.tableName(this.class)} by ${t} ${r}`),this.select().orderBy([t,r]).execute(...o)}async paginateBy(t,r,a={offset:1,limit:10},...s){const o=a.offset||1,{offset:n,bookmark:c,limit:d}=a;if(!n&&!c)throw new L("PaginateBy needs a page or a bookmark");const{log:l,ctx:u,ctxArgs:p}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let h;if(l.verbose(`paginating ${i.Model.tableName(this.class)} with page size ${d}`),c&&u.get("paginateByBookmark"))h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>r===e.OrderDirection.ASC?this.attr(i.Model.pk(this.class)).gt(c):this.attr(i.Model.pk(this.class)).lt(c))()).orderBy([t,r]).paginate(d,...p);else{if(!n)throw new L("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(d,...p)}const g=await h.page(o,c,...p);return h.serialize(g)}async findOneBy(t,r,...s){const{log:o,ctxArgs:n}=(await this.logCtx(s,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);o.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`);const c=await this.select().where(this.attr(t).eq(r)).limit(1).execute(...n);if(!c.length)throw new a.NotFoundError("No results found");return c[0]}async findBy(t,r,...a){const{log:s,ctxArgs:o}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${i.Model.tableName(this.class)} with ${t} ${r}`),this.select().where(this.attr(t).eq(r)).execute(...o)}async countOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.COUNT_OF,!0)).for(this.countOf);return a.verbose(`counting ${i.Model.tableName(this.class)}${t?" by "+t:""}`),this.count(t).execute(...s)}async maxOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MAX_OF,!0)).for(this.maxOf);return a.verbose(`finding max of ${t} in ${i.Model.tableName(this.class)}`),this.max(t).execute(...s)}async minOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.MIN_OF,!0)).for(this.minOf);return a.verbose(`finding min of ${t} in ${i.Model.tableName(this.class)}`),this.min(t).execute(...s)}async avgOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.AVG_OF,!0)).for(this.avgOf);return a.verbose(`calculating average of ${t} in ${i.Model.tableName(this.class)}`),this.avg(t).execute(...s)}async sumOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.SUM_OF,!0)).for(this.sumOf);return a.verbose(`calculating sum of ${t} in ${i.Model.tableName(this.class)}`),this.sum(t).execute(...s)}async distinctOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.DISTINCT_OF,!0)).for(this.distinctOf);return a.verbose(`finding distinct values of ${t} in ${i.Model.tableName(this.class)}`),this.distinct(t).execute(...s)}async groupOf(t,...r){const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PreparedStatementKeys.GROUP_OF,!0)).for(this.groupOf);return a.verbose(`grouping ${i.Model.tableName(this.class)} by ${t}`),this.select().groupBy(t).execute(...s)}async statement(t,...r){if(!ye.statements(this,t))throw new L("Invalid prepared statement requested "+t);const{log:a,ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return a.verbose("Executing prepared statement "+t),this[t](...s)}attr(e){return F.attr(e)}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),a=this.class.name;return this.adapter.observe(this,(e,t,r,...s)=>"string"==typeof e?e===a:n.Metadata.constr(e)===n.Metadata.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${a}`),this.observerHandler.observe(e,t),r.verbose("Registered new observer "+e.toString()),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:o,ctxArgs:n}=this.logCtx(s,this.updateObservers);o.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,Array.isArray(r)?r.map(e=>R._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,e)):R._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,r),...n)}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}static forModel(t,r,...s){let i;const o=r||n.Metadata.flavourOf(t)||R.currentFlavour;try{i=this.get(t,o)}catch(e){i=void 0}if(i instanceof ye)return i;const c=r||n.Metadata.flavourOf(t)||i&&n.Metadata.get(i,e.PersistenceKeys.ADAPTER)||R.currentFlavour,d=c?R.get(c):void 0;if(!d)throw new a.InternalError("No registered persistence adapter found flavour "+c);return i=i||d.repository(),new i(d,t,...s)}static get(e,t){const r=i.Model.tableName(e);let s=r;if(t&&(s=[r,t].join(a.DefaultSeparator)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new a.InternalError("Could not find repository registered under "+r)}static register(e,t,r){let s=i.Model.tableName(e);if(r&&(s=[s,r].join(a.DefaultSeparator)),s in this._cache&&this._cache[s]instanceof ye)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof ye?t.constructor:t,s=n.Metadata.get(a,r?n.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof ye?t.constructor:t;return n.Metadata.get(a,r?n.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function fe(t,r){if(!(r||(r=n.Decoration.flavourResolver(t instanceof i.Model?t.constructor:t))&&r!==n.DefaultFlavour))throw new a.InternalError("Could not retrieve flavour from model "+(t instanceof i.Model?t.constructor.name:t.name));return i.sf(e.PersistenceKeys.INJECTABLE,r,i.Model.tableName(t))}r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"listBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"paginateBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"findOneBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"findBy",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"countOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(se="undefined"!=typeof K&&K)?se:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"maxOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ie="undefined"!=typeof K&&K)?ie:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"minOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(oe="undefined"!=typeof K&&K)?oe:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"avgOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ne="undefined"!=typeof K&&K)?ne:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"sumOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ce="undefined"!=typeof K&&K)?ce:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"distinctOf",null),r.__decorate([H(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(de="undefined"!=typeof K&&K)?de:Object,void 0]),r.__metadata("design:returntype",Promise)],ye.prototype,"groupOf",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],ye.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],ye.prototype,"unObserve",null),R&&(R._baseRepository=ye);class me extends t.InjectableRegistryImp{get log(){return this.logger||(this.logger=s.Logging.for(this)),this.logger}constructor(){super()}get(r,a){const s=this.log.for(this.get);let o;try{o=super.get(r)}catch{}if(!o){let c;if("function"==typeof r?c=i.Model.get(r.name)||r:"symbol"!=typeof r&&"string"!=typeof r||(c=i.Model.get(r.toString())),!c)return;const d=e.PersistenceKeys.ADAPTER,l=a||n.Metadata.get(c,d);try{let e=l;try{l&&R.get(l)}catch{const t=R.current;t&&t.flavour===l&&(e=t.alias)}if(o=ye.forModel(c,e),o instanceof ye)return o;const r=l||n.Metadata.get(o.constructor,d)||n.Metadata.get(c,d);t.Injectables.register(o,fe(c,r))}catch(e){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(e?.message||JSON.stringify(e)));const t=ye.get(c,l);if("function"==typeof t){const e=l?R.get(l):R.current;if(!e)return;return new t(e,c)}}}return o}}e.TaskStatus=void 0,(le=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",le.SCHEDULED="scheduled",le.RUNNING="running",le.FAILED="failed",le.SUCCEEDED="succeeded",le.CANCELED="canceled",le.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(ue=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",ue.FIXED="fixed",e.JitterStrategy=void 0,(pe=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",pe.FULL="full",e.TaskEventType=void 0,(he=e.TaskEventType||(e.TaskEventType={})).STATUS="status",he.LOG="log",he.PROGRESS="progress",he.ALL="all",e.TaskType=void 0,(ge=e.TaskType||(e.TaskType={})).ATOMIC="atomic",ge.COMPOSITE="composite";const _e="tasks",we={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};n.Metadata.tasks=(()=>n.Metadata.innerGet(Symbol.for(_e))).bind(n.Metadata),n.Metadata.taskFor=(e=>{const t=n.Metadata.tasks();return t?t[e]:void 0}).bind(n.Metadata),n.Metadata.validationExceptions=((t,r)=>{const s=n.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],o=Object.entries(s).filter(([,e])=>e.includes(r)).map(([e])=>e);let c=[];return r!==a.OperationKeys.CREATE&&r!==a.OperationKeys.UPDATE||(c=i.Model.nestedRelations(t)),[...new Set([...o,...c])]}).bind(n.Metadata),n.Metadata.migrationsFor=(t=>{if(!(t=t??R.current))throw new a.InternalError("Could not get adapter for migrations");return n.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(n.Metadata),n.Metadata.migrations=(()=>{const t=n.Metadata.innerGet(Symbol.for([e.PersistenceKeys.MIGRATION,e.PersistenceKeys.BY_KEY].join("-")));return Object.values(t).flat().map(e=>[e.class.name,e.class])}).bind(n.Metadata),n.Metadata.relations=((t,r)=>{const s=n.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(s){if(!r)return Object.keys(s);if(!s[r])throw new a.InternalError("No relations metadata found for property "+r);return s[r]}}).bind(n.Metadata),i.Model.relations=(e,t)=>n.Metadata.relations(e instanceof i.Model?e.constructor:e,t)||[],i.Model.nestedRelations=((t,r=[])=>{let a=[];const s=n.Metadata.get(t,e.PersistenceKeys.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...r])];for(const e in s){const t=s[e];if(t?.class&&i.Model.relations(t.class)){const s=i.Model.relations(t.class).map(t=>`${e}.${t}`);r=[...r,...s],a=i.Model.nestedRelations(t.class,r)}}return[...new Set([...r,...a])]}).bind(i.Model),i.Model.generatedBySequence=((e,t)=>{const r="function"!=typeof e?e.constructor:e;return!!i.Model.sequenceFor(r).generated}).bind(i.Model),i.Model.fromTable=(t=>{const r=n.Metadata.innerGet(Symbol.for(e.PersistenceKeys.TABLE));if(!r||!r[t]||!i.Model.get(r[t].name))throw new a.InternalError("No table metadata found for model. did you use @table()?");return i.Model.get(r[t].name)}).bind(i.Model),n.Metadata.createdBy=(t=>{const r=n.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.CREATED_BY);if(!r)throw new a.InternalError("No createdBy metadata found for model. did you use @createdBy()?");return r}).bind(n.Metadata),n.Metadata.updatedBy=(t=>{const r=n.Metadata.get("function"!=typeof t?t.constructor:t,e.PersistenceKeys.UPDATED_BY);if(!r)throw new a.InternalError("No updatedBy metadata found for model. did you use @updatedBy()?");return r}).bind(n.Metadata),i.Model.tableName=t=>{if(!(t instanceof i.Model?i.Model.get(t.constructor.name):t))throw new a.InternalError("Unable to find model "+t);return n.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.TABLE)||(t instanceof i.Model?t.constructor.name:t.name)},i.Model.columnName=(t,r)=>n.Metadata.get(t instanceof i.Model?t.constructor:t,n.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,i.Model.sequenceName=(e,...t)=>[i.Model.tableName(e),...t].join("_"),i.Model.sequenceFor=(e,t)=>{if(t)throw new x("not currently supported");const r=i.Model.pkProps(e instanceof i.Model?e.constructor:e);if(!r)throw new a.InternalError("No sequence options defined for model. did you use the @pk decorator?");return r},i.Model.indexes=t=>{const r=n.Metadata.get(t instanceof i.Model?t.constructor:t,e.PersistenceKeys.INDEX);return Object.keys(r||{}).reduce((t,a)=>(t[a]={[e.PersistenceKeys.INDEX]:r[a]},t),{})},t.Injectables.services=()=>n.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>n.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class be extends v{constructor(){super()}logCtx(e,t,r=!1){if(!this.adapter)throw new a.InternalError("Adapter not set yet");return this.adapter.logCtx(e,t,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:r}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);r.verbose(`Initializing ${this.adapter}'s event Dispatch`);const s=this.adapter;[a.OperationKeys.CREATE,a.OperationKeys.UPDATE,a.OperationKeys.DELETE,a.BulkCrudOperationKeys.CREATE_ALL,a.BulkCrudOperationKeys.UPDATE_ALL,a.BulkCrudOperationKeys.DELETE_ALL].forEach(e=>{if(!s[e])throw new a.InternalError(`Method ${e} not found in ${s.alias} adapter to bind Observables Dispatch`);let t=Object.getOwnPropertyDescriptor(s,e),r=s;for(;!t&&r!==Object.prototype;)r=Object.getPrototypeOf(r),t=Object.getOwnPropertyDescriptor(r,e);function i(e){switch(e){case a.BulkCrudOperationKeys.CREATE_ALL:return a.OperationKeys.CREATE;case a.BulkCrudOperationKeys.UPDATE_ALL:return a.OperationKeys.UPDATE;case a.BulkCrudOperationKeys.DELETE_ALL:return a.OperationKeys.DELETE;default:return e}}t&&t.writable?s[e]=new Proxy(s[e],{apply:async(t,r,a)=>{const{log:s,ctxArgs:o,ctx:n}=r.logCtx(a.slice(3-(4-a.length),a.length),t),[c,d,l]=a,u=await t.call(r,c,d,l,...o),p=[c,i(e),d];return n.get("observeFullResult")&&p.push(Array.isArray(u)?u.map(e=>c(e)):c(u)),this.updateObservers(...p,...o).catch(t=>s.error(`Failed to dispatch observer refresh for ${e} on ${c.name||c} for ${d}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof R))throw new x("Only Adapters can be observed by dispatch");return this.adapter=e,this.models=R.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(e)}unObserve(e){if(this.adapter!==e)throw new x("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 a.InternalError("Model must be provided for observer update");const o=e&&"string"==typeof e?e:i.Model.tableName(e),{log:n,ctxArgs:c,ctx:d}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${o}: ${r}${d.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(e,t,r,...c)}catch(e){throw new a.InternalError("Failed to refresh dispatch: "+e)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${o}:${t}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Ee(e,t,r,a){if(e.get("allowGenerationOverride")&&void 0!==a[r])return;let{seed:s,args:i}=t;s&&"function"==typeof s&&(s=s(a,...i||[],e)),a[r]=await B.instance.generate(s)}function ve(t=!1,r,...s){"function"==typeof t&&(r=t,t=!1);const o=e.PersistenceKeys.UUID;return n.Decoration.for(o).define({decorator:(t,r,...s)=>{const o={update:t,seed:r,args:s},c=[i.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Ee,o,{priority:54})];return t&&c.push(a.onUpdate(Ee,o,{priority:54})),t||c.push(a.readonly()),n.apply(...c)},args:[t,r,...s]}).apply()}async function Se(e,t,r,s,o){const n=t.logger.for(Se);if(!s){const t=i.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=ye.forModel(t,r),n.info("Retrieved "+s.toString())}let c;if(s=o?s.override(o):s,void 0===e[i.Model.pk(s.class)])n.info(`No pk found in ${i.Model.tableName(s.class)} - creating`),c=await s.create(e,t);else{n.info(`pk found in ${i.Model.tableName(s.class)} - attempting update`);try{c=await s.update(e,t),n.info("Updated "+i.Model.tableName(s.class))}catch(r){if(!(r instanceof a.NotFoundError))throw r;n.info("update Failed - creating new "+i.Model.tableName(s.class)),c=await s.create(e,t)}n.info("After create update: "+c)}return c}async function Oe(e,t,r,s){const o=s[r];if(!o)return;if("object"!=typeof o){const t=Ne(s,r,this.adapter.alias),a=await t.read(o,e);return await De(e,s,r,o,a),void(s[r]=o)}const n="function"!=typeof t.class||t.class.name?t.class:t.class();if(!n)throw new a.InternalError("Could not find model "+t.class);const c=ye.forModel(n,this.adapter.alias),d=await c.override(this._overrides).create(o,e),l=i.Model.pk(d);await De(e,s,r,d[l],d),s[r]=d[l]}async function Te(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;if("object"!=typeof o){const e=Ne(s,a,this.adapter.alias),r=await e.override(this._overrides).read(o,t);return await De(t,s,a,o,r),void(s[a]=o)}const n=await Se(s[a],t,this.adapter.alias,void 0,this._overrides),c=i.Model.pk(n);await De(t,s,a,n[c],n),s[a]=n[c]}async function xe(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const n=Ne(s,a,this.adapter.alias);let c;c=o instanceof i.Model?await n.delete(s[a][n.pk],t):await n.delete(s[a],t),await De(t,s,a,c[n.pk],c)}async function ke(e,t,r,s){const o=s[r];if(!o||!o.length)return;const n=typeof o[0];if(!o.every(e=>typeof e===n))throw new a.InternalError(`Invalid operation. All elements of property ${r} must match the same type.`);const c=e.logger.for(ke),d=new Set([...o]);if("object"!==n){const t=Ne(s,r,this.adapter.alias),a=await t.readAll([...d.values()],e);for(let t=0;t<a.length;t++){const s=a[t];c.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await De(e,s,r,[...d.values()][t],a)}return s[r]=[...d],void c.info("SET ONE TO MANY IDS: "+s[r])}const l=i.Model.pk(o[0].constructor),u=new Set;for(const t of o){c.info("Creating or updating one-to-many model: "+JSON.stringify(t));const a=await Se(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(a)} under ${a[l]}`),await De(e,s,r,a[l],a),c.info("Creating or updating one-to-many model: "+JSON.stringify(t)),u.add(a[l])}s[r]=[...u]}async function Ae(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return ke.call(this,t,r,a,s)}async function Ce(t,r,s,i){if(r.cascade.delete!==e.Cascade.CASCADE)return;const o=i[s];if(!o||!o.length)return;const n=typeof o[0];if(!o.every(e=>typeof e===n))throw new a.InternalError(`Invalid operation. All elements of property ${s} must match the same type.`);const c="function"!=typeof r.class||r.class.name?r.class:r.class(),d="object"===n,l=d?ye.forModel(c,this.adapter.alias):Ne(i,s,this.adapter.alias),u=[...new Set([...d?o.map(e=>e[l.pk]):o]).values()];let p,h;try{p=await l.deleteAll(u,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){h=p[e];try{await De(t,i,s,u[e],h)}catch(r){throw t.logger.error(`Failed to cache record ${u[e]} with key ${s} and model ${JSON.stringify(i,void 0,2)} `,r),r}}i[s]=u}function Me(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function De(e,t,r,a,s){const i=Me(t.constructor.name,r,a),o=e.get("cacheForPopulate")||{};return o[i]=s,e.accumulate({cacheForPopulate:o})}async function Pe(e,t,r,s){if(!t.populate)return;const i=s[r],o=Array.isArray(i);if(void 0===i||o&&0===i.length)return;const n=await(async(t,r,s,i)=>{let o,n;const c=[],d=t.get("cacheForPopulate")||{};for(const t of i){o=Me(r.constructor.name,s,t);try{if(n=d[o],!n)throw Error("Not found in cache")}catch(i){const o=Ne(r,s);if(!o)throw new a.InternalError("Could not find repo");n=await o.read(t,e)}c.push(n)}return c})(e,s,r,o?i:[i]);s[r]=o?n:n[0]}async function Be(t,r,s,o,n){if(r.cascade.update!==e.Cascade.CASCADE)return;const c=o[s];if(void 0===c||Array.isArray(c)&&0===c.length)return;if(!n)throw new a.InternalError("No way to compare old model. do you have updateValidation and mergeModels enabled?");function d(e){return Array.isArray(e)?e.map(d):"object"!=typeof e?e:e[i.Model.pk(e)]}const l=d(o[s]),u=d(n[s]);if(void 0===u||i.isEqual(l,u))return;if(Array.isArray(l)!==Array.isArray(u))throw new a.InternalError("Cannot cascade update for different array types");const p=(Array.isArray(l)?l:[l]).filter(Boolean),h=(Array.isArray(u)?u:[u]).filter(Boolean).filter(e=>!p.includes(e)),g=Ne(o,s);if(!g)throw new a.InternalError("Could not find repo");try{const e=await g.deleteAll(h,t);t.logger.debug(`Deleted ${e.length} entries from table ${i.Model.tableName(g.class)} due to cascade rules with `)}catch(e){throw new a.InternalError("Error deleting cascade entries: "+e)}}R&&(R._baseDispatch=be);const Ie=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Ne(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=n.Metadata.get(e instanceof i.Model?e.constructor:e,n.Metadata.key(i.ValidationKeys.REFLECT,t,i.ValidationKeys.LIST))?.clazz;if(!r)throw new a.InternalError("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=n.Metadata.getPropDesignTypes(e instanceof i.Model?e.constructor:e,t)?.designTypes;const o=s?.find(e=>!Ie.includes((""+e.name).toLowerCase()));return ye.forModel(o,r)}class Re extends a.BadRequestError{constructor(e,t=Re.name,r=401){super(e,t,r)}}class Le extends Re{constructor(e,t=Le.name){super(e,t,403)}}class $e extends a.InternalError{constructor(e){super(e,$e.name,503)}}function Ke(t){return n.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>(n.Metadata.set(e.PersistenceKeys.TABLE,t||r.name.toLowerCase(),r),n.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r)),args:[t]}).apply()}function Fe(t){return n.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>n.propMetadata(n.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}function je(t,r,a){return n.Decoration.for(e.PersistenceKeys.INDEX).define({decorator:(t,r,a)=>(s,i)=>("string"==typeof t&&(a=t,t=void 0,r=void 0),"string"==typeof r&&(a=r,r=void 0),!r&&t&&t.find(t=>![e.OrderDirection.ASC,e.OrderDirection.DSC].includes(t))&&(r=t,t=void 0),n.propMetadata(n.Metadata.key(`${e.PersistenceKeys.INDEX}${r&&r?.length?"."+r.join("."):""}`,i),{directions:t,compositions:r,name:a})(s,i)),args:[t,r,a]}).apply()}async function Ue(e,t,r,s){if(s[r]&&(await this.select().where(F.attribute(r).eq(s[r])).execute()).length)throw new a.ConflictError(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}async function qe(e,t,r,a){throw new Re("This adapter does not support user identification")}function Ye(){return n.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>n.apply(a.onCreate(qe),n.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply()}function Ge(){return n.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>n.apply(a.onUpdate(qe),n.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),args:[]}).apply()}function ze(){return a.timestamp([a.OperationKeys.CREATE])}function He(){return a.timestamp()}function Qe(e){const t="function"==typeof e&&e.name?e:e(),r=i.Model.pk(t);return n.Metadata.allowedTypes(t,r)||[]}function Ve(...t){return(r,a)=>{const s=n.Metadata.get(r,n.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],i=[...new Set([...s,...t])];return n.apply(n.metadata(n.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),i))(r,a)}}function We(t,r){return n.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(n.propMetadata(t,r)(a,s),n.propMetadata(n.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class Je extends i.Model{constructor(e){super(e)}}r.__decorate([ze(),r.__metadata("design:type",Date)],Je.prototype,"createdAt",void 0),r.__decorate([He(),r.__metadata("design:type",Date)],Je.prototype,"updatedAt",void 0);const Xe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ze=Xe,et={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},tt=Object.assign({},et,{type:"BigInt"});async function rt(e,t,r,s){if(!t.type||!t.generated||s[r])return;let o;t.name||(t.name=i.Model.sequenceName(s,"pk"));try{o=await this.adapter.Sequence(t,this._overrides)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${t.name}: ${e}`)}var n,c,d;n=s,c=r,d=await o.next(e),Reflect.set(n,c,d)}function at(t,r){return(s,o)=>{if(n.prop()(s,o),!t.type){const e=n.Metadata.type(s.constructor,o);if(![Number.name,String.name,BigInt.name].includes(e?.name||e))throw Error("Incorrrect option type");t.type=e}switch(t.type){case String.name||String.name.toLowerCase():case String:t.generated=void 0!==t.generated&&t.generated,t.type=String;break;case Number.name||String.name.toLowerCase():case Number:t.generated=void 0===t.generated||t.generated,t.type=Number;break;case BigInt.name||BigInt.name.toLowerCase():case BigInt:t.type=BigInt,t.generated=void 0===t.generated||t.generated;break;case"uuid":case"serial":t.generated=!0;break;default:throw Error("Unsupported type")}void 0===t.generated&&(t.generated=!0);const c=[n.prop(),je([e.OrderDirection.ASC,e.OrderDirection.DSC]),i.required(),a.readonly(),n.propMetadata(n.Metadata.key(a.DBKeys.ID,o),t),a.onCreate(rt,t,r)];return t.generated&&c.push(a.generated()),n.apply(...c)(s,o)}}function st(e){const t=Object.assign({},Ze);return delete t.generated,e=Object.assign({},t,e),n.Decoration.for(a.DBKeys.ID).define({decorator:at,args:[e,{priority:60}]}).apply()}e.SequenceModel=class extends Je{constructor(e){super(e)}},r.__decorate([st({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([i.required(),je(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([Ke("??sequence"),i.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class it extends v{static{this.lock=new o.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=ye.forModel(e.SequenceModel,r.alias).override(a)}async current(...e){const{log:t,ctx:r}=await this.logCtx(e,a.OperationKeys.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 a.NotFoundError){if(t.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new a.InternalError("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(e){throw new a.InternalError(`Failed to parse initial value for sequence ${i}: ${e}`)}}throw new a.InternalError(`Failed to retrieve current value for sequence ${s}: ${e}`)}}async increment(t,r){const{log:s,ctx:i}=this.adapter.logCtx([r],this.increment),{type:o,incrementBy:n,name:c}=this.options;if(!c)throw new a.InternalError("Sequence name is required");return it.lock.execute(async()=>{const r=t||n;if(r%n!==0)throw new a.InternalError("Value to increment does not consider the incrementBy setting: "+n);const d="function"==typeof o&&o?.name?o.name:o,l=await this.current(i),u=async t=>{try{return await this.repo.update(new e.SequenceModel({id:c,current:t}),i)}catch(r){if(r instanceof a.NotFoundError)return s.debug(`Sequence create ${c} current=${l} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===d)for(;;){const e=await Promise.resolve(B.instance.generate(l));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${l} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(d){case Number.name:return this.parse(e)+r;case BigInt.name:return this.parse(e)+BigInt(r);case String.name:return this.parse(e);case"serial":return await Promise.resolve(I.instance.generate(e));default:throw new a.InternalError("Should never happen")}})(l),h=await u(p);return s.debug(`Sequence.increment ${c} current=${l} next=${p}`),h.current},c)}async next(...e){const{ctx:t}=(await this.logCtx(e,a.OperationKeys.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.OperationKeys.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new x(`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,o=this.parse(this.options.incrementBy),n=await this.increment(this.parse(e)*o,r);let c=[];for(let t=0;e-1>=t;t++)c.push(n-o*this.parse(t));if(c=c.reverse(),c[c.length-1]!==n&&"String"!==i)throw new a.InternalError("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(e){return it.parseValue(this.options.type,e)}logCtx(t,r,a=!1){const s=this.adapter.logCtx([e.SequenceModel,...t],r,a);function i(e){return e.ctxArgs.shift(),e}return s instanceof Promise?s.then(i):i(s)}static pk(e){return i.Model.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 x(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function ot(r,s){return(o,c)=>c?t.inject(n.Metadata.constr(r))(o,c):(n.Metadata.set(a.DBKeys.REPOSITORY,n.Metadata.key(s||R.currentFlavour,i.Model.tableName(r)),o),n.metadata(a.DBKeys.REPOSITORY,o.name)(r),s=s||n.Metadata.get(o.constructor,e.PersistenceKeys.ADAPTER),ye.register(r,o,s),t.injectable(n.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(o))}R._baseSequence=it;class nt extends a.InternalError{constructor(e){super(e,nt.name,500)}}class ct extends s.LoggedClass{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,a){super(),this.adapter=e,this.query=t,this.size=r,this.clazz=a,P(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi"))}async pagePrefix(t,...r){const{ctxArgs:a}=(await this.adapter.logCtx([this.clazz,...r],e.PreparedStatementKeys.PAGE_BY,!0)).for(this.pagePrefix);return a.shift(),[t,...a]}async pagePrepared(t,r,...a){const{log:s,ctxArgs:i}=this.adapter.logCtx(!r||r instanceof E?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof E||(this._bookmark=r);const o=ye.forModel(this.clazz,this.adapter.alias),n=this.query,{method:c,args:d,params:l}=n,u=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!c.match(u))throw new x(`Method ${c} is not supported for pagination`);u.lastIndex=0;const p=c.replace(u,e.PreparedStatementKeys.PAGE_BY),h=[p,...d];let g={limit:this.size,offset:t,bookmark:this._bookmark};p!==e.PreparedStatementKeys.PAGE_BY||h.length>2?g={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(g);const y=await o.statement(...h,...i);return this.apply(y)}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 $("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new $(`Only ${this._totalPages} are available. Cannot go to page ${e}`);return e}async page(e=1,t,...r){const{ctxArgs:a}=this.adapter.logCtx([t,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(e,...a);throw new x("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 a.SerializationError(e)}}apply(e){const t="string"==typeof e?ct.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 a.SerializationError(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 dt,lt,ut,pt,ht,gt,yt;class ft extends v{constructor(e,t){super(),this.adapter=e,this.overrides=t,this._inCountMode=!1,[this.execute,this.paginate].forEach(e=>{a.prefixMethod(this,e,(...t)=>this.executionPrefix(e,...t),e.name)})}async executionPrefix(t,...r){const{ctx:a,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...r],t.name===this.paginate.name?e.PreparedStatementKeys.PAGE_BY:e.PersistenceKeys.QUERY,!0,this.overrides||{})).for(t);s.shift();const o=a.get("forcePrepareSimpleQueries"),n=a.get("forcePrepareComplexQueries");i.silly(`statement force simple ${o}, forceComplex: ${n}`);const c=this.hasAggregation()&&!this.whereCondition&&!this.selectSelector?.length&&1>=(this.groupBySelectors?.length||0);return(o&&(this.isSimpleQuery()||c)||n)&&(i.silly(`squashing ${n?"complex":"simple"} query to prepared statement`),await this.prepare(a),i.silly(`squashed ${n?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(ft)}select(e){return Object.defineProperty(this,"selectSelector",{value:e,writable:!1}),this}distinct(e){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!e)throw new L("distinct() requires a selector when not chained after count()");return this.distinctSelector=e,this}max(e){return this.maxSelector=e,this}min(e){return this.minSelector=e,this}sum(e){return this.sumSelector=e,this}avg(e){return this.avgSelector=e,this}count(e){return this.countSelector=e??null,this._inCountMode=!0,this}from(e){if(this.fromSelector="string"==typeof e?i.Model.get(e):e,!this.fromSelector)throw new L("Could not find selector model: "+e);return this}where(e){return this.whereCondition=e,this}orderBy(e,t){return this.orderBySelectors=[this.normalizeOrderCriterion(e,t)],this}thenBy(e,t){if(Array.isArray(e)||void 0!==t){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new L("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new L("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(e),this}normalizeOrderCriterion(e,t){if(Array.isArray(e)){const[t,r]=e;return[t,this.normalizeOrderDirection(r)]}return[e,this.normalizeOrderDirection(t)]}normalizeOrderDirection(t){if(!t)throw new L("orderBy direction is required when specifying the attribute separately.");const r=(t+"").toLowerCase();if(r===e.OrderDirection.ASC)return e.OrderDirection.ASC;if(r===e.OrderDirection.DSC)return e.OrderDirection.DSC;throw new L(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new L("groupBy must be called before orderBy.");return this.groupBySelectors=[e],this}limit(e){return this.limitSelector=e,this}offset(e){return this.offsetSelector=e,this}async execute(...e){const{log:t,ctx:r,ctxArgs:a}=this.logCtx(e,this.execute);try{if(this.prepared)return this.executePrepared(...e);t.silly("Building raw statement...");const s=this.build();t.silly("executing raw statement");const o=await this.raw(s,...a);if(this.hasAggregation())return o;if(!this.selectSelector){const e=i.Model.pk(this.fromSelector),t=function(t){const a=t[e];return this.adapter.revert(t,this.fromSelector,a,void 0,r)}.bind(this);return this.groupBySelectors?.length?this.revertGroupedResults(o,t):Array.isArray(o)?o.map(t):t(o)}return o}catch(e){throw new L(e)}}revertGroupedResults(e,t){return Array.isArray(e)?e.map(t):e&&"object"==typeof e?Object.entries(e).reduce((e,[r,a])=>(e[r]=this.revertGroupedResults(a,t),e),{}):e}async executePrepared(...e){const t=ye.forModel(this.fromSelector,this.adapter.alias),{method:r,args:a,params:s}=this.prepared;return t.statement(r,...a,s,...e)}async raw(e,...t){const{ctx:r,ctxArgs:a}=this.logCtx(t,this.raw);if(!r.get("allowRawStatements"))throw new x("Raw statements are not allowed in the current configuration");const s=await this.adapter.raw(e,!0,...a);if(this.hasAggregation())return s;if(!this.selectSelector)return s;const o=i.Model.pk(this.fromSelector),n=function(e){const t=e[o];return this.adapter.revert(e,this.fromSelector,t,void 0,r)}.bind(this);return Array.isArray(s)?s.map(n):n(s)}prepareCondition(t,r){let{attr1:a,operator:s,comparison:i}=t;const o={};switch(s){case e.GroupOperator.AND:case e.GroupOperator.OR:{let e=a,t=i;if("string"!=typeof a){const t=this.prepareCondition(a,r);e=t.method,o.args=[...o.args||[],...t.args||[]]}if(i instanceof F){const e=this.prepareCondition(i,r);t=e.method,o.args=[...o.args||[],...e.args||[]]}o.method=`${e} ${s.toLowerCase()} ${t}`;break}case e.Operator.EQUAL:o.method=a,o.args=[...o.args||[],i];break;case e.Operator.DIFFERENT:o.method=a+" diff",o.args=[...o.args||[],i];break;case e.Operator.REGEXP:o.method=a+" matches",o.args=[...o.args||[],i];break;case e.Operator.BIGGER:o.method=a+" bigger",o.args=[...o.args||[],i];break;case e.Operator.BIGGER_EQ:o.method=a+" bigger than equal";break;case e.Operator.SMALLER:o.method=a+" less",o.args=[...o.args||[],i];break;case e.Operator.SMALLER_EQ:o.method=a+" less than equal",o.args=[...o.args||[],i];break;case e.Operator.IN:o.method=a+" in",o.args=[...o.args||[],i];break;default:throw new L("Unsupported operator "+s)}return o}squash(t){if(this.whereCondition&&this.whereCondition.comparison instanceof F)return;if(!this.whereCondition&&!this.selectSelector?.length){if(void 0!==this.countSelector&&!this.countDistinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.COUNT_OF,args:null!==this.countSelector?[this.countSelector]:[],params:{}};if(this.maxSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MAX_OF,args:[this.maxSelector],params:{}};if(this.minSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.MIN_OF,args:[this.minSelector],params:{}};if(this.avgSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.AVG_OF,args:[this.avgSelector],params:{}};if(this.sumSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.SUM_OF,args:[this.sumSelector],params:{}};if(this.distinctSelector)return{class:this.fromSelector,method:e.PreparedStatementKeys.DISTINCT_OF,args:[this.distinctSelector],params:{}};if(1===this.groupBySelectors?.length)return{class:this.fromSelector,method:e.PreparedStatementKeys.GROUP_OF,args:[this.groupBySelectors[0]],params:{}}}if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let r;this.whereCondition&&(r=this.whereCondition.attr1);const a=this.orderBySelectors?.[0]?this.orderBySelectors[0]:r?[r,e.OrderDirection.DSC]:[i.Model.pk(this.fromSelector),e.OrderDirection.DSC],[s,o]=a,n={direction:o};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const c={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[s],params:n};return r&&(c.method=e.PreparedStatementKeys.FIND_BY,c.args=[r,this.whereCondition.comparison],c.params=n),c}async prepare(t){if(t=t||await this.adapter.context(e.PersistenceKeys.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}if(t.get("forcePrepareSimpleQueries")||t.get("forcePrepareComplexQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const r=[],a={},i={class:this.fromSelector,args:r,params:a};let o,n=e.QueryClause.FIND_BY;void 0!==this.countSelector?(n=e.QueryClause.COUNT_BY,o=null!==this.countSelector?this.countSelector:void 0):this.sumSelector?(n=e.QueryClause.SUM_BY,o=this.sumSelector):this.avgSelector?(n=e.QueryClause.AVG_BY,o=this.avgSelector):this.minSelector?(n=e.QueryClause.MIN_BY,o=this.minSelector):this.maxSelector?(n=e.QueryClause.MAX_BY,o=this.maxSelector):this.distinctSelector?(n=e.QueryClause.DISTINCT_BY,o=this.distinctSelector):!this.groupBySelectors?.length||this.selectSelector?.length||this.whereCondition||(n=e.QueryClause.GROUP_BY_PREFIX,o=this.groupBySelectors[0]);const c=[n];if(o&&c.push(o),this.whereCondition){const e=this.prepareCondition(this.whereCondition,t);c.push(e.method),e.args&&e.args.length&&r.push(...e.args)}if(this.selectSelector&&c.push(e.QueryClause.SELECT,this.selectSelector.join(` ${e.QueryClause.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...r]=this.orderBySelectors;c.push(e.QueryClause.ORDER_BY,t[0]),a.direction=t[1],r.length&&(a.order=this.orderBySelectors.map(([e,t])=>[e,t]),r.forEach(([t])=>{c.push(e.QueryClause.THEN_BY,t)}))}if(this.groupBySelectors?.length&&n!==e.QueryClause.GROUP_BY_PREFIX){const[t,...r]=this.groupBySelectors;c.push(e.QueryClause.GROUP_BY,t),r.forEach(t=>c.push(e.QueryClause.THEN_BY,t))}else this.groupBySelectors?.length&&n===e.QueryClause.GROUP_BY_PREFIX&&this.groupBySelectors.slice(1).forEach(t=>c.push(e.QueryClause.THEN_BY,t));return this.limitSelector&&(a.limit=this.limitSelector),this.offsetSelector&&(a.skip=this.offsetSelector),i.method=s.toCamelCase(c.join(" ")),i.params=a,this.prepared=i,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelectors&&this.groupBySelectors.length||void 0!==this.countSelector||this.countDistinctSelector||this.maxSelector||this.minSelector||this.sumSelector||this.avgSelector||this.distinctSelector)}hasAggregation(){return void 0!==this.countSelector||void 0!==this.countDistinctSelector||void 0!==this.maxSelector||void 0!==this.minSelector||void 0!==this.sumSelector||void 0!==this.avgSelector||void 0!==this.distinctSelector||(this.groupBySelectors?.length||0)>0}async paginate(e,...t){t.pop();try{return this.adapter.Paginator(this.prepared||this.build(),e,this.fromSelector)}catch(e){throw new L(e)}}toString(){return this.adapter.flavour+" statement"}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array]),r.__metadata("design:returntype",Object)],ft.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(dt="undefined"!=typeof S&&S)?dt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(lt="undefined"!=typeof S&&S)?lt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ut="undefined"!=typeof S&&S)?ut:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(pt="undefined"!=typeof S&&S)?pt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"sum",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ht="undefined"!=typeof S&&S)?ht:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"avg",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(gt="undefined"!=typeof S&&S)?gt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],ft.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[F]),r.__metadata("design:returntype",Object)],ft.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],ft.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],ft.prototype,"thenBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(yt="undefined"!=typeof Key&&Key)?yt:Object]),r.__metadata("design:returntype",Object)],ft.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],ft.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],ft.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],ft.prototype,"execute",null);class mt extends v{constructor(e){super(),this.name=e,this.observers=[],this.Context=E}observe(e,t){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new T,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(e,t),r.verbose("Registered new observer "+(e.constructor.name||e.toString())),()=>this.unObserve(e)}unObserve(e){if(!this.observerHandler)throw new a.InternalError("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 a.InternalError("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:o}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(e,t,r,...o)}async flags(e,t,...r){t.correlationId=t.correlationId||`${e}-${B.instance.generate()}`;const a=t.logger||s.Logging.for(this);return a.setConfig({correlationId:t.correlationId}),Object.assign({},h,t,{args:r,timestamp:new Date,operation:e,logger:a})}async refresh(e,t,r,...a){return this.updateObservers(e,t,r,...a)}async context(e,t,...r){this.log.for(this.context).silly(`creating new context for ${e} operation with flag overrides: ${JSON.stringify(t)}`);let a=r.pop();void 0===a||a instanceof E||(r.push(a),a=void 0),t=a?Object.assign({},a.toOverrides(),t):t;const s=await this.flags("string"==typeof e?e:e.name,t,...[...r,a].filter(Boolean));if(a){if(!(a instanceof this.Context)){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}if(a.get("operation")!==e){const e=(new this.Context).accumulate({...a.cache,...s,parentContext:a});return a.accumulate({childContexts:[...a.getOrUndefined("childContexts")||[],e]}),e}return a.accumulate(s)}return(new this.Context).accumulate({...s})}logCtx(e,t,r=!1,a){return v.logCtx.call(this,t,a||{},r,...e.filter(e=>void 0!==e))}static get(e){if(!e)throw new a.InternalError("No name provided");const r=C(e),s=t.Injectables.get(r);if(s)return s;throw new a.InternalError("No Service found for "+("string"==typeof e?e:"symbol"==typeof e?e.toString():e.name))}static async boot(...r){let s=r.pop();void 0===s||s instanceof E||(r.push(s),s=void 0);const i=await mt.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new E(s).accumulate({...i,parentContext:s}):(new E).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=mt.prototype.logCtx(r,this.boot),c=t.Injectables.services();for(const[e,r]of Object.entries(c))try{o.verbose(`Booting ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);s instanceof _t&&(o.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(t){throw new a.InternalError(`Failed to boot ${e} service:${t}`)}}static async shutdown(...r){let s=r.pop();void 0===s||s instanceof E||(r.push(s),s=void 0);const i=await mt.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...r);s=s?new E(s).accumulate({...i,parentContext:s}):(new E).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=mt.prototype.logCtx(r,this.shutdown),c=t.Injectables.services();for(const[e,r]of Object.entries(c).reverse())try{o.verbose(`Shutting down ${r.name} service...`);const s=t.Injectables.get(r);if(!s)throw new a.InternalError("Failed to resolve injectable for "+e);if(s instanceof _t){o.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(e){o.error(`Failed to gracefully shutdown ${r.name} service`,e)}}}catch(t){throw new a.InternalError(`Failed to Shutdown services ${e}: ${t}`)}}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],mt.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],mt.prototype,"unObserve",null);class _t extends mt{constructor(){super()}async boot(...t){const{log:r,ctxArgs:a}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.boot);r.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...a);this._config=s,this._client=i}get config(){if(!this._config)throw new a.InternalError("Config not initialized");return this._config}get client(){if(!this._client)throw new a.InternalError("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 wt(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&D(r,e))throw Error(`Operation "${e}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return s.apply(this,t)},a}}r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Promise)],_t.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],_t.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],_t.prototype,"client",null);const bt=()=>wt(a.OperationKeys.CREATE),Et=()=>wt(a.OperationKeys.READ),vt=()=>wt(a.OperationKeys.UPDATE),St=()=>wt(a.OperationKeys.DELETE);function Ot(r){return(a,s,i)=>{i||s?(n.prop()(a,s),r=r||n.Metadata.type(a.constructor,s)):r=r||a,r=C(r);const o=[];if(i&&"number"==typeof i.value)o.push(t.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");o.push(t.inject(r))}else n.Metadata.set(e.PersistenceKeys.SERVICE,r,a),o.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return n.apply(...o)(a,s,i)}}const Tt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class xt extends mt{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ye.forModel(this.clazz)),this._repository}constructor(e,t){super(t??e.name+"Service"),this.clazz=e}static getService(e){if(!e)throw new a.InternalError("No name provided");const t=Tt(e);try{const e=mt.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}for(e,...t){return new Proxy(this,{get:(r,a,s)=>"repo"===a?r.repo.override(e,...t):Reflect.get(r,a,s)})}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create);return this.repo.create(e,...r)}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(e,...r)}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.UPDATE,!0)).for(this.update);return this.repo.update(e,...r)}async updateAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(e,...r)}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}static forModel(e,t){let a;t=Tt(t||e);try{a=xt.get(t)}catch(e){a=void 0}if(a instanceof xt)return a;const s=this;let i=class extends s{constructor(){super(e)}};return i=r.__decorate([Ot(t),r.__metadata("design:paramtypes",[])],i),new i}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}}r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"create",null),r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"createAll",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"delete",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"deleteAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"read",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"readAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],xt.prototype,"query",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],xt.prototype,"update",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],xt.prototype,"updateAll",null),e.TaskBackoffModel=class extends i.Model{constructor(t){super(t),this.strategy=e.BackoffStrategy.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=e.JitterStrategy.FULL}},r.__decorate([i.required(),i.type(String),i.option(e.BackoffStrategy),n.description("the backoff strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),r.__decorate([i.required(),n.description("base interval between attempts"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),r.__decorate([i.required(),n.description("max interval"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),r.__decorate([i.type(String),i.option(e.JitterStrategy),n.description("optional jitter strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"jitter",void 0),e.TaskBackoffModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskBackoffModel),e.TaskErrorModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),n.description("The error message"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),r.__decorate([n.prop(),n.description("The error stack"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),r.__decorate([n.prop(),n.description("The error code"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),r.__decorate([n.prop(),n.description("The error details"),r.__metadata("design:type",Object)],e.TaskErrorModel.prototype,"details",void 0),e.TaskErrorModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskErrorModel),e.TaskEventModel=class extends i.Model{constructor(e){super(e),this.ts=new Date}},r.__decorate([a.composed(["taskId","classification","uuid"],":"),st(),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),r.__decorate([a.readonly(),i.required(),a.transient(),ve(!1),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"uuid",void 0),r.__decorate([a.readonly(),i.required(),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"taskId",void 0),r.__decorate([i.date(),i.required(),r.__metadata("design:type",Date)],e.TaskEventModel.prototype,"ts",void 0),r.__decorate([a.readonly(),i.required(),i.option(e.TaskEventType),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"classification",void 0),r.__decorate([n.prop(),a.readonly(),r.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=r.__decorate([Ke("task_event"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class kt extends i.JSONSerializer{constructor(){super()}preSerialize(e,...t){if(null===e||"object"!=typeof e)return e;const r=Object.assign({},e);if(e instanceof F)return r[i.ModelKeys.ANCHOR]="??condition",r;if(i.Model.isModel(e)){let t;try{t=n.Metadata.modelName(e.constructor)}catch(e){t=void 0}t&&(r[i.ModelKeys.ANCHOR]=t)}return r}deserialize(e,...t){const r=JSON.parse(e),a=r[i.ModelKeys.ANCHOR];return a?"??condition"===a?F.from(r):i.Model.build(r,a):r}serialize(e,...t){return JSON.stringify(this.preSerialize(e))}}e.TaskLogEntryModel=class extends i.Model{constructor(e){super(e),this.ts=new Date}},r.__decorate([i.date(),i.required(),r.__metadata("design:type",Date)],e.TaskLogEntryModel.prototype,"ts",void 0),r.__decorate([i.required(),i.option(s.LogLevel),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"level",void 0),r.__decorate([i.required(),n.prop(),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),r.__decorate([n.prop(),r.__metadata("design:type",Object)],e.TaskLogEntryModel.prototype,"meta",void 0),e.TaskLogEntryModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskLogEntryModel),e.TaskModel=class extends i.Model{constructor(t){super(t),this.atomicity=e.TaskType.ATOMIC,this.status=e.TaskStatus.PENDING,this.attempt=0,this.logTail=[]}},r.__decorate([st({type:"uuid"}),n.description("the task id"),r.__metadata("design:type",String)],e.TaskModel.prototype,"id",void 0),r.__decorate([i.required(),i.type(String),i.option(e.TaskType),n.description("defines a single or composite task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),r.__decorate([i.required(),n.description("Holds task classification - must match @task()"),r.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),r.__decorate([i.required(),i.type(String),i.option(e.TaskStatus),n.description("Holds the task current status"),r.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),r.__decorate([n.prop(),a.serialize(kt),n.description("Holds task input"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),r.__decorate([n.prop(),a.serialize(kt),n.description("Holds the task output when successfully completed"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the error for failed tasks"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskModel.prototype,"error",void 0),r.__decorate([i.required(),i.min(0),n.description("Holds the current attempt"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),r.__decorate([i.min(1),i.required(),n.description("max attempts for the task"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),r.__decorate([i.required(),a.serialize(),n.description("backoff configuration"),r.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),r.__decorate([i.date(),n.description("Next execution timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),r.__decorate([i.date(),n.description("Task scheduled timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),r.__decorate([n.prop(),n.description("Task lease owner identifier"),r.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),r.__decorate([i.date(),n.description("Task lease expiration timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the various steps definition and inputs - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"steps",void 0),r.__decorate([i.min(0),n.prop(),n.description("Holds the current step - only for type === 'composite'"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the step results - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),r.__decorate([n.prop(),a.serialize(),n.description("Holds the task log entries"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),r.__decorate([Fe(),ze(),n.description("timestamp of creation"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),r.__decorate([Fe(),He(),n.description("timestamp of last update"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),r.__decorate([Fe(),Ye(),n.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),r.__decorate([Fe(),Ge(),n.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=r.__decorate([n.description("Holds the current step when applicable"),Ke("tasks"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),n.description("The status of a step"),r.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),r.__decorate([n.prop(),n.description("The result of a successful step"),r.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),r.__decorate([n.prop(),n.description("the error of a failed step"),r.__metadata("design:type",e.TaskErrorModel)],e.TaskStepResultModel.prototype,"error",void 0),e.TaskStepResultModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepResultModel),e.TaskStepSpecModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),n.prop(),n.description("task handler type"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),r.__decorate([n.description("optional task step input"),n.prop(),r.__metadata("design:type",Object)],e.TaskStepSpecModel.prototype,"input",void 0),e.TaskStepSpecModel=r.__decorate([i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskStepSpecModel);class At extends i.Model{constructor(t){super(t),this.baseMs=1e3,this.jitter=e.JitterStrategy.FULL,this.maxMs=6e4,this.strategy=e.BackoffStrategy.EXPONENTIAL,i.Model.fromModel(this,t)}setBaseMs(e){return this.baseMs=e,this}setJitter(e){return this.jitter=e,this}setMaxMs(e){return this.maxMs=e,this}setStrategy(e){return this.strategy=e,this}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskBackoffModel(this)}}r.__decorate([i.required(),i.min(1e3),r.__metadata("design:type",Number)],At.prototype,"baseMs",void 0),r.__decorate([i.required(),i.option(e.JitterStrategy),r.__metadata("design:type",String)],At.prototype,"jitter",void 0),r.__decorate([i.gt("baseMs"),i.min(1e3),i.required(),r.__metadata("design:type",Number)],At.prototype,"maxMs",void 0),r.__decorate([i.required(),i.option(e.BackoffStrategy),r.__metadata("design:type",String)],At.prototype,"strategy",void 0);class Ct extends i.Model{setClassification(e){return this.classification=e,this}setStatus(e){return this.status=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new At,r=this;return t.build=new Proxy(t.build,{apply:(e,t,a)=>(r.backoff=Reflect.apply(e,t,a),r)}),t}setInput(e){return this.input=e,this}setMaxAttempts(e){return this.maxAttempts=e,this}constructor(t){super(t),this.status=e.TaskStatus.PENDING,this.atomicity=e.TaskType.ATOMIC,this.backoff=new e.TaskBackoffModel,this.maxAttempts=1,i.Model.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new a.ValidationError(t);return new e.TaskModel(this)}}r.__decorate([i.required(),r.__metadata("design:type",String)],Ct.prototype,"classification",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Ct.prototype,"status",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],Ct.prototype,"atomicity",void 0),r.__decorate([i.required(),r.__metadata("design:type",e.TaskBackoffModel)],Ct.prototype,"backoff",void 0),r.__decorate([n.prop(),r.__metadata("design:type",Object)],Ct.prototype,"input",void 0),r.__decorate([i.min(1),i.required(),r.__metadata("design:type",Number)],Ct.prototype,"maxAttempts",void 0);class Mt extends Ct{constructor(t){super(t),this.stepResults=[],i.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setSteps(e){return this.steps=e,this}addStep(t,r){this.steps=this.steps||[];const a=new Date;return this.steps.push(new e.TaskStepSpecModel({classification:t,input:r,createdAt:a,updatedAt:a})),this}}r.__decorate([i.list(()=>e.TaskStepSpecModel),r.__metadata("design:type",Array)],Mt.prototype,"steps",void 0);class Dt extends O{get type(){if(!this._type){const e=n.Metadata.get(this.constructor,_e);"string"==typeof e?this._type=e:e&&"string"==typeof e.type&&(this._type=e.type)}if(!this._type)throw new a.InternalError("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),a.wrapMethodWithContext(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(e,...t){const{log:r,ctx:a,ctxArgs:s}=this.logCtx(t,this.runPrefix);return r.info(`Running task ${a.taskId} attempt ${a.attempt}`),[e,...s]}runSuffix(e,t){const{log:r}=this.logCtx([t],this.runPrefix);return r.info(`Concluded task ${t.taskId} attempt ${t.attempt}`),e}}function Pt(e){return n.Decoration.for(_e).define({decorator:e=>t=>{const r={type:e};return n.Metadata.set(_e,e,t),n.metadata(_e,r)(t)},args:[e]}).apply()}e.CleanUpTask=class extends Dt{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof F)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=F.attr("status").eq(e.TaskStatus.SUCCEEDED).and(F.attr("updatedAt").lte(t.successfulExpiry)),i=F.attr("status").eq(e.TaskStatus.FAILED).and(F.attr("updatedAt").lte(t.failedExpiry)),o=F.attr("status").eq(e.TaskStatus.CANCELED).and(F.attr("updatedAt").lte(t.cancelledExpiry));s=r.or(i).or(o)}a.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(r);if(0===i.length)return a.info("No tasks found for cleanup"),[];a.info(`Found ${i.length} tasks to delete`);const o=await this.tasks.deleteAll(i.map(e=>e.id),r);return a.info(`Successfully deleted ${o.length} tasks`),a.debug("deleted tasks:",o),o}catch(e){throw a.error("Error during task cleanup",e),e}}},r.__decorate([ot(e.TaskModel),r.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=r.__decorate([Pt("cleanup-task"),r.__metadata("design:paramtypes",[])],e.CleanUpTask);class Bt{constructor(e,t=150,r=300,a){this.logger=e,this.bufferSize=t,this.maxBufferSize=r,this.pipe=a,this.history=[],this.root=this.logger.root,Object.values(s.LogLevel).forEach(e=>{this[e]=new Proxy(this[e],{apply:(t,r,a)=>{t.apply(r,a),r.push(e,...a)}})})}push(e,t,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([e,t,r])}flush(e){const t=this.history;return this.history=[],e&&t.length?e(t).catch(e=>this.logger.error("Failed to pipe logs",e)).finally(()=>this.history=[]):(this.history=[],t)}benchmark(e){return this.logger.benchmark(e)}clear(){return this.logger=this.logger.clear(),this}debug(e,t){this.logger.debug(e,t)}error(e,t,r){this.logger.error(e,t,r)}for(e,...t){return new Proxy(this,{get:(r,a)=>"logger"===a?Reflect.get(r,a).for(e,...t):Reflect.get(r,a)})}info(e,t){this.logger.info(e,t)}setConfig(e){this.logger.setConfig(e)}silly(e,t){this.logger.silly(e,t)}trace(e,t){this.logger.trace(e,t)}verbose(e,t,r){this.logger.verbose(e,t,r)}warn(e,t){this.logger.warn(e,t)}}function It(t,r={logProgress:!0,logStatus:!0,style:!0}){return async i=>{switch(t=t.for(i.taskId,{style:!1,timestamp:!1,logLevel:!1}),i.classification){case e.TaskEventType.LOG:{const e=i.payload;for(let[a,i,o]of e){r.style||(i=s.style(i),i=i.clear().toString());const e=[i];a===s.LogLevel.verbose&&e.push(1),e.push(o);try{t[a](...e)}catch(e){t.error("Failed to pipe task logs",e)}}break}case e.TaskEventType.PROGRESS:if(r.logProgress){const{currentStep:e,totalSteps:r}=i.payload;t.info(`### STEP ${e}/${r}`)}break;case e.TaskEventType.STATUS:if(r.logStatus){const r=i.payload?.status??i.payload;let o=s.style(r);switch(r){case e.TaskStatus.SUCCEEDED:o=o.green.bold;break;case e.TaskStatus.RUNNING:o=o.blue.bold;break;case e.TaskStatus.PENDING:o=o.yellow;break;case e.TaskStatus.WAITING_RETRY:o=o.yellow.bold;break;case e.TaskStatus.FAILED:o=o.red.bold;break;case e.TaskStatus.CANCELED:o=o.magenta.bold;break;case e.TaskStatus.SCHEDULED:o=o.cyan;break;default:throw new a.InternalError("Received unknown task status: "+i.payload)}t.info("### STATUS "+o)}break;default:throw new a.InternalError("Unknown task event classification: "+i.classification)}}}function Nt(t,r){const a=r.strategy===e.BackoffStrategy.FIXED?r.baseMs:r.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(a,r.maxMs);return r.jitter===e.JitterStrategy.FULL?Math.floor(Math.random()*s):s}function Rt(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Lt(e){return new Promise(t=>setTimeout(t,e))}class $t extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=$t.name,Object.setPrototypeOf(this,$t.prototype)}}class Kt extends E{get taskId(){return this.get("taskId")}get logger(){return super.logger}get pipe(){return this.get("pipe")}flush(){return this.get("flush")()}get attempt(){return this.get("attempt")}get progress(){return this.get("progress")}get heartbeat(){return this.get("heartbeat")}cacheResult(e,t){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[e]=t,this.cache.put("resultCache",r)}changeState(e,t){throw new $t({status:e,...t})}cancel(t,r){this.changeState(e.TaskStatus.CANCELED,{error:this.toTaskError(t,r)})}retry(t){this.changeState(e.TaskStatus.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,r){const a=t instanceof Date?t:t.build();this.changeState(e.TaskStatus.SCHEDULED,{error:this.toTaskError(r),scheduledTo:a})}toTaskError(t,r){if(t||r)return t instanceof e.TaskErrorModel?t:t instanceof Error?Rt(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}constructor(e){super(e)}}class Ft{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=n.Metadata.tasks();e&&Object.entries(e).forEach(([e,t])=>{let r;try{r=new t}catch(t){throw new a.InternalError(`Failed to initialize handler with key ${e}: ${t}`)}this.register(r)})}register(e){if(this.handlers.has(e.type))throw new a.InternalError("Duplicate task handler: "+e.type);this.handlers.set(e.type,e)}get(e){return this.handlers.get(e)}}class jt extends T{constructor(){super(...arguments),this.listeners=new Set}observe(e,t){return super.observe(e,t)}unObserve(e){super.unObserve(e)}emit(t,r){this.updateObservers(e.TaskEventModel,t.classification,t.id,t,r)}async updateObservers(e,t,r,a,...s){const{log:i,ctxArgs:o}=R.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(a=>{const{filter:s}=a;if(!s)return!0;try{return s(e,t,r,...o)}catch(e){return i.error(`Failed to filter observer ${a.observer.toString()}: ${e}`),!1}}).map(e=>{e.observer.refresh(a,...o)}))).forEach((e,t)=>{"rejected"===e.status&&i.error(`Failed to update observable ${this.observers[t].toString()}: ${e.reason}`)})}}class Ut extends a.BaseError{constructor(e,t,r,a,s,i=500){super(e,r,i),this.taskId=t,this.details=a,this.meta=s}}class qt extends Ut{constructor(e,t,r){super(qt.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class Yt extends Ut{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(Yt.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class Gt extends Ut{constructor(e,t,r){super(Gt.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class zt extends Ut{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(zt.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class Ht{constructor(t,r){this.bus=t,this.task=r,this.resolved=!1,this.unregistration=t.observe(this,(t,r,a,...s)=>a.startsWith(this.task.id)&&(t===e.TaskEventModel||t===i.Model.tableName(e.TaskEventModel))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED,e.TaskStatus.WAITING_RETRY,e.TaskStatus.SCHEDULED])}wait(){return this.awaitStatusTerminal([e.TaskStatus.SUCCEEDED,e.TaskStatus.FAILED,e.TaskStatus.CANCELED])}attach(e,t={logProgress:!0,logStatus:!0,style:!0}){this.pipe(It(e,t))}logs(t){this.pipe(async r=>{if(r.classification!==e.TaskEventType.LOG)return;const a=r.payload;await t(a)},e.TaskEventType.LOG)}pipe(t,r=e.TaskEventType.ALL){this.pipes=this.pipes||{},this.pipes[r]=this.pipes[r]||new Set,this.pipes[r].add(t)}succeed(e){this.complete()}fail(e){this.complete()}cancel(e){e.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(e.TaskStatus.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(e.TaskStatus.FAILED,t)}onCancel(t){return this.registerStatusHandler(e.TaskStatus.CANCELED,t)}awaitStatusTerminal(t){return new Promise((r,a)=>{const s=[];let i=!1;const o=async t=>{if(!i){(()=>{if(!i){i=!0;for(const e of s)e()}})();try{t.payload?.status===e.TaskStatus.SUCCEEDED?r(this.extractOutput(t)):a(this.extractError(t))}catch(e){a(e)}}};t.forEach(e=>{const t=this.registerStatusHandler(e,o);s.push(t)})})}extractOutput(e){return void 0!==e.payload?.output?e.payload.output:this.task.output}extractError(e){const t=e.payload?.status??this.task.status,r=this.buildMeta(t,e.payload);return this.createTaskControlError(t,e.payload?.error??this.task.error,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[e.TaskStatus.SUCCEEDED,e.TaskStatus.CANCELED,e.TaskStatus.FAILED].includes(t)}async track(t,r){if(!t.payload)return;const a=t.payload.status;this.task.status=a,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),a!==e.TaskStatus.SUCCEEDED?(a===e.TaskStatus.FAILED&&this.fail(),a===e.TaskStatus.CANCELED&&this.cancel(t),a===e.TaskStatus.WAITING_RETRY&&this.retry(),a===e.TaskStatus.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,r){const a=async(e,a)=>{e.payload?.status===t&&await r(e,a)};if(this.pipe(a,e.TaskEventType.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);a(e,this.getTerminalContext())}return()=>{this.pipes?.[e.TaskEventType.STATUS]?.delete(a)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new E),this.terminalContext}buildTerminalEvent(t){const r={status:t};return t===e.TaskStatus.SUCCEEDED&&(r.output=this.task.output),t!==e.TaskStatus.FAILED&&t!==e.TaskStatus.CANCELED||!this.task.error||(r.error=this.task.error),this.task.nextRunAt&&(r.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(r.scheduledTo=this.task.scheduledTo),new e.TaskEventModel({classification:e.TaskEventType.STATUS,taskId:this.task.id,payload:r})}createTaskControlError(t,r,a){switch(t){case e.TaskStatus.FAILED:return new qt(this.task.id,r,a);case e.TaskStatus.CANCELED:return new Gt(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new Yt(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new zt(this.task.id,r,a);default:return new qt(this.task.id,r,a)}}buildMeta(e,t){const r={};if(t?.nextRunAt&&(r.nextRunAt=t.nextRunAt),t?.scheduledTo&&(r.scheduledTo=t.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===e.TaskStatus.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,r){if(!this.pipes)return;const a=this.pipes[e.TaskEventType.ALL]?[...this.pipes[e.TaskEventType.ALL].values()]:[];a.push(...this.pipes[t.classification]?.values()||[]);for(const e of a)try{await e(t,r)}catch(a){r.logger.error(`Failed to trigger pipe ${e.name} for event ${t.classification}. discarding event`,a)}}}class Qt extends O{get Context(){return Kt}get adapter(){return this.config.adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=ye.forModel(e.TaskModel,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=ye.forModel(e.TaskEventModel,this.config.adapter.alias)),this._events}constructor(e){super(),this.config=e,this.lock=new o.Lock,this.running=!1,this.config=Object.assign({},we,e,{bus:e.bus||new jt,registry:e.registry||new Ft})}async push(e,t=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push);i.verbose("pushing task "+e.classification);const o=await this.tasks.create(e,s);return i.info(`${e.classification} task registered under ${o.id}`),t?{task:o,tracker:new Ht(this.bus,o)}:o}schedule(t,r=!1,...a){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=e.TaskStatus.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,r,...a)}}}async track(e,...t){const{ctx:r,log:s}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.track);s.verbose("tracking task "+e);let i=await this.tasks.read(e,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${e}`),{task:i,tracker:new Ht(this.bus,i)}}async ensureTaskError(t,r){if(![e.TaskStatus.FAILED,e.TaskStatus.CANCELED].includes(t.status)||t.error)return t;let a=t;for(let e=0;6>e;e+=1){await Lt(20);try{const e=await this.tasks.read(a.id,r);if(e.error)return e;a=e}catch{break}}return a}async cancel(t,...r){const{ctx:a}=(await this.logCtx(r,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,a);if(s.status===e.TaskStatus.SUCCEEDED||s.status===e.TaskStatus.FAILED)return s;s.status=e.TaskStatus.CANCELED;const i=new e.TaskErrorModel({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const o=await this.tasks.update(s,a);return await this.emitStatus(a,o,e.TaskStatus.CANCELED,i),o}async isRunning(){await this.lock.acquire();const e=this.running;return this.lock.release(),e}async start(...e){const{ctx:t}=(await this.logCtx(e,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.loop(t))}async stop(...t){const{ctx:r,log:a}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||a.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(F.attr("status").eq(e.TaskStatus.RUNNING)).execute(r),i=r.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((e,t)=>{const o=setTimeout(()=>{a.error(`Graceful shutdown interrupted after ${i} ms...`),e()},i);Promise.allSettled(s.map(({id:e})=>new Promise((t,a)=>{this.track(e,r).then(({tracker:e})=>{e.resolve().then(t)}).catch(a)}))).then(t=>{clearTimeout(o),a.info(`Graceful shutdown completed before expiry. concluded ${t.length} tasks`),e()}).catch(e=>{clearTimeout(o),t(e)})})}async loop(...e){const{ctx:t}=this.logCtx(e,this.loop);for(;await this.isRunning();){const e=await this.claimBatch(t);await Promise.allSettled(e.map(e=>this.executeClaimed(e))),await Lt(e.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=t.timestamp,s=F.attribute("status").eq(e.TaskStatus.PENDING),i=F.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(F.attribute("nextRunAt").lte(a)),o=F.attribute("status").eq(e.TaskStatus.RUNNING).and(F.attribute("leaseExpiry").lte(a)),n=F.attribute("status").eq(e.TaskStatus.SCHEDULED).and(F.attribute("scheduledTo").lte(a)),c=s.or(i).or(o).or(n),d=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+d.length);const l=[];for(const e of d){const r=await this.tryClaim(e,t);if(r&&l.push(r),l.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+l.length),l}async tryClaim(t,r){const a=r.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,r)}catch{}const o=new e.TaskModel({...i,status:e.TaskStatus.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});a.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(o,r)}catch{return null}}async executeClaimed(t){const{ctx:r,log:i}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),o=new Kt(r).accumulate({taskId:t.id,logger:new Bt(i,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{},pipe:async e=>{const[,r]=await this.appendLog(o,t,e);await this.emitLog(o,t.id,r)},flush:async()=>o.logger.flush(o.pipe),progress:async e=>{await this.emitProgress(o,t.id,e)},heartbeat:async()=>{if(t.leaseOwner===this.config.workerId){t.leaseExpiry=new Date(Date.now()+this.config.leaseMs);try{t=await this.tasks.update(t)}catch{}}}});await this.emitStatus(o,t,e.TaskStatus.RUNNING);try{let r;if(t.atomicity===e.TaskType.COMPOSITE){r=await this.runComposite(t,o);try{t=await this.tasks.read(t.id,o)}catch{}r?.stepResults&&(t.stepResults=r.stepResults,t.currentStep=r.stepResults.length)}else{const e=this.registry.get(t.classification);if(i.debug(`handler type for ${t.id} is ${e?.constructor?.name??"none"}`),!e)throw new a.InternalError("No task handler registered for type: "+t.classification);r=await e.run(t.input,o),i.verbose("handler finished for "+t.id)}t.status=e.TaskStatus.SUCCEEDED,t.output=r,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,o),o.logger.info(`task ${t.id} success state ${t.status}`),i.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(o,t,e.TaskStatus.SUCCEEDED,r)}catch(r){try{t=await this.tasks.read(t.id,o)}catch{}if(r instanceof $t)return void await this.handleTaskStateChange(r.request,t,o);if(i.error("task execution error",r),t.atomicity===e.TaskType.COMPOSITE){const r=this.normalizeStepResults(t.stepResults);if(t.stepResults=r,null==t.currentStep){const a=r.findIndex(t=>t.status===e.TaskStatus.FAILED);0>a||(t.currentStep=a)}}const a=(t.attempt??0)+1,n=Rt(r);if(a<t.maxAttempts){const r=Nt(a,this.normalizeBackoff(t.backoff)),c=new Date(Date.now()+r);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=c,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,o),i.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await this.emitStatus(o,t,e.TaskStatus.WAITING_RETRY),await o.pipe(s.LogLevel.warn,"Retry scheduled",{nextRunAt:c,delayMs:r,attempt:a})}else t.attempt=a,t.status=e.TaskStatus.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,o),i.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await this.emitStatus(o,t,e.TaskStatus.FAILED,n),await o.pipe(s.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts})}}async handleTaskStateChange(t,r,i){switch(r.leaseOwner=void 0,r.leaseExpiry=void 0,t.status){case e.TaskStatus.CANCELED:{const a=t.error??new e.TaskErrorModel({message:`Task ${r.id} canceled`});return r.status=e.TaskStatus.CANCELED,r.error=a,r.nextRunAt=void 0,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.CANCELED,a),void await i.pipe(s.LogLevel.warn,"Task canceled via context")}case e.TaskStatus.WAITING_RETRY:{const a=(r.attempt??0)+1,o=Nt(a,this.normalizeBackoff(r.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+o),c=t.error??new e.TaskErrorModel({message:`Task ${r.id} requested retry`});return r.status=e.TaskStatus.WAITING_RETRY,r.attempt=a,r.error=c,r.nextRunAt=n,r.scheduledTo=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.WAITING_RETRY,c),void await i.pipe(s.LogLevel.warn,"Retry requested",{nextRunAt:n,delayMs:o,attempt:a})}case e.TaskStatus.SCHEDULED:{if(!t.scheduledTo)throw new a.InternalError("Scheduled state requires a target date");const o=t.error??new e.TaskErrorModel({message:`Task ${r.id} rescheduled`});return r.status=e.TaskStatus.SCHEDULED,r.scheduledTo=t.scheduledTo,r.error=o,r.nextRunAt=void 0,r=await this.tasks.update(r,i),await this.emitStatus(i,r,e.TaskStatus.SCHEDULED,o),void await i.pipe(s.LogLevel.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new a.InternalError("Unsupported task state change requested: "+t.status)}}async runComposite(t,r){const{ctx:a}=(await this.logCtx([r],t.classification,!0)).for(this.runComposite),i=this.normalizeSteps(t.steps);let o=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),c=(e,t)=>{r.cacheResult(e,t),a instanceof Kt&&a!==r&&a.cacheResult(e,t)};for(let r=0;r<n.length;r+=1){const a=n[r];if(a?.status===e.TaskStatus.SUCCEEDED){const e=i[r];if(!e)continue;const s=`${t.id}:step:${r}`;c(e.classification,a.output),c(s,a.output)}}for(;o<i.length;){const a=i[o],d=this.registry.get(a.classification);if(!d)throw Error("No task handler registered for composite step: "+a.classification);await r.pipe([s.LogLevel.info,`Composite step ${o+1}/${i.length}: ${a.classification}`]);try{const s=await d.run(a.input,r),l=o,u=new Date;n[l]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:s,createdAt:u,updatedAt:u});const p=`${t.id}:step:${l}`;c(a.classification,s),c(p,s),o=l+1,t.stepResults=n,t.currentStep=o,t=await this.tasks.update(t),await this.emitProgress(r,t.id,{currentStep:o,totalSteps:i.length,output:s})}catch(r){const a=new Date;throw n[o]=new e.TaskStepResultModel({status:e.TaskStatus.FAILED,error:Rt(r),createdAt:a,updatedAt:a}),t.stepResults=n,t.currentStep=o,t.error=Rt(r),t=await this.tasks.update(t),r}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof e.TaskBackoffModel)return t;let r=t??{};if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskBackoffModel(r)}normalizeSteps(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepSpecModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepSpecModel(r)}):[]}normalizeStepResults(t){if(!t)return[];let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{return[]}return r instanceof Set&&(r=Array.from(r)),Array.isArray(r)?r.map(t=>{if(t instanceof e.TaskStepResultModel)return t;let r=t;if("string"==typeof r)try{r=JSON.parse(r)}catch{r={}}return new e.TaskStepResultModel(r)}):[]}async appendLog(t,r,a){const s=(Array.isArray(a)&&Array.isArray(a[0])?a:[a]).map(([t,r,a])=>new e.TaskLogEntryModel({level:t,msg:r,meta:a})),i=[...r.logTail??[],...s].slice(-this.config.logTailMax);r.logTail=i;try{return[await this.tasks.update(r,t),s]}catch{return[r,[]]}}async emitStatus(t,r,a,s){t instanceof Kt&&await t.flush();const i={status:a};s&&s instanceof e.TaskErrorModel?i.error=s:s&&(i.output=s),r.nextRunAt&&(i.nextRunAt=r.nextRunAt),r.scheduledTo&&(i.scheduledTo=r.scheduledTo);const o=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,i);this.bus.emit(o,t)}async emitLog(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.LOG,a.map(e=>({ts:e.ts,level:e.level,msg:e.msg,meta:e.meta})));this.bus.emit(s,t)}async emitProgress(t,r,a){const s=await this.persistEvent(t,r,e.TaskEventType.PROGRESS,a);this.bus.emit(s,t)}async persistEvent(t,r,a,s){const i=new e.TaskEventModel({taskId:r,classification:a,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,r,...a){return this.adapter.context(t,r,e.TaskModel,...a)}}class Vt extends _t{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||r instanceof E)throw new a.InternalError("No/invalid config provided");const{log:s}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize);if(!r.adapter)throw new a.InternalError("No adapter provided");s.info("Initializing Task Engine...");const i=new Qt(r);return s.verbose(i+" initialized"),{client:i,config:r}}async push(e,t=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.OperationKeys.CREATE,!0)).for(this.push),i=await this.client.push(e,t,...s);return await this.client.isRunning()||this.client.start(),i}async track(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.push);return this.client.track(e,...r)}async create(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.CREATE,!0)).for(this.create),s=await this.repo.create(e,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.CREATE_ALL,!0)).for(this.createAll),s=await this.repo.createAll(e,...r);return await this.client.isRunning()||this.client.start(),s}async delete(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.DELETE,!0)).for(this.delete);return this.repo.delete(e,...r)}async deleteAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(e,...r)}async read(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.OperationKeys.READ,!0)).for(this.read);return this.repo.read(e,...r)}async readAll(e,...t){const{ctxArgs:r}=(await this.logCtx(t,a.BulkCrudOperationKeys.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(e,...r)}async query(t,...r){const{ctxArgs:s}=(await this.logCtx(r,e.PersistenceKeys.QUERY,!0)).for(this.query),i=this.repo?.[t];if("function"!=typeof i)throw new a.InternalError(`Method "${t}" is not implemented`);return i.apply(this.repo,s)}async update(e,...t){throw new x("Updates to tasks are not available")}async updateAll(e,...t){throw new x("Updates to tasks are not available")}async listBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,r,...s)}async paginateBy(t,r,a,...s){const{ctxArgs:i}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,r,a,...i)}async findOneBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,r,...s)}async findBy(t,r,...a){const{ctxArgs:s}=(await this.logCtx(a,e.PreparedStatementKeys.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,r,...s)}async statement(t,...r){const{ctxArgs:a}=(await this.logCtx(r,e.PersistenceKeys.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...a)}refresh(e,t,r,...a){return this.repo.refresh(e,t,r,...a)}observe(e,t){return this.repo.observe(e,t)}unObserve(e){return this.repo.unObserve(e)}updateObservers(e,t,r,...a){return this.repo.updateObservers(e,t,r,...a)}logCtx(e,t,r=!1){const a=this.repo.adapter.logCtx([this.repo.class,...e],t,r,this.repo._overrides||{});function s(e){return e.ctxArgs.shift(),e}return a instanceof Promise?a.then(s):s(a)}async shutdown(...t){const{ctxArgs:r,ctx:a,log:s}=(await this.logCtx(t,e.PersistenceKeys.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...r),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(a),s.verbose("gracefully shutdown task runner")}}r.__decorate([ot(e.TaskModel),r.__metadata("design:type",Object)],Vt.prototype,"repo",void 0),r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"create",null),r.__decorate([bt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"createAll",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"delete",null),r.__decorate([St(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"deleteAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"read",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"readAll",null),r.__decorate([Et(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"query",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"update",null),r.__decorate([vt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Vt.prototype,"updateAll",null),t.Injectables.setRegistry(new me);const Wt="##VERSION##",Jt="##PACKAGE##";n.Metadata.registerLibrary(Jt,Wt),e.AbsContextual=O,e.Adapter=R,e.AuthorizationError=Re,e.BaseModel=Je,e.BigIntSequence=tt,e.ClientBasedService=_t,e.CompositeTaskBuilder=Mt,e.Condition=F,e.ConnectionError=$e,e.Context=E,e.ContextLock=b,e.ContextualLoggedClass=v,e.DefaultAdapterFlags=g,e.DefaultCascade=q,e.DefaultContextFlags=h,e.DefaultRepositoryFilters=re,e.DefaultSequenceOptions=Ze,e.DefaultTaskEngineConfig=we,e.Dispatch=be,e.ForbiddenError=Le,e.InjectablesRegistry=me,e.MethodQueryBuilder=z,e.MigrationError=k,e.MigrationRuleError=A,e.ModelService=xt,e.MultipleSelectOperationKeys=_,e.NonTransactionOperationKeys=f,e.NoneSequenceOptions=Xe,e.NumericSequence=et,e.ObserverError=nt,e.ObserverHandler=T,e.OperatorsMap=Y,e.PACKAGE_NAME=Jt,e.PaginationOperationKeys=w,e.Paginator=ct,e.PagingError=$,e.PersistenceService=class extends _t{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof E||!r.every(e=>Array.isArray(e)))throw new a.InternalError("Missing/invalid configuration");const{log:s,ctxArgs:i}=(await this.logCtx(t,e.PersistenceKeys.INITIALIZATION,!0)).for(this.initialize),o=r.map(([e,t,...r])=>{try{s.silly(`Initializing ${e.name} with config: ${JSON.stringify(t)}`);const a=new e(t,...r);return s.debug(`Initialized ${a.toString()}...`),a}catch(t){throw new a.InternalError(`Failed to initialize ${e.name}: ${t}`)}});for(const e of o)try{await e.initialize(...i)}catch(t){throw new a.InternalError(`Failed to initialize ${e.toString()}: ${t}`)}return{client:o,config:r}}},e.QueryError=L,e.Repository=ye,e.SelectOperationKeys=m,e.Sequence=it,e.Serial=I,e.Service=mt,e.Statement=ft,e.TaskBackoffBuilder=At,e.TaskBuilder=Ct,e.TaskCancelError=Gt,e.TaskContext=Kt,e.TaskControlError=Ut,e.TaskEngine=Qt,e.TaskEventBus=jt,e.TaskFailError=qt,e.TaskHandler=Dt,e.TaskHandlerRegistry=Ft,e.TaskIOSerializer=kt,e.TaskLogger=Bt,e.TaskRescheduleError=zt,e.TaskRetryError=Yt,e.TaskService=Vt,e.TaskTracker=Ht,e.TasksKey=_e,e.TransactionOperationKeys=y,e.UUID=B,e.UnsupportedError=x,e.VERSION=Wt,e.applyViewDecorator=Q,e.auth=t=>{const r=e.PersistenceKeys.AUTH;return n.Decoration.for(r).define({decorator:e=>n.metadata(r,e),args:[t]}).apply()},e.cacheModelForPopulate=De,e.cascadeDelete=Be,e.column=Fe,e.computeBackoffMs=Nt,e.create=bt,e.createOrUpdate=Se,e.createdAt=ze,e.createdBy=Ye,e.createdByOnCreateUpdate=qe,e.del=St,e.generateInjectableNameForRepository=fe,e.getFilters=ae,e.getLogPipe=It,e.getPkTypes=Qe,e.getPopulateKey=Me,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=je,e.injectableServiceKey=C,e.isOperationBlocked=D,e.manyToMany=(t,r=q,a=!0,s,o)=>{const c=e.PersistenceKeys.MANY_TO_MANY;return n.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const o={class:e,cascade:t,populate:r};a&&(o.joinTable=a),s&&(o.name=s);const d=Qe(e),l=[n.prop(),We(c,o),i.list([e,...d])];return n.apply(...l)},args:[t,r,a,s,o]}).apply()},e.manyToOne=(t,r=q,a=!0,s,o)=>{const c=e.PersistenceKeys.MANY_TO_ONE;return n.Decoration.for(c).define({decorator:(e,t,r,a,s)=>{const o={class:e,cascade:t,populate:r};a&&(o.joinTable=a),s&&(o.name=s);const d=Qe(e),l=[n.prop(),We(c,o),i.type([e,...d])];return n.apply(...l)},args:[t,r,a,s,o]}).apply()},e.noValidateOn=Ve,e.noValidateOnCreate=()=>Ve(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>Ve(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>Ve(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=q,s=!0,o,c)=>{const d=e.PersistenceKeys.ONE_TO_MANY;return n.Decoration.for(d).define({decorator:(e,t,r,s,o)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),o&&(c.name=o);const l=Qe(e),u=[n.prop(),We(d,c),i.list([e,...l]),a.onCreate(ke,c,{priority:70}),a.onUpdate(Ae,c,{priority:70}),a.onDelete(Ce,c,{priority:70}),a.afterUpdate(Be,c,{priority:70}),a.afterAny(Pe,c,{priority:70})];return n.apply(...u)},args:[t,r,s,o,c]}).apply()},e.oneToManyOnCreate=ke,e.oneToManyOnDelete=Ce,e.oneToManyOnUpdate=Ae,e.oneToOne=(t,r=q,s=!0,o,c)=>{const d=e.PersistenceKeys.ONE_TO_ONE;return n.Decoration.for(d).define({decorator:(e,t,r,s,o)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),o&&(c.name=o);const l=Qe(e),u=[n.prop(),We(d,c),i.type([e,...l]),a.onCreate(Oe,c,{priority:70}),a.onUpdate(Te,c,{priority:70}),a.onDelete(xe,c,{priority:70}),a.afterUpdate(Be,c,{priority:70}),a.afterAny(Pe,c,{priority:70})];return n.apply(...u)},args:[t,r,s,o,c]}).apply()},e.oneToOneOnCreate=Oe,e.oneToOneOnDelete=xe,e.oneToOneOnUpdate=Te,e.onlyOnBulk=ee,e.onlyOnCreate=V,e.onlyOnDelete=J,e.onlyOnFilter=te,e.onlyOnSingle=Z,e.onlyOnTransactional=X,e.onlyOnUpdate=W,e.pk=st,e.pkDec=at,e.pkOnCreate=rt,e.populate=Pe,e.prefixMethod=P,e.prepared=H,e.promiseSequence=M,e.query=(t={})=>n.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const i=z.getFieldsFromMethodName(a);return n.apply(n.methodMetadata(n.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:i}),H(),(e=>(t,r,a)=>{a.value=new Proxy(a.value,{apply(t,r,a){const{action:s,select:i,selector:o,where:n,groupBy:c,orderBy:d,limit:l,offset:u}=z.build(t.name,...a),p=r;let h;switch(s){case"find":case"page":h=p.select(i);break;case"count":h=p.count(o);break;case"sum":h=p.sum(o);break;case"avg":h=p.avg(o);break;case"min":h=p.min(o);break;case"max":h=p.max(o);break;case"distinct":h=p.distinct(o);break;case"group":h=p.select(),o&&(h=h.groupBy(o));break;default:throw new L("Unsupported action: "+s)}if(n&&(h=h.where(n)),c&&c.length>0&&"group"!==s){h=h.groupBy(c[0]);for(let e=1;e<c.length;e++)h=h.thenBy(c[e])}else if(c&&c.length>0&&"group"===s)for(const e of c)h=h.thenBy(e);const{allowLimit:g,allowOffset:y,allowOrderBy:f,throws:m}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...e},_=[{key:"orderBy",value:(d||[])[0],allowed:f},{key:"limit",value:l,allowed:g},{key:"offset",value:u,allowed:y}];for(const e of _)if(void 0!==e.value){if(!e.allowed&&m)throw new L(e.key[0].toUpperCase()+e.key.slice(1)+" is not allowed for this query");e.allowed&&(h=h[e.key](e.value))}if("page"===s){const e=a[a.length-1],t="number"==typeof e?e:e?.limit??10;return h.paginate(t)}return h.execute()}})})(t))(r,a,s)},args:[t]}).apply(),e.read=Et,e.relation=We,e.repository=ot,e.repositoryFromTypeMetadata=Ne,e.roles=t=>n.metadata(e.PersistenceKeys.AUTH_ROLE,t),e.route=(t,r)=>{const a=e.PersistenceKeys.DECAF_ROUTE;return n.Decoration.for(a).define({decorator:()=>(e,s,i)=>{const o={path:r,httpMethod:t,handler:i};return n.apply(n.methodMetadata(n.Metadata.key(a,s),o))(e,s,i)},args:[]}).apply()},e.serializeError=Rt,e.service=Ot,e.sleep=Lt,e.table=Ke,e.task=Pt,e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return n.Decoration.for(t).define(i.async(),a.onCreateUpdate(Ue),n.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=Ue,e.update=vt,e.updatedAt=He,e.updatedBy=Ge,e.uuid=ve,e.uuidCreateUpdateHandler=Ee,e.view=t=>n.Decoration.for(e.Operator.VIEW).define({decorator:t=>Q(e.Operator.VIEW,"view",t),args:[t]}).apply()},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@decaf-ts/injectable-decorators"),require("tslib"),require("@decaf-ts/db-decorators"),require("@decaf-ts/logging"),require("@decaf-ts/decorator-validation"),require("@decaf-ts/transactional-decorators"),require("@decaf-ts/decoration")):"function"==typeof define&&define.amd?define(["exports","@decaf-ts/injectable-decorators","tslib","@decaf-ts/db-decorators","@decaf-ts/logging","@decaf-ts/decorator-validation","@decaf-ts/transactional-decorators","@decaf-ts/decoration"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsTransactionalDecorators,e.decafTsDecoration);
|
|
2
2
|
//# sourceMappingURL=core.cjs.map
|