@decaf-ts/core 0.8.56 → 0.8.57

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 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,l,d,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,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.BETWEEN="BETWEEN",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",l.STARTS_WITH="STARTS_WITH",l.ENDS_WITH="ENDS_WITH",l.GROUP_BY="group-by",l.COUNT="count",l.SUM="sum",l.MAX="v_max",l.MIN="v_min",l.DISTINCT="distinct",l.VIEW="view",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.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.FIND="find",u.PAGE="page",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",p.THROTTLE="throttle",p.DEFAULT_QUERY_ATTR="default-query-attr";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,breakOnSingleFailureInBulk:!0,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,e.PreparedStatementKeys.FIND,e.PreparedStatementKeys.PAGE],w=[e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.PAGE];class b 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,t=new Set){if(t.has(this))return;t.add(this);const r=this.getOrUndefined(e);if(null!=r)return r;let a=this.getOrUndefined("childContexts");if(a&&a.length&&(a=a.filter(e=>!t.has(e)),a.length)){const r=a.map(r=>r.getFromChildren(e,t)).flat().filter(e=>null!=e);if(!r.length)return;return r.some(e=>"object"!=typeof e)?r[0]:r.reduce((e,t)=>Object.assign(e,t),{})}}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 E extends s.LoggedClass{logCtx(e,t,r=!1,a){return E.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 b;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 v extends E{constructor(){super(),this._Context=b}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 b||(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}=E.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 O extends a.InternalError{constructor(e){super(e,O.name,500)}}class A extends a.InternalError{constructor(e,t=A.name){super(e,t,500)}}class k extends A{constructor(e){super(e,k.name)}}function x(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):o.Metadata.Symbol(o.Metadata.constr(e)).toString().replaceAll(".","-")}async function C(e,t=!1){if(!t){const t=[];for(const r of e)t.push(await r());return t}const r=[];for(const t of e)try{r.push({status:"fulfilled",value:await t()})}catch(e){r.push({status:"rejected",reason:e})}return r}function M(e,t){const{handler:r,args:s}=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)}function D(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 k)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 P{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 P._instance||(P._instance=new P),P._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}}class B{constructor(e,...t){this.adapter=e}async begin(...e){}async commit(...e){}async rollback(...e){}}class N extends n.Lock{constructor(e){super(),this.adapterTransaction=e,this.acquireCount=0,this.lock=new n.Lock}async acquire(...e){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...e)):this.lock.release()}async release(...e){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...e)}catch(t){await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+t),...e)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(e,...t){await this.lock.acquire();try{await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+e),...t)}catch(e){throw new a.InternalError("Failed to rollback transaction: "+e)}finally{this.lock.release()}}}const R=o.Decoration.flavourResolver.bind(o.Decoration);function L(e,t,r,a){if(!t)return e;const s=e,i=[],o=[];for(const e of s)"fulfilled"===e.status?i.push(e.value):o.push(e.reason);if(o.length){r.warn(`Bulk ${a} encountered ${o.length} failure(s) while continuing`);const e=new AggregateError(o,`Bulk ${a} failed for ${o.length} item(s)`);throw e.results=s,e}return i}o.Decoration.flavourResolver=e=>{try{const t=R(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=$._currentFlavour;if(s){const e=$._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class $ extends v{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!$._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return $._baseRepository}transactionLock(...e){return new B(this,...e)}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){const{log:r,ctx:a}=(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 $._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);$._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),$._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),$._currentFlavour=this.alias)}Dispatch(){return new $._baseDispatch}ObserverHandler(){return new T}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new $._baseSequence(e,this,t)}async flags(e,t,r,...n){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,l=c?i.Model.tableName(c)+" - ":"";r.correlationId=r.correlationId||`${l}${e}-${P.instance.generate()}`;const d=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:n,writeOperation:y.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?o.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:d})}get Context(){return b}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 b||(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.getOrUndefined("operation"),a=s.getOrUndefined("affectedTables");if(!t||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:l}=this.logCtx(n,this.revert),d=i.Model.pk(r),u=new r;u[d]=s,c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==d).reduce((e,a)=>(e[a]=t[i.Model.columnName(r,a)],e),u);return l.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);o.debug(`Creating ${t.length} entries ${c} table`);const l=!(n.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.create(e,t,r[a],...s,n.override({noEmitSingle:!0})));return L(l?await C(d,!0):await C(d),l,o,a.BulkCrudOperationKeys.CREATE_ALL)}async readAll(e,t,...r){const{log:s,ctx:o}=this.logCtx(r,this.readAll),n=i.Model.tableName(e);s.debug(`Reading ${t.length} entries ${n} table`);const c=!(o.get("breakOnSingleFailureInBulk")??1),l=t.map(t=>()=>this.read(e,t,...r,o.override({noEmitSingle:!0})));return L(c?await C(l,!0):await C(l),c,s,a.BulkCrudOperationKeys.READ_ALL)}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);o.debug(`Updating ${t.length} entries ${c} table`);const l=!(n.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.update(e,t,r[a],...s,n.override({noEmitSingle:!0})));return L(l?await C(d,!0):await C(d),l,o,a.BulkCrudOperationKeys.UPDATE_ALL)}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${t.length} entries from ${e} table`);const o=!(i.get("breakOnSingleFailureInBulk")??1),n=t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0})));return L(o?await C(n,!0):await C(n),o,s,a.BulkCrudOperationKeys.DELETE_ALL)}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 o.Metadata.flavourOf(e)}static get currentFlavour(){if(!$._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return $._currentFlavour}static get current(){return $.get(this.currentFlavour)}static get(e){if(!e)return $.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 o.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 o.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)],$.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,b]),r.__metadata("design:returntype",Promise)],$.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],$.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],$.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],$.prototype,"client",null);class F extends a.InternalError{constructor(e){super(e,F.name,500)}}class j extends a.InternalError{constructor(e){super(e,j.name,500)}}class U 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 U.and(this,e)}or(e){return U.or(this,e)}not(t){return new U(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof U)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 U){if(!(this.comparison instanceof U)&&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 U.group(t,e.GroupOperator.AND,r)}static or(t,r){return U.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new U(e,t,r)}static attribute(e){return(new U.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)}startsWith(t){return this.setOp(e.Operator.STARTS_WITH,t)}endsWith(t){return this.setOp(e.Operator.ENDS_WITH,t)}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 U(this.attr1,this.operator,this.comparison)}catch(e){throw new F(e)}}}}static builder(){return new U.Builder}static from(e){return new U(e)}}var q,Y;r.__decorate([i.required(),r.__metadata("design:type",Object)],U.prototype,"attr1",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],U.prototype,"operator",void 0),r.__decorate([i.required(),r.__metadata("design:type",Object)],U.prototype,"comparison",void 0),e.OrderDirection=void 0,(q=e.OrderDirection||(e.OrderDirection={})).ASC="asc",q.DSC="desc",e.Cascade=void 0,(Y=e.Cascade||(e.Cascade={})).CASCADE="cascade",Y.NONE="none";const G={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},z={Equals:(e,t)=>U.attribute(e).eq(t),Diff:(e,t)=>U.attribute(e).dif(t),LessThan:(e,t)=>U.attribute(e).lt(t),LessThanEqual:(e,t)=>U.attribute(e).lte(t),GreaterThan:(e,t)=>U.attribute(e).gt(t),GreaterThanEqual:(e,t)=>U.attribute(e).gte(t),In:(e,t)=>U.attribute(e).in(t),Matches:(e,t)=>U.attribute(e).regexp(t)},H=e=>e.charAt(0).toLowerCase()+e.slice(1);class Q extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(Q.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),l=this.buildWhere(o,t),{orderBy:d,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,o);return{action:a,select:n,selector:i,where:l,groupBy:c,orderBy:d,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?H(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(H).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(H).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(H(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?z[n]:z.Equals;if(!c)throw Error("Unsupported operator "+n);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+s);const d=c(s,l);o=0===a?d:i[a-1]===e.QueryClause.AND?o.and(d):o.or(d)}),o}static parseFieldAndOperator(e){for(const t of Object.keys(z))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:H(r),operator:t}}return{field:H(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=Q.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new F("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new F(`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,l;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]||(l=o[2]),{orderBy:n,limit:c,offset:l}}}function V(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function W(e,t,r){return(a,s)=>{const i=r?.name||((e,t,r)=>{const a=(o.Metadata.get(e.constructor,t)||{})[r]||{};return Object.keys(a).length+1+""})(a,e,s),n=o.Metadata.key(e,s,i),c={...r||{},kind:t,attribute:s};return o.propMetadata(n,c)(a,s)}}function J(e){return ae(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function X(e){return ae(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function Z(e){return ae(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function ee(e){return ae(e,y)}function te(e){return ae(e,Object.values(a.OperationKeys))}function re(e){return ae(e,Object.values(a.BulkCrudOperationKeys))}function ae(e,t){return(r,s,n,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=E.prototype.logCtx(c,ae);return l.silly(`filtering ${s} event for${r?" "+(i.Model.tableName(r)||r):""} ${n}`),("string"==typeof r?r===i.Model.tableName(e)||r===e.constructor.name:o.Metadata.constr(e)===o.Metadata.constr(r))&&t.includes(s)}}const se={onlyOnCreate:J,onlyOnUpdate:X,onlyOnDelete:Z,onlyOnTransactional:ee,onlyOnSingle:te,onlyOnBulk:re};function ie(e){const t=Object.assign({},se);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var oe,ne,ce,le,de,ue,pe,he,ge,ye,fe;class me 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 ie(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&&(me.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.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 l=i.Model.sequenceFor(e[0]);let d=[];if(i.Model.generatedBySequence(this.class)?(l.name||(l.name=i.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...s)):i.Model.generated(this.class,this.pk)||(d=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),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[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 l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=i.Model.merge(d,e,this.class))),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,d]}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 l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>i.Model.merge(d[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[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(d[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,d]}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],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.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:l}=a;if(!n&&!c)throw new F("PaginateBy needs a page or a bookmark");const{log:d,ctx:u,ctxArgs:p}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let h;if(d.verbose(`paginating ${i.Model.tableName(this.class)} with page size ${l}`),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(l,...p);else{if(!n)throw new F("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(l,...p)}const g=await h.page(o,c,...p);return h.serialize(g)}async find(t,r=e.OrderDirection.ASC,...a){if("string"!=typeof t)throw new F("Find value must be a string");const s=this.getDefaultQueryAttributes(),o=this.buildDefaultStartsWithCondition(t,s),{log:n,ctxArgs:c}=(await this.logCtx(a,e.PreparedStatementKeys.FIND,!0)).for(this.find);return n.verbose(`finding ${i.Model.tableName(this.class)} by default attributes ${s.join(", ")}`),this.select().where(o).orderBy([s[0],r]).execute(...c)}async page(t,r=e.OrderDirection.ASC,a={offset:1,limit:10},...s){if("string"!=typeof t)throw new F("Page value must be a string");const o=a.offset||1,{offset:n,bookmark:c,limit:l}=a;if(!n&&!c)throw new F("PaginateBy needs a page or a bookmark");const d=this.getDefaultQueryAttributes(),u=this.buildDefaultStartsWithCondition(t,d),{log:p,ctx:h,ctxArgs:g}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE,!0)).for(this.page);p.verbose(`paging ${i.Model.tableName(this.class)} by default attributes ${d.join(", ")}`);const y=l??10,f=d[0],m=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let _;if(c&&h.get("paginateByBookmark")){const t=i.Model.pk(this.class),a=r===e.OrderDirection.ASC?this.attr(t).gt(c):this.attr(t).lt(c);_=await m.select().where(u.and(a)).orderBy([f,r]).paginate(y,...g)}else{if(!n)throw new F("PaginateBy needs a page or a bookmark");_=await m.select().where(u).orderBy([f,r]).paginate(y,...g)}const w=await _.page(o,c,...g);return _.serialize(w)}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(!me.statements(this,t))throw new F("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)}getDefaultQueryAttributes(){const e=i.Model.defaultQueryAttributes(this.class);if(!e||!e.length)throw new F("No default query attributes defined for "+i.Model.tableName(this.class));return e}buildDefaultStartsWithCondition(e,t){if("string"!=typeof e)throw new F("Default query value must be a string");let r;for(const a of t){const t=this.attr(a).startsWith(e);r=r?r.or(t):t}if(!r)throw new F("No default query attributes available for "+i.Model.tableName(this.class));return r}attr(e){return U.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:o.Metadata.constr(e)===o.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=>$._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,e)):$._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 n=r||o.Metadata.flavourOf(t)||$.currentFlavour;try{i=this.get(t,n)}catch(e){i=void 0}if(i instanceof me)return i;const c=r||o.Metadata.flavourOf(t)||i&&o.Metadata.get(i,e.PersistenceKeys.ADAPTER)||$.currentFlavour,l=c?$.get(c):void 0;if(!l)throw new a.InternalError("No registered persistence adapter found flavour "+c);return i=i||l.repository(),new i(l,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 me)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof me?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof me?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function _e(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof i.Model?t.constructor:t))&&r!==o.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([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"listBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"paginateBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"find",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"page",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"findOneBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"findBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"countOf",null),r.__decorate([V(),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)],me.prototype,"maxOf",null),r.__decorate([V(),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)],me.prototype,"minOf",null),r.__decorate([V(),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)],me.prototype,"avgOf",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(le="undefined"!=typeof K&&K)?le:Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"sumOf",null),r.__decorate([V(),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)],me.prototype,"distinctOf",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ue="undefined"!=typeof K&&K)?ue:Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"groupOf",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],me.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],me.prototype,"unObserve",null),$&&($._baseRepository=me);class we 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 n;try{n=super.get(r)}catch{}if(!n){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 l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&$.get(d)}catch{const t=$.current;t&&t.flavour===d&&(e=t.alias)}if(n=me.forModel(c,e),n instanceof me)return n;const r=d||o.Metadata.get(n.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(n,_e(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=me.get(c,d);if("function"==typeof t){const e=d?$.get(d):$.current;if(!e)return;return new t(e,c)}}}return n}}e.TaskStatus=void 0,(pe=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",pe.SCHEDULED="scheduled",pe.RUNNING="running",pe.FAILED="failed",pe.SUCCEEDED="succeeded",pe.CANCELED="canceled",pe.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(he=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",he.FIXED="fixed",e.JitterStrategy=void 0,(ge=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",ge.FULL="full",e.TaskEventType=void 0,(ye=e.TaskEventType||(e.TaskEventType={})).STATUS="status",ye.LOG="log",ye.PROGRESS="progress",ye.ALL="all",e.TaskType=void 0,(fe=e.TaskType||(e.TaskType={})).ATOMIC="atomic",fe.COMPOSITE="composite";const be="tasks",Ee={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};function ve(r,s){return(n,c)=>c?t.inject(o.Metadata.constr(r))(n,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||$.currentFlavour,i.Model.tableName(r)),n),o.metadata(a.DBKeys.REPOSITORY,n.name)(r),s=s||o.Metadata.get(n.constructor,e.PersistenceKeys.ADAPTER),me.register(r,n,s),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(n))}o.Metadata.tasks=(()=>o.Metadata.innerGet(Symbol.for(be))).bind(o.Metadata),o.Metadata.taskFor=(e=>{const t=o.Metadata.tasks();return t?t[e]:void 0}).bind(o.Metadata),o.Metadata.validationExceptions=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],n=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([...n,...c])]}).bind(o.Metadata),o.Metadata.migrationsFor=(t=>{if(!(t=t??$.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.migrations=(()=>{const t=o.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(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.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(o.Metadata),i.Model.relations=(e,t)=>o.Metadata.relations(e instanceof i.Model?e.constructor:e,t)||[],i.Model.nestedRelations=((t,r=[])=>{let a=[];const s=o.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=o.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),o.Metadata.createdBy=(t=>{const r=o.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(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.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(o.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 o.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)=>o.Metadata.get(t instanceof i.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,i.Model.defaultQueryAttributes=t=>{const r="function"==typeof t?t:t.constructor;return o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR))||[i.Model.pk(t)]},i.Model.sequenceName=(e,...t)=>[i.Model.tableName(e),...t].join("_"),i.Model.sequenceFor=(e,t)=>{if(t)throw new O("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=o.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=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class Se extends a.InternalError{constructor(e){super(e,Se.name,500)}}var Te;e.AuthKeys=void 0,(Te=e.AuthKeys||(e.AuthKeys={})).AUTH="auth",Te.ROLES="roles",Te.NAMESPACE="namespace";const Oe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ae=Oe,ke={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},xe=Object.assign({},ke,{type:"BigInt"});function Ce(t,r,a){return o.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),o.propMetadata(o.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 Me(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,l;n=s,c=r,l=await o.next(e),Reflect.set(n,c,l)}function De(t,r){return(s,n)=>{if(o.prop()(s,n),!t.type){const e=o.Metadata.type(s.constructor,n);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=[o.prop(),Ce([e.OrderDirection.ASC,e.OrderDirection.DSC]),i.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,n),t),a.onCreate(Me,t,r)];return t.generated&&c.push(a.generated()),o.apply(...c)(s,n)}}function Pe(e){const t=Object.assign({},Ae);return delete t.generated,e=Object.assign({},t,e),o.Decoration.for(a.DBKeys.ID).define({decorator:De,args:[e,{priority:60}]}).apply()}async function Ie(e,t,r,s,o){const n=t.logger.for(Ie);if(!s){const t=i.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=me.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 Be(e,t,r,s){const o=s[r];if(!o)return;if(je(s,t),"object"!=typeof o){const t=Xe(s,r,this.adapter.alias),a=await t.override(this._overrides).read(o,e);return await Qe(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=me.forModel(n,this.adapter.alias),l=await c.override(this._overrides).create(o,e),d=i.Model.pk(l);await Qe(e,s,r,l[d],l),s[r]=l[d]}async function Ne(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=Xe(s,a,this.adapter.alias),r=await e.override(this._overrides).read(o,t);return await Qe(t,s,a,o,r),void(s[a]=o)}const n=await Ie(s[a],t,this.adapter.alias,void 0,this._overrides),c=i.Model.pk(n);await Qe(t,s,a,n[c],n),s[a]=n[c]}async function Re(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const n=Xe(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 Qe(t,s,a,c[n.pk],c)}async function Le(e,t,r,a,s){const o=a[r];if(!o||!o.length)return;je(a,t);const n=e.logger.for(Le),c=Xe(a,r,this.adapter.alias),l=i.Model.pk("function"!=typeof t.class||t.class.name?t.class:t.class()),d=new Set;for(const t of o){let s;"object"!=typeof t?(s=await c.override(this._overrides).read(t,e),n.debug("read: "+s[l])):(n.verbose("Creating or updating one-to-many model: "+t[l]),s=await Ie(t,e,this.adapter.alias,void 0,this._overrides)),n.debug(`caching for populate: ${JSON.stringify(s)} under ${s[l]}`),await Qe(e,a,r,s[l],s),d.add(s[l])}a[r]=[...d]}async function $e(t,r,a,s,i){const{cascade:o}=r;if(o.update===e.Cascade.CASCADE)return Le.call(this,t,r,a,s,i)}async function Ke(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(),l="object"===n,d=l?me.forModel(c,this.adapter.alias):Xe(i,s,this.adapter.alias),u=[...new Set([...l?o.map(e=>e[d.pk]):o]).values()];let p,h;try{p=await d.override(this._overrides).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 Qe(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}async function Fe(e,t,r,s){const o=s[r];if(!o)return;je(s,t);const n=e.logger.for(Fe);if("object"!=typeof o){const t=Xe(s,r,this.adapter.alias),a=await t.override(this._overrides).read(o,e);return await Qe(e,s,r,o,a),void(s[r]=o)}if(!(t.class instanceof i.Model?t.class.constructor:t.class))throw new a.InternalError("Could not find model "+t.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(o));const c=await Ie(o,e,this.adapter.alias,void 0,this._overrides),l=i.Model.pk(c);n.info(`caching: ${JSON.stringify(c)} under ${c[l]}`),await Qe(e,s,r,c[l],c),s[r]=c[l]}function je(t,r){let s;const i="function"==typeof r.class&&r.class.name?r.class:r.class(),n=o.Metadata.get(i,e.PersistenceKeys.RELATIONS);if(n&&(s=Object.values(n)?.find(e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r})),!0===s?.populate&&!0===r?.populate)throw new a.InternalError("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function Ue(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Fe.call(this,t,r,a,s)}async function qe(t,r,a,s){if(r.cascade.delete!==e.Cascade.CASCADE)return;const i=s[a];if(!i)return;const o="object"==typeof i,n=o?me.forModel(i,this.adapter.alias):Xe(s,a,this.adapter.alias),c=o?i[n.pk]:i,l=await n.override(this._overrides).delete(c);await Qe(t,s,a,c,l),s[a]=c}async function Ye(e,t,r,s){const o=s[r];if(!o||!o.length)return;je(s,t);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(Ye),l=new Set([...o]);if("object"!==n){const a=Xe(s,r,this.adapter.alias),i=await a.override(this._overrides).readAll([...l.values()],e);for(let t=0;t<i.length;t++){const a=i[t];c.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(a)),await Qe(e,a,r,[...l.values()][t],i)}return await Ge.call(this,s,[...o],c,e,t),s[r]=[...l],void c.info("SET MANY TO MANY IDS: "+s[r])}const d=i.Model.pk(o[0].constructor),u=new Set;for(const t of o){c.info("Creating or updating many-to-many model: "+JSON.stringify(t));const a=await Ie(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(a)} under ${a[d]}`),await Qe(e,s,r,a[d],a),c.info("Creating or updating many-to-many model: "+JSON.stringify(t)),t.id=a.id,u.add(a[d])}const p=i.Model.pk(s.constructor);if(void 0===s[p]){const t=await(async(e,t,r)=>{const s=t[i.Model.pk(t.constructor)];if(void 0!==s)return s;const o=i.Model.sequenceFor(t.constructor);let n;o?.name||(o.name=i.Model.sequenceName(t,"pk"));try{return n=await e.adapter.Sequence(o,e._overrides),await n.next(r)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${o.name}: ${e}`)}})(this,s,e);s[p]=t}const h=await Ge.call(this,s,o,c,e,t);c.info("Junction model created: "+h.name),s[r]=[...u]}async function Ge(e,t,r,a,s){const{JunctionModel:o,fkA:n,fkB:c}=ze(e,t[0],s),l=[];for(const s of t){r.info("Creating or updating many-to-many junction model: "+JSON.stringify(s));const t={[n]:e instanceof i.Model?e[i.Model.pk(e.constructor)]:e,[c]:s instanceof i.Model?s[i.Model.pk(s.constructor)]:s},d=await Ie(new o(t),a,this.adapter.alias,void 0,this._overrides);d?.id&&l.push(d.id)}if(l.length===t?.length){const e=me.forModel(o);await(e?.override(this._overrides).readAll(l))}return o}function ze(t,r,s){const n=i.Model.tableName(t);let c;if(r instanceof i.Model)c=i.Model.tableName(r);else if(i.Model.isModel(r)&&"function"==typeof r)c=r.name?r.name:r()?.name;else if(s?.class){const e="function"!=typeof s.class||s.class.name?s.class:s.class();c=i.Model.tableName(e)}if(!n||!c)throw new a.InternalError("Missing tablenames to create junction table");const l=s?.joinTable?.name?s?.joinTable?.name:`${n}_${c}`,d=n?.toLowerCase()+"_fk",u=c?.toLowerCase()+"_fk",p=class extends i.Model{constructor(e){super(e)}};Object.defineProperty(p,"name",{value:l,writable:!1}),Pe({type:Number})(p.prototype,"id"),i.required()(p.prototype,d),i.required()(p.prototype,u);const h=i.model()(p);return o.Metadata.set(p,e.PersistenceKeys.TABLE,l),{fkA:d,fkB:u,JunctionModel:h}}function He(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function Qe(e,t,r,a,s){const i=He(t.constructor.name,r,a),o=e.get("cacheForPopulate")||{};return o[i]=s,e.accumulate({cacheForPopulate:o})}async function Ve(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=this,c=await(async(t,r,s,i)=>{let o,c;const l=[];let d;try{d=t.get("operation")}catch(e){d=void 0}const u=d===a.OperationKeys.READ||d===a.BulkCrudOperationKeys.READ_ALL?{}:t.get("cacheForPopulate")||{};for(const t of i){o=He(r.constructor.name,s,t);try{if(c=u[o],!c)throw Error("Not found in cache")}catch(i){const o=Xe(r,s);if(!o)throw new a.InternalError("Could not find repo");c=await o.override(n._overrides).read(t,e)}l.push(c)}return l})(e,s,r,o?i:[i]);s[r]=o?c:c[0]}async function We(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 l(e){return Array.isArray(e)?e.map(l):"object"!=typeof e?e:e[i.Model.pk(e)]}const d=l(o[s]),u=l(n[s]);if(void 0===u||i.isEqual(d,u))return;if(Array.isArray(d)!==Array.isArray(u))throw new a.InternalError("Cannot cascade update for different array types");const p=(Array.isArray(d)?d:[d]).filter(Boolean),h=(Array.isArray(u)?u:[u]).filter(Boolean).filter(e=>!p.includes(e)),g=Xe(o,s);if(!g)throw new a.InternalError("Could not find repo");try{const e=await g.override(this._overrides).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)}}const Je=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Xe(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=o.Metadata.get(e instanceof i.Model?e.constructor:e,o.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=o.Metadata.getPropDesignTypes(e instanceof i.Model?e.constructor:e,t)?.designTypes;const n=s?.find(e=>!Je.includes((""+e.name).toLowerCase()));return me.forModel(n,r)}class Ze extends a.BadRequestError{constructor(e,t=Ze.name,r=401){super(e,t,r)}}class et extends Ze{constructor(e,t=et.name){super(e,t,403)}}class tt extends a.InternalError{constructor(e){super(e,tt.name,503)}}function rt(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>(o.Metadata.set(e.PersistenceKeys.TABLE,t||r.name.toLowerCase(),r),o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r)),args:[t]}).apply()}function at(t){return o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}async function st(e,t,r,s){if(s[r]&&(await this.select().where(U.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 it(e,t,r,a){throw new Ze("This adapter does not support user identification")}function ot(){return o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(it),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply()}function nt(){return o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(it),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),args:[]}).apply()}function ct(){return a.timestamp([a.OperationKeys.CREATE])}function lt(){return a.timestamp()}function dt(e){return[()=>{const t="function"==typeof e&&e.name?e:e(),r=i.Model.pk(t);return(o.Metadata.allowedTypes(t,r)||[])[0]}]}function ut(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],i=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),i))(r,a)}}function pt(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class ht extends i.Model{constructor(e){super(e)}}r.__decorate([ct(),r.__metadata("design:type",Date)],ht.prototype,"createdAt",void 0),r.__decorate([lt(),r.__metadata("design:type",Date)],ht.prototype,"updatedAt",void 0),e.SequenceModel=class extends ht{constructor(e){super(e)}},r.__decorate([Pe({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([i.required(),Ce(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([rt("??sequence"),i.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class gt 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,D(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}|${e.PreparedStatementKeys.FIND}`,"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 b?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof b||(this._bookmark=r);const o=me.forModel(this.clazz,this.adapter.alias),n=this.query,{method:c,args:l,params:d}=n;if(c===e.PreparedStatementKeys.FIND){const r=[e.PreparedStatementKeys.PAGE,...l],a={limit:this.size,offset:t,bookmark:this._bookmark};r.push(a);const s=await o.statement(...r,...i);return this.apply(s)}const u=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!c.match(u))throw new O(`Method ${c} is not supported for pagination`);u.lastIndex=0;const p=c.replace(u,e.PreparedStatementKeys.PAGE_BY),h=[p,...l];let g={limit:this.size,offset:t,bookmark:this._bookmark};p!==e.PreparedStatementKeys.PAGE_BY||h.length>2?g={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(d.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 j("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new j(`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 O("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?gt.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total||this._totalPages,this._recordCount=t.count||this._recordCount,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 yt,ft,mt,_t,wt,bt,Et;class vt extends E{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(vt)}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 F("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 F("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 F("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new F("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 F("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 F(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new F("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 F(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=me.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 O("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 U){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 F("Unsupported operator "+s)}return o}squash(t){const r=this.matchDefaultQueryCondition();if(r){const t=this.getOrderDirection();return{class:this.fromSelector,method:e.PreparedStatementKeys.FIND,args:[r.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof U)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 a;this.whereCondition&&(a=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:a?[a,e.OrderDirection.DSC]:[i.Model.pk(this.fromSelector),e.OrderDirection.DSC],[o,n]=s,c={direction:n};this.limitSelector&&(c.limit=this.limitSelector),this.offsetSelector&&(c.offset=this.offsetSelector);const l={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[o],params:c};return a&&(l.method=e.PreparedStatementKeys.FIND_BY,l.args=[a,this.whereCondition.comparison],l.params=c),l}matchDefaultQueryCondition(){if(!this.whereCondition)return;const e=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!e)return;const t=i.Model.defaultQueryAttributes(this.fromSelector);if(!t||!t.length)return;const r=Array.from(new Set(t.map(String))),a=Array.from(new Set(e.attributes.map(String)));return r.length===a.length&&r.every(e=>a.includes(e))?{value:e.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(e){const t=this.collectStartsWithAttributes(e);if(t)return{attributes:Array.from(new Set(t.attributes)),value:t.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:r,operator:a,comparison:s}=t;if(a===e.Operator.STARTS_WITH){if("string"!=typeof r||"string"!=typeof s)return;return{attributes:[r],value:s}}if(a===e.GroupOperator.OR){const e=r instanceof U?this.collectStartsWithAttributes(r):void 0,t=s instanceof U?this.collectStartsWithAttributes(s):void 0;return e&&t&&e.value===t.value?{attributes:[...e.attributes,...t.attributes],value:e.value}:void 0}return a===e.GroupOperator.AND?(r instanceof U?this.collectStartsWithAttributes(r):void 0)||(s instanceof U?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??e.OrderDirection.ASC}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 F(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)],vt.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(yt="undefined"!=typeof S&&S)?yt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ft="undefined"!=typeof S&&S)?ft:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(mt="undefined"!=typeof S&&S)?mt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(_t="undefined"!=typeof S&&S)?_t:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"sum",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(wt="undefined"!=typeof S&&S)?wt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"avg",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(bt="undefined"!=typeof S&&S)?bt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],vt.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[U]),r.__metadata("design:returntype",Object)],vt.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],vt.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],vt.prototype,"thenBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Et="undefined"!=typeof Key&&Key)?Et:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],vt.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],vt.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],vt.prototype,"execute",null);class St extends E{constructor(e){super(),this.name=e,this.observers=[],this.Context=b}for(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof St?i.for(e,...t):i instanceof me?i.override(e):i}})}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}-${P.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 b||(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 E.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=x(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 b||(r.push(s),s=void 0);const i=await St.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new b(s).accumulate({...i,parentContext:s}):(new b).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=St.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 Tt&&(o.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(e){throw new a.InternalError(`Failed to boot ${r.name} service:${e}`)}}static async shutdown(...r){let s=r.pop();void 0===s||s instanceof b||(r.push(s),s=void 0);const i=await St.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...r);s=s?new b(s).accumulate({...i,parentContext:s}):(new b).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=St.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 Tt){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)],St.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],St.prototype,"unObserve",null);class Tt extends St{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...")}}function Ot(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&M(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)],Tt.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Tt.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Tt.prototype,"client",null);const At=()=>Ot(a.OperationKeys.CREATE),kt=()=>Ot(a.OperationKeys.READ),xt=()=>Ot(a.OperationKeys.UPDATE),Ct=()=>Ot(a.OperationKeys.DELETE);function Mt(r){return(a,s,i)=>{i||s?(o.prop()(a,s),r=r||o.Metadata.type(a.constructor,s)):r=r||a,r=x(r);const n=[];if(i&&"number"==typeof i.value)n.push(t.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");n.push(t.inject(r))}else o.Metadata.set(e.PersistenceKeys.SERVICE,r,a),n.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return o.apply(...n)(a,s,i)}}const Dt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Pt extends St{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=me.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=Dt(e);try{const e=St.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}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=Dt(t||e);try{a=Pt.get(t)}catch(e){a=void 0}if(a instanceof Pt)return a;const s=this;let i=class extends s{constructor(){super(e)}};return i=r.__decorate([Mt(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([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"create",null),r.__decorate([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"createAll",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"delete",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"deleteAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"read",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"readAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],Pt.prototype,"query",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"update",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],Pt.prototype,"updateAll",null);class It extends E{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,l,d]=a,u=await t.call(r,c,l,d,...o),p=[c,i(e),l];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 ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof $))throw new O("Only Adapters can be observed by dispatch");return this.adapter=e,this.models=$.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 O("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:l}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${o}: ${r}${l.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 Bt(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 P.instance.generate(s)}function Nt(t=!1,r,...s){"function"==typeof t&&(r=t,t=!1);const n=e.PersistenceKeys.UUID;return o.Decoration.for(n).define({decorator:(t,r,...s)=>{const n={update:t,seed:r,args:s},c=[i.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Bt,n,{priority:54})];return t&&c.push(a.onUpdate(Bt,n,{priority:54})),t||c.push(a.readonly()),o.apply(...c)},args:[t,r,...s]}).apply()}$&&($._baseDispatch=It);class Rt extends E{static{this.lock=new n.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=me.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 Rt.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 l="function"==typeof o&&o?.name?o.name:o,d=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=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===l)for(;;){const e=await Promise.resolve(P.instance.generate(d));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(l){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")}})(d),h=await u(p);return s.debug(`Sequence.increment ${c} current=${d} 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 O(`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 Rt.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 O(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function Lt(e,...t){let r;if(e instanceof Pt&&(r=e.repo.adapter),e instanceof me&&(r=e.adapter),e instanceof $&&(r=e),!r)throw new a.InternalError("Could not find adapter to extract transaction");return r.transactionLock(...t)}function $t(e,...t){return new N(Lt(e,...t))}$._baseSequence=Rt,o.Decoration.for(n.TransactionalKeys.TRANSACTIONAL).define({decorator:(...e)=>(t,r,s)=>{if(!s)throw new a.InternalError("This decorator only applies to methods");return o.method()(t,r,s),o.Metadata.set(t.constructor,o.Metadata.key(n.TransactionalKeys.TRANSACTIONAL,r),{data:e}),s.value=new Proxy(s.value,{async apply(e,t,r){const{log:s,ctx:i}=(await t.logCtx(r,e.name,!0)).for(e),o=i.getOrUndefined("transactionLock")||$t(t);let n;i.put("transactionLock",o),await o.acquire();try{n=await e.call(t,...r,i)}catch(e){try{await o.rollback(e)}catch(e){s.error("Failed to rollback transaction",e)}throw e}try{await o.release()}catch(e){throw new a.InternalError("Failed to release transaction: "+e)}return n}}),s}}).apply(),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),o.description("the backoff strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),r.__decorate([i.required(),o.description("base interval between attempts"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),r.__decorate([i.required(),o.description("max interval"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),r.__decorate([i.type(String),i.option(e.JitterStrategy),o.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(),o.description("The error message"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),r.__decorate([o.prop(),o.description("The error stack"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),r.__decorate([o.prop(),o.description("The error code"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),r.__decorate([o.prop(),o.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"],":"),Pe(),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),r.__decorate([a.readonly(),i.required(),a.transient(),Nt(!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([o.prop(),a.readonly(),r.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=r.__decorate([rt("task_event"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class Kt extends i.JSONSerializer{constructor(){super()}preSerialize(e,...t){return this.serializeValue(e,...t)}deserialize(e,...t){const r=JSON.parse(e);return this.rebuildValue(r)}serializeValue(e,...t){if(null==e)return e;if("object"!=typeof e)return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>this.serializeValue(e,...t));if(e instanceof U){const r=this.serializePlain(e,...t);return r[i.ModelKeys.ANCHOR]="??condition",r}return i.Model.isModel(e)?this.serializeModel(e,...t):this.serializePlain(e,...t)}serializeModel(e,...t){const r=this.serializePlain(e,...t),a=this.getMetadata(e.constructor)??e.constructor?.name;return a&&(r[i.ModelKeys.ANCHOR]=a),r}serializePlain(e,...t){const r={};for(const[a,s]of Object.entries(e))r[a]=this.serializeValue(s,...t);return r}getMetadata(e){try{return o.Metadata.modelName(e)}catch{return}}rebuildValue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.rebuildValue(e));const t=e[i.ModelKeys.ANCHOR],r=this.rebuildObject(e);return t?"??condition"===t?U.from(r):i.Model.build(r,t):r}rebuildObject(e){const t={};for(const[r,a]of Object.entries(e))r!==i.ModelKeys.ANCHOR&&(t[r]=this.rebuildValue(a));return t}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(),o.prop(),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),r.__decorate([o.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([Pe({type:"uuid"}),o.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),o.description("defines a single or composite task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),r.__decorate([i.required(),o.description("Holds task classification - must match @task()"),r.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),r.__decorate([o.prop(),o.description("optional task name for ambiguity"),r.__metadata("design:type",String)],e.TaskModel.prototype,"name",void 0),r.__decorate([i.required(),i.type(String),i.option(e.TaskStatus),o.description("Holds the task current status"),r.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),r.__decorate([o.prop(),a.serialize(Kt),o.description("Holds task input"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),r.__decorate([o.prop(),a.serialize(Kt),o.description("Holds the task output when successfully completed"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),r.__decorate([o.prop(),a.serialize(),o.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),o.description("Holds the current attempt"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),r.__decorate([i.min(1),i.required(),o.description("max attempts for the task"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),r.__decorate([i.required(),a.serialize(),o.description("backoff configuration"),r.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),r.__decorate([i.date(),o.description("Next execution timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),r.__decorate([i.date(),o.description("Task scheduled timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),r.__decorate([o.prop(),o.description("Task lease owner identifier"),r.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),r.__decorate([i.date(),o.description("Task lease expiration timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),r.__decorate([o.prop(),a.serialize(),o.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),o.prop(),o.description("Holds the current step - only for type === 'composite'"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),r.__decorate([o.prop(),a.serialize(),o.description("Holds the step results - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),r.__decorate([o.prop(),a.serialize(),o.description("Holds the task log entries"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),r.__decorate([at(),ct(),o.description("timestamp of creation"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),r.__decorate([at(),lt(),o.description("timestamp of last update"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),r.__decorate([at(),ot(),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),r.__decorate([at(),nt(),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=r.__decorate([o.description("Holds the current step when applicable"),rt("tasks"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("The status of a step"),r.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),r.__decorate([o.prop(),o.description("The result of a successful step"),r.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),r.__decorate([o.prop(),o.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(),o.prop(),o.description("task handler type"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),r.__decorate([o.description("optional task step input"),o.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 Ft 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)],Ft.prototype,"baseMs",void 0),r.__decorate([i.required(),i.option(e.JitterStrategy),r.__metadata("design:type",String)],Ft.prototype,"jitter",void 0),r.__decorate([i.gt("baseMs"),i.min(1e3),i.required(),r.__metadata("design:type",Number)],Ft.prototype,"maxMs",void 0),r.__decorate([i.required(),i.option(e.BackoffStrategy),r.__metadata("design:type",String)],Ft.prototype,"strategy",void 0);class jt extends i.Model{setClassification(e){return this.classification=e,this}setName(e){return this.name=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new Ft,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)],jt.prototype,"classification",void 0),r.__decorate([o.prop(),r.__metadata("design:type",String)],jt.prototype,"name",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],jt.prototype,"status",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],jt.prototype,"atomicity",void 0),r.__decorate([i.required(),r.__metadata("design:type",e.TaskBackoffModel)],jt.prototype,"backoff",void 0),r.__decorate([o.prop(),r.__metadata("design:type",Object)],jt.prototype,"input",void 0),r.__decorate([i.min(1),i.required(),r.__metadata("design:type",Number)],jt.prototype,"maxAttempts",void 0);class Ut extends jt{constructor(t){super(t),this.stepResults=[],i.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setAtomicity(t){throw new a.InternalError("Atomicity locked to "+e.TaskType.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t)),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)],Ut.prototype,"steps",void 0);class qt extends v{get type(){if(!this._type){const e=o.Metadata.get(this.constructor,be);"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 Yt(e){return o.Decoration.for(be).define({decorator:e=>t=>{const r={type:e};return o.Metadata.set(be,e,t),o.metadata(be,r)(t)},args:[e]}).apply()}e.CleanUpTask=class extends qt{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof U)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=U.attr("status").eq(e.TaskStatus.SUCCEEDED).and(U.attr("updatedAt").lte(t.successfulExpiry)),i=U.attr("status").eq(e.TaskStatus.FAILED).and(U.attr("updatedAt").lte(t.failedExpiry)),o=U.attr("status").eq(e.TaskStatus.CANCELED).and(U.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([ve(e.TaskModel),r.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=r.__decorate([Yt("cleanup-task"),r.__metadata("design:paramtypes",[])],e.CleanUpTask);class Gt{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 zt(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 Ht(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 Qt(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Vt(e){return new Promise(t=>setTimeout(t,e))}class Wt extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=Wt.name,Object.setPrototypeOf(this,Wt.prototype)}}class Jt extends b{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 Wt({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?Qt(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}constructor(e){super(e)}}class Xt{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=o.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 Zt 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}=$.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 er 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 tr extends er{constructor(e,t,r){super(tr.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class rr extends er{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(rr.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class ar extends er{constructor(e,t,r){super(ar.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class sr extends er{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(sr.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class ir{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.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(zt(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.getNextAction(t),a=e.payload?.originalError;if(a instanceof Error)return this.assignNextAction(a,r);const s=this.buildMeta(t,e.payload),i=this.createTaskControlError(t,e.payload?.error??this.task.error,s);return this.assignNextAction(i,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 b),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 tr(this.task.id,r,a);case e.TaskStatus.CANCELED:return new ar(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new rr(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new sr(this.task.id,r,a);default:return new tr(this.task.id,r,a)}}assignNextAction(e,t){return t&&(e.nextAction=t),e}getNextAction(t){switch(t){case e.TaskStatus.CANCELED:return e.TaskStatus.CANCELED;case e.TaskStatus.WAITING_RETRY:return e.TaskStatus.WAITING_RETRY;case e.TaskStatus.SCHEDULED:return e.TaskStatus.SCHEDULED;case e.TaskStatus.FAILED:return e.TaskStatus.FAILED;default:return}}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 or extends v{get Context(){return Jt}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=me.forModel(e.TaskModel,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=me.forModel(e.TaskEventModel,this.config.adapter.alias)),this._events}static createTaskContext(e,t){const r=new Jt(e);return t&&Object.keys(t).length?r.accumulate(t):r}constructor(e){super(),this.config=e,this.lock=new n.Lock,this.running=!1,this.config=Object.assign({},Ee,e,{bus:e.bus||new Zt,registry:e.registry||new Xt})}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 ir(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 ir(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 Vt(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(U.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 Vt(e.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=new Date,s=U.attribute("status").eq(e.TaskStatus.PENDING),i=U.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(U.attribute("nextRunAt").lte(a)),o=U.attribute("status").eq(e.TaskStatus.RUNNING).and(U.attribute("leaseExpiry").lte(a)),n=U.attribute("status").eq(e.TaskStatus.SCHEDULED).and(U.attribute("scheduledTo").lte(a)),c=s.or(i).or(o).or(n),l=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+l.length);const d=[];for(const e of l){const r=await this.tryClaim(e,t);if(r&&d.push(r),d.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+d.length),d}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 Jt(r).accumulate({taskId:t.id,logger:new Gt(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 Wt)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=Qt(r);if(a<t.maxAttempts){const c=Ht(a,this.normalizeBackoff(t.backoff)),l=new Date(Date.now()+c);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=l,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 o.pipe(s.LogLevel.warn,"Retry scheduled",{nextRunAt:l,delayMs:c,attempt:a}),await this.emitStatus(o,t,e.TaskStatus.WAITING_RETRY,n,r)}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 o.pipe(s.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(o,t,e.TaskStatus.FAILED,n,r)}}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=Ht(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 Jt&&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],l=this.registry.get(a.classification);if(!l)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 l.run(a.input,r),d=o,u=new Date;n[d]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:s,createdAt:u,updatedAt:u});const p=`${t.id}:step:${d}`;c(a.classification,s),c(p,s),o=d+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:Qt(r),createdAt:a,updatedAt:a}),t.stepResults=n,t.currentStep=o,t.error=Qt(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,i){t instanceof Jt&&await t.flush();const o={status:a};s&&s instanceof e.TaskErrorModel?o.error=s:s&&(o.output=s),r.nextRunAt&&(o.nextRunAt=r.nextRunAt),r.scheduledTo&&(o.scheduledTo=r.scheduledTo);const n=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,o),c=void 0!==i?Object.assign({},o,{originalError:i}):o,l=new e.TaskEventModel({...n,payload:c});this.bus.emit(l,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 nr extends Tt{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||r instanceof b)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(r.engine||or)(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 O("Updates to tasks are not available")}async updateAll(e,...t){throw new O("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")}}function cr(e,t){return e.reduce((e,r)=>e+(e=>{if(null==e)return 0;try{return Buffer.byteLength(JSON.stringify(e))}catch{return 0}})(r[t]),0)}function lr(e,t){Array.isArray(e)?t.push(...e):void 0!==e&&t.push(e)}r.__decorate([ve(e.TaskModel),r.__metadata("design:type",Object)],nr.prototype,"repo",void 0),r.__decorate([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"create",null),r.__decorate([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"createAll",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"delete",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"deleteAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"read",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"readAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"query",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"update",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"updateAll",null),t.Injectables.setRegistry(new we);const dr="##VERSION##",ur="##PACKAGE##";o.Metadata.registerLibrary(ur,dr),e.AbsContextual=v,e.Adapter=$,e.AdapterTransaction=B,e.AuthorizationError=Ze,e.BaseModel=ht,e.BigIntSequence=xe,e.ClientBasedService=Tt,e.CompositeTaskBuilder=Ut,e.Condition=U,e.ConnectionError=tt,e.Context=b,e.ContextLock=N,e.ContextualLoggedClass=E,e.DefaultAdapterFlags=g,e.DefaultCascade=G,e.DefaultContextFlags=h,e.DefaultRepositoryFilters=se,e.DefaultSequenceOptions=Ae,e.DefaultTaskEngineConfig=Ee,e.Dispatch=It,e.ForbiddenError=et,e.InjectablesRegistry=we,e.MethodQueryBuilder=Q,e.MigrationError=A,e.MigrationRuleError=k,e.ModelService=Pt,e.MultipleSelectOperationKeys=_,e.NonTransactionOperationKeys=f,e.NoneSequenceOptions=Oe,e.NumericSequence=ke,e.ObserverError=Se,e.ObserverHandler=T,e.OperatorsMap=z,e.PACKAGE_NAME=ur,e.PaginationOperationKeys=w,e.Paginator=gt,e.PagingError=j,e.PersistenceService=class extends Tt{constructor(){super()}for(e,...t){throw new O("Persistence service cannot be overridden")}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof b||!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=F,e.Repository=me,e.SelectOperationKeys=m,e.Sequence=Rt,e.Serial=I,e.Service=St,e.Statement=vt,e.TaskBackoffBuilder=Ft,e.TaskBuilder=jt,e.TaskCancelError=ar,e.TaskContext=Jt,e.TaskControlError=er,e.TaskEngine=or,e.TaskEventBus=Zt,e.TaskFailError=tr,e.TaskHandler=qt,e.TaskHandlerRegistry=Xt,e.TaskIOSerializer=Kt,e.TaskLogger=Gt,e.TaskRescheduleError=sr,e.TaskRetryError=rr,e.TaskService=nr,e.TaskTracker=ir,e.TasksKey=be,e.TransactionOperationKeys=y,e.UUID=P,e.UnsupportedError=O,e.VERSION=dr,e.allowIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:o,ctxArgs:n}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,o)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...n)}})},e.applyViewDecorator=W,e.auth=t=>{const r=e.PersistenceKeys.AUTH;return o.Decoration.for(r).define({decorator:e=>o.metadata(r,e),args:[t]}).apply()},e.blockIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:o,ctxArgs:n}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,o)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...n)}})},e.cacheModelForPopulate=Qe,e.cascadeDelete=We,e.column=at,e.computeBackoffMs=Ht,e.create=At,e.createOrUpdate=Ie,e.createdAt=ct,e.createdBy=ot,e.createdByOnCreateUpdate=it,e.defaultQueryAttr=()=>(t,r)=>{const a=o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR);let s=o.Metadata.get(t.constructor,a)||[];return s=[...new Set([...s,r])],o.apply(o.propMetadata(a,s))(t,r)},e.del=Ct,e.generateInjectableNameForRepository=_e,e.getAdapterTransaction=Lt,e.getAndConstructJunctionTable=ze,e.getContextLock=$t,e.getFilters=ie,e.getLogPipe=zt,e.getPkTypes=dt,e.getPopulateKey=He,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=Ce,e.injectableServiceKey=x,e.isOperationBlocked=M,e.isTaskError=(e,t)=>e instanceof Error&&"nextAction"in e&&"string"==typeof e.nextAction&&(!t||e instanceof t),e.manyToMany=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.list([e,...d]),a.onCreate(Ye,c),a.onUpdate($e,c),a.afterAny(Ve,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToManyOnCreate=Ye,e.manyToManyOnDelete=async function(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(),l="object"===n,d=l?me.forModel(c,this.adapter.alias):Xe(i,s,this.adapter.alias),u=[...new Set([...l?o.map(e=>e[d.pk]):o]).values()];let p,h;try{p=await d.override(this._overrides).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 Qe(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},e.manyToManyOnUpdate=async function(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Ye.call(this,t,r,a,s)},e.manyToOne=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.type([e,...d]),a.onCreate(Fe,c),a.onUpdate(Ue,c),a.onDelete(qe,c),a.afterAny(Ve,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToOneOnCreate=Fe,e.manyToOneOnDelete=qe,e.manyToOneOnUpdate=Ue,e.noValidateOn=ut,e.noValidateOnCreate=()=>ut(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>ut(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>ut(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.list([e,...d]),a.onCreate(Le,c,{priority:70}),a.onUpdate($e,c,{priority:70}),a.onDelete(Ke,c,{priority:70}),a.afterUpdate(We,c,{priority:70}),a.afterAny(Ve,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToManyOnCreateUpdate=Le,e.oneToManyOnDelete=Ke,e.oneToManyOnUpdate=$e,e.oneToOne=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.type([e,...d]),a.onCreate(Be,c,{priority:70}),a.onUpdate(Ne,c,{priority:70}),a.onDelete(Re,c,{priority:70}),a.afterUpdate(We,c,{priority:70}),a.afterAny(Ve,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToOneOnCreate=Be,e.oneToOneOnDelete=Re,e.oneToOneOnUpdate=Ne,e.onlyOnBulk=re,e.onlyOnCreate=J,e.onlyOnDelete=Z,e.onlyOnFilter=ae,e.onlyOnSingle=te,e.onlyOnTransactional=ee,e.onlyOnUpdate=X,e.pk=Pe,e.pkDec=De,e.pkOnCreate=Me,e.populate=Ve,e.prefixMethod=D,e.prepared=V,e.promiseSequence=C,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const i=Q.getFieldsFromMethodName(a);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:i}),V(),(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:l,limit:d,offset:u}=Q.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 F("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:(l||[])[0],allowed:f},{key:"limit",value:d,allowed:g},{key:"offset",value:u,allowed:y}];for(const e of _)if(void 0!==e.value){if(!e.allowed&&m)throw new F(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=kt,e.relation=pt,e.repository=ve,e.repositoryFromTypeMetadata=Xe,e.roles=t=>o.metadata(e.PersistenceKeys.AUTH_ROLE,t),e.route=(t,r)=>{const a=e.PersistenceKeys.DECAF_ROUTE;return o.Decoration.for(a).define({decorator:()=>(e,s,i)=>{const n={path:r,httpMethod:t,handler:i};return o.apply(o.methodMetadata(o.Metadata.key(a,s),n))(e,s,i)},args:[]}).apply()},e.serializeError=Qt,e.service=Mt,e.sleep=Vt,e.table=rt,e.task=Yt,e.throttle=(t={count:1},r=0)=>function s(i,n,c){return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.THROTTLE,n),t),(i,o,n)=>{n.value=new Proxy(n.value,{async apply(i,n,c){const l=c,d=(()=>{try{return"function"==typeof t?t(...l):t}catch(e){throw new a.InternalError("Failed to obtain throttling configuration from handler: "+e)}})(),{log:u,ctx:p}=(await n.logCtx(c,e.PersistenceKeys.THROTTLE,!0)).for(s),h=(e=>{const t=(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isFinite(e)||0>e)throw new a.InternalError("@throttling() argument indexes must be non-negative integers");return e});return Array.from(new Set(t)).sort((e,t)=>e-t)})(r);if(!h.length)throw new a.InternalError("@throttling() expects at least one argument index to throttle");h.forEach(e=>{if(e>=l.length)throw new a.InternalError(`@throttling() requires argument index ${e} but only ${l.length} provided`);if(!Array.isArray(l[e]))throw new a.InternalError(`@throttling() expects argument at index ${e} to be an array`)});const g=h.map(e=>l[e]),y=g[0].length;if(!g.every(e=>e.length===y))throw new a.InternalError("@throttling() requires all targeted arguments to have the same length");if(0===y)return i.apply(n,l);const f=((e,t,r)=>{if("count"in r){if(0>=r.count)throw new a.InternalError("@throttling() configuration 'count' must be greater than zero");const t=[];for(let a=0;e>a;a+=r.count)t.push({start:a,end:Math.min(e,a+r.count)});return t}if("bufferSize"in r){if(0>=r.bufferSize)throw new a.InternalError("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,o=0;for(let a=0;e>a;a++){const e=cr(t,a);o>0&&o+e>r.bufferSize?(s.push({start:i,end:a}),i=a,o=e):o+=e}return i>=e&&s.length||s.push({start:i,end:e}),s}return[{start:0,end:e}]})(y,g,d),m=f.map(({start:e,end:t})=>l.map((r,a)=>{const s=h.indexOf(a);return-1===s?r:g[s].slice(e,t)})),_=p.get("breakOnSingleFailureInBulk")??!0,w=[],b=[];for(const e of m){try{lr(await i.apply(n,e),w)}catch(e){if(_)throw e;b.push(e)}d.delayMs&&await new Promise(e=>setTimeout(e,d.delayMs))}if(b.length){u.warn(`${o+""} throttled execution continued with ${b.length} failure(s)`);const e=new AggregateError(b,`Throttled ${o+""} failed for ${b.length} chunk(s)`);throw e.results=w,e}return w}})})(i,n,c)},e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(i.async(),a.onCreateUpdate(st),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=st,e.update=xt,e.updatedAt=lt,e.updatedBy=nt,e.uuid=Nt,e.uuidCreateUpdateHandler=Bt,e.validBidirectionalRelation=je,e.view=t=>o.Decoration.for(e.Operator.VIEW).define({decorator:t=>W(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/decoration"),require("@decaf-ts/transactional-decorators")):"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/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsTransactionalDecorators);
1
+ var e,t;e=this,t=function(e,t,r,a,s,i,o,n){"use strict";var c,l,d,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,(l=e.Operator||(e.Operator={})).EQUAL="EQUAL",l.DIFFERENT="DIFFERENT",l.BIGGER="BIGGER",l.BIGGER_EQ="BIGGER_EQ",l.SMALLER="SMALLER",l.SMALLER_EQ="SMALLER_EQ",l.BETWEEN="BETWEEN",l.NOT="NOT",l.IN="IN",l.REGEXP="REGEXP",l.STARTS_WITH="STARTS_WITH",l.ENDS_WITH="ENDS_WITH",l.GROUP_BY="group-by",l.COUNT="count",l.SUM="sum",l.MAX="v_max",l.MIN="v_min",l.DISTINCT="distinct",l.VIEW="view",e.GroupOperator=void 0,(d=e.GroupOperator||(e.GroupOperator={})).AND="AND",d.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.FIND="find",u.PAGE="page",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",p.THROTTLE="throttle",p.DEFAULT_QUERY_ATTR="default-query-attr";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,breakOnSingleFailureInBulk:!0,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,e.PreparedStatementKeys.FIND,e.PreparedStatementKeys.PAGE],w=[e.PreparedStatementKeys.PAGE_BY,e.PreparedStatementKeys.PAGE];class b 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,t=new Set){if(t.has(this))return;t.add(this);const r=this.getOrUndefined(e);if(null!=r)return r;let a=this.getOrUndefined("childContexts");if(a&&a.length&&(a=a.filter(e=>!t.has(e)),a.length)){const r=a.map(r=>r.getFromChildren(e,t)).reduce((e,t)=>(Array.isArray(t)?e.push(...t):null!=t&&e.push(t),e),[]).filter(e=>null!=e);if(!r.length)return;return r.some(e=>"object"!=typeof e)?r[0]:r.reduce((e,t)=>Object.assign(e,t),{})}}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 E extends s.LoggedClass{logCtx(e,t,r=!1,a){return E.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 b;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 v extends E{constructor(){super(),this._Context=b}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 b||(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}=E.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 O extends a.InternalError{constructor(e){super(e,O.name,500)}}class A extends a.InternalError{constructor(e,t=A.name){super(e,t,500)}}class k extends A{constructor(e){super(e,k.name)}}function x(e){if(!e)throw new a.InternalError("No name provided");return"string"==typeof e?e.replaceAll(".","-"):o.Metadata.Symbol(o.Metadata.constr(e)).toString().replaceAll(".","-")}async function C(e,t=!1){if(!t){const t=[];for(const r of e)t.push(await r());return t}const r=[];for(const t of e)try{r.push({status:"fulfilled",value:await t()})}catch(e){r.push({status:"rejected",reason:e})}return r}function M(e,t){const{handler:r,args:s}=o.Metadata.get(e,a.OperationKeys.REFLECT+a.OperationKeys.BLOCK)||{};return!!r&&(r(...s,t)??!1)}function D(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 k)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 P{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 P._instance||(P._instance=new P),P._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}}class B{constructor(e,...t){this.adapter=e}async begin(...e){}async commit(...e){}async rollback(...e){}}class N extends n.Lock{constructor(e){super(),this.adapterTransaction=e,this.acquireCount=0,this.lock=new n.Lock}async acquire(...e){await this.lock.acquire(),this.acquireCount++,1===this.acquireCount?(this.lock.release(),await this.adapterTransaction.begin(...e)):this.lock.release()}async release(...e){if(await this.lock.acquire(),this.acquireCount--,0===this.acquireCount)try{await this.adapterTransaction.commit(...e)}catch(t){await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+t),...e)}finally{this.lock.release()}else 0>this.acquireCount?(this.acquireCount=0,this.lock.release()):this.lock.release()}async rollback(e,...t){await this.lock.acquire();try{await this.adapterTransaction.rollback(new a.InternalError("Failed to submit transaction: "+e),...t)}catch(e){throw new a.InternalError("Failed to rollback transaction: "+e)}finally{this.lock.release()}}}const R=o.Decoration.flavourResolver.bind(o.Decoration);function L(e,t,r,a){if(!t)return e;const s=e,i=[],o=[];for(const e of s)"fulfilled"===e.status?i.push(e.value):o.push(e.reason);if(o.length){r.warn(`Bulk ${a} encountered ${o.length} failure(s) while continuing`);const e=new AggregateError(o,`Bulk ${a} failed for ${o.length} item(s)`);throw e.results=s,e}return i}o.Decoration.flavourResolver=e=>{try{const t=R(e);if(t&&t!==o.DefaultFlavour)return t;const r="function"==typeof e?e:e?.constructor,a=r&&"function"==typeof o.Metadata.registeredFlavour?o.Metadata.registeredFlavour(r):void 0;if(a&&a!==o.DefaultFlavour)return a;const s=$._currentFlavour;if(s){const e=$._cache?.[s];return e?.flavour?e.flavour:s}}catch(e){return o.DefaultFlavour}};class $ extends v{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!$._baseRepository)throw new a.InternalError("This should be overridden when necessary. Otherwise it will be replaced lazily");return $._baseRepository}transactionLock(...e){return new B(this,...e)}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){const{log:r,ctx:a}=(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 $._cache)throw new a.InternalError(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);$._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),$._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),$._currentFlavour=this.alias)}Dispatch(){return new $._baseDispatch}ObserverHandler(){return new T}isReserved(e){return!e}async initialize(...e){}async Sequence(e,t){return new $._baseSequence(e,this,t)}async flags(e,t,r,...n){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,l=c?i.Model.tableName(c)+" - ":"";r.correlationId=r.correlationId||`${l}${e}-${P.instance.generate()}`;const d=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:n,writeOperation:y.includes(e),timestamp:new Date,operation:e,ignoredValidationProperties:t?o.Metadata.validationExceptions(Array.isArray(t)&&t[0]?t[0]:t,e):[],logger:d})}get Context(){return b}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 b||(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.getOrUndefined("operation"),a=s.getOrUndefined("affectedTables");if(!t||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:l}=this.logCtx(n,this.revert),d=i.Model.pk(r),u=new r;u[d]=s,c.silly(`Rebuilding model ${u.constructor.name} id ${s}`);const p=t[e.PersistenceKeys.METADATA],h=Object.keys(u).filter(e=>e!==d).reduce((e,a)=>(e[a]=t[i.Model.columnName(r,a)],e),u);return l.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);o.debug(`Creating ${t.length} entries ${c} table`);const l=!(n.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.create(e,t,r[a],...s,n.override({noEmitSingle:!0})));return L(l?await C(d,!0):await C(d),l,o,a.BulkCrudOperationKeys.CREATE_ALL)}async readAll(e,t,...r){const{log:s,ctx:o}=this.logCtx(r,this.readAll),n=i.Model.tableName(e);s.debug(`Reading ${t.length} entries ${n} table`);const c=!(o.get("breakOnSingleFailureInBulk")??1),l=t.map(t=>()=>this.read(e,t,...r,o.override({noEmitSingle:!0})));return L(c?await C(l,!0):await C(l),c,s,a.BulkCrudOperationKeys.READ_ALL)}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);o.debug(`Updating ${t.length} entries ${c} table`);const l=!(n.get("breakOnSingleFailureInBulk")??1),d=t.map((t,a)=>()=>this.update(e,t,r[a],...s,n.override({noEmitSingle:!0})));return L(l?await C(d,!0):await C(d),l,o,a.BulkCrudOperationKeys.UPDATE_ALL)}async deleteAll(e,t,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);s.debug(`Deleting ${t.length} entries from ${e} table`);const o=!(i.get("breakOnSingleFailureInBulk")??1),n=t.map(t=>()=>this.delete(e,t,...r,i.override({noEmitSingle:!0})));return L(o?await C(n,!0):await C(n),o,s,a.BulkCrudOperationKeys.DELETE_ALL)}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 o.Metadata.flavourOf(e)}static get currentFlavour(){if(!$._currentFlavour)throw new a.InternalError("No persistence flavour set. Please initialize your adapter");return $._currentFlavour}static get current(){return $.get(this.currentFlavour)}static get(e){if(!e)return $.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 o.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 o.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)],$.prototype,"shutdownProxies",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,Object,b]),r.__metadata("design:returntype",Promise)],$.prototype,"context",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],$.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],$.prototype,"unObserve",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],$.prototype,"client",null);class F extends a.InternalError{constructor(e){super(e,F.name,500)}}class j extends a.InternalError{constructor(e){super(e,j.name,500)}}class U 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 U.and(this,e)}or(e){return U.or(this,e)}not(t){return new U(this,e.Operator.NOT,t)}hasErrors(...t){const r=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof U)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 U){if(!(this.comparison instanceof U)&&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 U.group(t,e.GroupOperator.AND,r)}static or(t,r){return U.group(t,e.GroupOperator.OR,r)}static group(e,t,r){return new U(e,t,r)}static attribute(e){return(new U.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)}startsWith(t){return this.setOp(e.Operator.STARTS_WITH,t)}endsWith(t){return this.setOp(e.Operator.ENDS_WITH,t)}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 U(this.attr1,this.operator,this.comparison)}catch(e){throw new F(e)}}}}static builder(){return new U.Builder}static from(e){return new U(e)}}var q,Y;r.__decorate([i.required(),r.__metadata("design:type",Object)],U.prototype,"attr1",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],U.prototype,"operator",void 0),r.__decorate([i.required(),r.__metadata("design:type",Object)],U.prototype,"comparison",void 0),e.OrderDirection=void 0,(q=e.OrderDirection||(e.OrderDirection={})).ASC="asc",q.DSC="desc",e.Cascade=void 0,(Y=e.Cascade||(e.Cascade={})).CASCADE="cascade",Y.NONE="none";const G={update:e.Cascade.CASCADE,delete:e.Cascade.NONE},z={Equals:(e,t)=>U.attribute(e).eq(t),Diff:(e,t)=>U.attribute(e).dif(t),LessThan:(e,t)=>U.attribute(e).lt(t),LessThanEqual:(e,t)=>U.attribute(e).lte(t),GreaterThan:(e,t)=>U.attribute(e).gt(t),GreaterThanEqual:(e,t)=>U.attribute(e).gte(t),In:(e,t)=>U.attribute(e).in(t),Matches:(e,t)=>U.attribute(e).regexp(t)},H=e=>e.charAt(0).toLowerCase()+e.slice(1);class Q extends s.LoggedClass{static get log(){return this._logger||(this._logger=s.Logging.for(Q.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),l=this.buildWhere(o,t),{orderBy:d,limit:u,offset:p}=this.extractOrderLimitOffset(e,t,o);return{action:a,select:n,selector:i,where:l,groupBy:c,orderBy:d,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?H(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(H).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(H).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(H(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?z[n]:z.Equals;if(!c)throw Error("Unsupported operator "+n);const l=r[a];if(void 0===l)throw Error("Invalid value for field "+s);const d=c(s,l);o=0===a?d:i[a-1]===e.QueryClause.AND?o.and(d):o.or(d)}),o}static parseFieldAndOperator(e){for(const t of Object.keys(z))if(e.endsWith(t)){const r=e.slice(0,-t.length);return{field:H(r),operator:t}}return{field:H(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=Q.log.for(this.getProperlyOrderByOrThrow);if(r||t){if(r&&!t)throw new F("Expected OrderBy clause, but no sortable field was found in method name.");if(r||!t){if(!Object.values(e.OrderDirection).includes(r))throw new F(`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,l;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]||(l=o[2]),{orderBy:n,limit:c,offset:l}}}function V(){return o.Decoration.for(e.PersistenceKeys.STATEMENT).define({decorator:()=>(t,r,a)=>o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.STATEMENT,r),!0))(t,r,a),args:[]}).apply()}function W(e,t,r){return(a,s)=>{const i=r?.name||((e,t,r)=>{const a=(o.Metadata.get(e.constructor,t)||{})[r]||{};return Object.keys(a).length+1+""})(a,e,s),n=o.Metadata.key(e,s,i),c={...r||{},kind:t,attribute:s};return o.propMetadata(n,c)(a,s)}}function J(e){return ae(e,[a.OperationKeys.CREATE,a.BulkCrudOperationKeys.CREATE_ALL])}function X(e){return ae(e,[a.OperationKeys.UPDATE,a.BulkCrudOperationKeys.UPDATE_ALL])}function Z(e){return ae(e,[a.OperationKeys.DELETE,a.BulkCrudOperationKeys.DELETE_ALL])}function ee(e){return ae(e,y)}function te(e){return ae(e,Object.values(a.OperationKeys))}function re(e){return ae(e,Object.values(a.BulkCrudOperationKeys))}function ae(e,t){return(r,s,n,...c)=>{if("string"==typeof e)throw new a.InternalError("clazz cannot be string. This should be impossible");const{log:l}=E.prototype.logCtx(c,ae);return l.silly(`filtering ${s} event for${r?" "+(i.Model.tableName(r)||r):""} ${n}`),("string"==typeof r?r===i.Model.tableName(e)||r===e.constructor.name:o.Metadata.constr(e)===o.Metadata.constr(r))&&t.includes(s)}}const se={onlyOnCreate:J,onlyOnUpdate:X,onlyOnDelete:Z,onlyOnTransactional:ee,onlyOnSingle:te,onlyOnBulk:re};function ie(e){const t=Object.assign({},se);return Object.entries(t).forEach(([r,a])=>{t[r]=a(e.class)}),t}var oe,ne,ce,le,de,ue,pe,he,ge,ye,fe;class me 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 ie(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&&(me.register(t,this,this.adapter.alias),e)&&o.Metadata.get(t,o.DecorationKeys.FLAVOUR)===o.DefaultFlavour&&o.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 l=i.Model.sequenceFor(e[0]);let d=[];if(i.Model.generatedBySequence(this.class)?(l.name||(l.name=i.Model.sequenceName(e[0],"pk")),d=await(await this.adapter.Sequence(l,this._overrides)).range(e.length,...s)):i.Model.generated(this.class,this.pk)||(d=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),l.type&&(e[this.pk]="String"!==l.type||l.generated?d[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 l=e[this.pk];if(!l)throw new a.InternalError("No value for the Id is defined under the property "+this.pk);let d;if(r.get("applyUpdateValidation")&&(d=await this.read(l,r),r.get("mergeForUpdate")&&(e=i.Model.merge(d,e,this.class))),n||await a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d),!c){const t=r.get("ignoredValidationProperties")||[];o.silly("ignored validation properties: "+t);const s=await Promise.resolve(e.hasErrors(d,...t));if(s)throw new a.ValidationError(s.toString())}return[e,...s,d]}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 l=e.map(e=>{const t=e[this.pk];if(!t)throw new a.InternalError("missing id on update operation");return t});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(e=e.map((e,t)=>i.Model.merge(d[t],e,this.class)))),n||await Promise.all(e.map((e,t)=>a.enforceDBDecorators(this,r,e,a.OperationKeys.UPDATE,a.OperationKeys.ON,d?d[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(d[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,d]}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],l=this.select().where(t).orderBy(c);return s&&l.limit(s),i&&l.offset(i),l.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:l}=a;if(!n&&!c)throw new F("PaginateBy needs a page or a bookmark");const{log:d,ctx:u,ctxArgs:p}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE_BY,!0)).for(this.paginateBy);let h;if(d.verbose(`paginating ${i.Model.tableName(this.class)} with page size ${l}`),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(l,...p);else{if(!n)throw new F("PaginateBy needs a page or a bookmark");h=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,r]).paginate(l,...p)}const g=await h.page(o,c,...p);return h.serialize(g)}async find(t,r=e.OrderDirection.ASC,...a){if("string"!=typeof t)throw new F("Find value must be a string");const s=this.getDefaultQueryAttributes(),o=this.buildDefaultStartsWithCondition(t,s),{log:n,ctxArgs:c}=(await this.logCtx(a,e.PreparedStatementKeys.FIND,!0)).for(this.find);return n.verbose(`finding ${i.Model.tableName(this.class)} by default attributes ${s.join(", ")}`),this.select().where(o).orderBy([s[0],r]).execute(...c)}async page(t,r=e.OrderDirection.ASC,a={offset:1,limit:10},...s){if("string"!=typeof t)throw new F("Page value must be a string");const o=a.offset||1,{offset:n,bookmark:c,limit:l}=a;if(!n&&!c)throw new F("PaginateBy needs a page or a bookmark");const d=this.getDefaultQueryAttributes(),u=this.buildDefaultStartsWithCondition(t,d),{log:p,ctx:h,ctxArgs:g}=(await this.logCtx(s,e.PreparedStatementKeys.PAGE,!0)).for(this.page);p.verbose(`paging ${i.Model.tableName(this.class)} by default attributes ${d.join(", ")}`);const y=l??10,f=d[0],m=this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1});let _;if(c&&h.get("paginateByBookmark")){const t=i.Model.pk(this.class),a=r===e.OrderDirection.ASC?this.attr(t).gt(c):this.attr(t).lt(c);_=await m.select().where(u.and(a)).orderBy([f,r]).paginate(y,...g)}else{if(!n)throw new F("PaginateBy needs a page or a bookmark");_=await m.select().where(u).orderBy([f,r]).paginate(y,...g)}const w=await _.page(o,c,...g);return _.serialize(w)}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(!me.statements(this,t))throw new F("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)}getDefaultQueryAttributes(){const e=i.Model.defaultQueryAttributes(this.class);if(!e||!e.length)throw new F("No default query attributes defined for "+i.Model.tableName(this.class));return e}buildDefaultStartsWithCondition(e,t){if("string"!=typeof e)throw new F("Default query value must be a string");let r;for(const a of t){const t=this.attr(a).startsWith(e);r=r?r.or(t):t}if(!r)throw new F("No default query attributes available for "+i.Model.tableName(this.class));return r}attr(e){return U.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:o.Metadata.constr(e)===o.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=>$._baseSequence.parseValue(i.Model.sequenceFor(this.class).type,e)):$._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 n=r||o.Metadata.flavourOf(t)||$.currentFlavour;try{i=this.get(t,n)}catch(e){i=void 0}if(i instanceof me)return i;const c=r||o.Metadata.flavourOf(t)||i&&o.Metadata.get(i,e.PersistenceKeys.ADAPTER)||$.currentFlavour,l=c?$.get(c):void 0;if(!l)throw new a.InternalError("No registered persistence adapter found flavour "+c);return i=i||l.repository(),new i(l,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 me)throw new a.InternalError(s+" already has a registered instance");this._cache[s]=t}static statements(t,r){const a=t instanceof me?t.constructor:t,s=o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.STATEMENT,r):e.PersistenceKeys.STATEMENT);return(r?s:Object.keys(s))||!1}static queries(t,r){const a=t instanceof me?t.constructor:t;return o.Metadata.get(a,r?o.Metadata.key(e.PersistenceKeys.QUERY,r):e.PersistenceKeys.QUERY)}}function _e(t,r){if(!(r||(r=o.Decoration.flavourResolver(t instanceof i.Model?t.constructor:t))&&r!==o.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([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"listBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"paginateBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"find",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,String,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"page",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"findOneBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"findBy",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"countOf",null),r.__decorate([V(),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)],me.prototype,"maxOf",null),r.__decorate([V(),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)],me.prototype,"minOf",null),r.__decorate([V(),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)],me.prototype,"avgOf",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(le="undefined"!=typeof K&&K)?le:Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"sumOf",null),r.__decorate([V(),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)],me.prototype,"distinctOf",null),r.__decorate([V(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ue="undefined"!=typeof K&&K)?ue:Object,void 0]),r.__metadata("design:returntype",Promise)],me.prototype,"groupOf",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,Function]),r.__metadata("design:returntype",Function)],me.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],me.prototype,"unObserve",null),$&&($._baseRepository=me);class we 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 n;try{n=super.get(r)}catch{}if(!n){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 l=e.PersistenceKeys.ADAPTER,d=a||o.Metadata.get(c,l);try{let e=d;try{d&&$.get(d)}catch{const t=$.current;t&&t.flavour===d&&(e=t.alias)}if(n=me.forModel(c,e),n instanceof me)return n;const r=d||o.Metadata.get(n.constructor,l)||o.Metadata.get(c,l);t.Injectables.register(n,_e(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=me.get(c,d);if("function"==typeof t){const e=d?$.get(d):$.current;if(!e)return;return new t(e,c)}}}return n}}e.TaskStatus=void 0,(pe=e.TaskStatus||(e.TaskStatus={})).PENDING="pending",pe.SCHEDULED="scheduled",pe.RUNNING="running",pe.FAILED="failed",pe.SUCCEEDED="succeeded",pe.CANCELED="canceled",pe.WAITING_RETRY="waiting_retry",e.BackoffStrategy=void 0,(he=e.BackoffStrategy||(e.BackoffStrategy={})).EXPONENTIAL="exponential",he.FIXED="fixed",e.JitterStrategy=void 0,(ge=e.JitterStrategy||(e.JitterStrategy={})).NONE="none",ge.FULL="full",e.TaskEventType=void 0,(ye=e.TaskEventType||(e.TaskEventType={})).STATUS="status",ye.LOG="log",ye.PROGRESS="progress",ye.ALL="all",e.TaskType=void 0,(fe=e.TaskType||(e.TaskType={})).ATOMIC="atomic",fe.COMPOSITE="composite";const be="tasks",Ee={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};function ve(r,s){return(n,c)=>c?t.inject(o.Metadata.constr(r))(n,c):(o.Metadata.set(a.DBKeys.REPOSITORY,o.Metadata.key(s||$.currentFlavour,i.Model.tableName(r)),n),o.metadata(a.DBKeys.REPOSITORY,n.name)(r),s=s||o.Metadata.get(n.constructor,e.PersistenceKeys.ADAPTER),me.register(r,n,s),t.injectable(o.Metadata.constr(r),{callback:e=>(Object.defineProperty(e,a.DBKeys.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:r}),e)})(n))}o.Metadata.tasks=(()=>o.Metadata.innerGet(Symbol.for(be))).bind(o.Metadata),o.Metadata.taskFor=(e=>{const t=o.Metadata.tasks();return t?t[e]:void 0}).bind(o.Metadata),o.Metadata.validationExceptions=((t,r)=>{const s=o.Metadata.get(t,e.PersistenceKeys.NO_VALIDATE)||[],n=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([...n,...c])]}).bind(o.Metadata),o.Metadata.migrationsFor=(t=>{if(!(t=t??$.current))throw new a.InternalError("Could not get adapter for migrations");return o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.MIGRATION),t.alias).map(e=>e.class)}).bind(o.Metadata),o.Metadata.migrations=(()=>{const t=o.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(o.Metadata),o.Metadata.relations=((t,r)=>{const s=o.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(o.Metadata),i.Model.relations=(e,t)=>o.Metadata.relations(e instanceof i.Model?e.constructor:e,t)||[],i.Model.nestedRelations=((t,r=[])=>{let a=[];const s=o.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=o.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),o.Metadata.createdBy=(t=>{const r=o.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(o.Metadata),o.Metadata.updatedBy=(t=>{const r=o.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(o.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 o.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)=>o.Metadata.get(t instanceof i.Model?t.constructor:t,o.Metadata.key(e.PersistenceKeys.COLUMN,r))||r,i.Model.defaultQueryAttributes=t=>{const r="function"==typeof t?t:t.constructor;return o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR))||[i.Model.pk(t)]},i.Model.sequenceName=(e,...t)=>[i.Model.tableName(e),...t].join("_"),i.Model.sequenceFor=(e,t)=>{if(t)throw new O("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=o.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=()=>o.Metadata.innerGet(Symbol.for(e.PersistenceKeys.SERVICE)),t.Injectables.repositories=()=>o.Metadata.innerGet(Symbol.for(a.DBKeys.REPOSITORY));class Se extends a.InternalError{constructor(e){super(e,Se.name,500)}}var Te;e.AuthKeys=void 0,(Te=e.AuthKeys||(e.AuthKeys={})).AUTH="auth",Te.ROLES="roles",Te.NAMESPACE="namespace";const Oe={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},Ae=Oe,ke={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},xe=Object.assign({},ke,{type:"BigInt"});function Ce(t,r,a){return o.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),o.propMetadata(o.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 Me(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,l;n=s,c=r,l=await o.next(e),Reflect.set(n,c,l)}function De(t,r){return(s,n)=>{if(o.prop()(s,n),!t.type){const e=o.Metadata.type(s.constructor,n);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=[o.prop(),Ce([e.OrderDirection.ASC,e.OrderDirection.DSC]),i.required(),a.readonly(),o.propMetadata(o.Metadata.key(a.DBKeys.ID,n),t),a.onCreate(Me,t,r)];return t.generated&&c.push(a.generated()),o.apply(...c)(s,n)}}function Pe(e){const t=Object.assign({},Ae);return delete t.generated,e=Object.assign({},t,e),o.Decoration.for(a.DBKeys.ID).define({decorator:De,args:[e,{priority:60}]}).apply()}async function Ie(e,t,r,s,o){const n=t.logger.for(Ie);if(!s){const t=i.Model.get(e.constructor.name);if(!t)throw new a.InternalError("Could not find model "+e.constructor.name);s=me.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 Be(e,t,r,s){const o=s[r];if(!o)return;if(je(s,t),"object"!=typeof o){const t=Xe(s,r,this.adapter.alias),a=await t.override(this._overrides).read(o,e);return await Qe(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=me.forModel(n,this.adapter.alias),l=await c.override(this._overrides).create(o,e),d=i.Model.pk(l);await Qe(e,s,r,l[d],l),s[r]=l[d]}async function Ne(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=Xe(s,a,this.adapter.alias),r=await e.override(this._overrides).read(o,t);return await Qe(t,s,a,o,r),void(s[a]=o)}const n=await Ie(s[a],t,this.adapter.alias,void 0,this._overrides),c=i.Model.pk(n);await Qe(t,s,a,n[c],n),s[a]=n[c]}async function Re(t,r,a,s){const o=s[a];if(!o)return;if(r.cascade.update!==e.Cascade.CASCADE)return;const n=Xe(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 Qe(t,s,a,c[n.pk],c)}async function Le(e,t,r,a,s){const o=a[r];if(!o||!o.length)return;je(a,t);const n=e.logger.for(Le),c=Xe(a,r,this.adapter.alias),l=i.Model.pk("function"!=typeof t.class||t.class.name?t.class:t.class()),d=new Set;for(const t of o){let s;"object"!=typeof t?(s=await c.override(this._overrides).read(t,e),n.debug("read: "+s[l])):(n.verbose("Creating or updating one-to-many model: "+t[l]),s=await Ie(t,e,this.adapter.alias,void 0,this._overrides)),n.debug(`caching for populate: ${JSON.stringify(s)} under ${s[l]}`),await Qe(e,a,r,s[l],s),d.add(s[l])}a[r]=[...d]}async function $e(t,r,a,s,i){const{cascade:o}=r;if(o.update===e.Cascade.CASCADE)return Le.call(this,t,r,a,s,i)}async function Ke(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(),l="object"===n,d=l?me.forModel(c,this.adapter.alias):Xe(i,s,this.adapter.alias),u=[...new Set([...l?o.map(e=>e[d.pk]):o]).values()];let p,h;try{p=await d.override(this._overrides).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 Qe(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}async function Fe(e,t,r,s){const o=s[r];if(!o)return;je(s,t);const n=e.logger.for(Fe);if("object"!=typeof o){const t=Xe(s,r,this.adapter.alias),a=await t.override(this._overrides).read(o,e);return await Qe(e,s,r,o,a),void(s[r]=o)}if(!(t.class instanceof i.Model?t.class.constructor:t.class))throw new a.InternalError("Could not find model "+t.class);n.info("Creating or updating many-to-one model: "+JSON.stringify(o));const c=await Ie(o,e,this.adapter.alias,void 0,this._overrides),l=i.Model.pk(c);n.info(`caching: ${JSON.stringify(c)} under ${c[l]}`),await Qe(e,s,r,c[l],c),s[r]=c[l]}function je(t,r){let s;const i="function"==typeof r.class&&r.class.name?r.class:r.class(),n=o.Metadata.get(i,e.PersistenceKeys.RELATIONS);if(n&&(s=Object.values(n)?.find(e=>{const r="function"==typeof e.class&&e.class.name?e.class:e.class();return t instanceof r})),!0===s?.populate&&!0===r?.populate)throw new a.InternalError("Bidirectional populate is not allowed. Please set populate to false on one side of the relation.");return!0}async function Ue(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Fe.call(this,t,r,a,s)}async function qe(t,r,a,s){if(r.cascade.delete!==e.Cascade.CASCADE)return;const i=s[a];if(!i)return;const o="object"==typeof i,n=o?me.forModel(i,this.adapter.alias):Xe(s,a,this.adapter.alias),c=o?i[n.pk]:i,l=await n.override(this._overrides).delete(c);await Qe(t,s,a,c,l),s[a]=c}async function Ye(e,t,r,s){const o=s[r];if(!o||!o.length)return;je(s,t);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(Ye),l=new Set([...o]);if("object"!==n){const a=Xe(s,r,this.adapter.alias),i=await a.override(this._overrides).readAll([...l.values()],e);for(let t=0;t<i.length;t++){const a=i[t];c.info("FOUND MANY TO MANY VALUE: "+JSON.stringify(a)),await Qe(e,a,r,[...l.values()][t],i)}return await Ge.call(this,s,[...o],c,e,t),s[r]=[...l],void c.info("SET MANY TO MANY IDS: "+s[r])}const d=i.Model.pk(o[0].constructor),u=new Set;for(const t of o){c.info("Creating or updating many-to-many model: "+JSON.stringify(t));const a=await Ie(t,e,this.adapter.alias,void 0,this._overrides);c.info(`caching: ${JSON.stringify(a)} under ${a[d]}`),await Qe(e,s,r,a[d],a),c.info("Creating or updating many-to-many model: "+JSON.stringify(t)),t.id=a.id,u.add(a[d])}const p=i.Model.pk(s.constructor);if(void 0===s[p]){const t=await(async(e,t,r)=>{const s=t[i.Model.pk(t.constructor)];if(void 0!==s)return s;const o=i.Model.sequenceFor(t.constructor);let n;o?.name||(o.name=i.Model.sequenceName(t,"pk"));try{return n=await e.adapter.Sequence(o,e._overrides),await n.next(r)}catch(e){throw new a.InternalError(`Failed to instantiate Sequence ${o.name}: ${e}`)}})(this,s,e);s[p]=t}const h=await Ge.call(this,s,o,c,e,t);c.info("Junction model created: "+h.name),s[r]=[...u]}async function Ge(e,t,r,a,s){const{JunctionModel:o,fkA:n,fkB:c}=ze(e,t[0],s),l=[];for(const s of t){r.info("Creating or updating many-to-many junction model: "+JSON.stringify(s));const t={[n]:e instanceof i.Model?e[i.Model.pk(e.constructor)]:e,[c]:s instanceof i.Model?s[i.Model.pk(s.constructor)]:s},d=await Ie(new o(t),a,this.adapter.alias,void 0,this._overrides);d?.id&&l.push(d.id)}if(l.length===t?.length){const e=me.forModel(o);await(e?.override(this._overrides).readAll(l))}return o}function ze(t,r,s){const n=i.Model.tableName(t);let c;if(r instanceof i.Model)c=i.Model.tableName(r);else if(i.Model.isModel(r)&&"function"==typeof r)c=r.name?r.name:r()?.name;else if(s?.class){const e="function"!=typeof s.class||s.class.name?s.class:s.class();c=i.Model.tableName(e)}if(!n||!c)throw new a.InternalError("Missing tablenames to create junction table");const l=s?.joinTable?.name?s?.joinTable?.name:`${n}_${c}`,d=n?.toLowerCase()+"_fk",u=c?.toLowerCase()+"_fk",p=class extends i.Model{constructor(e){super(e)}};Object.defineProperty(p,"name",{value:l,writable:!1}),Pe({type:Number})(p.prototype,"id"),i.required()(p.prototype,d),i.required()(p.prototype,u);const h=i.model()(p);return o.Metadata.set(p,e.PersistenceKeys.TABLE,l),{fkA:d,fkB:u,JunctionModel:h}}function He(t,r,a){return[e.PersistenceKeys.POPULATE,t,r,a].join(".")}async function Qe(e,t,r,a,s){const i=He(t.constructor.name,r,a),o=e.get("cacheForPopulate")||{};return o[i]=s,e.accumulate({cacheForPopulate:o})}async function Ve(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=this,c=await(async(t,r,s,i)=>{let o,c;const l=[];let d;try{d=t.get("operation")}catch(e){d=void 0}const u=d===a.OperationKeys.READ||d===a.BulkCrudOperationKeys.READ_ALL?{}:t.get("cacheForPopulate")||{};for(const t of i){o=He(r.constructor.name,s,t);try{if(c=u[o],!c)throw Error("Not found in cache")}catch(i){const o=Xe(r,s);if(!o)throw new a.InternalError("Could not find repo");c=await o.override(n._overrides).read(t,e)}l.push(c)}return l})(e,s,r,o?i:[i]);s[r]=o?c:c[0]}async function We(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 l(e){return Array.isArray(e)?e.map(l):"object"!=typeof e?e:e[i.Model.pk(e)]}const d=l(o[s]),u=l(n[s]);if(void 0===u||i.isEqual(d,u))return;if(Array.isArray(d)!==Array.isArray(u))throw new a.InternalError("Cannot cascade update for different array types");const p=(Array.isArray(d)?d:[d]).filter(Boolean),h=(Array.isArray(u)?u:[u]).filter(Boolean).filter(e=>!p.includes(e)),g=Xe(o,s);if(!g)throw new a.InternalError("Could not find repo");try{const e=await g.override(this._overrides).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)}}const Je=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Xe(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=o.Metadata.get(e instanceof i.Model?e.constructor:e,o.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=o.Metadata.getPropDesignTypes(e instanceof i.Model?e.constructor:e,t)?.designTypes;const n=s?.find(e=>!Je.includes((""+e.name).toLowerCase()));return me.forModel(n,r)}class Ze extends a.BadRequestError{constructor(e,t=Ze.name,r=401){super(e,t,r)}}class et extends Ze{constructor(e,t=et.name){super(e,t,403)}}class tt extends a.InternalError{constructor(e){super(e,tt.name,503)}}function rt(t){return o.Decoration.for(e.PersistenceKeys.TABLE).define({decorator:t=>r=>(o.Metadata.set(e.PersistenceKeys.TABLE,t||r.name.toLowerCase(),r),o.metadata(e.PersistenceKeys.TABLE,t||r.name.toLowerCase())(r)),args:[t]}).apply()}function at(t){return o.Decoration.for(e.PersistenceKeys.COLUMN).define({decorator:t=>(r,a)=>o.propMetadata(o.Metadata.key(e.PersistenceKeys.COLUMN,a),t||a)(r,a),args:[t]}).apply()}async function st(e,t,r,s){if(s[r]&&(await this.select().where(U.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 it(e,t,r,a){throw new Ze("This adapter does not support user identification")}function ot(){return o.Decoration.for(e.PersistenceKeys.CREATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onCreate(it),o.propMetadata(e.PersistenceKeys.CREATED_BY,r),a.generated(e.PersistenceKeys.CREATED_BY))(t,r),args:[]}).apply()}function nt(){return o.Decoration.for(e.PersistenceKeys.UPDATED_BY).define({decorator:()=>(t,r)=>o.apply(a.onUpdate(it),o.propMetadata(e.PersistenceKeys.UPDATED_BY,r),a.generated(e.PersistenceKeys.UPDATED_BY))(t,r),args:[]}).apply()}function ct(){return a.timestamp([a.OperationKeys.CREATE])}function lt(){return a.timestamp()}function dt(e){return[()=>{const t="function"==typeof e&&e.name?e:e(),r=i.Model.pk(t);return(o.Metadata.allowedTypes(t,r)||[])[0]}]}function ut(...t){return(r,a)=>{const s=o.Metadata.get(r,o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a))||[],i=[...new Set([...s,...t])];return o.apply(o.metadata(o.Metadata.key(e.PersistenceKeys.NO_VALIDATE,a),i))(r,a)}}function pt(t,r){return o.Decoration.for(e.PersistenceKeys.RELATIONS).define({decorator:(t,r)=>(a,s)=>(o.propMetadata(t,r)(a,s),o.propMetadata(o.Metadata.key(e.PersistenceKeys.RELATIONS,s),Object.assign({},r,{key:t}))(a,s)),args:[t,r]}).apply()}class ht extends i.Model{constructor(e){super(e)}}r.__decorate([ct(),r.__metadata("design:type",Date)],ht.prototype,"createdAt",void 0),r.__decorate([lt(),r.__metadata("design:type",Date)],ht.prototype,"updatedAt",void 0),e.SequenceModel=class extends ht{constructor(e){super(e)}},r.__decorate([Pe({type:String,generated:!1}),r.__metadata("design:type",String)],e.SequenceModel.prototype,"id",void 0),r.__decorate([i.required(),Ce(),r.__metadata("design:type",Object)],e.SequenceModel.prototype,"current",void 0),e.SequenceModel=r.__decorate([rt("??sequence"),i.model(),r.__metadata("design:paramtypes",[Object])],e.SequenceModel);class gt 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,D(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}|${e.PreparedStatementKeys.FIND}`,"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 b?[r,...a]:[...a],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${r?" - bookmark "+r:""}`),!r||r instanceof b||(this._bookmark=r);const o=me.forModel(this.clazz,this.adapter.alias),n=this.query,{method:c,args:l,params:d}=n;if(c===e.PreparedStatementKeys.FIND){const r=[e.PreparedStatementKeys.PAGE,...l],a={limit:this.size,offset:t,bookmark:this._bookmark};r.push(a);const s=await o.statement(...r,...i);return this.apply(s)}const u=RegExp(`^${e.PreparedStatementKeys.FIND_BY}|${e.PreparedStatementKeys.LIST_BY}`,"gi");if(!c.match(u))throw new O(`Method ${c} is not supported for pagination`);u.lastIndex=0;const p=c.replace(u,e.PreparedStatementKeys.PAGE_BY),h=[p,...l];let g={limit:this.size,offset:t,bookmark:this._bookmark};p!==e.PreparedStatementKeys.PAGE_BY||h.length>2?g={direction:d.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(d.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 j("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&e>this._totalPages)throw new j(`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 O("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?gt.deserialize(e):e;return this._currentPage=t.current,this._totalPages=t.total||this._totalPages,this._recordCount=t.count||this._recordCount,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 yt,ft,mt,_t,wt,bt,Et;class vt extends E{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(vt)}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 F("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 F("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 F("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(e,t)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new F("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 F("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 F(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(e.OrderDirection).join(", ")}.`)}groupBy(e){if(this.orderBySelectors&&this.orderBySelectors.length)throw new F("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 F(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=me.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 O("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 U){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 F("Unsupported operator "+s)}return o}squash(t){const r=this.matchDefaultQueryCondition();if(r){const t=this.getOrderDirection();return{class:this.fromSelector,method:e.PreparedStatementKeys.FIND,args:[r.value,t],params:{direction:t}}}if(this.whereCondition&&this.whereCondition.comparison instanceof U)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 a;this.whereCondition&&(a=this.whereCondition.attr1);const s=this.orderBySelectors?.[0]?this.orderBySelectors[0]:a?[a,e.OrderDirection.DSC]:[i.Model.pk(this.fromSelector),e.OrderDirection.DSC],[o,n]=s,c={direction:n};this.limitSelector&&(c.limit=this.limitSelector),this.offsetSelector&&(c.offset=this.offsetSelector);const l={class:this.fromSelector,method:e.PreparedStatementKeys.LIST_BY,args:[o],params:c};return a&&(l.method=e.PreparedStatementKeys.FIND_BY,l.args=[a,this.whereCondition.comparison],l.params=c),l}matchDefaultQueryCondition(){if(!this.whereCondition)return;const e=this.extractDefaultStartsWithAttributes(this.whereCondition);if(!e)return;const t=i.Model.defaultQueryAttributes(this.fromSelector);if(!t||!t.length)return;const r=Array.from(new Set(t.map(String))),a=Array.from(new Set(e.attributes.map(String)));return r.length===a.length&&r.every(e=>a.includes(e))?{value:e.value,attributes:r}:void 0}extractDefaultStartsWithAttributes(e){const t=this.collectStartsWithAttributes(e);if(t)return{attributes:Array.from(new Set(t.attributes)),value:t.value}}collectStartsWithAttributes(t){if(!t)return;const{attr1:r,operator:a,comparison:s}=t;if(a===e.Operator.STARTS_WITH){if("string"!=typeof r||"string"!=typeof s)return;return{attributes:[r],value:s}}if(a===e.GroupOperator.OR){const e=r instanceof U?this.collectStartsWithAttributes(r):void 0,t=s instanceof U?this.collectStartsWithAttributes(s):void 0;return e&&t&&e.value===t.value?{attributes:[...e.attributes,...t.attributes],value:e.value}:void 0}return a===e.GroupOperator.AND?(r instanceof U?this.collectStartsWithAttributes(r):void 0)||(s instanceof U?this.collectStartsWithAttributes(s):void 0):void 0}getOrderDirection(){return this.orderBySelectors?.[0]?.[1]??e.OrderDirection.ASC}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 F(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)],vt.prototype,"select",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(yt="undefined"!=typeof S&&S)?yt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"distinct",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(ft="undefined"!=typeof S&&S)?ft:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"max",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(mt="undefined"!=typeof S&&S)?mt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"min",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(_t="undefined"!=typeof S&&S)?_t:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"sum",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(wt="undefined"!=typeof S&&S)?wt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"avg",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(bt="undefined"!=typeof S&&S)?bt:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"count",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",Object)],vt.prototype,"from",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[U]),r.__metadata("design:returntype",Object)],vt.prototype,"where",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],vt.prototype,"orderBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,String]),r.__metadata("design:returntype",Object)],vt.prototype,"thenBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",["function"==typeof(Et="undefined"!=typeof Key&&Key)?Et:Object]),r.__metadata("design:returntype",Object)],vt.prototype,"groupBy",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],vt.prototype,"limit",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Number]),r.__metadata("design:returntype",Object)],vt.prototype,"offset",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[void 0]),r.__metadata("design:returntype",Promise)],vt.prototype,"execute",null);class St extends E{constructor(e){super(),this.name=e,this.observers=[],this.Context=b}for(e,...t){return new Proxy(this,{get(r,a,s){const i=Reflect.get(r,a,s);return"object"!=typeof i?i:i instanceof St?i.for(e,...t):i instanceof me?i.override(e):i}})}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}-${P.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 b||(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 E.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=x(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 b||(r.push(s),s=void 0);const i=await St.prototype.flags(e.PersistenceKeys.INITIALIZATION,{},...r);s=s?new b(s).accumulate({...i,parentContext:s}):(new b).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=St.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 Tt&&(o.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(e){throw new a.InternalError(`Failed to boot ${r.name} service:${e}`)}}static async shutdown(...r){let s=r.pop();void 0===s||s instanceof b||(r.push(s),s=void 0);const i=await St.prototype.flags(e.PersistenceKeys.SHUTDOWN,{},...r);s=s?new b(s).accumulate({...i,parentContext:s}):(new b).accumulate(i),r=[...r,s];const{log:o,ctxArgs:n}=St.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 Tt){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)],St.prototype,"observe",null),r.__decorate([s.final(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object]),r.__metadata("design:returntype",void 0)],St.prototype,"unObserve",null);class Tt extends St{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...")}}function Ot(e){return function(t,r,a){const s=a.value;return a.value=function(...t){const r=this.class;if(r&&M(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)],Tt.prototype,"boot",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Tt.prototype,"config",null),r.__decorate([s.final(),r.__metadata("design:type",Object),r.__metadata("design:paramtypes",[])],Tt.prototype,"client",null);const At=()=>Ot(a.OperationKeys.CREATE),kt=()=>Ot(a.OperationKeys.READ),xt=()=>Ot(a.OperationKeys.UPDATE),Ct=()=>Ot(a.OperationKeys.DELETE);function Mt(r){return(a,s,i)=>{i||s?(o.prop()(a,s),r=r||o.Metadata.type(a.constructor,s)):r=r||a,r=x(r);const n=[];if(i&&"number"==typeof i.value)n.push(t.inject(r));else if(i||s){if(i)throw Error("Invalid decorator usage. Should be impossible");n.push(t.inject(r))}else o.Metadata.set(e.PersistenceKeys.SERVICE,r,a),n.push(t.injectable(r,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:r})}));return o.apply(...n)(a,s,i)}}const Dt=e=>"string"==typeof e?e.endsWith("Service")?e:e+"Service":"symbol"==typeof e?e.toString():e.name+"Service";class Pt extends St{get class(){if(!this.clazz)throw new a.InternalError("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=me.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=Dt(e);try{const e=St.get(t);if(e)return e}catch(e){}throw new a.InternalError("No ModelService found for alias "+t)}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=Dt(t||e);try{a=Pt.get(t)}catch(e){a=void 0}if(a instanceof Pt)return a;const s=this;let i=class extends s{constructor(){super(e)}};return i=r.__decorate([Mt(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([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"create",null),r.__decorate([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"createAll",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"delete",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"deleteAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"read",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"readAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,Object]),r.__metadata("design:returntype",Promise)],Pt.prototype,"query",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],Pt.prototype,"update",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,Object]),r.__metadata("design:returntype",Promise)],Pt.prototype,"updateAll",null);class It extends E{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,l,d]=a,u=await t.call(r,c,l,d,...o),p=[c,i(e),l];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 ${l}: ${t}`)),u}}):this.log.error(`Could not find method ${e} to bind Observables Dispatch`)})}async close(){}observe(e){if(!(e instanceof $))throw new O("Only Adapters can be observed by dispatch");return this.adapter=e,this.models=$.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 O("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:l}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${t}:${o}: ${r}${l.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 Bt(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 P.instance.generate(s)}function Nt(t=!1,r,...s){"function"==typeof t&&(r=t,t=!1);const n=e.PersistenceKeys.UUID;return o.Decoration.for(n).define({decorator:(t,r,...s)=>{const n={update:t,seed:r,args:s},c=[i.required(),a.generated(e.PersistenceKeys.UUID),a.onCreate(Bt,n,{priority:54})];return t&&c.push(a.onUpdate(Bt,n,{priority:54})),t||c.push(a.readonly()),o.apply(...c)},args:[t,r,...s]}).apply()}$&&($._baseDispatch=It);class Rt extends E{static{this.lock=new n.MultiLock}constructor(t,r,a={}){super(),this.options=t,this.adapter=r,this.repo=me.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 Rt.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 l="function"==typeof o&&o?.name?o.name:o,d=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=${d} next=${t}`),this.repo.create(new e.SequenceModel({id:c,current:t}),i);throw r}};if("uuid"===l)for(;;){const e=await Promise.resolve(P.instance.generate(d));try{const t=await u(e);return s.debug(`Sequence uuid increment ${c} current=${d} next=${e}`),t.current}catch(e){if(e instanceof a.ConflictError)continue;throw e}}const p=await(async e=>{switch(l){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")}})(d),h=await u(p);return s.debug(`Sequence.increment ${c} current=${d} 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 O(`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 Rt.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 O(`Unsupported sequence type: ${e} for adapter ${this}`)}}}function Lt(e,...t){let r;if(e instanceof Pt&&(r=e.repo.adapter),e instanceof me&&(r=e.adapter),e instanceof $&&(r=e),!r)throw new a.InternalError("Could not find adapter to extract transaction");return r.transactionLock(...t)}function $t(e,...t){return new N(Lt(e,...t))}$._baseSequence=Rt,o.Decoration.for(n.TransactionalKeys.TRANSACTIONAL).define({decorator:(...e)=>(t,r,s)=>{if(!s)throw new a.InternalError("This decorator only applies to methods");return o.method()(t,r,s),o.Metadata.set(t.constructor,o.Metadata.key(n.TransactionalKeys.TRANSACTIONAL,r),{data:e}),s.value=new Proxy(s.value,{async apply(e,t,r){const{log:s,ctx:i}=(await t.logCtx(r,e.name,!0)).for(e),o=i.getOrUndefined("transactionLock")||$t(t);let n;i.put("transactionLock",o),await o.acquire();try{n=await e.call(t,...r,i)}catch(e){try{await o.rollback(e)}catch(e){s.error("Failed to rollback transaction",e)}throw e}try{await o.release()}catch(e){throw new a.InternalError("Failed to release transaction: "+e)}return n}}),s}}).apply(),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),o.description("the backoff strategy"),r.__metadata("design:type",String)],e.TaskBackoffModel.prototype,"strategy",void 0),r.__decorate([i.required(),o.description("base interval between attempts"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"baseMs",void 0),r.__decorate([i.required(),o.description("max interval"),r.__metadata("design:type",Number)],e.TaskBackoffModel.prototype,"maxMs",void 0),r.__decorate([i.type(String),i.option(e.JitterStrategy),o.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(),o.description("The error message"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"message",void 0),r.__decorate([o.prop(),o.description("The error stack"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"stack",void 0),r.__decorate([o.prop(),o.description("The error code"),r.__metadata("design:type",String)],e.TaskErrorModel.prototype,"code",void 0),r.__decorate([o.prop(),o.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"],":"),Pe(),r.__metadata("design:type",String)],e.TaskEventModel.prototype,"id",void 0),r.__decorate([a.readonly(),i.required(),a.transient(),Nt(!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([o.prop(),a.readonly(),r.__metadata("design:type",Object)],e.TaskEventModel.prototype,"payload",void 0),e.TaskEventModel=r.__decorate([rt("task_event"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskEventModel);class Kt extends i.JSONSerializer{constructor(){super()}preSerialize(e,...t){return this.serializeValue(e,...t)}deserialize(e,...t){const r=JSON.parse(e);return this.rebuildValue(r)}serializeValue(e,...t){if(null==e)return e;if("object"!=typeof e)return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>this.serializeValue(e,...t));if(e instanceof U){const r=this.serializePlain(e,...t);return r[i.ModelKeys.ANCHOR]="??condition",r}return i.Model.isModel(e)?this.serializeModel(e,...t):this.serializePlain(e,...t)}serializeModel(e,...t){const r=this.serializePlain(e,...t),a=this.getMetadata(e.constructor)??e.constructor?.name;return a&&(r[i.ModelKeys.ANCHOR]=a),r}serializePlain(e,...t){const r={};for(const[a,s]of Object.entries(e))r[a]=this.serializeValue(s,...t);return r}getMetadata(e){try{return o.Metadata.modelName(e)}catch{return}}rebuildValue(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>this.rebuildValue(e));const t=e[i.ModelKeys.ANCHOR],r=this.rebuildObject(e);return t?"??condition"===t?U.from(r):i.Model.build(r,t):r}rebuildObject(e){const t={};for(const[r,a]of Object.entries(e))r!==i.ModelKeys.ANCHOR&&(t[r]=this.rebuildValue(a));return t}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(),o.prop(),r.__metadata("design:type",String)],e.TaskLogEntryModel.prototype,"msg",void 0),r.__decorate([o.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([Pe({type:"uuid"}),o.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),o.description("defines a single or composite task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"atomicity",void 0),r.__decorate([i.required(),o.description("Holds task classification - must match @task()"),r.__metadata("design:type",String)],e.TaskModel.prototype,"classification",void 0),r.__decorate([o.prop(),o.description("optional task name for ambiguity"),r.__metadata("design:type",String)],e.TaskModel.prototype,"name",void 0),r.__decorate([i.required(),i.type(String),i.option(e.TaskStatus),o.description("Holds the task current status"),r.__metadata("design:type",String)],e.TaskModel.prototype,"status",void 0),r.__decorate([o.prop(),a.serialize(Kt),o.description("Holds task input"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"input",void 0),r.__decorate([o.prop(),a.serialize(Kt),o.description("Holds the task output when successfully completed"),r.__metadata("design:type",Object)],e.TaskModel.prototype,"output",void 0),r.__decorate([o.prop(),a.serialize(),o.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),o.description("Holds the current attempt"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"attempt",void 0),r.__decorate([i.min(1),i.required(),o.description("max attempts for the task"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"maxAttempts",void 0),r.__decorate([i.required(),a.serialize(),o.description("backoff configuration"),r.__metadata("design:type",e.TaskBackoffModel)],e.TaskModel.prototype,"backoff",void 0),r.__decorate([i.date(),o.description("Next execution timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"nextRunAt",void 0),r.__decorate([i.date(),o.description("Task scheduled timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"scheduledTo",void 0),r.__decorate([o.prop(),o.description("Task lease owner identifier"),r.__metadata("design:type",String)],e.TaskModel.prototype,"leaseOwner",void 0),r.__decorate([i.date(),o.description("Task lease expiration timestamp"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"leaseExpiry",void 0),r.__decorate([o.prop(),a.serialize(),o.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),o.prop(),o.description("Holds the current step - only for type === 'composite'"),r.__metadata("design:type",Number)],e.TaskModel.prototype,"currentStep",void 0),r.__decorate([o.prop(),a.serialize(),o.description("Holds the step results - only for type === 'composite'"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"stepResults",void 0),r.__decorate([o.prop(),a.serialize(),o.description("Holds the task log entries"),r.__metadata("design:type",Array)],e.TaskModel.prototype,"logTail",void 0),r.__decorate([at(),ct(),o.description("timestamp of creation"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"createdAt",void 0),r.__decorate([at(),lt(),o.description("timestamp of last update"),r.__metadata("design:type",Date)],e.TaskModel.prototype,"updatedAt",void 0),r.__decorate([at(),ot(),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"createdBy",void 0),r.__decorate([at(),nt(),o.description("Holds the creator of the task"),r.__metadata("design:type",String)],e.TaskModel.prototype,"updatedBy",void 0),e.TaskModel=r.__decorate([o.description("Holds the current step when applicable"),rt("tasks"),i.model(),r.__metadata("design:paramtypes",[Object])],e.TaskModel),e.TaskStepResultModel=class extends i.Model{constructor(e){super(e)}},r.__decorate([i.required(),o.description("The status of a step"),r.__metadata("design:type",String)],e.TaskStepResultModel.prototype,"status",void 0),r.__decorate([o.prop(),o.description("The result of a successful step"),r.__metadata("design:type",Object)],e.TaskStepResultModel.prototype,"output",void 0),r.__decorate([o.prop(),o.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(),o.prop(),o.description("task handler type"),r.__metadata("design:type",String)],e.TaskStepSpecModel.prototype,"classification",void 0),r.__decorate([o.description("optional task step input"),o.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 Ft 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)],Ft.prototype,"baseMs",void 0),r.__decorate([i.required(),i.option(e.JitterStrategy),r.__metadata("design:type",String)],Ft.prototype,"jitter",void 0),r.__decorate([i.gt("baseMs"),i.min(1e3),i.required(),r.__metadata("design:type",Number)],Ft.prototype,"maxMs",void 0),r.__decorate([i.required(),i.option(e.BackoffStrategy),r.__metadata("design:type",String)],Ft.prototype,"strategy",void 0);class jt extends i.Model{setClassification(e){return this.classification=e,this}setName(e){return this.name=e,this}setAtomicity(e){return this.atomicity=e,this}setBackoff(e){if(e)return this.backoff=e,this;const t=new Ft,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)],jt.prototype,"classification",void 0),r.__decorate([o.prop(),r.__metadata("design:type",String)],jt.prototype,"name",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],jt.prototype,"status",void 0),r.__decorate([i.required(),r.__metadata("design:type",String)],jt.prototype,"atomicity",void 0),r.__decorate([i.required(),r.__metadata("design:type",e.TaskBackoffModel)],jt.prototype,"backoff",void 0),r.__decorate([o.prop(),r.__metadata("design:type",Object)],jt.prototype,"input",void 0),r.__decorate([i.min(1),i.required(),r.__metadata("design:type",Number)],jt.prototype,"maxAttempts",void 0);class Ut extends jt{constructor(t){super(t),this.stepResults=[],i.Model.fromModel(this,t),this.atomicity=e.TaskType.COMPOSITE}setAtomicity(t){throw new a.InternalError("Atomicity locked to "+e.TaskType.COMPOSITE)}setSteps(t){return this.steps=(t??[]).map(t=>t instanceof e.TaskStepSpecModel?t:new e.TaskStepSpecModel(t)),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)],Ut.prototype,"steps",void 0);class qt extends v{get type(){if(!this._type){const e=o.Metadata.get(this.constructor,be);"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 Yt(e){return o.Decoration.for(be).define({decorator:e=>t=>{const r={type:e};return o.Metadata.set(be,e,t),o.metadata(be,r)(t)},args:[e]}).apply()}e.CleanUpTask=class extends qt{constructor(){super()}async run(t,r){const a=r.logger;try{let s;if(t instanceof U)s=t,a.info("Starting task cleanup with custom condition");else{a.info("Starting task cleanup with expiry dates");const r=U.attr("status").eq(e.TaskStatus.SUCCEEDED).and(U.attr("updatedAt").lte(t.successfulExpiry)),i=U.attr("status").eq(e.TaskStatus.FAILED).and(U.attr("updatedAt").lte(t.failedExpiry)),o=U.attr("status").eq(e.TaskStatus.CANCELED).and(U.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([ve(e.TaskModel),r.__metadata("design:type",Object)],e.CleanUpTask.prototype,"tasks",void 0),e.CleanUpTask=r.__decorate([Yt("cleanup-task"),r.__metadata("design:paramtypes",[])],e.CleanUpTask);class Gt{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 zt(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 Ht(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 Qt(t){return new e.TaskErrorModel({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function Vt(e){return new Promise(t=>setTimeout(t,e))}class Wt extends Error{constructor(e){super("Task requested state change: "+e.status),this.request=e,this.name=Wt.name,Object.setPrototypeOf(this,Wt.prototype)}}class Jt extends b{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 Wt({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?Qt(t):new e.TaskErrorModel({message:(t??"Task requested state change")+"",details:r})}get resultCache(){return this.get("resultCache")}constructor(e){super(e)}}class Xt{constructor(){this.handlers=new Map,this.initialize()}initialize(){const e=o.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 Zt 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}=$.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 er 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 tr extends er{constructor(e,t,r){super(tr.name,e,t?.message??`Task ${e} failed`,t,r,500)}}class rr extends er{constructor(e,t,r){const a=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(rr.name,e,t?.message??`Task ${e} scheduled for retry${a?" at "+a:""}`,t,r,409)}}class ar extends er{constructor(e,t,r){super(ar.name,e,t?.message??`Task ${e} canceled`,t,r,400)}}class sr extends er{constructor(e,t,r){const a=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(sr.name,e,t?.message??`Task ${e} rescheduled${a?" to "+a:""}`,t,r,202)}}class ir{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.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(zt(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.getNextAction(t),a=e.payload?.originalError;if(a instanceof Error)return this.assignNextAction(a,r);const s=this.buildMeta(t,e.payload),i=this.createTaskControlError(t,e.payload?.error??this.task.error,s);return this.assignNextAction(i,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 b),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 tr(this.task.id,r,a);case e.TaskStatus.CANCELED:return new ar(this.task.id,r,a);case e.TaskStatus.WAITING_RETRY:return new rr(this.task.id,r,a);case e.TaskStatus.SCHEDULED:return new sr(this.task.id,r,a);default:return new tr(this.task.id,r,a)}}assignNextAction(e,t){return t&&(e.nextAction=t),e}getNextAction(t){switch(t){case e.TaskStatus.CANCELED:return e.TaskStatus.CANCELED;case e.TaskStatus.WAITING_RETRY:return e.TaskStatus.WAITING_RETRY;case e.TaskStatus.SCHEDULED:return e.TaskStatus.SCHEDULED;case e.TaskStatus.FAILED:return e.TaskStatus.FAILED;default:return}}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 or extends v{get Context(){return Jt}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=me.forModel(e.TaskModel,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=me.forModel(e.TaskEventModel,this.config.adapter.alias)),this._events}static createTaskContext(e,t){const r=new Jt(e);return t&&Object.keys(t).length?r.accumulate(t):r}constructor(e){super(),this.config=e,this.lock=new n.Lock,this.running=!1,this.config=Object.assign({},Ee,e,{bus:e.bus||new Zt,registry:e.registry||new Xt})}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 ir(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 ir(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 Vt(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(U.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 Vt(e.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const r=t.logger.for(this.claimBatch),a=new Date,s=U.attribute("status").eq(e.TaskStatus.PENDING),i=U.attribute("status").eq(e.TaskStatus.WAITING_RETRY).and(U.attribute("nextRunAt").lte(a)),o=U.attribute("status").eq(e.TaskStatus.RUNNING).and(U.attribute("leaseExpiry").lte(a)),n=U.attribute("status").eq(e.TaskStatus.SCHEDULED).and(U.attribute("scheduledTo").lte(a)),c=s.or(i).or(o).or(n),l=await this.tasks.select().where(c).limit(Math.max(4*this.config.concurrency,20)).execute();r.verbose("claimBatch candidates:"+l.length);const d=[];for(const e of l){const r=await this.tryClaim(e,t);if(r&&d.push(r),d.length>=this.config.concurrency)break}return r.verbose("claimBatch claimed:"+d.length),d}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 Jt(r).accumulate({taskId:t.id,logger:new Gt(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 Wt)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=Qt(r);if(a<t.maxAttempts){const c=Ht(a,this.normalizeBackoff(t.backoff)),l=new Date(Date.now()+c);t.attempt=a,t.status=e.TaskStatus.WAITING_RETRY,t.nextRunAt=l,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 o.pipe(s.LogLevel.warn,"Retry scheduled",{nextRunAt:l,delayMs:c,attempt:a}),await this.emitStatus(o,t,e.TaskStatus.WAITING_RETRY,n,r)}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 o.pipe(s.LogLevel.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts}),await this.emitStatus(o,t,e.TaskStatus.FAILED,n,r)}}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=Ht(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 Jt&&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],l=this.registry.get(a.classification);if(!l)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 l.run(a.input,r),d=o,u=new Date;n[d]=new e.TaskStepResultModel({status:e.TaskStatus.SUCCEEDED,output:s,createdAt:u,updatedAt:u});const p=`${t.id}:step:${d}`;c(a.classification,s),c(p,s),o=d+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:Qt(r),createdAt:a,updatedAt:a}),t.stepResults=n,t.currentStep=o,t.error=Qt(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,i){t instanceof Jt&&await t.flush();const o={status:a};s&&s instanceof e.TaskErrorModel?o.error=s:s&&(o.output=s),r.nextRunAt&&(o.nextRunAt=r.nextRunAt),r.scheduledTo&&(o.scheduledTo=r.scheduledTo);const n=await this.persistEvent(t,r.id,e.TaskEventType.STATUS,o),c=void 0!==i?Object.assign({},o,{originalError:i}):o,l=new e.TaskEventModel({...n,payload:c});this.bus.emit(l,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 nr extends Tt{constructor(){super()}async initialize(...t){const r=t.shift();if(!r||r instanceof b)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(r.engine||or)(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 O("Updates to tasks are not available")}async updateAll(e,...t){throw new O("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")}}function cr(e,t){return e.reduce((e,r)=>e+(e=>{if(null==e)return 0;try{return Buffer.byteLength(JSON.stringify(e))}catch{return 0}})(r[t]),0)}function lr(e,t){Array.isArray(e)?t.push(...e):void 0!==e&&t.push(e)}r.__decorate([ve(e.TaskModel),r.__metadata("design:type",Object)],nr.prototype,"repo",void 0),r.__decorate([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"create",null),r.__decorate([At(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"createAll",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"delete",null),r.__decorate([Ct(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"deleteAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Object,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"read",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"readAll",null),r.__decorate([kt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[String,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"query",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[e.TaskModel,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"update",null),r.__decorate([xt(),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[Array,void 0]),r.__metadata("design:returntype",Promise)],nr.prototype,"updateAll",null),t.Injectables.setRegistry(new we);const dr="##VERSION##",ur="##PACKAGE##";o.Metadata.registerLibrary(ur,dr),e.AbsContextual=v,e.Adapter=$,e.AdapterTransaction=B,e.AuthorizationError=Ze,e.BaseModel=ht,e.BigIntSequence=xe,e.ClientBasedService=Tt,e.CompositeTaskBuilder=Ut,e.Condition=U,e.ConnectionError=tt,e.Context=b,e.ContextLock=N,e.ContextualLoggedClass=E,e.DefaultAdapterFlags=g,e.DefaultCascade=G,e.DefaultContextFlags=h,e.DefaultRepositoryFilters=se,e.DefaultSequenceOptions=Ae,e.DefaultTaskEngineConfig=Ee,e.Dispatch=It,e.ForbiddenError=et,e.InjectablesRegistry=we,e.MethodQueryBuilder=Q,e.MigrationError=A,e.MigrationRuleError=k,e.ModelService=Pt,e.MultipleSelectOperationKeys=_,e.NonTransactionOperationKeys=f,e.NoneSequenceOptions=Oe,e.NumericSequence=ke,e.ObserverError=Se,e.ObserverHandler=T,e.OperatorsMap=z,e.PACKAGE_NAME=ur,e.PaginationOperationKeys=w,e.Paginator=gt,e.PagingError=j,e.PersistenceService=class extends Tt{constructor(){super()}for(e,...t){throw new O("Persistence service cannot be overridden")}async initialize(...t){const r=t.shift();if(!r||!Array.isArray(r)||r instanceof b||!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=F,e.Repository=me,e.SelectOperationKeys=m,e.Sequence=Rt,e.Serial=I,e.Service=St,e.Statement=vt,e.TaskBackoffBuilder=Ft,e.TaskBuilder=jt,e.TaskCancelError=ar,e.TaskContext=Jt,e.TaskControlError=er,e.TaskEngine=or,e.TaskEventBus=Zt,e.TaskFailError=tr,e.TaskHandler=qt,e.TaskHandlerRegistry=Xt,e.TaskIOSerializer=Kt,e.TaskLogger=Gt,e.TaskRescheduleError=sr,e.TaskRetryError=rr,e.TaskService=nr,e.TaskTracker=ir,e.TasksKey=be,e.TransactionOperationKeys=y,e.UUID=P,e.UnsupportedError=O,e.VERSION=dr,e.allowIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:o,ctxArgs:n}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,o)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...n)}})},e.applyViewDecorator=W,e.auth=t=>{const r=e.PersistenceKeys.AUTH;return o.Decoration.for(r).define({decorator:e=>o.metadata(r,e),args:[t]}).apply()},e.blockIf=(e,...t)=>(r,s,i)=>{i.value=new Proxy(i.value,{async apply(r,s,i){const{ctx:o,ctxArgs:n}=await s.logCtx(i,r.name,!0);let c;try{c=e(...i,...t,o)}catch(e){throw new a.InternalError("Failed to execute auth validation handler: "+e)}if(c)throw c;return r.call(s,...n)}})},e.cacheModelForPopulate=Qe,e.cascadeDelete=We,e.column=at,e.computeBackoffMs=Ht,e.create=At,e.createOrUpdate=Ie,e.createdAt=ct,e.createdBy=ot,e.createdByOnCreateUpdate=it,e.defaultQueryAttr=()=>(t,r)=>{const a=o.Metadata.key(e.PersistenceKeys.DEFAULT_QUERY_ATTR);let s=o.Metadata.get(t.constructor,a)||[];return s=[...new Set([...s,r])],o.apply(o.propMetadata(a,s))(t,r)},e.del=Ct,e.generateInjectableNameForRepository=_e,e.getAdapterTransaction=Lt,e.getAndConstructJunctionTable=ze,e.getContextLock=$t,e.getFilters=ie,e.getLogPipe=zt,e.getPkTypes=dt,e.getPopulateKey=He,e.getTagForDeleteKey=(t,r,a)=>[e.PersistenceKeys.TAG_FOR_DELETION,t,a].join("."),e.index=Ce,e.injectableServiceKey=x,e.isOperationBlocked=M,e.isTaskError=(e,t)=>e instanceof Error&&"nextAction"in e&&"string"==typeof e.nextAction&&(!t||e instanceof t),e.manyToMany=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.list([e,...d]),a.onCreate(Ye,c),a.onUpdate($e,c),a.afterAny(Ve,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToManyOnCreate=Ye,e.manyToManyOnDelete=async function(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(),l="object"===n,d=l?me.forModel(c,this.adapter.alias):Xe(i,s,this.adapter.alias),u=[...new Set([...l?o.map(e=>e[d.pk]):o]).values()];let p,h;try{p=await d.override(this._overrides).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 Qe(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},e.manyToManyOnUpdate=async function(t,r,a,s){const{cascade:i}=r;if(i.update===e.Cascade.CASCADE)return Ye.call(this,t,r,a,s)},e.manyToOne=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.MANY_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.type([e,...d]),a.onCreate(Fe,c),a.onUpdate(Ue,c),a.onDelete(qe,c),a.afterAny(Ve,c)];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.manyToOneOnCreate=Fe,e.manyToOneOnDelete=qe,e.manyToOneOnUpdate=Ue,e.noValidateOn=ut,e.noValidateOnCreate=()=>ut(a.OperationKeys.CREATE),e.noValidateOnCreateUpdate=()=>ut(a.OperationKeys.UPDATE,a.OperationKeys.CREATE),e.noValidateOnUpdate=()=>ut(a.OperationKeys.UPDATE),e.normalizeImport=async e=>e.then(e=>e.default||e),e.oneToMany=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_MANY;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.list([e,...d]),a.onCreate(Le,c,{priority:70}),a.onUpdate($e,c,{priority:70}),a.onDelete(Ke,c,{priority:70}),a.afterUpdate(We,c,{priority:70}),a.afterAny(Ve,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToManyOnCreateUpdate=Le,e.oneToManyOnDelete=Ke,e.oneToManyOnUpdate=$e,e.oneToOne=(t,r=G,s=!0,n,c)=>{const l=e.PersistenceKeys.ONE_TO_ONE;return o.Decoration.for(l).define({decorator:(e,t,r,s,n)=>{const c={class:e,cascade:t,populate:r};s&&(c.joinTable=s),n&&(c.name=n);const d=dt(e),u=[o.prop(),pt(l,c),i.type([e,...d]),a.onCreate(Be,c,{priority:70}),a.onUpdate(Ne,c,{priority:70}),a.onDelete(Re,c,{priority:70}),a.afterUpdate(We,c,{priority:70}),a.afterAny(Ve,c,{priority:70})];return o.apply(...u)},args:[t,r,s,n,c]}).apply()},e.oneToOneOnCreate=Be,e.oneToOneOnDelete=Re,e.oneToOneOnUpdate=Ne,e.onlyOnBulk=re,e.onlyOnCreate=J,e.onlyOnDelete=Z,e.onlyOnFilter=ae,e.onlyOnSingle=te,e.onlyOnTransactional=ee,e.onlyOnUpdate=X,e.pk=Pe,e.pkDec=De,e.pkOnCreate=Me,e.populate=Ve,e.prefixMethod=D,e.prepared=V,e.promiseSequence=C,e.query=(t={})=>o.Decoration.for(e.PersistenceKeys.QUERY).define({decorator:t=>(r,a,s)=>{const i=Q.getFieldsFromMethodName(a);return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.QUERY,a),{...t,fields:i}),V(),(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:l,limit:d,offset:u}=Q.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 F("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:(l||[])[0],allowed:f},{key:"limit",value:d,allowed:g},{key:"offset",value:u,allowed:y}];for(const e of _)if(void 0!==e.value){if(!e.allowed&&m)throw new F(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=kt,e.relation=pt,e.repository=ve,e.repositoryFromTypeMetadata=Xe,e.roles=t=>o.metadata(e.PersistenceKeys.AUTH_ROLE,t),e.route=(t,r)=>{const a=e.PersistenceKeys.DECAF_ROUTE;return o.Decoration.for(a).define({decorator:()=>(e,s,i)=>{const n={path:r,httpMethod:t,handler:i};return o.apply(o.methodMetadata(o.Metadata.key(a,s),n))(e,s,i)},args:[]}).apply()},e.serializeError=Qt,e.service=Mt,e.sleep=Vt,e.table=rt,e.task=Yt,e.throttle=(t={count:1},r=0)=>function s(i,n,c){return o.apply(o.methodMetadata(o.Metadata.key(e.PersistenceKeys.THROTTLE,n),t),(i,o,n)=>{n.value=new Proxy(n.value,{async apply(i,n,c){const l=c,d=(()=>{try{return"function"==typeof t?t(...l):t}catch(e){throw new a.InternalError("Failed to obtain throttling configuration from handler: "+e)}})(),{log:u,ctx:p}=(await n.logCtx(c,e.PersistenceKeys.THROTTLE,!0)).for(s),h=(e=>{const t=(Array.isArray(e)?e:[e]).map(e=>{if(!Number.isFinite(e)||0>e)throw new a.InternalError("@throttling() argument indexes must be non-negative integers");return e});return Array.from(new Set(t)).sort((e,t)=>e-t)})(r);if(!h.length)throw new a.InternalError("@throttling() expects at least one argument index to throttle");h.forEach(e=>{if(e>=l.length)throw new a.InternalError(`@throttling() requires argument index ${e} but only ${l.length} provided`);if(!Array.isArray(l[e]))throw new a.InternalError(`@throttling() expects argument at index ${e} to be an array`)});const g=h.map(e=>l[e]),y=g[0].length;if(!g.every(e=>e.length===y))throw new a.InternalError("@throttling() requires all targeted arguments to have the same length");if(0===y)return i.apply(n,l);const f=((e,t,r)=>{if("count"in r){if(0>=r.count)throw new a.InternalError("@throttling() configuration 'count' must be greater than zero");const t=[];for(let a=0;e>a;a+=r.count)t.push({start:a,end:Math.min(e,a+r.count)});return t}if("bufferSize"in r){if(0>=r.bufferSize)throw new a.InternalError("@throttling() configuration 'bufferSize' must be greater than zero");const s=[];let i=0,o=0;for(let a=0;e>a;a++){const e=cr(t,a);o>0&&o+e>r.bufferSize?(s.push({start:i,end:a}),i=a,o=e):o+=e}return i>=e&&s.length||s.push({start:i,end:e}),s}return[{start:0,end:e}]})(y,g,d),m=f.map(({start:e,end:t})=>l.map((r,a)=>{const s=h.indexOf(a);return-1===s?r:g[s].slice(e,t)})),_=p.get("breakOnSingleFailureInBulk")??!0,w=[],b=[];for(const e of m){try{lr(await i.apply(n,e),w)}catch(e){if(_)throw e;b.push(e)}d.delayMs&&await new Promise(e=>setTimeout(e,d.delayMs))}if(b.length){u.warn(`${o+""} throttled execution continued with ${b.length} failure(s)`);const e=new AggregateError(b,`Throttled ${o+""} failed for ${b.length} chunk(s)`);throw e.results=w,e}return w}})})(i,n,c)},e.unique=()=>{const t=e.PersistenceKeys.UNIQUE;return o.Decoration.for(t).define(i.async(),a.onCreateUpdate(st),o.propMetadata(t,{})).apply()},e.uniqueOnCreateUpdate=st,e.update=xt,e.updatedAt=lt,e.updatedBy=nt,e.uuid=Nt,e.uuidCreateUpdateHandler=Bt,e.validBidirectionalRelation=je,e.view=t=>o.Decoration.for(e.Operator.VIEW).define({decorator:t=>W(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/decoration"),require("@decaf-ts/transactional-decorators")):"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/decoration","@decaf-ts/transactional-decorators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).core={},e.decafTsInjectableDecorators,e.tslib,e.decafTsDbDecorators,e.decafTsLogging,e.decafTsDecoratorValidation,e.decafTsDecoration,e.decafTsTransactionalDecorators);
2
2
  //# sourceMappingURL=core.cjs.map