@decaf-ts/core 0.8.20 → 0.8.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as a,OperationKeys as o,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as p,Repository as d,wrapMethodWithContext as h,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,generated as v,onCreate as x,onUpdate as A,readonly as E,BadRequestError as O,ConflictError as C,onCreateUpdate as T,timestamp as N,onDelete as k,afterUpdate as D,afterAny as _,SerializationError as $,prefixMethod as P,composed as B,transient as R,serialize as I}from"@decaf-ts/db-decorators";import{LoggedClass as L,Logging as F,final as j,toCamelCase as U,LogLevel as M,style as Y}from"@decaf-ts/logging";import{Model as G,hashObj as z,required as H,sf as q,isEqual as Q,ValidationKeys as V,async as W,type as J,list as X,model as Z,option as K,date as tt,JSONSerializer as et,ModelKeys as rt,min as st,gt as it}from"@decaf-ts/decorator-validation";import{Lock as nt,MultiLock as at}from"@decaf-ts/transactional-decorators";import{Metadata as ot,Decoration as ct,DefaultFlavour as lt,apply as ut,methodMetadata as pt,DecorationKeys as dt,uses as ht,metadata as gt,propMetadata as ft,prop as yt,description as mt}from"@decaf-ts/decoration";var wt,bt,vt,xt,At;(t=>{t.FIND_BY="findBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(wt||(wt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct"})(bt||(bt={})),(t=>{t.AND="AND",t.OR="OR"})(vt||(vt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy"})(xt||(xt={})),(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.UUID="uuid",t.TAG_FOR_DELETION="tag_for_deletion",t.INITIALIZATION="initialization",t.SHUTDOWN="shutdown",t.BY_KEY="by-key",t.AUTH="auth",t.AUTH_ROLE="auth-role",t.DECAF_ROUTE="DecafRoute"})(At||(At={}));const Et=Object.assign({},{ignoreDevSafeGuards:!1}),Ot=Object.assign({},a,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),St=[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Ct=[o.READ,c.READ_ALL],Tt=[At.STATEMENT,xt.FIND_ONE_BY],Nt=[At.QUERY,xt.PAGE_BY,xt.LIST_BY,xt.FIND_BY],kt=[xt.PAGE_BY];class Dt extends nt{constructor(){super()}}class _t extends l{constructor(t){super(t)}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new u(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t){const e=this.getOrUndefined(t);if(e)return e;const r=this.getOrUndefined("childContexts");return r&&r.length?r.map(e=>e.getFromChildren(t)).flat().reduce((t,e)=>Object.assign(t,e),{}):void 0}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new u("Invalid property access to overridden context: "+n);return n in t?t[n]:Reflect.apply(e,s,i)}}):Reflect.get(e,r,s)})}toOverrides(){return this.cache.keys().reduce((t,e)=>(t[e]=this.get(e),t),{})}accumulate(t){return super.accumulate(t)}}class $t extends L{logCtx(t,e,r=!1,s){return $t.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static logFrom(t,e,r,s){const i=t.context?e.clear().for(t):e.for(t);return s?i.for(s):i}static logCtx(t,e,r=!1,...s){const i=(t,e,r)=>{const s=e.log||F.get();return e.log=t.context?s.clear().for(t):s.for(t),"string"==typeof r?e.for=t=>Object.assign(e,{log:e.log.for(t)}):e.log=e.log.for(r),e};let n=s.pop();const a=n instanceof _t;if(n&&!a&&(s.push(n),n=void 0),!r&&!a)throw new u("No context provided");if(a&&!r){if(!n)throw new u("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},t)}return async function(...r){if(!this)throw new u("No contextual provided");if(!this.context)throw new u("Invalid contextual provided");return this.context("string"==typeof t?t:t.name,e||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(e=>i(this,{log:e.logger,ctx:e,ctxArgs:[...s,e]},t))}}class Pt extends $t{constructor(){super(),this._Context=_t}get Context(){return this._Context}async context(t,e,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof t?t:t.name} operation with flag overrides: ${Object.keys(e)}`);let s=r.pop();return s instanceof _t||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(e):new this.Context(s).accumulate(e)}}class Bt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new u("Observer already registered");return this.observers.push({observer:t,filter:e}),()=>this.unObserve(t)}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new u("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=$t.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(s=>{s.observer.refresh(t,e,r,...n)}))).forEach((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class Rt extends u{constructor(t){super(t,Rt.name,500)}}class It extends u{constructor(t,e=It.name){super(t,e,500)}}class Lt extends It{constructor(t){super(t,Lt.name)}}function Ft(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):ot.Symbol(ot.constr(t)).toString().replaceAll(".","-")}function jt(t){return t.reduce((t,e)=>t.then(async t=>[...t,await e()]),Promise.resolve([]))}function Ut(t,e){const{handler:r,args:s}=ot.get(t,o.REFLECT+o.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function Mt(t){return t.then(t=>t.default||t)}function Yt(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof Lt)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class Gt{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})}static get instance(){return Gt._instance||(Gt._instance=new Gt),Gt._instance}}class zt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return zt._instance||(zt._instance=new zt),zt._instance}}const Ht=ct.flavourResolver.bind(ct);ct.flavourResolver=t=>{try{const e=Ht(t);if(e&&e!==lt)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof ot.registeredFlavour?ot.registeredFlavour(r):void 0;if(s&&s!==lt)return s;const i=qt._currentFlavour;if(i){const t=qt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return lt}};class qt extends Pt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!qt._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return qt._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(...t){(await this.logCtx(t,At.SHUTDOWN,!0)).for(this.shutdown),await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.alias in qt._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);qt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),qt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),qt._currentFlavour=this.alias)}Dispatch(){return new qt._baseDispatch}ObserverHandler(){return new Bt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new qt._baseSequence(t,this,e)}async flags(t,e,r,...s){if("string"==typeof e)throw new u("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(e)?e.length?e[0]:void 0:e,n=i?G.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${Gt.instance.generate()}`;const a=r.logger||F.for(this);return Object.assign({},Ot,r,{affectedTables:e?[...new Set([...(Array.isArray(e)?e:[e]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:St.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?ot.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:a})}get Context(){return _t}async context(t,e,r,...s){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>G.tableName(t)):G.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof _t||(s.push(i),i=void 0),e=i?Object.assign({},i.toOverrides(),e):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}const e=i.get("operation"),s=i.getOrUndefined("affectedTables");if(e!==t||r&&r!==s){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const i=G.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[At.METADATA]&&(r.silly("Passing along persistence metadata for "+t[At.METADATA]),Object.defineProperty(i,At.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[At.METADATA]})),{record:i,id:t[G.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:a}=this.logCtx(i,this.revert),o=G.pk(e),c=new e;c[o]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[At.METADATA],p=Object.keys(c).filter(t=>t!==o).reduce((r,s)=>(r[s]=t[G.columnName(e,s)],r),c);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in p&&void 0!==p[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);p[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(p,At.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),p}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new p("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new p("Ids and models must have the same length");const a=G.tableName(t);return i.debug(`Creating ${e.length} entries ${a} table`),jt(e.map((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0}))))}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=G.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),jt(e.map(e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0}))))}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new u("Ids and models must have the same length");const a=G.tableName(t);return i.debug(`Updating ${e.length} entries ${a} table`),jt(e.map((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0}))))}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${e.length} entries from ${t} table`),jt(e.map(e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0}))))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).debug(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),a=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(s&&o||!s&&a)&&await this.observerHandler.updateObservers(t,e,r,...n)}}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return ot.flavourOf(t)}static get currentFlavour(){if(!qt._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return qt._currentFlavour}static get current(){return qt.get(this.currentFlavour)}static get(t){if(!t)return qt.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new u(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return ot.flavouredAs(t).filter(G.isModel)}catch(t){throw new u(t)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${z(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return this.proxies[r]=i,i}migrations(){return ot.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([j(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],qt.prototype,"shutdownProxies",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,_t]),n("design:returntype",Promise)],qt.prototype,"context",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],qt.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],qt.prototype,"unObserve",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],qt.prototype,"client",null);class Qt extends u{constructor(t){super(t,Qt.name,500)}}class Vt extends u{constructor(t){super(t,Vt.name,500)}}class Wt extends G{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):G.fromModel(this,t)}and(t){return Wt.and(this,t)}or(t){return Wt.or(this,t)}not(t){return new Wt(this,bt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Wt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(bt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof Wt){if(!(this.comparison instanceof Wt)&&this.operator!==bt.NOT)return{comparison:{condition:t}};if(-1===Object.values(vt).indexOf(this.operator)&&this.operator!==bt.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return Wt.group(t,vt.AND,e)}static or(t,e){return Wt.group(t,vt.OR,e)}static group(t,e,r){return new Wt(t,e,r)}static attribute(t){return(new Wt.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(bt.EQUAL,t)}dif(t){return this.setOp(bt.DIFFERENT,t)}gt(t){return this.setOp(bt.BIGGER,t)}lt(t){return this.setOp(bt.SMALLER,t)}gte(t){return this.setOp(bt.BIGGER_EQ,t)}lte(t){return this.setOp(bt.SMALLER_EQ,t)}in(t){return this.setOp(bt.IN,t)}regexp(t){return this.setOp(bt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new Wt(this.attr1,this.operator,this.comparison)}catch(t){throw new Qt(t)}}}}static builder(){return new Wt.Builder}static from(t){return new Wt(t)}}var Jt,Xt;i([H(),n("design:type",Object)],Wt.prototype,"attr1",void 0),i([H(),n("design:type",String)],Wt.prototype,"operator",void 0),i([H(),n("design:type",Object)],Wt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(Jt||(Jt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(Xt||(Xt={}));const Zt={update:Xt.CASCADE,delete:Xt.NONE},Kt={Equals:(t,e)=>Wt.attribute(t).eq(e),Diff:(t,e)=>Wt.attribute(t).dif(e),LessThan:(t,e)=>Wt.attribute(t).lt(e),LessThanEqual:(t,e)=>Wt.attribute(t).lte(e),GreaterThan:(t,e)=>Wt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>Wt.attribute(t).gte(e),In:(t,e)=>Wt.attribute(t).in(e),Matches:(t,e)=>Wt.attribute(t).regexp(e)},te=t=>t.charAt(0).toLowerCase()+t.slice(1);class ee extends L{static get log(){return this._logger||(this._logger=F.for(ee.name)),this._logger}static build(t,...e){if(!t.startsWith(wt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),i=this.extractGroupBy(t),n=this.buildWhere(r,e),{orderBy:a,limit:o,offset:c}=this.extractOrderLimitOffset(t,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:a,limit:o,offset:c}}static extractCore(t){const e=t.substring(wt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static getFieldsFromMethodName(t){return(this.extractCore(t).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")})}static extractSelect(t){const e=t.indexOf(wt.SELECT);if(-1===e)return;const r=t.substring(e+wt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(wt.AND).map(te).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(wt.GROUP_BY);if(-1!==e)return t.substring(e+wt.GROUP_BY.length).split(wt.ORDER_BY)[0].split(wt.THEN_BY).map(te).filter(Boolean)}static buildWhere(t,e){if(!t&&0===e.length)return;const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let i;if(r.forEach((t,r)=>{const{field:n,operator:a}=this.parseFieldAndOperator(t),o=a?Kt[a]:Kt.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=o(n,c);i=0===r?l:s[r-1]===wt.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(t){for(const e of Object.keys(Kt))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:te(r),operator:e}}return{field:te(t)}}static extractOrderByField(t){const e=t.match(/OrderBy(.+)$/);if(!e)return;const r=e[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,e){const r=ee.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new Qt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(Jt).includes(e))throw new Qt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(Jt).join(", ")}.`);return[[t,e]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(t,e){const r=this.extractCore(t).split(/And|Or/).length,s=e.slice(r)??[];let i,n,a;if(s.at(-1)instanceof l&&s.pop(),s.length>=1){const e=s[0],r=this.extractOrderByField(t);i=this.getProperlyOrderByOrThrow(r,e)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(a=s[2]),{orderBy:i,limit:n,offset:a}}}function re(){return ct.for(At.STATEMENT).define({decorator:()=>(t,e,r)=>ut(pt(ot.key(At.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function se(t={}){return ct.for(At.QUERY).define({decorator:t=>(e,r,s)=>{const i=ee.getFieldsFromMethodName(r);return ut(pt(ot.key(At.QUERY,r),{...t,fields:i}),re(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:a,orderBy:o,limit:c,offset:l}=ee.build(e.name,...s);let u=r.select(i);n&&(u=u.where(n));const{allowLimit:p,allowOffset:d,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(o||[])[0],allowed:h},{key:"limit",value:c,allowed:p},{key:"offset",value:l,allowed:d}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new Qt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(u=u[t.key](t.value))}return u.execute()}})})(t))(e,r,s)},args:[t]}).apply()}function ie(t){return ue(t,[o.CREATE,c.CREATE_ALL])}function ne(t){return ue(t,[o.UPDATE,c.UPDATE_ALL])}function ae(t){return ue(t,[o.DELETE,c.DELETE_ALL])}function oe(t){return ue(t,St)}function ce(t){return ue(t,Object.values(o))}function le(t){return ue(t,Object.values(c))}function ue(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:a}=$t.prototype.logCtx(n,ue);return a.silly(`filtering ${s} event for${r?" "+(G.tableName(r)||r):""} ${i}`),("string"==typeof r?r===G.tableName(t)||r===t.constructor.name:ot.constr(t)===ot.constr(r))&&e.includes(s)}}const pe={onlyOnCreate:ie,onlyOnUpdate:ne,onlyOnDelete:ae,onlyOnTransactional:oe,onlyOnSingle:ce,onlyOnBulk:le};function de(t){const e=Object.assign({},pe);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}class he extends d{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 u("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=G.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return de(this)}constructor(t,e,...r){super(e),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},t&&(this._adapter=t),e&&(he.register(e,this,this.adapter.alias),t)&&ot.get(e,dt.FLAVOUR)===lt&&ht(t.flavour)(e);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;h(s,s[e+"Prefix"],t,s[e+"Suffix"])}),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(t,e,r=!1,s){const i=this.adapter.logCtx([this.class,...t],e,r,Object.assign({},s||{},this._overrides||{}));function n(t){return t.ctxArgs.shift(),t}return i instanceof Promise?i.then(n):n(i)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new Bt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${a}`),t=new this.class(t),n||await f(this,r,t,o.CREATE,o.ON),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new p(s.toString())}return[t,...s]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${G.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,r)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${G.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${a}`),!t.length)return[t,...s];const l=G.sequenceFor(t[0]);let d=[];if(G.generatedBySequence(this.class)?(l.name||(l.name=G.sequenceName(t[0],"pk")),d=await(await this.adapter.Sequence(l)).range(t.length,...s)):G.generated(this.class,this.pk)||(d=t.map((t,e)=>{if(void 0===t[this.pk])throw new u("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),l.type&&(t[this.pk]="String"!==l.type||l.generated?d[e]:""+t[this.pk]),n||await f(this,r,t,o.CREATE,o.ON),t))),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),n=y(s);if(n)throw new p(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const a=new this.class;return a[this.pk]=t,n||await f(this,r,a,o.READ,o.ON),[t,...s]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${G.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,f(this,r,e,o.READ,o.ON)})),[t,...s]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${G.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${G.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${a}`);const c=t[this.pk];if(!c)throw new u("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(c,r),r.get("mergeForUpdate")&&(t=G.merge(l,t,this.class))),n||await f(this,r,t,o.UPDATE,o.ON,l),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new p(s.toString())}return[t,...s,l]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.verbose(`Updating ${t.length} new ${this.class.name} in table ${G.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${a}`);const l=t.map(t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>G.merge(d[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>f(this,r,t,o.UPDATE,o.ON,d?d[e]:void 0))),!a){const e=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+e),s=r.get("applyUpdateValidation")?await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(d[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=y(s);if(n)throw new p(n)}return[t,...s,d]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await f(this,r,e,o.DELETE,o.ON)}return[t,...s]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${G.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.readAll(t,...s);await Promise.all(e.map(async t=>f(this,r,t,o.DELETE,o.ON)))}return[t,...s]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${G.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement(this._overrides).select(t).from(this.class)}async query(t,e,r=Jt.ASC,s,i,...n){const{ctxArgs:a}=(await this.logCtx(n,At.QUERY,!0)).for(this.query),o=[e,r],c=this.select().where(t).orderBy(o);return s&&c.limit(s),i&&c.offset(i),c.execute(...a)}async listBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,xt.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${G.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...i)}async paginateBy(t,e,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:a,limit:o}=r;if(!n&&!a)throw new Qt("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,xt.PAGE_BY,!0)).for(this.paginateBy);let p;if(c.verbose(`paginating ${G.tableName(this.class)} with page size ${o}`),a&&l.get("paginateByBookmark"))p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===Jt.ASC?this.attr(G.pk(this.class)).gt(a):this.attr(G.pk(this.class)).lt(a))()).orderBy([t,e]).paginate(o,...u);else{if(!n)throw new Qt("PaginateBy needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(o,...u)}const d=await p.page(i,a,...u);return p.serialize(d)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,xt.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${G.tableName(this.class)} with ${t} ${e}`);const n=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,xt.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${G.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async statement(t,...e){if(!he.statements(this,t))throw new Qt("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,At.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}attr(t){return Wt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=G.tableName(this.class);return this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:ot.constr(t)===ot.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString()),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>qt._baseSequence.parseValue(G.sequenceFor(this.class).type,t)):qt._baseSequence.parseValue(G.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||ot.flavourOf(t)||qt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof he)return s;const n=e||ot.flavourOf(t)||s&&ot.get(s,At.ADAPTER)||qt.currentFlavour,a=n?qt.get(n):void 0;if(!a)throw new u("No registered persistence adapter found flavour "+n);return s=s||a.repository(),new s(a,t,...r)}static get(t,e){const r=G.tableName(t);let s=r;if(e&&(s=[r,e].join(w)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new u("Could not find repository registered under "+r)}static register(t,e,r){let s=G.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof he)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof he?t.constructor:t,s=ot.get(r,e?ot.key(At.STATEMENT,e):At.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof he?t.constructor:t;return ot.get(r,e?ot.key(At.QUERY,e):At.QUERY)}}function ge(t,e){if(!(e||(e=ct.flavourResolver(t instanceof G?t.constructor:t))&&e!==lt))throw new u("Could not retrieve flavour from model "+(t instanceof G?t.constructor.name:t.name));return q(At.INJECTABLE,e,G.tableName(t))}i([re(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],he.prototype,"listBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],he.prototype,"paginateBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],he.prototype,"findOneBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],he.prototype,"findBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],he.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],he.prototype,"unObserve",null),qt&&(qt._baseRepository=he);class fe extends t{get log(){return this.logger||(this.logger=F.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=G.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=G.get(t.toString())),!n)return;const a=At.ADAPTER,o=r||ot.get(n,a);try{let t=o;try{o&&qt.get(o)}catch{const e=qt.current;e&&e.flavour===o&&(t=e.alias)}if(i=he.forModel(n,t),i instanceof he)return i;const r=o||ot.get(i.constructor,a)||ot.get(n,a);e.register(i,ge(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=he.get(n,o);if("function"==typeof e){const t=o?qt.get(o):qt.current;if(!t)return;return new e(t,n)}}}return i}}var ye,me,we,be,ve;(t=>{t.PENDING="pending",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(ye||(ye={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(me||(me={})),(t=>{t.NONE="none",t.FULL="full"})(we||(we={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(be||(be={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(ve||(ve={}));const xe="tasks",Ae={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};ot.tasks=(()=>ot.innerGet(Symbol.for(xe))).bind(ot),ot.taskFor=(t=>{const e=ot.tasks();return e?e[t]:void 0}).bind(ot),ot.validationExceptions=((t,e)=>{const r=ot.get(t,At.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t);let i=[];return e!==o.CREATE&&e!==o.UPDATE||(i=G.nestedRelations(t)),[...new Set([...s,...i])]}).bind(ot),ot.migrationsFor=(t=>{if(!(t=t??qt.current))throw new u("Could not get adapter for migrations");return ot.innerGet(Symbol.for(At.MIGRATION),t.alias).map(t=>t.class)}).bind(ot),ot.migrations=(()=>{const t=ot.innerGet(Symbol.for([At.MIGRATION,At.BY_KEY].join("-")));return Object.values(t).flat().map(t=>[t.class.name,t.class])}).bind(ot),ot.relations=((t,e)=>{const r=ot.get(t,At.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new u("No relations metadata found for property "+e);return r[e]}}).bind(ot),G.relations=(t,e)=>ot.relations(t instanceof G?t.constructor:t,e)||[],G.nestedRelations=((t,e=[])=>{let r=[];const s=ot.get(t,At.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&G.relations(i.class)){const s=G.relations(i.class).map(e=>`${t}.${e}`);e=[...e,...s],r=G.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(G),G.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!G.sequenceFor(r).generated}).bind(G),G.fromTable=(t=>{const e=ot.innerGet(Symbol.for(At.TABLE));if(!e||!e[t]||!G.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return G.get(e[t].name)}).bind(G),ot.createdBy=(t=>{const e=ot.get("function"!=typeof t?t.constructor:t,At.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(ot),ot.updatedBy=(t=>{const e=ot.get("function"!=typeof t?t.constructor:t,At.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(ot),G.tableName=t=>{if(!(t instanceof G?G.get(t.constructor.name):t))throw new u("Unable to find model "+t);return ot.get(t instanceof G?t.constructor:t,At.TABLE)||(t instanceof G?t.constructor.name:t.name)},G.columnName=(t,e)=>ot.get(t instanceof G?t.constructor:t,ot.key(At.COLUMN,e))||e,G.sequenceName=(t,...e)=>[G.tableName(t),...e].join("_"),G.sequenceFor=(t,e)=>{if(e)throw new Rt("not currently supported");const r=G.pkProps(t instanceof G?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},G.indexes=t=>{const e=ot.get(t instanceof G?t.constructor:t,At.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[At.INDEX]:e[r]},t),{})},e.services=()=>ot.innerGet(Symbol.for(At.SERVICE)),e.repositories=()=>ot.innerGet(Symbol.for(b.REPOSITORY));class Ee extends $t{constructor(){super()}logCtx(t,e,r=!1){if(!this.adapter)throw new u("Adapter not set yet");return this.adapter.logCtx(t,e,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:e}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(t=>{if(!r[t])throw new u(`Method ${t} not found in ${r.alias} adapter to bind Observables Dispatch`);let e=Object.getOwnPropertyDescriptor(r,t),s=r;for(;!e&&s!==Object.prototype;)s=Object.getPrototypeOf(s),e=Object.getOwnPropertyDescriptor(s,t);function i(t){switch(t){case c.CREATE_ALL:return o.CREATE;case c.UPDATE_ALL:return o.UPDATE;case c.DELETE_ALL:return o.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:a,ctx:o}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,p=await e.call(r,c,l,u,...a),d=[c,i(t),l];return o.get("observeFullResult")&&d.push(p),this.updateObservers(...d,...a).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`)),p}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof qt))throw new Rt("Only Adapters can be observed by dispatch");return this.adapter=t,this.models=qt.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(t)}unObserve(t){if(this.adapter!==t)throw new Rt("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){if(!t)throw new u("Model must be provided for observer update");const i=t&&"string"==typeof t?t:G.tableName(t),{log:n,ctxArgs:a,ctx:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${o.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...a)}catch(t){throw new u("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Oe(t,e,r,s){if(t.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=e;i&&"function"==typeof i&&(i=i(s,...n||[],t)),s[r]=await Gt.instance.generate(i)}function Se(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=At.UUID;return ct.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[H(),v(At.UUID),x(Oe,s,{priority:54})];return t&&i.push(A(Oe,s,{priority:54})),t||i.push(E()),ut(...i)},args:[t,e,...r]}).apply()}async function Ce(t,e,r,s,i){const n=e.logger.for(Ce);if(!s){const e=G.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=he.forModel(e,r),n.info("Retrieved "+s.toString())}let a;if(s=i?s.override(i):s,void 0===t[G.pk(s.class)])n.info(`No pk found in ${G.tableName(s.class)} - creating`),a=await s.create(t,e);else{n.info(`pk found in ${G.tableName(s.class)} - attempting update`);try{a=await s.update(t,e),n.info("Updated "+G.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+G.tableName(s.class)),a=await s.create(t,e)}n.info("After create update: "+a)}return a}async function Te(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=je(s,r,this.adapter.alias),n=await e.read(i,t);return await Re(t,s,r,i,n),void(s[r]=i)}const n="function"!=typeof e.class||e.class.name?e.class:e.class();if(!n)throw new u("Could not find model "+e.class);const a=he.forModel(n,this.adapter.alias),o=await a.override(this._overrides).create(i,t),c=G.pk(o);await Re(t,s,r,o[c],o),s[r]=o[c]}async function Ne(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Xt.CASCADE)return;if("object"!=typeof i){const e=je(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Re(t,s,r,i,n),void(s[r]=i)}const n=await Ce(s[r],t,this.adapter.alias,void 0,this._overrides),a=G.pk(n);await Re(t,s,r,n[a],n),s[r]=n[a]}async function ke(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Xt.CASCADE)return;const n=je(s,r,this.adapter.alias);let a;a=i instanceof G?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Re(t,s,r,a[n.pk],a)}async function De(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a=t.logger.for(De),o=new Set([...i]);if("object"!==n){const e=je(s,r,this.adapter.alias),i=await e.readAll([...o.values()],t);for(let e=0;e<i.length;e++){const s=i[e];a.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await Re(t,s,r,[...o.values()][e],i)}return s[r]=[...o],void a.info("SET ONE TO MANY IDS: "+s[r])}const c=G.pk(i[0].constructor),l=new Set;for(const e of i){a.info("Creating or updating one-to-many model: "+JSON.stringify(e));const i=await Ce(e,t,this.adapter.alias,void 0,this._overrides);a.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Re(t,s,r,i[c],i),a.info("Creating or updating one-to-many model: "+JSON.stringify(e)),l.add(i[c])}s[r]=[...l]}async function _e(t,e,r,s){const{cascade:i}=e;if(i.update===Xt.CASCADE)return De.call(this,t,e,r,s)}async function $e(t,e,r,s){if(e.cascade.delete!==Xt.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?he.forModel(a,this.adapter.alias):je(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let p,d;try{p=await c.deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){d=p[e];try{await Re(t,s,r,l[e],d)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}function Pe(t,e,r){return[At.POPULATE,t,e,r].join(".")}function Be(t,e,r){return[At.TAG_FOR_DELETION,t,r].join(".")}async function Re(t,e,r,s,i){const n=Pe(e.constructor.name,r,s),a=t.get("cacheForPopulate")||{};return a[n]=i,t.accumulate({cacheForPopulate:a})}async function Ie(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const a=await(async(e,r,s,i)=>{let n,a;const o=[],c=e.get("cacheForPopulate")||{};for(const e of i){n=Pe(r.constructor.name,s,e);try{if(a=c[n],!a)throw Error("Not found in cache")}catch(i){const n=je(r,s);if(!n)throw new u("Could not find repo");a=await n.read(e,t)}o.push(a)}return o})(t,s,r,n?i:[i]);s[r]=n?a:a[0]}async function Le(t,e,r,s,i){if(e.cascade.update!==Xt.CASCADE)return;const n=s[r];if(void 0===n||Array.isArray(n)&&0===n.length)return;if(!i)throw new u("No way to compare old model. do you have updateValidation and mergeModels enabled?");function a(t){return Array.isArray(t)?t.map(a):"object"!=typeof t?t:t[G.pk(t)]}const o=a(s[r]),c=a(i[r]);if(void 0===c||Q(o,c))return;if(Array.isArray(o)!==Array.isArray(c))throw new u("Cannot cascade update for different array types");const l=(Array.isArray(o)?o:[o]).filter(Boolean),p=(Array.isArray(c)?c:[c]).filter(Boolean).filter(t=>!l.includes(t)),d=je(s,r);if(!d)throw new u("Could not find repo");try{const e=await d.deleteAll(p,t);t.logger.debug(`Deleted ${e.length} entries from table ${G.tableName(d.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}qt&&(qt._baseDispatch=Ee);const Fe=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function je(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=ot.get(t instanceof G?t.constructor:t,ot.key(V.REFLECT,e,V.LIST))?.clazz;if(!r)throw new u("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map(t=>"function"!=typeof t||t.name?t:t())}else s=ot.getPropDesignTypes(t instanceof G?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Fe.includes((""+t.name).toLowerCase()));return he.forModel(i,r)}class Ue extends O{constructor(t,e=Ue.name,r=401){super(t,e,r)}}class Me extends Ue{constructor(t,e=Me.name){super(t,e,403)}}class Ye extends u{constructor(t){super(t,Ye.name,503)}}function Ge(t){return ct.for(At.TABLE).define({decorator:t=>e=>(ot.set(At.TABLE,t||e.name.toLowerCase(),e),gt(At.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function ze(t){return ct.for(At.COLUMN).define({decorator:t=>(e,r)=>ft(ot.key(At.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function He(t,e,r){return ct.for(At.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![Jt.ASC,Jt.DSC].includes(t))&&(e=t,t=void 0),ft(ot.key(`${At.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function qe(t,e,r,s){if(s[r]&&(await this.select().where(Wt.attribute(r).eq(s[r])).execute()).length)throw new C(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Qe(){const t=At.UNIQUE;return ct.for(t).define(W(),T(qe),ft(t,{})).apply()}async function Ve(t,e,r,s){throw new Ue("This adapter does not support user identification")}function We(){return ct.for(At.CREATED_BY).define({decorator:()=>(t,e)=>ut(x(Ve),ft(At.CREATED_BY,e),v(At.CREATED_BY))(t,e),args:[]}).apply()}function Je(){return ct.for(At.UPDATED_BY).define({decorator:()=>(t,e)=>ut(A(Ve),ft(At.UPDATED_BY,e),v(At.UPDATED_BY))(t,e),args:[]}).apply()}function Xe(){return N([o.CREATE])}function Ze(){return N()}function Ke(t){const e="function"==typeof t&&t.name?t:t(),r=G.pk(e);return ot.allowedTypes(e,r)||[]}function tr(t,e=Zt,r=!0,s,i){const n=At.ONE_TO_ONE;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),J([t,...o]),x(Te,a,{priority:70}),A(Ne,a,{priority:70}),k(ke,a,{priority:70}),D(Le,a,{priority:70}),_(Ie,a,{priority:70})];return ut(...c)},args:[t,e,r,s,i]}).apply()}function er(t,e=Zt,r=!0,s,i){const n=At.ONE_TO_MANY;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),X([t,...o]),x(De,a,{priority:70}),A(_e,a,{priority:70}),k($e,a,{priority:70}),D(Le,a,{priority:70}),_(Ie,a,{priority:70})];return ut(...c)},args:[t,e,r,s,i]}).apply()}function rr(t,e=Zt,r=!0,s,i){const n=At.MANY_TO_ONE;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),J([t,...o])];return ut(...c)},args:[t,e,r,s,i]}).apply()}function sr(t,e=Zt,r=!0,s,i){const n=At.MANY_TO_MANY;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),X([t,...o])];return ut(...c)},args:[t,e,r,s,i]}).apply()}function ir(...t){return(e,r)=>{const s=ot.get(e,ot.key(At.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return ut(gt(ot.key(At.NO_VALIDATE,r),i))(e,r)}}function nr(){return ir(o.CREATE)}function ar(){return ir(o.UPDATE)}function or(){return ir(o.UPDATE,o.CREATE)}function cr(t,e){return ct.for(At.RELATIONS).define({decorator:(t,e)=>(r,s)=>(ft(t,e)(r,s),ft(ot.key(At.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class lr extends G{constructor(t){super(t)}}i([Xe(),n("design:type",Date)],lr.prototype,"createdAt",void 0),i([Ze(),n("design:type",Date)],lr.prototype,"updatedAt",void 0);const ur={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},pr=ur,dr={type:"Number",generated:!0,startWith:0,incrementBy:1,cycle:!1},hr=Object.assign({},dr,{type:"BigInt"});async function gr(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=G.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,o;n=s,a=r,o=await i.next(t),Reflect.set(n,a,o)}function fr(t,e){return(r,s)=>{if(yt()(r,s),!t.type){const e=ot.type(r.constructor,s);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 i=[yt(),He([Jt.ASC,Jt.DSC]),H(),E(),ft(ot.key(b.ID,s),t),x(gr,t,e)];return t.generated&&i.push(v()),ut(...i)(r,s)}}function yr(t){const e=Object.assign({},pr);return delete e.generated,t=Object.assign({},e,t),ct.for(b.ID).define({decorator:fr,args:[t,{priority:60}]}).apply()}let mr=class extends lr{constructor(t){super(t)}};i([yr({type:String,generated:!1}),n("design:type",String)],mr.prototype,"id",void 0),i([H(),He(),n("design:type",Object)],mr.prototype,"current",void 0),mr=i([Ge("??sequence"),Z(),n("design:paramtypes",[Object])],mr);class wr extends $t{static{this.lock=new at}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=he.forModel(mr,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,o.READ,!0),{name:s,startWith:i}=this.options;try{const t=await this.repo.read(s,r);return this.parse(t.current)}catch(t){if(t instanceof m){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new u("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new u(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new u(`Failed to retrieve current value for sequence ${s}: ${t}`)}}async increment(t,e){const{log:r,ctx:s}=this.adapter.logCtx([e],this.increment),{type:i,incrementBy:n,name:a}=this.options;if(!a)throw new u("Sequence name is required");return wr.lock.execute(async()=>{const e=t||n;if(e%n!==0)throw new u("Value to increment does not consider the incrementBy setting: "+n);const o="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new mr({id:a,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${a} current=${c} next=${t}`),this.repo.create(new mr({id:a,current:t}),s);throw e}};if("uuid"===o)for(;;){const t=await Promise.resolve(Gt.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${a} current=${c} next=${t}`),e.current}catch(t){if(t instanceof C)continue;throw t}}const p=await(async t=>{switch(o){case Number.name:return this.parse(t)+e;case BigInt.name:return this.parse(t)+BigInt(e);case String.name:return this.parse(t);case"serial":return await Promise.resolve(zt.instance.generate(t));default:throw new u("Should never happen")}})(c),d=await l(p);return r.debug(`Sequence.increment ${a} current=${c} next=${p}`),d.current},a)}async next(...t){const{ctx:e}=(await this.logCtx(t,o.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,o.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Rt(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),a=await this.increment(this.parse(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(a-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==a&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return wr.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([mr,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return G.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new Rt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function br(t,e){return(i,n)=>n?r(ot.constr(t))(i,n):(ot.set(b.REPOSITORY,ot.key(e||qt.currentFlavour,G.tableName(t)),i),gt(b.REPOSITORY,i.name)(t),e=e||ot.get(i.constructor,At.ADAPTER),he.register(t,i,e),s(ot.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}qt._baseSequence=wr;class vr extends u{constructor(t){super(t,vr.name,500)}}class xr extends L{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,Yt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${xt.FIND_BY}|${xt.LIST_BY}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],xt.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[t,...r]}async pagePrepared(t,e,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!e||e instanceof _t?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof _t||(this._bookmark=e);const n=he.forModel(this.clazz,this.adapter.alias),a=this.query,{method:o,args:c,params:l}=a,u=RegExp(`^${xt.FIND_BY}|${xt.LIST_BY}`,"gi");if(!o.match(u))throw new Rt(`Method ${o} is not supported for pagination`);u.lastIndex=0;const p=o.replace(u,xt.PAGE_BY),d=[p,...c];let h={limit:this.size,offset:t,bookmark:this._bookmark};p!==xt.PAGE_BY||d.length>2?h={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:d.push(l.direction),d.push(h);const g=await n.statement(...d,...i);return this.apply(g)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new Vt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new Vt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,e,...r){const{ctxArgs:s}=this.adapter.logCtx([e,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...s);throw new Rt("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new $(t)}}apply(t){const e="string"==typeof t?xr.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total,this._recordCount=e.count,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new $(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}var Ar,Er,Or,Sr;class Cr extends $t{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{P(this,t,(...e)=>this.executionPrefix(t,...e),t.name)})}async executionPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...e],t.name===this.paginate.name?xt.PAGE_BY:At.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=r.get("forcePrepareSimpleQueries"),a=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${a}`),(n&&this.isSimpleQuery()||a)&&(i.silly(`squashing ${a?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${a?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Cr)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}count(t){return this.countSelector=t,this}from(t){if(this.fromSelector="string"==typeof t?G.get(t):t,!this.fromSelector)throw new Qt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const{log:e,ctxArgs:r}=this.logCtx(t,this.execute);try{if(this.prepared)return this.executePrepared(...t);e.silly("Building raw statement...");const s=this.build();return e.silly("executing raw statement"),await this.raw(s,...r)}catch(t){throw new Qt(t)}}async executePrepared(...t){const e=he.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new Rt("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(!this.selectSelector)return i;const n=G.pk(this.fromSelector),a=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(a):a(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case vt.AND:case vt.OR:{let t=r,a=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof Wt){const t=this.prepareCondition(i,e);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;break}case bt.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case bt.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case bt.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case bt.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case bt.BIGGER_EQ:n.method=r+" bigger than equal";break;case bt.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case bt.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case bt.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Qt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof Wt)return;e=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:e?[e,Jt.DSC]:[G.pk(this.fromSelector),Jt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const a={class:this.fromSelector,method:xt.LIST_BY,args:[s],params:n};return e&&(a.method=xt.FIND_BY,a.args=[e,this.whereCondition.comparison],a.params=n),a}async prepare(t){if(t=t||await this.adapter.context(At.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},i=[wt.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);i.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&i.push(wt.SELECT,this.selectSelector.join(` ${wt.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(wt.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(wt.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=U(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new Qt(t)}}toString(){return this.adapter.flavour+" statement"}}i([j(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Cr.prototype,"select",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ar="undefined"!=typeof S&&S)?Ar:Object]),n("design:returntype",Object)],Cr.prototype,"distinct",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Er="undefined"!=typeof S&&S)?Er:Object]),n("design:returntype",Object)],Cr.prototype,"max",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Or="undefined"!=typeof S&&S)?Or:Object]),n("design:returntype",Object)],Cr.prototype,"min",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Sr="undefined"!=typeof S&&S)?Sr:Object]),n("design:returntype",Object)],Cr.prototype,"count",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Cr.prototype,"from",null),i([j(),n("design:type",Function),n("design:paramtypes",[Wt]),n("design:returntype",Object)],Cr.prototype,"where",null),i([j(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Cr.prototype,"orderBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Cr.prototype,"groupBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Cr.prototype,"limit",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Cr.prototype,"offset",null),i([j(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Cr.prototype,"execute",null);class Tr extends $t{constructor(t){super(),this.name=t,this.observers=[],this.Context=_t}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Bt,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(t,e),r.verbose("Registered new observer "+(t.constructor.name||t.toString())),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(t);const e=this.log.for(this.unObserve);e.verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,e.verbose("No longer being observed"))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,r,...n)}async flags(t,e,...r){e.correlationId=e.correlationId||`${t}-${Gt.instance.generate()}`;const s=e.logger||F.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Et,e,{args:r,timestamp:new Date,operation:t,logger:s})}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}async context(t,e,...r){this.log.for(this.context).silly(`creating new context for ${t} operation with flag overrides: ${JSON.stringify(e)}`);let s=r.pop();void 0===s||s instanceof _t||(r.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const i=await this.flags("string"==typeof t?t:t.name,e,...[...r,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}if(s.get("operation")!==t){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(i)}return(new this.Context).accumulate({...i})}logCtx(t,e,r=!1,s){return $t.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static get(t){if(!t)throw new u("No name provided");const r=Ft(t),s=e.get(r);if(s)return s;throw new u("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof _t||(t.push(r),r=void 0);const s=await Tr.prototype.flags(At.INITIALIZATION,{},...t);r=r?new _t(r).accumulate({...s,parentContext:r}):(new _t).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Tr.prototype.logCtx(t,this.boot),a=e.services();for(const[t,r]of Object.entries(a))try{i.verbose(`Booting ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);s instanceof Nr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(e){throw new u(`Failed to boot ${t} service:${e}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof _t||(t.push(r),r=void 0);const s=await Tr.prototype.flags(At.SHUTDOWN,{},...t);r=r?new _t(r).accumulate({...s,parentContext:r}):(new _t).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Tr.prototype.logCtx(t,this.shutdown),a=e.services();for(const[t,r]of Object.entries(a).reverse())try{i.verbose(`Shutting down ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);if(s instanceof Nr){i.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(t){i.error(`Failed to gracefully shutdown ${r.name} service`,t)}}}catch(e){throw new u(`Failed to Shutdown services ${t}: ${e}`)}}}i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Tr.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Tr.prototype,"unObserve",null);class Nr extends Tr{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.boot);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new u("Config not initialized");return this._config}get client(){if(!this._client)throw new u("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}function kr(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Ut(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],Nr.prototype,"boot",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],Nr.prototype,"config",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],Nr.prototype,"client",null);const Dr=()=>kr(o.CREATE),_r=()=>kr(o.READ),$r=()=>kr(o.UPDATE),Pr=()=>kr(o.DELETE);function Br(t){return(e,i,n)=>{n||i?(yt()(e,i),t=t||ot.type(e.constructor,i)):t=t||e,t=Ft(t);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else ot.set(At.SERVICE,t,e),a.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return ut(...a)(e,i,n)}}function Rr(t){const e=At.AUTH;return ct.for(e).define({decorator:t=>gt(e,t),args:[t]}).apply()}const Ir=t=>gt(At.AUTH_ROLE,t);function Lr(t,e){const r=At.DECAF_ROUTE;return ct.for(r).define({decorator:()=>(s,i,n)=>{const a={path:e,httpMethod:t,handler:n};return ut(pt(ot.key(r,i),a))(s,i,n)},args:[]}).apply()}const Fr=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class jr extends Tr{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=he.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new u("No name provided");const e=Fr(t);try{const t=Tr.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,i)})}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,xt.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=Fr(e||t);try{r=jr.get(e)}catch(t){r=void 0}if(r instanceof jr)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=i([Br(e),n("design:paramtypes",[])],a),new a}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}}i([Dr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"create",null),i([Dr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],jr.prototype,"createAll",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"delete",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],jr.prototype,"deleteAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"read",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],jr.prototype,"readAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],jr.prototype,"query",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"update",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],jr.prototype,"updateAll",null);class Ur extends Nr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof _t||!e.every(t=>Array.isArray(t)))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.initialize),i=e.map(([t,e,...s])=>{try{r.silly(`Initializing ${t.name} with config: ${JSON.stringify(e)}`);const i=new t(e,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(e){throw new u(`Failed to initialize ${t.name}: ${e}`)}});for(const t of i)try{await t.initialize(...s)}catch(e){throw new u(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let Mr=class extends G{constructor(t){super(t),this.strategy=me.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=we.FULL}};i([H(),J(String),K(me),mt("the backoff strategy"),n("design:type",String)],Mr.prototype,"strategy",void 0),i([H(),mt("base interval between attempts"),n("design:type",Number)],Mr.prototype,"baseMs",void 0),i([H(),mt("max interval"),n("design:type",Number)],Mr.prototype,"maxMs",void 0),i([J(String),K(we),mt("optional jitter strategy"),n("design:type",String)],Mr.prototype,"jitter",void 0),Mr=i([Z(),n("design:paramtypes",[Object])],Mr);let Yr=class extends G{constructor(t){super(t)}};i([H(),mt("The error message"),n("design:type",String)],Yr.prototype,"message",void 0),i([yt(),mt("The error stack"),n("design:type",String)],Yr.prototype,"stack",void 0),i([yt(),mt("The error code"),n("design:type",String)],Yr.prototype,"code",void 0),i([yt(),mt("The error details"),n("design:type",Object)],Yr.prototype,"details",void 0),Yr=i([Z(),n("design:paramtypes",[Object])],Yr);let Gr=class extends G{constructor(t){super(t),this.ts=new Date}};i([B(["taskId","classification","uuid"],":"),yr(),n("design:type",String)],Gr.prototype,"id",void 0),i([E(),H(),R(),Se(!1),n("design:type",String)],Gr.prototype,"uuid",void 0),i([E(),H(),n("design:type",String)],Gr.prototype,"taskId",void 0),i([tt(),H(),n("design:type",Date)],Gr.prototype,"ts",void 0),i([E(),H(),K(be),n("design:type",String)],Gr.prototype,"classification",void 0),i([yt(),E(),n("design:type",Object)],Gr.prototype,"payload",void 0),Gr=i([Ge("task_event"),Z(),n("design:paramtypes",[Object])],Gr);class zr extends et{constructor(){super()}preSerialize(t,...e){if(null===t||"object"!=typeof t)return t;const r=Object.assign({},t);if(t instanceof Wt)return r[rt.ANCHOR]="??condition",r;if(G.isModel(t)){let e;try{e=ot.modelName(t.constructor)}catch(t){e=void 0}e&&(r[rt.ANCHOR]=e)}return r}deserialize(t,...e){const r=JSON.parse(t),s=r[rt.ANCHOR];return s?"??condition"===s?Wt.from(r):G.build(r,s):r}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Hr=class extends G{constructor(t){super(t),this.ts=new Date}};i([tt(),H(),n("design:type",Date)],Hr.prototype,"ts",void 0),i([H(),K(M),n("design:type",String)],Hr.prototype,"level",void 0),i([H(),yt(),n("design:type",String)],Hr.prototype,"msg",void 0),i([yt(),n("design:type",Object)],Hr.prototype,"meta",void 0),Hr=i([Z(),n("design:paramtypes",[Object])],Hr);let qr=class extends G{constructor(t){super(t),this.atomicity=ve.ATOMIC,this.status=ye.PENDING,this.attempt=0,this.logTail=[]}};i([yr({type:"uuid"}),mt("the task id"),n("design:type",String)],qr.prototype,"id",void 0),i([H(),J(String),K(ve),mt("defines a single or composite task"),n("design:type",String)],qr.prototype,"atomicity",void 0),i([H(),mt("Holds task classification - must match @task()"),n("design:type",String)],qr.prototype,"classification",void 0),i([H(),J(String),K(ye),mt("Holds the task current status"),n("design:type",String)],qr.prototype,"status",void 0),i([yt(),I(zr),mt("Holds task input"),n("design:type",Object)],qr.prototype,"input",void 0),i([yt(),I(zr),mt("Holds the task output when successfully completed"),n("design:type",Object)],qr.prototype,"output",void 0),i([yt(),I(),mt("Holds the error for failed tasks"),n("design:type",Yr)],qr.prototype,"error",void 0),i([H(),st(0),mt("Holds the current attempt"),n("design:type",Number)],qr.prototype,"attempt",void 0),i([st(1),H(),mt("max attempts for the task"),n("design:type",Number)],qr.prototype,"maxAttempts",void 0),i([H(),I(),mt("backoff configuration"),n("design:type",Mr)],qr.prototype,"backoff",void 0),i([tt(),mt("Next execution timestamp"),n("design:type",Date)],qr.prototype,"nextRunAt",void 0),i([yt(),mt("Task lease owner identifier"),n("design:type",String)],qr.prototype,"leaseOwner",void 0),i([tt(),mt("Task lease expiration timestamp"),n("design:type",Date)],qr.prototype,"leaseExpiry",void 0),i([yt(),I(),mt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],qr.prototype,"steps",void 0),i([st(0),yt(),mt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],qr.prototype,"currentStep",void 0),i([yt(),I(),mt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],qr.prototype,"stepResults",void 0),i([yt(),I(),mt("Holds the task log entries"),n("design:type",Array)],qr.prototype,"logTail",void 0),i([ze(),Xe(),mt("timestamp of creation"),n("design:type",Date)],qr.prototype,"createdAt",void 0),i([ze(),Ze(),mt("timestamp of last update"),n("design:type",Date)],qr.prototype,"updatedAt",void 0),i([ze(),We(),mt("Holds the creator of the task"),n("design:type",String)],qr.prototype,"createdBy",void 0),i([ze(),Je(),mt("Holds the creator of the task"),n("design:type",String)],qr.prototype,"updatedBy",void 0),qr=i([mt("Holds the current step when applicable"),Ge("tasks"),Z(),n("design:paramtypes",[Object])],qr);let Qr=class extends G{constructor(t){super(t)}};i([H(),mt("The status of a step"),n("design:type",String)],Qr.prototype,"status",void 0),i([yt(),mt("The result of a successful step"),n("design:type",Object)],Qr.prototype,"output",void 0),i([yt(),mt("the error of a failed step"),n("design:type",Yr)],Qr.prototype,"error",void 0),Qr=i([Z(),n("design:paramtypes",[Object])],Qr);let Vr=class extends G{constructor(t){super(t)}};i([H(),yt(),mt("task handler type"),n("design:type",String)],Vr.prototype,"classification",void 0),i([mt("optional task step input"),yt(),n("design:type",Object)],Vr.prototype,"input",void 0),Vr=i([Z(),n("design:paramtypes",[Object])],Vr);class Wr extends G{constructor(t){super(t),this.baseMs=1e3,this.jitter=we.FULL,this.maxMs=6e4,this.strategy=me.EXPONENTIAL,G.fromModel(this,t)}setBaseMs(t){return this.baseMs=t,this}setJitter(t){return this.jitter=t,this}setMaxMs(t){return this.maxMs=t,this}setStrategy(t){return this.strategy=t,this}build(){const t=this.hasErrors();if(t)throw new p(t);return new Mr(this)}}i([H(),st(1e3),n("design:type",Number)],Wr.prototype,"baseMs",void 0),i([H(),K(we),n("design:type",String)],Wr.prototype,"jitter",void 0),i([it("baseMs"),st(1e3),H(),n("design:type",Number)],Wr.prototype,"maxMs",void 0),i([H(),K(me),n("design:type",String)],Wr.prototype,"strategy",void 0);class Jr extends G{setClassification(t){return this.classification=t,this}setStatus(t){return this.status=t,this}setAtomicity(t){return this.atomicity=t,this}setBackoff(t){if(t)return this.backoff=t,this;const e=new Wr,r=this;return e.build=new Proxy(e.build,{apply:(t,e,s)=>(r.backoff=Reflect.apply(t,e,s),r)}),e}setInput(t){return this.input=t,this}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=ye.PENDING,this.atomicity=ve.ATOMIC,this.backoff=new Mr,this.maxAttempts=1,G.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new p(t);return new qr(this)}}i([H(),n("design:type",String)],Jr.prototype,"classification",void 0),i([H(),n("design:type",String)],Jr.prototype,"status",void 0),i([H(),n("design:type",String)],Jr.prototype,"atomicity",void 0),i([H(),n("design:type",Mr)],Jr.prototype,"backoff",void 0),i([yt(),n("design:type",Object)],Jr.prototype,"input",void 0),i([st(1),H(),n("design:type",Number)],Jr.prototype,"maxAttempts",void 0);class Xr extends Jr{constructor(t){super(t),this.stepResults=[],G.fromModel(this,t),this.atomicity=ve.COMPOSITE}setSteps(t){return this.steps=t,this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new Vr({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([X(()=>Vr),n("design:type",Array)],Xr.prototype,"steps",void 0);class Zr extends Pt{get type(){if(!this._type){const t=ot.get(this.constructor,xe);"string"==typeof t?this._type=t:t&&"string"==typeof t.type&&(this._type=t.type)}if(!this._type)throw new u("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),h(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(t,...e){const{log:r,ctx:s,ctxArgs:i}=this.logCtx(e,this.runPrefix);return r.info(`Running task ${s.taskId} attempt ${s.attempt}`),[t,...i]}runSuffix(t,e){const{log:r}=this.logCtx([e],this.runPrefix);return r.info(`Concluded task ${e.taskId} attempt ${e.attempt}`),t}}function Kr(t){return ct.for(xe).define({decorator:t=>e=>{const r={type:t};return ot.set(xe,t,e),gt(xe,r)(e)},args:[t]}).apply()}let ts=class extends Zr{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof Wt)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=Wt.attr("status").eq(ye.SUCCEEDED).and(Wt.attr("updatedAt").lte(t.successfulExpiry)),i=Wt.attr("status").eq(ye.FAILED).and(Wt.attr("updatedAt").lte(t.failedExpiry)),n=Wt.attr("status").eq(ye.CANCELED).and(Wt.attr("updatedAt").lte(t.cancelledExpiry));s=e.or(i).or(n)}r.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(e);if(0===i.length)return r.info("No tasks found for cleanup"),[];r.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(t=>t.id),e);return r.info(`Successfully deleted ${n.length} tasks`),r.debug("deleted tasks:",n),n}catch(t){throw r.error("Error during task cleanup",t),t}}};i([br(qr),n("design:type",Object)],ts.prototype,"tasks",void 0),ts=i([Kr("cleanup-task"),n("design:paramtypes",[])],ts);class es{constructor(t,e=150,r=300,s){this.logger=t,this.bufferSize=e,this.maxBufferSize=r,this.pipe=s,this.history=[],this.root=this.logger.root,Object.values(M).forEach(t=>{this[t]=new Proxy(this[t],{apply:(e,r,s)=>{e.apply(r,s),r.push(t,...s)}})})}push(t,e,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([t,e,r])}flush(t){const e=this.history;return this.history=[],t&&e.length?t(e).catch(t=>this.logger.error("Failed to pipe logs",t)).finally(()=>this.history=[]):(this.history=[],e)}benchmark(t){return this.logger.benchmark(t)}clear(){return this.logger=this.logger.clear(),this}debug(t,e){this.logger.debug(t,e)}error(t,e,r){this.logger.error(t,e,r)}for(t,...e){return new Proxy(this,{get:(r,s)=>"logger"===s?Reflect.get(r,s).for(t,...e):Reflect.get(r,s)})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function rs(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1,timestamp:!1,logLevel:!1}),r.classification){case be.LOG:{const s=r.payload;for(let[r,i,n]of s){e.style||(i=Y(i),i=i.clear().toString());const s=[i];r===M.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case be.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case be.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=Y(e);switch(e){case ye.SUCCEEDED:s=s.green.bold;break;case ye.RUNNING:s=s.blue.bold;break;case ye.PENDING:s=s.yellow;break;case ye.WAITING_RETRY:s=s.yellow.bold;break;case ye.FAILED:s=s.red.bold;break;case ye.CANCELED:s=s.red;break;default:throw new u("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;default:throw new u("Unknown task event classification: "+r.classification)}}}class ss extends _t{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(t,e){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[t]=e,this.cache.put("resultCache",r)}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class is{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=ot.tasks();t&&Object.entries(t).forEach(([t,e])=>{let r;try{r=new e}catch(e){throw new u(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)})}register(t){if(this.handlers.has(t.type))throw new u("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class ns extends Bt{constructor(){super(...arguments),this.listeners=new Set}observe(t,e){return super.observe(t,e)}unObserve(t){super.unObserve(t)}emit(t,e){this.updateObservers(Gr,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:a}=qt.logCtx(this.updateObservers,void 0,!1,...i);(await Promise.allSettled(this.observers.filter(s=>{const{filter:i}=s;if(!i)return!0;try{return i(t,e,r,...a)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(t=>{t.observer.refresh(s,...a)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}function as(t,e){const r=e.strategy===me.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===we.FULL?Math.floor(Math.random()*s):s}function os(t){return new Yr({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function cs(t){return new Promise(e=>setTimeout(e,t))}class ls{constructor(t,e){this.bus=t,this.task=e,this.resolved=!1,this.unregistration=t.observe(this,(t,e,r,...s)=>r.startsWith(this.task.id)&&(t===Gr||t===G.tableName(Gr))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([ye.SUCCEEDED,ye.FAILED,ye.CANCELED,ye.WAITING_RETRY])}wait(){return this.awaitStatusTerminal([ye.SUCCEEDED,ye.FAILED,ye.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(rs(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==be.LOG)return;const r=e.payload;await t(r)},be.LOG)}pipe(t,e=be.ALL){this.pipes=this.pipes||{},this.pipes[e]=this.pipes[e]||new Set,this.pipes[e].add(t)}succeed(t){this.complete(t)}fail(t){this.complete(t)}cancel(t){t.payload?.error&&this.fail(t.payload.error)}retry(t){t.payload&&t.payload.error&&(this.task.error=t.payload.error)}onSucceed(t){return this.registerStatusHandler(ye.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(ye.FAILED,t)}onCancel(t){return this.registerStatusHandler(ye.CANCELED,t)}awaitStatusTerminal(t){return new Promise((e,r)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const t of s)t()}})();try{t.payload?.status===ye.SUCCEEDED?e(this.extractOutput(t)):r(this.extractError(t))}catch(t){r(t)}}};t.forEach(t=>{const e=this.registerStatusHandler(t,n);s.push(e)})})}extractOutput(t){return void 0!==t.payload?.output?t.payload.output:this.task.output}extractError(t){if(t.payload?.error)return t.payload.error;if(this.task.error)return this.task.error;if(this.lastTerminalPayload instanceof Yr)return this.lastTerminalPayload;const e=t.payload?.status??this.task.status,r=e===ye.WAITING_RETRY?`Task ${this.task.id} scheduled for retry`:`Task ${this.task.id} ${e}`;return new Yr({message:r})}complete(t){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0,this.lastTerminalPayload=t)}isTerminalStatus(t){return[ye.SUCCEEDED,ye.CANCELED,ye.FAILED].includes(t)}async track(t,e){t.payload&&(this.task.status=t.payload.status,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),t.payload.status===ye.SUCCEEDED&&this.succeed(t.payload.output),t.payload.status===ye.FAILED&&this.fail(t.payload.error),t.payload.status===ye.CANCELED&&this.cancel(t),t.payload.status===ye.WAITING_RETRY&&this.retry(t))}registerStatusHandler(t,e){const r=async(r,s)=>{r.payload?.status===t&&await e(r,s)};if(this.pipe(r,be.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[be.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new _t),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===ye.SUCCEEDED&&(e.output=this.task.output),t!==ye.FAILED&&t!==ye.CANCELED||!this.task.error||(e.error=this.task.error),new Gr({classification:be.STATUS,taskId:this.task.id,payload:e})}resolveTerminalState(){this.isTerminalStatus(this.task.status)&&(this.task.status!==ye.SUCCEEDED?this.task.error&&this.fail(this.task.error):this.succeed(this.task.output))}async refresh(t,e){if(!this.pipes)return;const r=this.pipes[be.ALL]?[...this.pipes[be.ALL].values()]:[];r.push(...this.pipes[t.classification]?.values()||[]);for(const s of r)try{await s(t,e)}catch(r){e.logger.error(`Failed to trigger pipe ${s.name} for event ${t.classification}. discarding event`,r)}}}class us extends Pt{get Context(){return ss}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=he.forModel(qr,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=he.forModel(Gr,this.config.adapter.alias)),this._events}constructor(t){super(),this.config=t,this.lock=new nt,this.running=!1,this.config=Object.assign({},Ae,t,{bus:t.bus||new ns,registry:t.registry||new is})}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,o.CREATE,!0)).for(this.push);i.verbose("pushing task "+t.classification);const n=await this.tasks.create(t,s);return i.info(`${t.classification} task registered under ${n.id}`),e?{task:n,tracker:new ls(this.bus,n)}:n}async track(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,o.READ,!0)).for(this.track);s.verbose("tracking task "+t);let i=await this.tasks.read(t,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${t}`),{task:i,tracker:new ls(this.bus,i)}}async ensureTaskError(t,e){if(![ye.FAILED,ye.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await cs(20);try{const t=await this.tasks.read(r.id,e);if(t.error)return t;r=t}catch{break}}return r}async cancel(t,...e){const{ctx:r}=(await this.logCtx(e,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,r);if(s.status===ye.SUCCEEDED||s.status===ye.FAILED)return s;s.status=ye.CANCELED;const i=new Yr({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0;const n=await this.tasks.update(s,r);return await this.emitStatus(r,n,ye.CANCELED,i),n}async isRunning(){await this.lock.acquire();const t=this.running;return this.lock.release(),t}async start(...t){const{ctx:e}=(await this.logCtx(t,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.loop(e))}async stop(...t){const{ctx:e,log:r}=(await this.logCtx(t,At.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||r.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(Wt.attr("status").eq(ye.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((t,n)=>{const a=setTimeout(()=>{r.error(`Graceful shutdown interrupted after ${i} ms...`),t()},i);Promise.allSettled(s.map(({id:t})=>new Promise((r,s)=>{this.track(t,e).then(({tracker:t})=>{t.resolve().then(r)}).catch(s)}))).then(e=>{clearTimeout(a),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()}).catch(t=>{clearTimeout(a),n(t)})})}async loop(...t){const{ctx:e}=this.logCtx(t,this.loop);for(;await this.isRunning();){const t=await this.claimBatch(e);await Promise.allSettled(t.map(t=>this.executeClaimed(t))),await cs(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=t.timestamp,s=Wt.attribute("status").eq(ye.PENDING),i=Wt.attribute("status").eq(ye.WAITING_RETRY).and(Wt.attribute("nextRunAt").lte(r)),n=Wt.attribute("status").eq(ye.RUNNING).and(Wt.attribute("leaseExpiry").lte(r)),a=s.or(i).or(n),o=await this.tasks.select().where(a).limit(Math.max(4*this.config.concurrency,20)).execute();e.verbose("claimBatch candidates:"+o.length);const c=[];for(const e of o){const r=await this.tryClaim(e,t);if(r&&c.push(r),c.length>=this.config.concurrency)break}return e.verbose("claimBatch claimed:"+c.length),c}async tryClaim(t,e){const r=e.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,e)}catch{}const n=new qr({...i,status:ye.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4))});r.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,e)}catch{return null}}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=new ss(e).accumulate({taskId:t.id,logger:new es(r,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{},pipe:async e=>{const[,r]=await this.appendLog(s,t,e);await this.emitLog(s,t.id,r)},flush:async()=>s.logger.flush(s.pipe),progress:async e=>{await this.emitProgress(s,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(s,t,ye.RUNNING);try{let e;if(t.atomicity===ve.COMPOSITE){e=await this.runComposite(t,s);try{t=await this.tasks.read(t.id,s)}catch{}e?.stepResults&&(t.stepResults=e.stepResults,t.currentStep=e.stepResults.length)}else{const i=this.registry.get(t.classification);if(r.debug(`handler type for ${t.id} is ${i?.constructor?.name??"none"}`),!i)throw new u("No task handler registered for type: "+t.classification);e=await i.run(t.input,s),r.verbose("handler finished for "+t.id)}t.status=ye.SUCCEEDED,t.output=e,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),s.logger.info(`task ${t.id} success state ${t.status}`),r.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,ye.SUCCEEDED,e)}catch(e){r.error("task execution error",e);try{t=await this.tasks.read(t.id,s)}catch{}if(t.atomicity===ve.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===ye.FAILED);0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=os(e);if(i<t.maxAttempts){const e=as(i,this.normalizeBackoff(t.backoff)),a=new Date(Date.now()+e);t.attempt=i,t.status=ye.WAITING_RETRY,t.nextRunAt=a,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,ye.WAITING_RETRY),await s.pipe(M.warn,"Retry scheduled",{nextRunAt:a,delayMs:e,attempt:i})}else t.attempt=i,t.status=ye.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,ye.FAILED,n),await s.pipe(M.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts})}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite),s=this.normalizeSteps(t.steps);let i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),a=(t,s)=>{e.cacheResult(t,s),r instanceof ss&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===ye.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;a(i.classification,r.output),a(n,r.output)}}for(;i<s.length;){const r=s[i],o=this.registry.get(r.classification);if(!o)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([M.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await o.run(r.input,e),l=i,u=new Date;n[l]=new Qr({status:ye.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const p=`${t.id}:step:${l}`;a(r.classification,c),a(p,c),i=l+1,t.stepResults=n,t.currentStep=i,t=await this.tasks.update(t),await this.emitProgress(e,t.id,{currentStep:i,totalSteps:s.length,output:c})}catch(e){const r=new Date;throw n[i]=new Qr({status:ye.FAILED,error:os(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=os(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Mr)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Mr(e)}normalizeSteps(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map(t=>{if(t instanceof Vr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Vr(e)}):[]}normalizeStepResults(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map(t=>{if(t instanceof Qr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Qr(e)}):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map(([t,e,r])=>new Hr({level:t,msg:e,meta:r})),i=[...e.logTail??[],...s].slice(-this.config.logTailMax);e.logTail=i;try{return[await this.tasks.update(e,t),s]}catch{return[e,[]]}}async emitStatus(t,e,r,s){t instanceof ss&&await t.flush();const i={status:r};s&&s instanceof Yr?i.error=s:s&&(i.output=s);const n=await this.persistEvent(t,e.id,be.STATUS,i);this.bus.emit(n,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,be.LOG,r.map(t=>({ts:t.ts,level:t.level,msg:t.msg,meta:t.meta})));this.bus.emit(s,t)}async emitProgress(t,e,r){const s=await this.persistEvent(t,e,be.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Gr({taskId:e,classification:r,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,e,...r){return this.adapter.context(t,e,qr,...r)}}class ps extends Nr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof _t)throw new u("No/invalid config provided");const{log:r}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.initialize);if(!e.adapter)throw new u("No adapter provided");r.info("Initializing Task Engine...");const s=new us(e);return r.verbose(s+" initialized"),{client:s,config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,o.CREATE,!0)).for(this.push),i=await this.client.push(t,e,...s);return await this.client.isRunning()||this.client.start(),i}async track(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.push);return this.client.track(t,...r)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.create),s=await this.repo.create(t,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll),s=await this.repo.createAll(t,...r);return await this.client.isRunning()||this.client.start(),s}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){throw new Rt("Updates to tasks are not available")}async updateAll(t,...e){throw new Rt("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,xt.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}async shutdown(...t){const{ctxArgs:e,ctx:r,log:s}=(await this.logCtx(t,At.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...e),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(r),s.verbose("gracefully shutdown task runner")}}i([br(qr),n("design:type",Object)],ps.prototype,"repo",void 0),i([Dr(),n("design:type",Function),n("design:paramtypes",[qr,void 0]),n("design:returntype",Promise)],ps.prototype,"create",null),i([Dr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"createAll",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ps.prototype,"delete",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"deleteAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ps.prototype,"read",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"readAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],ps.prototype,"query",null),i([$r(),n("design:type",Function),n("design:paramtypes",[qr,void 0]),n("design:returntype",Promise)],ps.prototype,"update",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"updateAll",null),e.setRegistry(new fe);const ds="##VERSION##",hs="##PACKAGE##";ot.registerLibrary(hs,ds);export{Pt as AbsContextual,qt as Adapter,Ue as AuthorizationError,me as BackoffStrategy,lr as BaseModel,hr as BigIntSequence,Xt as Cascade,ts as CleanUpTask,Nr as ClientBasedService,Xr as CompositeTaskBuilder,Wt as Condition,Ye as ConnectionError,_t as Context,Dt as ContextLock,$t as ContextualLoggedClass,Ot as DefaultAdapterFlags,Zt as DefaultCascade,Et as DefaultContextFlags,pe as DefaultRepositoryFilters,pr as DefaultSequenceOptions,Ae as DefaultTaskEngineConfig,Ee as Dispatch,Me as ForbiddenError,vt as GroupOperator,fe as InjectablesRegistry,we as JitterStrategy,ee as MethodQueryBuilder,It as MigrationError,Lt as MigrationRuleError,jr as ModelService,Nt as MultipleSelectOperationKeys,Ct as NonTransactionOperationKeys,ur as NoneSequenceOptions,dr as NumericSequence,vr as ObserverError,Bt as ObserverHandler,bt as Operator,Kt as OperatorsMap,Jt as OrderDirection,hs as PACKAGE_NAME,kt as PaginationOperationKeys,xr as Paginator,Vt as PagingError,At as PersistenceKeys,Ur as PersistenceService,xt as PreparedStatementKeys,wt as QueryClause,Qt as QueryError,he as Repository,Tt as SelectOperationKeys,wr as Sequence,mr as SequenceModel,zt as Serial,Tr as Service,Cr as Statement,Wr as TaskBackoffBuilder,Mr as TaskBackoffModel,Jr as TaskBuilder,ss as TaskContext,us as TaskEngine,Yr as TaskErrorModel,ns as TaskEventBus,Gr as TaskEventModel,be as TaskEventType,Zr as TaskHandler,is as TaskHandlerRegistry,zr as TaskIOSerializer,Hr as TaskLogEntryModel,es as TaskLogger,qr as TaskModel,ps as TaskService,ye as TaskStatus,Qr as TaskStepResultModel,Vr as TaskStepSpecModel,ls as TaskTracker,ve as TaskType,xe as TasksKey,St as TransactionOperationKeys,Gt as UUID,Rt as UnsupportedError,ds as VERSION,Rr as auth,Re as cacheModelForPopulate,Le as cascadeDelete,ze as column,as as computeBackoffMs,Dr as create,Ce as createOrUpdate,Xe as createdAt,We as createdBy,Ve as createdByOnCreateUpdate,Pr as del,ge as generateInjectableNameForRepository,de as getFilters,rs as getLogPipe,Ke as getPkTypes,Pe as getPopulateKey,Be as getTagForDeleteKey,He as index,Ft as injectableServiceKey,Ut as isOperationBlocked,sr as manyToMany,rr as manyToOne,ir as noValidateOn,nr as noValidateOnCreate,or as noValidateOnCreateUpdate,ar as noValidateOnUpdate,Mt as normalizeImport,er as oneToMany,De as oneToManyOnCreate,$e as oneToManyOnDelete,_e as oneToManyOnUpdate,tr as oneToOne,Te as oneToOneOnCreate,ke as oneToOneOnDelete,Ne as oneToOneOnUpdate,le as onlyOnBulk,ie as onlyOnCreate,ae as onlyOnDelete,ue as onlyOnFilter,ce as onlyOnSingle,oe as onlyOnTransactional,ne as onlyOnUpdate,yr as pk,fr as pkDec,gr as pkOnCreate,Ie as populate,Yt as prefixMethod,re as prepared,jt as promiseSequence,se as query,_r as read,cr as relation,br as repository,je as repositoryFromTypeMetadata,Ir as roles,Lr as route,os as serializeError,Br as service,cs as sleep,Ge as table,Kr as task,Qe as unique,qe as uniqueOnCreateUpdate,$r as update,Ze as updatedAt,Je as updatedBy,Se as uuid,Oe as uuidCreateUpdateHandler};
1
+ import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as a,OperationKeys as o,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as p,Repository as d,wrapMethodWithContext as h,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,generated as v,onCreate as x,onUpdate as A,readonly as E,BadRequestError as O,ConflictError as C,onCreateUpdate as T,timestamp as N,onDelete as k,afterUpdate as D,afterAny as _,SerializationError as $,prefixMethod as P,composed as B,transient as R,serialize as I}from"@decaf-ts/db-decorators";import{LoggedClass as L,Logging as F,final as j,toCamelCase as U,LogLevel as M,style as Y}from"@decaf-ts/logging";import{Model as G,hashObj as z,required as H,sf as q,isEqual as Q,ValidationKeys as V,async as W,type as J,list as X,model as Z,option as K,date as tt,JSONSerializer as et,ModelKeys as rt,min as st,gt as it}from"@decaf-ts/decorator-validation";import{Lock as nt,MultiLock as at}from"@decaf-ts/transactional-decorators";import{Metadata as ot,Decoration as ct,DefaultFlavour as lt,apply as ut,methodMetadata as pt,DecorationKeys as dt,uses as ht,metadata as gt,propMetadata as ft,prop as yt,description as mt}from"@decaf-ts/decoration";var wt,bt,vt,xt,At;(t=>{t.FIND_BY="findBy",t.SELECT="Select",t.AND="And",t.OR="Or",t.GROUP_BY="GroupBy",t.ORDER_BY="OrderBy",t.THEN="Then",t.THEN_BY="ThenBy"})(wt||(wt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.NOT="NOT",t.IN="IN",t.REGEXP="REGEXP",t.GROUP_BY="group-by",t.COUNT="count",t.SUM="sum",t.MAX="v_max",t.MIN="v_min",t.DISTINCT="distinct"})(bt||(bt={})),(t=>{t.AND="AND",t.OR="OR"})(vt||(vt={})),(t=>{t.LIST_BY="listBy",t.FIND_BY="findBy",t.FIND_ONE_BY="findOneBy",t.PAGE_BY="paginateBy"})(xt||(xt={})),(t=>{t.PERSISTENCE="persistence",t.INDEX="index",t.UNIQUE="unique",t.ADAPTER="adapter",t.INJECTABLE="decaf_{0}_adapter_for_{1}",t.SERVICE="service",t.TABLE="table",t.COLUMN="column",t.METADATA="__metadata",t.OWNERSHIP="ownership",t.CREATED_BY="ownership.created-by",t.UPDATED_BY="ownership.updated-by",t.RELATIONS="__relations",t.RELATION="relation",t.ONE_TO_ONE="relation.one-to-one",t.ONE_TO_MANY="relation.one-to-many",t.MANY_TO_ONE="relation.many-to-one",t.MANY_TO_MANY="relation.many-to-many",t.POPULATE="populate",t.NO_VALIDATE="no-validate",t.MIGRATION="migration",t.STATEMENT="statement",t.QUERY="query",t.UUID="uuid",t.TAG_FOR_DELETION="tag_for_deletion",t.INITIALIZATION="initialization",t.SHUTDOWN="shutdown",t.BY_KEY="by-key",t.AUTH="auth",t.AUTH_ROLE="auth-role",t.DECAF_ROUTE="DecafRoute"})(At||(At={}));const Et=Object.assign({},{ignoreDevSafeGuards:!1}),Ot=Object.assign({},a,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),St=[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Ct=[o.READ,c.READ_ALL],Tt=[At.STATEMENT,xt.FIND_ONE_BY],Nt=[At.QUERY,xt.PAGE_BY,xt.LIST_BY,xt.FIND_BY],kt=[xt.PAGE_BY];class Dt extends nt{constructor(){super()}}class _t extends l{constructor(t){super(t)}pushPending(t,e){const r=this.pending()||{};if(r[t]=r[t]||[],r[t].includes(e))throw new u(`Trying to push a repeated pending ${t} task: ${e}`);r[t].push(e),this.accumulate({pending:r})}getFromChildren(t){const e=this.getOrUndefined(t);if(e)return e;const r=this.getOrUndefined("childContexts");return r&&r.length?r.map(e=>e.getFromChildren(t)).flat().reduce((t,e)=>Object.assign(t,e),{}):void 0}pending(){return this.getFromChildren("pending")}getOrUndefined(t){try{return this.get(t)}catch(t){return}}override(t){return new Proxy(this,{get:(e,r,s)=>"get"===r?new Proxy(e.get,{apply:(e,r,i)=>{const n=i[0];if(!n)throw new u("Invalid property access to overridden context: "+n);return n in t?t[n]:Reflect.apply(e,s,i)}}):Reflect.get(e,r,s)})}toOverrides(){return this.cache.keys().reduce((t,e)=>(t[e]=this.get(e),t),{})}accumulate(t){return super.accumulate(t)}}class $t extends L{logCtx(t,e,r=!1,s){return $t.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static logFrom(t,e,r,s){const i=t.context?e.clear().for(t):e.for(t);return s?i.for(s):i}static logCtx(t,e,r=!1,...s){const i=(t,e,r)=>{const s=e.log||F.get();return e.log=t.context?s.clear().for(t):s.for(t),"string"==typeof r?e.for=t=>Object.assign(e,{log:e.log.for(t)}):e.log=e.log.for(r),e};let n=s.pop();const a=n instanceof _t;if(n&&!a&&(s.push(n),n=void 0),!r&&!a)throw new u("No context provided");if(a&&!r){if(!n)throw new u("Missing context. should be impossible");return i(this,{log:n.logger,ctx:n,ctxArgs:[...s,n]},t)}return async function(...r){if(!this)throw new u("No contextual provided");if(!this.context)throw new u("Invalid contextual provided");return this.context("string"==typeof t?t:t.name,e||{},...r)}.call(this,...[...s,n].filter(Boolean)).then(e=>i(this,{log:e.logger,ctx:e,ctxArgs:[...s,e]},t))}}class Pt extends $t{constructor(){super(),this._Context=_t}get Context(){return this._Context}async context(t,e,...r){this.log.for(this.context).debug(`Creating new context for ${"string"==typeof t?t:t.name} operation with flag overrides: ${Object.keys(e)}`);let s=r.pop();return s instanceof _t||(r.push(s),s=void 0),this.flags,!s||s instanceof this.Context?(new this.Context).accumulate(e):new this.Context(s).accumulate(e)}}class Bt{constructor(){this.observers=[]}count(){return this.observers.length}observe(t,e){if(-1!==this.observers.map(t=>t.observer).indexOf(t))throw new u("Observer already registered");return this.observers.push({observer:t,filter:e}),()=>this.unObserve(t)}unObserve(t){const e=this.observers.map(t=>t.observer).indexOf(t);if(-1===e)throw new u("Failed to find Observer");this.observers.splice(e,1)}async updateObservers(t,e,r,...s){const{log:i,ctxArgs:n}=$t.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:a}=s;if(!a)return!0;try{return a(t,e,r,...n)}catch(t){return i.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(s=>{s.observer.refresh(t,e,r,...n)}))).forEach((t,e)=>{"rejected"===t.status&&i.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class Rt extends u{constructor(t){super(t,Rt.name,500)}}class It extends u{constructor(t,e=It.name){super(t,e,500)}}class Lt extends It{constructor(t){super(t,Lt.name)}}function Ft(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):ot.Symbol(ot.constr(t)).toString().replaceAll(".","-")}function jt(t){return t.reduce((t,e)=>t.then(async t=>[...t,await e()]),Promise.resolve([]))}function Ut(t,e){const{handler:r,args:s}=ot.get(t,o.REFLECT+o.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function Mt(t){return t.then(t=>t.default||t)}function Yt(t,e,r,s){const i=async function(...t){let s;try{s=await Promise.resolve(r.call(this,...t))}catch(t){if(t instanceof Lt)return;throw t}return Promise.resolve(e.apply(this,s))}.bind(t),n=s||e.name;Object.defineProperty(i,"name",{enumerable:!0,configurable:!0,writable:!1,value:n}),t[n]=i}class Gt{generate(t){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)})}static get instance(){return Gt._instance||(Gt._instance=new Gt),Gt._instance}}class zt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return zt._instance||(zt._instance=new zt),zt._instance}}const Ht=ct.flavourResolver.bind(ct);ct.flavourResolver=t=>{try{const e=Ht(t);if(e&&e!==lt)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof ot.registeredFlavour?ot.registeredFlavour(r):void 0;if(s&&s!==lt)return s;const i=qt._currentFlavour;if(i){const t=qt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return lt}};class qt extends Pt{static{this._cache={}}get config(){return this._config}get alias(){return this._alias||this.flavour}repository(){if(!qt._baseRepository)throw new u("This should be overridden when necessary. Otherwise it will be replaced lazily");return qt._baseRepository}async shutdownProxies(t){if(this.proxies){if(t&&!(t in this.proxies))throw new u("No proxy found for "+t);if(t)try{await this.proxies[t].shutdown(),delete this.proxies[t]}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`)}else for(const t in this.proxies){try{await this.proxies[t].shutdown()}catch(e){this.log.error(`Failed to shutdown proxied adapter ${t}: ${e}`);continue}delete this.proxies[t]}}}async shutdown(...t){(await this.logCtx(t,At.SHUTDOWN,!0)).for(this.shutdown),await this.shutdownProxies(),this.dispatch&&await this.dispatch.close()}constructor(t,e,r){if(super(),this._config=t,this.flavour=e,this._alias=r,this.alias in qt._cache)throw new u(`${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} already registered`);qt._cache[this.alias]=this,this.log.info(`Created ${this.alias} persistence adapter ${this._alias?`(${this.flavour}) `:""} persistence adapter`),qt._currentFlavour||(this.log.verbose(`Defined ${this.alias} persistence adapter as current`),qt._currentFlavour=this.alias)}Dispatch(){return new qt._baseDispatch}ObserverHandler(){return new Bt}isReserved(t){return!t}async initialize(...t){}async Sequence(t,e){return new qt._baseSequence(t,this,e)}async flags(t,e,r,...s){if("string"==typeof e)throw new u("Model must be a constructor or array of constructors or undefined. this should be impossible");const i=Array.isArray(e)?e.length?e[0]:void 0:e,n=i?G.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${Gt.instance.generate()}`;const a=r.logger||F.for(this);return Object.assign({},Ot,r,{affectedTables:e?[...new Set([...(Array.isArray(e)?e:[e]).filter(Boolean),...r.affectedTables?Array.isArray(r.affectedTables)?r.affectedTables:[r.affectedTables]:[]])]:r.affectedTables,args:s,writeOperation:St.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?ot.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:a})}get Context(){return _t}async context(t,e,r,...s){this.log.for(this.context).silly(`creating new context for ${t} operation on ${r?Array.isArray(r)?r.map(t=>G.tableName(t)):G.tableName(r):"no"} table ${e&&Object.keys(e)?Object.keys(e).length:"no"} with flag overrides`);let i=s.pop();void 0===i||i instanceof _t||(s.push(i),i=void 0),e=i?Object.assign({},i.toOverrides(),e):e;const n=await this.flags("string"==typeof t?t:t.name,r,e,...[...s,i].filter(Boolean));if(i){if(!(i instanceof this.Context)){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}const e=i.get("operation"),s=i.getOrUndefined("affectedTables");if(e!==t||r&&r!==s){const t=(new this.Context).accumulate({...i.cache,...n,parentContext:i});return i.accumulate({childContexts:[...i.getOrUndefined("childContexts")||[],t]}),t}return i.accumulate(n)}return(new this.Context).accumulate({...n})}prepare(t,...e){const{log:r}=this.logCtx(e,this.prepare),s=t.segregate(),i=Object.entries(s.model).reduce((e,[r,s])=>{if(void 0===s)return e;const i=G.columnName(t.constructor,r);if(this.isReserved(i))throw new u(`Property name ${i} is reserved`);return e[i]=s,e},{});return t[At.METADATA]&&(r.silly("Passing along persistence metadata for "+t[At.METADATA]),Object.defineProperty(i,At.METADATA,{enumerable:!1,writable:!0,configurable:!0,value:t[At.METADATA]})),{record:i,id:t[G.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:a}=this.logCtx(i,this.revert),o=G.pk(e),c=new e;c[o]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[At.METADATA],p=Object.keys(c).filter(t=>t!==o).reduce((r,s)=>(r[s]=t[G.columnName(e,s)],r),c);return a.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in p&&void 0!==p[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);p[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(p,At.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),p}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new p("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new p("Ids and models must have the same length");const a=G.tableName(t);return i.debug(`Creating ${e.length} entries ${a} table`),jt(e.map((e,i)=>()=>this.create(t,e,r[i],...s,n.override({noEmitSingle:!0}))))}async readAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.readAll),n=G.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),jt(e.map(e=>()=>this.read(t,e,...r,i.override({noEmitSingle:!0}))))}async updateAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.updateAll);if(e.length!==r.length)throw new u("Ids and models must have the same length");const a=G.tableName(t);return i.debug(`Updating ${e.length} entries ${a} table`),jt(e.map((e,i)=>()=>this.update(t,e,r[i],...s,n.override({noEmitSingle:!0}))))}async deleteAll(t,e,...r){const{log:s,ctx:i}=this.logCtx(r,this.deleteAll);return s.debug(`Deleting ${e.length} entries from ${t} table`),jt(e.map(e=>()=>this.delete(t,e,...r,i.override({noEmitSingle:!0}))))}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1}),this.observerHandler.observe(t,e);const r=this.log.for(this.observe);return r.silly("Registering new observer "+t.toString()),this.dispatch||(r.verbose("Creating dispatch for "+this.alias),this.dispatch=this.Dispatch(),this.dispatch.observe(this)),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).debug(`Observer ${t.toString()} removed`)}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{ctx:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);if(!i.get("noEmit")){const s=Array.isArray(r),a=!i.get("noEmitSingle"),o=!i.get("noEmitBulk");(s&&o||!s&&a)&&await this.observerHandler.updateObservers(t,e,r,...n)}}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}toString(){return this.flavour+" adapter"}static flavourOf(t){return ot.flavourOf(t)}static get currentFlavour(){if(!qt._currentFlavour)throw new u("No persistence flavour set. Please initialize your adapter");return qt._currentFlavour}static get current(){return qt.get(this.currentFlavour)}static get(t){if(!t)return qt.get(this._currentFlavour);if(t in this._cache)return this._cache[t];throw new u(`No Adapter registered under ${t}.`)}static setCurrent(t){this._currentFlavour=t}static models(t){try{return ot.flavouredAs(t).filter(G.isModel)}catch(t){throw new u(t)}}static decoration(){}get client(){return this._client||(this._client=this.getClient()),this._client}for(t,...e){this.proxies||(this.proxies={});const r=`${this.alias} - ${z(t)}`;if(r in this.proxies)return this.proxies[r];let s;const i=new Proxy(this,{get:(e,r,i)=>{if("_config"===r){const s=Reflect.get(e,r,i);return Object.assign({},s,t)}return"_client"===r?s:Reflect.get(e,r,i)},set:(t,e,r,i)=>"_client"===e?(s=r,!0):Reflect.set(t,e,r,i)});return this.proxies[r]=i,i}migrations(){return ot.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([j(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],qt.prototype,"shutdownProxies",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,_t]),n("design:returntype",Promise)],qt.prototype,"context",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],qt.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],qt.prototype,"unObserve",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],qt.prototype,"client",null);class Qt extends u{constructor(t){super(t,Qt.name,500)}}class Vt extends u{constructor(t){super(t,Vt.name,500)}}class Wt extends G{constructor(t,e,r){super(),this.attr1=void 0,this.operator=void 0,this.comparison=void 0,e||r?(this.attr1=t,this.operator=e,this.comparison=r):G.fromModel(this,t)}and(t){return Wt.and(this,t)}or(t){return Wt.or(this,t)}not(t){return new Wt(this,bt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Wt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(bt).indexOf(this.operator))return{operator:{condition:t}}}if(this.attr1 instanceof Wt){if(!(this.comparison instanceof Wt)&&this.operator!==bt.NOT)return{comparison:{condition:t}};if(-1===Object.values(vt).indexOf(this.operator)&&this.operator!==bt.NOT)return{operator:{condition:t}}}},r=super.hasErrors(...t);return this.isAsync()?(async()=>await Promise.resolve(r)??e())():r??e()}static and(t,e){return Wt.group(t,vt.AND,e)}static or(t,e){return Wt.group(t,vt.OR,e)}static group(t,e,r){return new Wt(t,e,r)}static attribute(t){return(new Wt.Builder).attribute(t)}static attr(t){return this.attribute(t)}static{this.Builder=class{constructor(){this.attr1=void 0,this.operator=void 0,this.comparison=void 0}attribute(t){return this.attr1=t,this}attr(t){return this.attribute(t)}eq(t){return this.setOp(bt.EQUAL,t)}dif(t){return this.setOp(bt.DIFFERENT,t)}gt(t){return this.setOp(bt.BIGGER,t)}lt(t){return this.setOp(bt.SMALLER,t)}gte(t){return this.setOp(bt.BIGGER_EQ,t)}lte(t){return this.setOp(bt.SMALLER_EQ,t)}in(t){return this.setOp(bt.IN,t)}regexp(t){return this.setOp(bt.REGEXP,RegExp(t).source)}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new Wt(this.attr1,this.operator,this.comparison)}catch(t){throw new Qt(t)}}}}static builder(){return new Wt.Builder}static from(t){return new Wt(t)}}var Jt,Xt;i([H(),n("design:type",Object)],Wt.prototype,"attr1",void 0),i([H(),n("design:type",String)],Wt.prototype,"operator",void 0),i([H(),n("design:type",Object)],Wt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(Jt||(Jt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(Xt||(Xt={}));const Zt={update:Xt.CASCADE,delete:Xt.NONE},Kt={Equals:(t,e)=>Wt.attribute(t).eq(e),Diff:(t,e)=>Wt.attribute(t).dif(e),LessThan:(t,e)=>Wt.attribute(t).lt(e),LessThanEqual:(t,e)=>Wt.attribute(t).lte(e),GreaterThan:(t,e)=>Wt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>Wt.attribute(t).gte(e),In:(t,e)=>Wt.attribute(t).in(e),Matches:(t,e)=>Wt.attribute(t).regexp(e)},te=t=>t.charAt(0).toLowerCase()+t.slice(1);class ee extends L{static get log(){return this._logger||(this._logger=F.for(ee.name)),this._logger}static build(t,...e){if(!t.startsWith(wt.FIND_BY))throw Error("Unsupported method "+t);const r=this.extractCore(t),s=this.extractSelect(t),i=this.extractGroupBy(t),n=this.buildWhere(r,e),{orderBy:a,limit:o,offset:c}=this.extractOrderLimitOffset(t,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:a,limit:o,offset:c}}static extractCore(t){const e=t.substring(wt.FIND_BY.length),r=e.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return r?e.substring(0,r.index):e}static getFieldsFromMethodName(t){return(this.extractCore(t).split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/).map(t=>{const{operator:e,field:r}=this.parseFieldAndOperator(t);return r+(e??"")})}static extractSelect(t){const e=t.indexOf(wt.SELECT);if(-1===e)return;const r=t.substring(e+wt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(wt.AND).map(te).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(wt.GROUP_BY);if(-1!==e)return t.substring(e+wt.GROUP_BY.length).split(wt.ORDER_BY)[0].split(wt.THEN_BY).map(te).filter(Boolean)}static buildWhere(t,e){if(!t&&0===e.length)return;const r=(t.split(/OrderBy|GroupBy/)[0]||"").split(/And|Or/),s=t.match(/And|Or/g)||[];let i;if(r.forEach((t,r)=>{const{field:n,operator:a}=this.parseFieldAndOperator(t),o=a?Kt[a]:Kt.Equals;if(!o)throw Error("Unsupported operator "+a);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=o(n,c);i=0===r?l:s[r-1]===wt.AND?i.and(l):i.or(l)}),0!==r.length){if(!i)throw Error("No conditions found in method name");return i}}static parseFieldAndOperator(t){for(const e of Object.keys(Kt))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:te(r),operator:e}}return{field:te(t)}}static extractOrderByField(t){const e=t.match(/OrderBy(.+)$/);if(!e)return;const r=e[1];return r.charAt(0).toLowerCase()+r.slice(1)}static getProperlyOrderByOrThrow(t,e){const r=ee.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new Qt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(Jt).includes(e))throw new Qt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(Jt).join(", ")}.`);return[[t,e]]}r.debug("Ignoring OrderBy clause because direction is undefined.")}}static extractOrderLimitOffset(t,e){const r=this.extractCore(t).split(/And|Or/).length,s=e.slice(r)??[];let i,n,a;if(s.at(-1)instanceof l&&s.pop(),s.length>=1){const e=s[0],r=this.extractOrderByField(t);i=this.getProperlyOrderByOrThrow(r,e)}return 2>s.length||"number"!=typeof s[1]||(n=s[1]),3>s.length||"number"!=typeof s[2]||(a=s[2]),{orderBy:i,limit:n,offset:a}}}function re(){return ct.for(At.STATEMENT).define({decorator:()=>(t,e,r)=>ut(pt(ot.key(At.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function se(t={}){return ct.for(At.QUERY).define({decorator:t=>(e,r,s)=>{const i=ee.getFieldsFromMethodName(r);return ut(pt(ot.key(At.QUERY,r),{...t,fields:i}),re(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:a,orderBy:o,limit:c,offset:l}=ee.build(e.name,...s);let u=r.select(i);n&&(u=u.where(n));const{allowLimit:p,allowOffset:d,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(o||[])[0],allowed:h},{key:"limit",value:c,allowed:p},{key:"offset",value:l,allowed:d}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new Qt(t.key[0].toUpperCase()+t.key.slice(1)+" is not allowed for this query");t.allowed&&(u=u[t.key](t.value))}return u.execute()}})})(t))(e,r,s)},args:[t]}).apply()}function ie(t){return ue(t,[o.CREATE,c.CREATE_ALL])}function ne(t){return ue(t,[o.UPDATE,c.UPDATE_ALL])}function ae(t){return ue(t,[o.DELETE,c.DELETE_ALL])}function oe(t){return ue(t,St)}function ce(t){return ue(t,Object.values(o))}function le(t){return ue(t,Object.values(c))}function ue(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:a}=$t.prototype.logCtx(n,ue);return a.silly(`filtering ${s} event for${r?" "+(G.tableName(r)||r):""} ${i}`),("string"==typeof r?r===G.tableName(t)||r===t.constructor.name:ot.constr(t)===ot.constr(r))&&e.includes(s)}}const pe={onlyOnCreate:ie,onlyOnUpdate:ne,onlyOnDelete:ae,onlyOnTransactional:oe,onlyOnSingle:ce,onlyOnBulk:le};function de(t){const e=Object.assign({},pe);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}class he extends d{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 u("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=G.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return de(this)}constructor(t,e,...r){super(e),this.observers=[],this._overrides={ignoreHandlers:!1,ignoreValidation:!1,allowGenerationOverride:!1,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,ignoreDevSafeGuards:!1,mergeForUpdate:!0,applyUpdateValidation:!0},t&&(this._adapter=t),e&&(he.register(e,this,this.adapter.alias),t)&&ot.get(e,dt.FLAVOUR)===lt&&ht(t.flavour)(e);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;h(s,s[e+"Prefix"],t,s[e+"Suffix"])}),g(s,s[this.updateAll.name+"Prefix"],this.updateAll,s[this.updateAll.name+"Suffix"])}logCtx(t,e,r=!1,s){const i=this.adapter.logCtx([this.class,...t],e,r,Object.assign({},s||{},this._overrides||{}));function n(t){return t.ctxArgs.shift(),t}return i instanceof Promise?i.then(n):n(i)}override(t){return new Proxy(this,{get:(e,r,s)=>{const i=Reflect.get(e,r,s);return"_overrides"!==r?i:Object.assign({},i,t)}})}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"adapter"===s?this.adapter.for(t,...e):Reflect.get(r,s,i)})}ObserverHandler(){return new Bt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${a}`),t=new this.class(t),n||await f(this,r,t,o.CREATE,o.ON),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new p(s.toString())}return[t,...s]}async create(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);s.debug(`Creating new ${this.class.name} in table ${G.tableName(this.class)}`);let{record:n,id:a,transient:o}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,a,n,...i),this.adapter.revert(n,this.class,a,o,r)}async createAll(t,...e){if(!t.length)return t;const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.createAll);s.debug(`Creating ${t.length} new ${this.class.name} in table ${G.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),a=n.map(t=>t.id);let o=n.map(t=>t.record);return o=await this.adapter.createAll(this.class,a,o,...i),o.map((t,e)=>this.adapter.revert(t,this.class,a[e],r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async createAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${a}`),!t.length)return[t,...s];const l=G.sequenceFor(t[0]);let d=[];if(G.generatedBySequence(this.class)?(l.name||(l.name=G.sequenceName(t[0],"pk")),d=await(await this.adapter.Sequence(l)).range(t.length,...s)):G.generated(this.class,this.pk)||(d=t.map((t,e)=>{if(void 0===t[this.pk])throw new u("Primary key is not defined for model in position "+e);return t[this.pk]})),t=await Promise.all(t.map(async(t,e)=>(t=new this.class(t),l.type&&(t[this.pk]="String"!==l.type||l.generated?d[e]:""+t[this.pk]),n||await f(this,r,t,o.CREATE,o.ON),t))),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.all(t.map(t=>Promise.resolve(t.hasErrors(...e)))),n=y(s);if(n)throw new p(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const a=new this.class;return a[this.pk]=t,n||await f(this,r,a,o.READ,o.ON),[t,...s]}async read(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.read);s.debug(`reading ${this.class.name} from table ${G.tableName(this.class)} with pk ${this.pk}`);const n=await this.adapter.read(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async readAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAllPrefix),n=r.get("ignoreHandlers");return i.silly("handlerSetting: "+n),n||await Promise.all(t.map(async t=>{const e=new this.class;return e[this.pk]=t,f(this,r,e,o.READ,o.ON)})),[t,...s]}async readAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.readAll);return s.debug(`reading ${t.length} ${this.class.name} in table ${G.tableName(this.class)}`),(await this.adapter.readAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}async update(t,...e){const{ctxArgs:r,log:s,ctx:i}=this.logCtx(e,this.update);let{record:n,id:a,transient:o}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${G.tableName(this.class)} with id ${a}`),n=await this.adapter.update(this.class,a,n,...r),this.adapter.revert(n,this.class,a,o,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${a}`);const c=t[this.pk];if(!c)throw new u("No value for the Id is defined under the property "+this.pk);let l;if(r.get("applyUpdateValidation")&&(l=await this.read(c,r),r.get("mergeForUpdate")&&(t=G.merge(l,t,this.class))),n||await f(this,r,t,o.UPDATE,o.ON,l),!a){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new p(s.toString())}return[t,...s,l]}async updateAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.updateAll);s.verbose(`Updating ${t.length} new ${this.class.name} in table ${G.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r));return(await this.adapter.updateAll(this.class,n.map(t=>t.id),n.map(t=>t.record),...i)).map((t,e)=>this.adapter.revert(t,this.class,n[e].id,r.get("rebuildWithTransient")?n[e].transient:void 0,r))}async updateAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAllPrefix),n=r.get("ignoreHandlers"),a=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${a}`);const l=t.map(t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e});let d;if(r.get("applyUpdateValidation")&&(d=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>G.merge(d[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>f(this,r,t,o.UPDATE,o.ON,d?d[e]:void 0))),!a){const e=r.get("ignoredValidationProperties")||[];let s;i.silly("ignored validation properties: "+e),s=r.get("applyUpdateValidation")?await Promise.all(t.map((t,r)=>Promise.resolve(t.hasErrors(d[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=y(s);if(n)throw new p(n)}return[t,...s,d]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,o.DELETE,!0)).for(this.deletePrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.read(t,...s);await f(this,r,e,o.DELETE,o.ON)}return[t,...s]}async delete(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.delete);s.debug(`deleting new ${this.class.name} in table ${G.tableName(this.class)} with pk ${t}`);const n=await this.adapter.delete(this.class,t,...i);return this.adapter.revert(n,this.class,t,void 0,r)}async deleteAllPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAllPrefix),n=r.get("ignoreHandlers");if(i.silly("handlerSetting: "+n),!n){const e=await this.readAll(t,...s);await Promise.all(e.map(async t=>f(this,r,t,o.DELETE,o.ON)))}return[t,...s]}async deleteAll(t,...e){const{ctx:r,log:s,ctxArgs:i}=this.logCtx(e,this.create);return s.debug(`deleting ${t.length} ${this.class.name} in table ${G.tableName(this.class)}`),(await this.adapter.deleteAll(this.class,t,...i)).map((e,s)=>this.adapter.revert(e,this.class,t[s],void 0,r))}select(t){return this.adapter.Statement(this._overrides).select(t).from(this.class)}async query(t,e,r=Jt.ASC,s,i,...n){const{ctxArgs:a}=(await this.logCtx(n,At.QUERY,!0)).for(this.query),o=[e,r],c=this.select().where(t).orderBy(o);return s&&c.limit(s),i&&c.offset(i),c.execute(...a)}async listBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,xt.LIST_BY,!0)).for(this.listBy);return s.verbose(`listing ${G.tableName(this.class)} by ${t} ${e}`),this.select().orderBy([t,e]).execute(...i)}async paginateBy(t,e,r={offset:1,limit:10},...s){const i=r.offset||1,{offset:n,bookmark:a,limit:o}=r;if(!n&&!a)throw new Qt("PaginateBy needs a page or a bookmark");const{log:c,ctx:l,ctxArgs:u}=(await this.logCtx(s,xt.PAGE_BY,!0)).for(this.paginateBy);let p;if(c.verbose(`paginating ${G.tableName(this.class)} with page size ${o}`),a&&l.get("paginateByBookmark"))p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===Jt.ASC?this.attr(G.pk(this.class)).gt(a):this.attr(G.pk(this.class)).lt(a))()).orderBy([t,e]).paginate(o,...u);else{if(!n)throw new Qt("PaginateBy needs a page or a bookmark");p=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(o,...u)}const d=await p.page(i,a,...u);return p.serialize(d)}async findOneBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,xt.FIND_ONE_BY,!0)).for(this.findOneBy);s.verbose(`finding ${G.tableName(this.class)} with ${t} ${e}`);const n=await this.select().where(this.attr(t).eq(e)).limit(1).execute(...i);if(!n.length)throw new m("No results found");return n[0]}async findBy(t,e,...r){const{log:s,ctxArgs:i}=(await this.logCtx(r,xt.FIND_BY,!0)).for(this.findBy);return s.verbose(`finding ${G.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async statement(t,...e){if(!he.statements(this,t))throw new Qt("Invalid prepared statement requested "+t);const{log:r,ctxArgs:s}=(await this.logCtx(e,At.STATEMENT,!0)).for(this.statement);return r.verbose("Executing prepared statement "+t),this[t](...s)}attr(t){return Wt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=G.tableName(this.class);return this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:ot.constr(t)===ot.constr(this.class)),r.verbose(`now observing ${this.adapter} filtering on table === ${s}`),this.observerHandler.observe(t,e),r.verbose("Registered new observer "+t.toString()),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");this.observerHandler.unObserve(t),this.log.for(this.unObserve).verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(this.log.verbose(`No more observers registered for ${this.adapter}, unsubscribing`),this.adapter.unObserve(this),this.log.verbose("No longer observing adapter "+this.adapter.flavour))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,Array.isArray(r)?r.map(t=>qt._baseSequence.parseValue(G.sequenceFor(this.class).type,t)):qt._baseSequence.parseValue(G.sequenceFor(this.class).type,r),...n)}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}static forModel(t,e,...r){let s;const i=e||ot.flavourOf(t)||qt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof he)return s;const n=e||ot.flavourOf(t)||s&&ot.get(s,At.ADAPTER)||qt.currentFlavour,a=n?qt.get(n):void 0;if(!a)throw new u("No registered persistence adapter found flavour "+n);return s=s||a.repository(),new s(a,t,...r)}static get(t,e){const r=G.tableName(t);let s=r;if(e&&(s=[r,e].join(w)),s in this._cache)return this._cache[s];if(r in this._cache)return this._cache[r];throw new u("Could not find repository registered under "+r)}static register(t,e,r){let s=G.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof he)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof he?t.constructor:t,s=ot.get(r,e?ot.key(At.STATEMENT,e):At.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof he?t.constructor:t;return ot.get(r,e?ot.key(At.QUERY,e):At.QUERY)}}function ge(t,e){if(!(e||(e=ct.flavourResolver(t instanceof G?t.constructor:t))&&e!==lt))throw new u("Could not retrieve flavour from model "+(t instanceof G?t.constructor.name:t.name));return q(At.INJECTABLE,e,G.tableName(t))}i([re(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],he.prototype,"listBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],he.prototype,"paginateBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],he.prototype,"findOneBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],he.prototype,"findBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],he.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],he.prototype,"unObserve",null),qt&&(qt._baseRepository=he);class fe extends t{get log(){return this.logger||(this.logger=F.for(this)),this.logger}constructor(){super()}get(t,r){const s=this.log.for(this.get);let i;try{i=super.get(t)}catch{}if(!i){let n;if("function"==typeof t?n=G.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=G.get(t.toString())),!n)return;const a=At.ADAPTER,o=r||ot.get(n,a);try{let t=o;try{o&&qt.get(o)}catch{const e=qt.current;e&&e.flavour===o&&(t=e.alias)}if(i=he.forModel(n,t),i instanceof he)return i;const r=o||ot.get(i.constructor,a)||ot.get(n,a);e.register(i,ge(n,r))}catch(t){s.debug("No registered repository or adapter found. falling back to default adapter. Error: "+(t?.message||JSON.stringify(t)));const e=he.get(n,o);if("function"==typeof e){const t=o?qt.get(o):qt.current;if(!t)return;return new e(t,n)}}}return i}}var ye,me,we,be,ve;(t=>{t.PENDING="pending",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(ye||(ye={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(me||(me={})),(t=>{t.NONE="none",t.FULL="full"})(we||(we={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(be||(be={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(ve||(ve={}));const xe="tasks",Ae={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};ot.tasks=(()=>ot.innerGet(Symbol.for(xe))).bind(ot),ot.taskFor=(t=>{const e=ot.tasks();return e?e[t]:void 0}).bind(ot),ot.validationExceptions=((t,e)=>{const r=ot.get(t,At.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t);let i=[];return e!==o.CREATE&&e!==o.UPDATE||(i=G.nestedRelations(t)),[...new Set([...s,...i])]}).bind(ot),ot.migrationsFor=(t=>{if(!(t=t??qt.current))throw new u("Could not get adapter for migrations");return ot.innerGet(Symbol.for(At.MIGRATION),t.alias).map(t=>t.class)}).bind(ot),ot.migrations=(()=>{const t=ot.innerGet(Symbol.for([At.MIGRATION,At.BY_KEY].join("-")));return Object.values(t).flat().map(t=>[t.class.name,t.class])}).bind(ot),ot.relations=((t,e)=>{const r=ot.get(t,At.RELATIONS);if(r){if(!e)return Object.keys(r);if(!r[e])throw new u("No relations metadata found for property "+e);return r[e]}}).bind(ot),G.relations=(t,e)=>ot.relations(t instanceof G?t.constructor:t,e)||[],G.nestedRelations=((t,e=[])=>{let r=[];const s=ot.get(t,At.RELATIONS);if(!s||!Object.keys(s).length)return[...new Set([...e])];for(const t in s){const i=s[t];if(i?.class&&G.relations(i.class)){const s=G.relations(i.class).map(e=>`${t}.${e}`);e=[...e,...s],r=G.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(G),G.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!G.sequenceFor(r).generated}).bind(G),G.fromTable=(t=>{const e=ot.innerGet(Symbol.for(At.TABLE));if(!e||!e[t]||!G.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return G.get(e[t].name)}).bind(G),ot.createdBy=(t=>{const e=ot.get("function"!=typeof t?t.constructor:t,At.CREATED_BY);if(!e)throw new u("No createdBy metadata found for model. did you use @createdBy()?");return e}).bind(ot),ot.updatedBy=(t=>{const e=ot.get("function"!=typeof t?t.constructor:t,At.UPDATED_BY);if(!e)throw new u("No updatedBy metadata found for model. did you use @updatedBy()?");return e}).bind(ot),G.tableName=t=>{if(!(t instanceof G?G.get(t.constructor.name):t))throw new u("Unable to find model "+t);return ot.get(t instanceof G?t.constructor:t,At.TABLE)||(t instanceof G?t.constructor.name:t.name)},G.columnName=(t,e)=>ot.get(t instanceof G?t.constructor:t,ot.key(At.COLUMN,e))||e,G.sequenceName=(t,...e)=>[G.tableName(t),...e].join("_"),G.sequenceFor=(t,e)=>{if(e)throw new Rt("not currently supported");const r=G.pkProps(t instanceof G?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},G.indexes=t=>{const e=ot.get(t instanceof G?t.constructor:t,At.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[At.INDEX]:e[r]},t),{})},e.services=()=>ot.innerGet(Symbol.for(At.SERVICE)),e.repositories=()=>ot.innerGet(Symbol.for(b.REPOSITORY));class Ee extends $t{constructor(){super()}logCtx(t,e,r=!1){if(!this.adapter)throw new u("Adapter not set yet");return this.adapter.logCtx(t,e,r)}async initialize(...t){if(!this.adapter)return void this.log.for(this.initialize).verbose("No adapter observed for dispatch; skipping initialization");const{log:e}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.initialize);e.verbose(`Initializing ${this.adapter}'s event Dispatch`);const r=this.adapter;[o.CREATE,o.UPDATE,o.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL].forEach(t=>{if(!r[t])throw new u(`Method ${t} not found in ${r.alias} adapter to bind Observables Dispatch`);let e=Object.getOwnPropertyDescriptor(r,t),s=r;for(;!e&&s!==Object.prototype;)s=Object.getPrototypeOf(s),e=Object.getOwnPropertyDescriptor(s,t);function i(t){switch(t){case c.CREATE_ALL:return o.CREATE;case c.UPDATE_ALL:return o.UPDATE;case c.DELETE_ALL:return o.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:a,ctx:o}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,p=await e.call(r,c,l,u,...a),d=[c,i(t),l];return o.get("observeFullResult")&&d.push(p),this.updateObservers(...d,...a).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`)),p}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof qt))throw new Rt("Only Adapters can be observed by dispatch");return this.adapter=t,this.models=qt.models(this.adapter.alias),this.initialize().then(()=>this.log.verbose(`Dispatch initialized for ${this.adapter.alias} adapter`)),()=>this.unObserve(t)}unObserve(t){if(this.adapter!==t)throw new Rt("Only the adapter that was used to observe can be unobserved");this.adapter=void 0}async updateObservers(t,e,r,...s){if(!t)throw new u("Model must be provided for observer update");const i=t&&"string"==typeof t?t:G.tableName(t),{log:n,ctxArgs:a,ctx:o}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${o.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...a)}catch(t){throw new u("Failed to refresh dispatch: "+t)}else n.verbose(`No adapter observed for dispatch; skipping observer update for ${i}:${e}`)}toString(){return(this.adapter?this.adapter.toString():"uninitialized")+" event dispatch"}}async function Oe(t,e,r,s){if(t.get("allowGenerationOverride")&&void 0!==s[r])return;let{seed:i,args:n}=e;i&&"function"==typeof i&&(i=i(s,...n||[],t)),s[r]=await Gt.instance.generate(i)}function Se(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=At.UUID;return ct.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[H(),v(At.UUID),x(Oe,s,{priority:54})];return t&&i.push(A(Oe,s,{priority:54})),t||i.push(E()),ut(...i)},args:[t,e,...r]}).apply()}async function Ce(t,e,r,s,i){const n=e.logger.for(Ce);if(!s){const e=G.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=he.forModel(e,r),n.info("Retrieved "+s.toString())}let a;if(s=i?s.override(i):s,void 0===t[G.pk(s.class)])n.info(`No pk found in ${G.tableName(s.class)} - creating`),a=await s.create(t,e);else{n.info(`pk found in ${G.tableName(s.class)} - attempting update`);try{a=await s.update(t,e),n.info("Updated "+G.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+G.tableName(s.class)),a=await s.create(t,e)}n.info("After create update: "+a)}return a}async function Te(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=je(s,r,this.adapter.alias),n=await e.read(i,t);return await Re(t,s,r,i,n),void(s[r]=i)}const n="function"!=typeof e.class||e.class.name?e.class:e.class();if(!n)throw new u("Could not find model "+e.class);const a=he.forModel(n,this.adapter.alias),o=await a.override(this._overrides).create(i,t),c=G.pk(o);await Re(t,s,r,o[c],o),s[r]=o[c]}async function Ne(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Xt.CASCADE)return;if("object"!=typeof i){const e=je(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Re(t,s,r,i,n),void(s[r]=i)}const n=await Ce(s[r],t,this.adapter.alias,void 0,this._overrides),a=G.pk(n);await Re(t,s,r,n[a],n),s[r]=n[a]}async function ke(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Xt.CASCADE)return;const n=je(s,r,this.adapter.alias);let a;a=i instanceof G?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Re(t,s,r,a[n.pk],a)}async function De(t,e,r,s){const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a=t.logger.for(De),o=new Set([...i]);if("object"!==n){const e=je(s,r,this.adapter.alias),i=await e.readAll([...o.values()],t);for(let e=0;e<i.length;e++){const s=i[e];a.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await Re(t,s,r,[...o.values()][e],i)}return s[r]=[...o],void a.info("SET ONE TO MANY IDS: "+s[r])}const c=G.pk(i[0].constructor),l=new Set;for(const e of i){a.info("Creating or updating one-to-many model: "+JSON.stringify(e));const i=await Ce(e,t,this.adapter.alias,void 0,this._overrides);a.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Re(t,s,r,i[c],i),a.info("Creating or updating one-to-many model: "+JSON.stringify(e)),l.add(i[c])}s[r]=[...l]}async function _e(t,e,r,s){const{cascade:i}=e;if(i.update===Xt.CASCADE)return De.call(this,t,e,r,s)}async function $e(t,e,r,s){if(e.cascade.delete!==Xt.CASCADE)return;const i=s[r];if(!i||!i.length)return;const n=typeof i[0];if(!i.every(t=>typeof t===n))throw new u(`Invalid operation. All elements of property ${r} must match the same type.`);const a="function"!=typeof e.class||e.class.name?e.class:e.class(),o="object"===n,c=o?he.forModel(a,this.adapter.alias):je(s,r,this.adapter.alias),l=[...new Set([...o?i.map(t=>t[c.pk]):i]).values()];let p,d;try{p=await c.deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<p.length;e++){d=p[e];try{await Re(t,s,r,l[e],d)}catch(i){throw t.logger.error(`Failed to cache record ${l[e]} with key ${r} and model ${JSON.stringify(s,void 0,2)} `,i),i}}s[r]=l}function Pe(t,e,r){return[At.POPULATE,t,e,r].join(".")}function Be(t,e,r){return[At.TAG_FOR_DELETION,t,r].join(".")}async function Re(t,e,r,s,i){const n=Pe(e.constructor.name,r,s),a=t.get("cacheForPopulate")||{};return a[n]=i,t.accumulate({cacheForPopulate:a})}async function Ie(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const a=await(async(e,r,s,i)=>{let n,a;const o=[],c=e.get("cacheForPopulate")||{};for(const e of i){n=Pe(r.constructor.name,s,e);try{if(a=c[n],!a)throw Error("Not found in cache")}catch(i){const n=je(r,s);if(!n)throw new u("Could not find repo");a=await n.read(e,t)}o.push(a)}return o})(t,s,r,n?i:[i]);s[r]=n?a:a[0]}async function Le(t,e,r,s,i){if(e.cascade.update!==Xt.CASCADE)return;const n=s[r];if(void 0===n||Array.isArray(n)&&0===n.length)return;if(!i)throw new u("No way to compare old model. do you have updateValidation and mergeModels enabled?");function a(t){return Array.isArray(t)?t.map(a):"object"!=typeof t?t:t[G.pk(t)]}const o=a(s[r]),c=a(i[r]);if(void 0===c||Q(o,c))return;if(Array.isArray(o)!==Array.isArray(c))throw new u("Cannot cascade update for different array types");const l=(Array.isArray(o)?o:[o]).filter(Boolean),p=(Array.isArray(c)?c:[c]).filter(Boolean).filter(t=>!l.includes(t)),d=je(s,r);if(!d)throw new u("Could not find repo");try{const e=await d.deleteAll(p,t);t.logger.debug(`Deleted ${e.length} entries from table ${G.tableName(d.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}qt&&(qt._baseDispatch=Ee);const Fe=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function je(t,e,r){if(!t)throw Error("No model was provided to get repository");let s;if(Array.isArray(t[e])||t[e]instanceof Set){const r=ot.get(t instanceof G?t.constructor:t,ot.key(V.REFLECT,e,V.LIST))?.clazz;if(!r)throw new u("Failed to find types decorators for property "+e);s=(Array.isArray(r)?[...r]:[r]).map(t=>"function"!=typeof t||t.name?t:t())}else s=ot.getPropDesignTypes(t instanceof G?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Fe.includes((""+t.name).toLowerCase()));return he.forModel(i,r)}class Ue extends O{constructor(t,e=Ue.name,r=401){super(t,e,r)}}class Me extends Ue{constructor(t,e=Me.name){super(t,e,403)}}class Ye extends u{constructor(t){super(t,Ye.name,503)}}function Ge(t){return ct.for(At.TABLE).define({decorator:t=>e=>(ot.set(At.TABLE,t||e.name.toLowerCase(),e),gt(At.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function ze(t){return ct.for(At.COLUMN).define({decorator:t=>(e,r)=>ft(ot.key(At.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function He(t,e,r){return ct.for(At.INDEX).define({decorator:(t,e,r)=>(s,i)=>("string"==typeof t&&(r=t,t=void 0,e=void 0),"string"==typeof e&&(r=e,e=void 0),!e&&t&&t.find(t=>![Jt.ASC,Jt.DSC].includes(t))&&(e=t,t=void 0),ft(ot.key(`${At.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function qe(t,e,r,s){if(s[r]&&(await this.select().where(Wt.attribute(r).eq(s[r])).execute()).length)throw new C(`model already exists with property ${r} equal to ${JSON.stringify(s[r],void 0,2)}`)}function Qe(){const t=At.UNIQUE;return ct.for(t).define(W(),T(qe),ft(t,{})).apply()}async function Ve(t,e,r,s){throw new Ue("This adapter does not support user identification")}function We(){return ct.for(At.CREATED_BY).define({decorator:()=>(t,e)=>ut(x(Ve),ft(At.CREATED_BY,e),v(At.CREATED_BY))(t,e),args:[]}).apply()}function Je(){return ct.for(At.UPDATED_BY).define({decorator:()=>(t,e)=>ut(A(Ve),ft(At.UPDATED_BY,e),v(At.UPDATED_BY))(t,e),args:[]}).apply()}function Xe(){return N([o.CREATE])}function Ze(){return N()}function Ke(t){const e="function"==typeof t&&t.name?t:t(),r=G.pk(e);return ot.allowedTypes(e,r)||[]}function tr(t,e=Zt,r=!0,s,i){const n=At.ONE_TO_ONE;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),J([t,...o]),x(Te,a,{priority:70}),A(Ne,a,{priority:70}),k(ke,a,{priority:70}),D(Le,a,{priority:70}),_(Ie,a,{priority:70})];return ut(...c)},args:[t,e,r,s,i]}).apply()}function er(t,e=Zt,r=!0,s,i){const n=At.ONE_TO_MANY;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),X([t,...o]),x(De,a,{priority:70}),A(_e,a,{priority:70}),k($e,a,{priority:70}),D(Le,a,{priority:70}),_(Ie,a,{priority:70})];return ut(...c)},args:[t,e,r,s,i]}).apply()}function rr(t,e=Zt,r=!0,s,i){const n=At.MANY_TO_ONE;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),J([t,...o])];return ut(...c)},args:[t,e,r,s,i]}).apply()}function sr(t,e=Zt,r=!0,s,i){const n=At.MANY_TO_MANY;return ct.for(n).define({decorator:(t,e,r,s,i)=>{const a={class:t,cascade:e,populate:r};s&&(a.joinTable=s),i&&(a.name=i);const o=Ke(t),c=[yt(),cr(n,a),X([t,...o])];return ut(...c)},args:[t,e,r,s,i]}).apply()}function ir(...t){return(e,r)=>{const s=ot.get(e,ot.key(At.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return ut(gt(ot.key(At.NO_VALIDATE,r),i))(e,r)}}function nr(){return ir(o.CREATE)}function ar(){return ir(o.UPDATE)}function or(){return ir(o.UPDATE,o.CREATE)}function cr(t,e){return ct.for(At.RELATIONS).define({decorator:(t,e)=>(r,s)=>(ft(t,e)(r,s),ft(ot.key(At.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class lr extends G{constructor(t){super(t)}}i([Xe(),n("design:type",Date)],lr.prototype,"createdAt",void 0),i([Ze(),n("design:type",Date)],lr.prototype,"updatedAt",void 0);const ur={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},pr=ur,dr={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},hr=Object.assign({},dr,{type:"BigInt"});async function gr(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=G.sequenceName(s,"pk"));try{i=await this.adapter.Sequence(e,this._overrides)}catch(t){throw new u(`Failed to instantiate Sequence ${e.name}: ${t}`)}var n,a,o;n=s,a=r,o=await i.next(t),Reflect.set(n,a,o)}function fr(t,e){return(r,s)=>{if(yt()(r,s),!t.type){const e=ot.type(r.constructor,s);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 i=[yt(),He([Jt.ASC,Jt.DSC]),H(),E(),ft(ot.key(b.ID,s),t),x(gr,t,e)];return t.generated&&i.push(v()),ut(...i)(r,s)}}function yr(t){const e=Object.assign({},pr);return delete e.generated,t=Object.assign({},e,t),ct.for(b.ID).define({decorator:fr,args:[t,{priority:60}]}).apply()}let mr=class extends lr{constructor(t){super(t)}};i([yr({type:String,generated:!1}),n("design:type",String)],mr.prototype,"id",void 0),i([H(),He(),n("design:type",Object)],mr.prototype,"current",void 0),mr=i([Ge("??sequence"),Z(),n("design:paramtypes",[Object])],mr);class wr extends $t{static{this.lock=new at}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=he.forModel(mr,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,o.READ,!0),{name:s,startWith:i}=this.options;try{const t=await this.repo.read(s,r);return this.parse(t.current)}catch(t){if(t instanceof m){if(e.debug(`Sequence.current missing ${s}, returning startWith=${i}`),void 0===i)throw new u("Starting value is not defined for a non existing sequence");try{return this.parse(i)}catch(t){throw new u(`Failed to parse initial value for sequence ${i}: ${t}`)}}throw new u(`Failed to retrieve current value for sequence ${s}: ${t}`)}}async increment(t,e){const{log:r,ctx:s}=this.adapter.logCtx([e],this.increment),{type:i,incrementBy:n,name:a}=this.options;if(!a)throw new u("Sequence name is required");return wr.lock.execute(async()=>{const e=t||n;if(e%n!==0)throw new u("Value to increment does not consider the incrementBy setting: "+n);const o="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new mr({id:a,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${a} current=${c} next=${t}`),this.repo.create(new mr({id:a,current:t}),s);throw e}};if("uuid"===o)for(;;){const t=await Promise.resolve(Gt.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${a} current=${c} next=${t}`),e.current}catch(t){if(t instanceof C)continue;throw t}}const p=await(async t=>{switch(o){case Number.name:return this.parse(t)+e;case BigInt.name:return this.parse(t)+BigInt(e);case String.name:return this.parse(t);case"serial":return await Promise.resolve(zt.instance.generate(t));default:throw new u("Should never happen")}})(c),d=await l(p);return r.debug(`Sequence.increment ${a} current=${c} next=${p}`),d.current},a)}async next(...t){const{ctx:e}=(await this.logCtx(t,o.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,o.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Rt(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),a=await this.increment(this.parse(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(a-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==a&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return wr.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([mr,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return G.sequenceName(t,"pk")}static parseValue(t,e){switch("function"==typeof t&&t?.name?t.name:t){case Number.name||Number.name.toLowerCase():return"string"==typeof e?parseInt(e):"number"==typeof e?e:BigInt(e);case BigInt.name||BigInt.name.toLowerCase():return BigInt(e);case String.name||String.name.toLowerCase():return e.toString();case void 0:case"uuid":case"serial":return e;default:throw new Rt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function br(t,e){return(i,n)=>n?r(ot.constr(t))(i,n):(ot.set(b.REPOSITORY,ot.key(e||qt.currentFlavour,G.tableName(t)),i),gt(b.REPOSITORY,i.name)(t),e=e||ot.get(i.constructor,At.ADAPTER),he.register(t,i,e),s(ot.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}qt._baseSequence=wr;class vr extends u{constructor(t){super(t,vr.name,500)}}class xr extends L{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,Yt(this,this.page,this.pagePrefix,this.page.name)}isPreparedStatement(){const t=this.query;return t.method&&t.method.match(RegExp(`${xt.FIND_BY}|${xt.LIST_BY}`,"gi"))}async pagePrefix(t,...e){const{ctxArgs:r}=(await this.adapter.logCtx([this.clazz,...e],xt.PAGE_BY,!0)).for(this.pagePrefix);return r.shift(),[t,...r]}async pagePrepared(t,e,...r){const{log:s,ctxArgs:i}=this.adapter.logCtx(!e||e instanceof _t?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof _t||(this._bookmark=e);const n=he.forModel(this.clazz,this.adapter.alias),a=this.query,{method:o,args:c,params:l}=a,u=RegExp(`^${xt.FIND_BY}|${xt.LIST_BY}`,"gi");if(!o.match(u))throw new Rt(`Method ${o} is not supported for pagination`);u.lastIndex=0;const p=o.replace(u,xt.PAGE_BY),d=[p,...c];let h={limit:this.size,offset:t,bookmark:this._bookmark};p!==xt.PAGE_BY||d.length>2?h={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:d.push(l.direction),d.push(h);const g=await n.statement(...d,...i);return this.apply(g)}async next(...t){return this.page(this.current+1,...t)}async previous(...t){return this.page(this.current-1,...t)}validatePage(t){if(1>t||!Number.isInteger(t))throw new Vt("Page number cannot be under 1 and must be an integer");if(void 0!==this._totalPages&&t>this._totalPages)throw new Vt(`Only ${this._totalPages} are available. Cannot go to page ${t}`);return t}async page(t=1,e,...r){const{ctxArgs:s}=this.adapter.logCtx([e,...r],this.page);if(this.isPreparedStatement())return await this.pagePrepared(t,...s);throw new Rt("Raw support not available without subclassing this")}serialize(t,e=!1){const r={data:t,current:this.current,total:this.total,count:this.count,bookmark:this._bookmark};try{return e?JSON.stringify(r):r}catch(t){throw new $(t)}}apply(t){const e="string"==typeof t?xr.deserialize(t):t;return this._currentPage=e.current,this._totalPages=e.total,this._recordCount=e.count,this._bookmark=e.bookmark,e.data}static deserialize(t){try{return JSON.parse(t)}catch(t){throw new $(t)}}static isSerializedPage(t){return t&&"object"==typeof t&&Array.isArray(t.data)&&"number"==typeof t.total&&"number"==typeof t.current&&"number"==typeof t.count}}var Ar,Er,Or,Sr;class Cr extends $t{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{P(this,t,(...e)=>this.executionPrefix(t,...e),t.name)})}async executionPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.adapter.logCtx([this.fromSelector,...e],t.name===this.paginate.name?xt.PAGE_BY:At.QUERY,!0,this.overrides||{})).for(t);s.shift();const n=r.get("forcePrepareSimpleQueries"),a=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${a}`),(n&&this.isSimpleQuery()||a)&&(i.silly(`squashing ${a?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${a?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Cr)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}count(t){return this.countSelector=t,this}from(t){if(this.fromSelector="string"==typeof t?G.get(t):t,!this.fromSelector)throw new Qt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t){return this.orderBySelector=t,this}groupBy(t){return this.groupBySelector=t,this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const{log:e,ctxArgs:r}=this.logCtx(t,this.execute);try{if(this.prepared)return this.executePrepared(...t);e.silly("Building raw statement...");const s=this.build();return e.silly("executing raw statement"),await this.raw(s,...r)}catch(t){throw new Qt(t)}}async executePrepared(...t){const e=he.forModel(this.fromSelector,this.adapter.alias),{method:r,args:s,params:i}=this.prepared;return e.statement(r,...s,i,...t)}async raw(t,...e){const{ctx:r,ctxArgs:s}=this.logCtx(e,this.raw);if(!r.get("allowRawStatements"))throw new Rt("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(!this.selectSelector)return i;const n=G.pk(this.fromSelector),a=function(t){const e=t[n];return this.adapter.revert(t,this.fromSelector,e,void 0,r)}.bind(this);return Array.isArray(i)?i.map(a):a(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case vt.AND:case vt.OR:{let t=r,a=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof Wt){const t=this.prepareCondition(i,e);a=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${a}`;break}case bt.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case bt.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case bt.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case bt.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case bt.BIGGER_EQ:n.method=r+" bigger than equal";break;case bt.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case bt.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case bt.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Qt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelector)return;if(this.countSelector)return;if(this.maxSelector)return;if(this.minSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof Wt)return;e=this.whereCondition.attr1}const r=this.orderBySelector?this.orderBySelector:e?[e,Jt.DSC]:[G.pk(this.fromSelector),Jt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const a={class:this.fromSelector,method:xt.LIST_BY,args:[s],params:n};return e&&(a.method=xt.FIND_BY,a.args=[e,this.whereCondition.comparison],a.params=n),a}async prepare(t){if(t=t||await this.adapter.context(At.QUERY,this.overrides||{},this.fromSelector),this.isSimpleQuery()&&t.get("forcePrepareSimpleQueries")){const e=this.squash(t);if(e)return this.prepared=e,this}const e=[],r={},s={class:this.fromSelector,args:e,params:r},i=[wt.FIND_BY];if(this.whereCondition){const r=this.prepareCondition(this.whereCondition,t);i.push(r.method),r.args&&r.args.length&&e.push(...r.args)}return this.selectSelector&&i.push(wt.SELECT,this.selectSelector.join(` ${wt.AND.toLowerCase()} `)),this.orderBySelector&&(i.push(wt.ORDER_BY,this.orderBySelector[0]),r.direction=this.orderBySelector[1]),this.groupBySelector&&i.push(wt.GROUP_BY,this.groupBySelector),this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=U(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelector||this.countSelector||this.maxSelector||this.minSelector)}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new Qt(t)}}toString(){return this.adapter.flavour+" statement"}}i([j(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Cr.prototype,"select",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Ar="undefined"!=typeof S&&S)?Ar:Object]),n("design:returntype",Object)],Cr.prototype,"distinct",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Er="undefined"!=typeof S&&S)?Er:Object]),n("design:returntype",Object)],Cr.prototype,"max",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Or="undefined"!=typeof S&&S)?Or:Object]),n("design:returntype",Object)],Cr.prototype,"min",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Sr="undefined"!=typeof S&&S)?Sr:Object]),n("design:returntype",Object)],Cr.prototype,"count",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Cr.prototype,"from",null),i([j(),n("design:type",Function),n("design:paramtypes",[Wt]),n("design:returntype",Object)],Cr.prototype,"where",null),i([j(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],Cr.prototype,"orderBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Cr.prototype,"groupBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Cr.prototype,"limit",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Cr.prototype,"offset",null),i([j(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Cr.prototype,"execute",null);class Tr extends $t{constructor(t){super(),this.name=t,this.observers=[],this.Context=_t}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Bt,writable:!1});const r=this.log.for(this.observe);return this.observerHandler.observe(t,e),r.verbose("Registered new observer "+(t.constructor.name||t.toString())),()=>this.unObserve(t)}unObserve(t){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables? or are you unregistering whe you shouldn't");this.observerHandler.unObserve(t);const e=this.log.for(this.unObserve);e.verbose(`Observer ${t.toString()} removed`),this.observerHandler.count()||(delete this.observerHandler,e.verbose("No longer being observed"))}async updateObservers(t,e,r,...s){if(!this.observerHandler)throw new u("ObserverHandler not initialized. Did you register any observables?");const{log:i,ctxArgs:n}=this.logCtx(s,this.updateObservers);i.verbose(`Updating ${this.observerHandler.count()} observers for ${this}`),await this.observerHandler.updateObservers(t,e,r,...n)}async flags(t,e,...r){e.correlationId=e.correlationId||`${t}-${Gt.instance.generate()}`;const s=e.logger||F.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},Et,e,{args:r,timestamp:new Date,operation:t,logger:s})}async refresh(t,e,r,...s){return this.updateObservers(t,e,r,...s)}async context(t,e,...r){this.log.for(this.context).silly(`creating new context for ${t} operation with flag overrides: ${JSON.stringify(e)}`);let s=r.pop();void 0===s||s instanceof _t||(r.push(s),s=void 0),e=s?Object.assign({},s.toOverrides(),e):e;const i=await this.flags("string"==typeof t?t:t.name,e,...[...r,s].filter(Boolean));if(s){if(!(s instanceof this.Context)){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}if(s.get("operation")!==t){const t=(new this.Context).accumulate({...s.cache,...i,parentContext:s});return s.accumulate({childContexts:[...s.getOrUndefined("childContexts")||[],t]}),t}return s.accumulate(i)}return(new this.Context).accumulate({...i})}logCtx(t,e,r=!1,s){return $t.logCtx.call(this,e,s||{},r,...t.filter(t=>void 0!==t))}static get(t){if(!t)throw new u("No name provided");const r=Ft(t),s=e.get(r);if(s)return s;throw new u("No Service found for "+("string"==typeof t?t:"symbol"==typeof t?t.toString():t.name))}static async boot(...t){let r=t.pop();void 0===r||r instanceof _t||(t.push(r),r=void 0);const s=await Tr.prototype.flags(At.INITIALIZATION,{},...t);r=r?new _t(r).accumulate({...s,parentContext:r}):(new _t).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Tr.prototype.logCtx(t,this.boot),a=e.services();for(const[t,r]of Object.entries(a))try{i.verbose(`Booting ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);s instanceof Nr&&(i.verbose(`Initializing ${r.name} service...`),await s.boot(...n))}catch(e){throw new u(`Failed to boot ${t} service:${e}`)}}static async shutdown(...t){let r=t.pop();void 0===r||r instanceof _t||(t.push(r),r=void 0);const s=await Tr.prototype.flags(At.SHUTDOWN,{},...t);r=r?new _t(r).accumulate({...s,parentContext:r}):(new _t).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=Tr.prototype.logCtx(t,this.shutdown),a=e.services();for(const[t,r]of Object.entries(a).reverse())try{i.verbose(`Shutting down ${r.name} service...`);const s=e.get(r);if(!s)throw new u("Failed to resolve injectable for "+t);if(s instanceof Nr){i.verbose(`Gracefully shutting down ${r.name} service...`);try{await s.shutdown(...n)}catch(t){i.error(`Failed to gracefully shutdown ${r.name} service`,t)}}}catch(e){throw new u(`Failed to Shutdown services ${t}: ${e}`)}}}i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Tr.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Tr.prototype,"unObserve",null);class Nr extends Tr{constructor(){super()}async boot(...t){const{log:e,ctxArgs:r}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.boot);e.verbose(`Initializing ${this.toString()}...`);const{config:s,client:i}=await this.initialize(...r);this._config=s,this._client=i}get config(){if(!this._config)throw new u("Config not initialized");return this._config}get client(){if(!this._client)throw new u("Client not initialized");return this._client}async shutdown(...t){const{log:e}=await this.logCtx(t,this.shutdown,!0);e.info(`Shutting down ${this.name} service...`)}}function kr(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Ut(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],Nr.prototype,"boot",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],Nr.prototype,"config",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],Nr.prototype,"client",null);const Dr=()=>kr(o.CREATE),_r=()=>kr(o.READ),$r=()=>kr(o.UPDATE),Pr=()=>kr(o.DELETE);function Br(t){return(e,i,n)=>{n||i?(yt()(e,i),t=t||ot.type(e.constructor,i)):t=t||e,t=Ft(t);const a=[];if(n&&"number"==typeof n.value)a.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");a.push(r(t))}else ot.set(At.SERVICE,t,e),a.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return ut(...a)(e,i,n)}}function Rr(t){const e=At.AUTH;return ct.for(e).define({decorator:t=>gt(e,t),args:[t]}).apply()}const Ir=t=>gt(At.AUTH_ROLE,t);function Lr(t,e){const r=At.DECAF_ROUTE;return ct.for(r).define({decorator:()=>(s,i,n)=>{const a={path:e,httpMethod:t,handler:n};return ut(pt(ot.key(r,i),a))(s,i,n)},args:[]}).apply()}const Fr=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class jr extends Tr{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=he.forModel(this.clazz)),this._repository}constructor(t,e){super(e??t.name+"Service"),this.clazz=t}static getService(t){if(!t)throw new u("No name provided");const e=Fr(t);try{const t=Tr.get(e);if(t)return t}catch(t){}throw new u("No ModelService found for alias "+e)}for(t,...e){return new Proxy(this,{get:(r,s,i)=>"repo"===s?r.repo.for(t,...e):Reflect.get(r,s,i)})}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.create);return this.repo.create(t,...r)}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll);return this.repo.createAll(t,...r)}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.UPDATE,!0)).for(this.update);return this.repo.update(t,...r)}async updateAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.UPDATE_ALL,!0)).for(this.updateAll);return this.repo.updateAll(t,...r)}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,xt.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}static forModel(t,e){let r;e=Fr(e||t);try{r=jr.get(e)}catch(t){r=void 0}if(r instanceof jr)return r;const s=this;let a=class extends s{constructor(){super(t)}};return a=i([Br(e),n("design:paramtypes",[])],a),new a}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}}i([Dr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"create",null),i([Dr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],jr.prototype,"createAll",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"delete",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],jr.prototype,"deleteAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"read",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],jr.prototype,"readAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],jr.prototype,"query",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],jr.prototype,"update",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],jr.prototype,"updateAll",null);class Ur extends Nr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof _t||!e.every(t=>Array.isArray(t)))throw new u("Missing/invalid configuration");const{log:r,ctxArgs:s}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.initialize),i=e.map(([t,e,...s])=>{try{r.silly(`Initializing ${t.name} with config: ${JSON.stringify(e)}`);const i=new t(e,...s);return r.debug(`Initialized ${i.toString()}...`),i}catch(e){throw new u(`Failed to initialize ${t.name}: ${e}`)}});for(const t of i)try{await t.initialize(...s)}catch(e){throw new u(`Failed to initialize ${t.toString()}: ${e}`)}return{client:i,config:e}}}let Mr=class extends G{constructor(t){super(t),this.strategy=me.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=we.FULL}};i([H(),J(String),K(me),mt("the backoff strategy"),n("design:type",String)],Mr.prototype,"strategy",void 0),i([H(),mt("base interval between attempts"),n("design:type",Number)],Mr.prototype,"baseMs",void 0),i([H(),mt("max interval"),n("design:type",Number)],Mr.prototype,"maxMs",void 0),i([J(String),K(we),mt("optional jitter strategy"),n("design:type",String)],Mr.prototype,"jitter",void 0),Mr=i([Z(),n("design:paramtypes",[Object])],Mr);let Yr=class extends G{constructor(t){super(t)}};i([H(),mt("The error message"),n("design:type",String)],Yr.prototype,"message",void 0),i([yt(),mt("The error stack"),n("design:type",String)],Yr.prototype,"stack",void 0),i([yt(),mt("The error code"),n("design:type",String)],Yr.prototype,"code",void 0),i([yt(),mt("The error details"),n("design:type",Object)],Yr.prototype,"details",void 0),Yr=i([Z(),n("design:paramtypes",[Object])],Yr);let Gr=class extends G{constructor(t){super(t),this.ts=new Date}};i([B(["taskId","classification","uuid"],":"),yr(),n("design:type",String)],Gr.prototype,"id",void 0),i([E(),H(),R(),Se(!1),n("design:type",String)],Gr.prototype,"uuid",void 0),i([E(),H(),n("design:type",String)],Gr.prototype,"taskId",void 0),i([tt(),H(),n("design:type",Date)],Gr.prototype,"ts",void 0),i([E(),H(),K(be),n("design:type",String)],Gr.prototype,"classification",void 0),i([yt(),E(),n("design:type",Object)],Gr.prototype,"payload",void 0),Gr=i([Ge("task_event"),Z(),n("design:paramtypes",[Object])],Gr);class zr extends et{constructor(){super()}preSerialize(t,...e){if(null===t||"object"!=typeof t)return t;const r=Object.assign({},t);if(t instanceof Wt)return r[rt.ANCHOR]="??condition",r;if(G.isModel(t)){let e;try{e=ot.modelName(t.constructor)}catch(t){e=void 0}e&&(r[rt.ANCHOR]=e)}return r}deserialize(t,...e){const r=JSON.parse(t),s=r[rt.ANCHOR];return s?"??condition"===s?Wt.from(r):G.build(r,s):r}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Hr=class extends G{constructor(t){super(t),this.ts=new Date}};i([tt(),H(),n("design:type",Date)],Hr.prototype,"ts",void 0),i([H(),K(M),n("design:type",String)],Hr.prototype,"level",void 0),i([H(),yt(),n("design:type",String)],Hr.prototype,"msg",void 0),i([yt(),n("design:type",Object)],Hr.prototype,"meta",void 0),Hr=i([Z(),n("design:paramtypes",[Object])],Hr);let qr=class extends G{constructor(t){super(t),this.atomicity=ve.ATOMIC,this.status=ye.PENDING,this.attempt=0,this.logTail=[]}};i([yr({type:"uuid"}),mt("the task id"),n("design:type",String)],qr.prototype,"id",void 0),i([H(),J(String),K(ve),mt("defines a single or composite task"),n("design:type",String)],qr.prototype,"atomicity",void 0),i([H(),mt("Holds task classification - must match @task()"),n("design:type",String)],qr.prototype,"classification",void 0),i([H(),J(String),K(ye),mt("Holds the task current status"),n("design:type",String)],qr.prototype,"status",void 0),i([yt(),I(zr),mt("Holds task input"),n("design:type",Object)],qr.prototype,"input",void 0),i([yt(),I(zr),mt("Holds the task output when successfully completed"),n("design:type",Object)],qr.prototype,"output",void 0),i([yt(),I(),mt("Holds the error for failed tasks"),n("design:type",Yr)],qr.prototype,"error",void 0),i([H(),st(0),mt("Holds the current attempt"),n("design:type",Number)],qr.prototype,"attempt",void 0),i([st(1),H(),mt("max attempts for the task"),n("design:type",Number)],qr.prototype,"maxAttempts",void 0),i([H(),I(),mt("backoff configuration"),n("design:type",Mr)],qr.prototype,"backoff",void 0),i([tt(),mt("Next execution timestamp"),n("design:type",Date)],qr.prototype,"nextRunAt",void 0),i([yt(),mt("Task lease owner identifier"),n("design:type",String)],qr.prototype,"leaseOwner",void 0),i([tt(),mt("Task lease expiration timestamp"),n("design:type",Date)],qr.prototype,"leaseExpiry",void 0),i([yt(),I(),mt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],qr.prototype,"steps",void 0),i([st(0),yt(),mt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],qr.prototype,"currentStep",void 0),i([yt(),I(),mt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],qr.prototype,"stepResults",void 0),i([yt(),I(),mt("Holds the task log entries"),n("design:type",Array)],qr.prototype,"logTail",void 0),i([ze(),Xe(),mt("timestamp of creation"),n("design:type",Date)],qr.prototype,"createdAt",void 0),i([ze(),Ze(),mt("timestamp of last update"),n("design:type",Date)],qr.prototype,"updatedAt",void 0),i([ze(),We(),mt("Holds the creator of the task"),n("design:type",String)],qr.prototype,"createdBy",void 0),i([ze(),Je(),mt("Holds the creator of the task"),n("design:type",String)],qr.prototype,"updatedBy",void 0),qr=i([mt("Holds the current step when applicable"),Ge("tasks"),Z(),n("design:paramtypes",[Object])],qr);let Qr=class extends G{constructor(t){super(t)}};i([H(),mt("The status of a step"),n("design:type",String)],Qr.prototype,"status",void 0),i([yt(),mt("The result of a successful step"),n("design:type",Object)],Qr.prototype,"output",void 0),i([yt(),mt("the error of a failed step"),n("design:type",Yr)],Qr.prototype,"error",void 0),Qr=i([Z(),n("design:paramtypes",[Object])],Qr);let Vr=class extends G{constructor(t){super(t)}};i([H(),yt(),mt("task handler type"),n("design:type",String)],Vr.prototype,"classification",void 0),i([mt("optional task step input"),yt(),n("design:type",Object)],Vr.prototype,"input",void 0),Vr=i([Z(),n("design:paramtypes",[Object])],Vr);class Wr extends G{constructor(t){super(t),this.baseMs=1e3,this.jitter=we.FULL,this.maxMs=6e4,this.strategy=me.EXPONENTIAL,G.fromModel(this,t)}setBaseMs(t){return this.baseMs=t,this}setJitter(t){return this.jitter=t,this}setMaxMs(t){return this.maxMs=t,this}setStrategy(t){return this.strategy=t,this}build(){const t=this.hasErrors();if(t)throw new p(t);return new Mr(this)}}i([H(),st(1e3),n("design:type",Number)],Wr.prototype,"baseMs",void 0),i([H(),K(we),n("design:type",String)],Wr.prototype,"jitter",void 0),i([it("baseMs"),st(1e3),H(),n("design:type",Number)],Wr.prototype,"maxMs",void 0),i([H(),K(me),n("design:type",String)],Wr.prototype,"strategy",void 0);class Jr extends G{setClassification(t){return this.classification=t,this}setStatus(t){return this.status=t,this}setAtomicity(t){return this.atomicity=t,this}setBackoff(t){if(t)return this.backoff=t,this;const e=new Wr,r=this;return e.build=new Proxy(e.build,{apply:(t,e,s)=>(r.backoff=Reflect.apply(t,e,s),r)}),e}setInput(t){return this.input=t,this}setMaxAttempts(t){return this.maxAttempts=t,this}constructor(t){super(t),this.status=ye.PENDING,this.atomicity=ve.ATOMIC,this.backoff=new Mr,this.maxAttempts=1,G.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new p(t);return new qr(this)}}i([H(),n("design:type",String)],Jr.prototype,"classification",void 0),i([H(),n("design:type",String)],Jr.prototype,"status",void 0),i([H(),n("design:type",String)],Jr.prototype,"atomicity",void 0),i([H(),n("design:type",Mr)],Jr.prototype,"backoff",void 0),i([yt(),n("design:type",Object)],Jr.prototype,"input",void 0),i([st(1),H(),n("design:type",Number)],Jr.prototype,"maxAttempts",void 0);class Xr extends Jr{constructor(t){super(t),this.stepResults=[],G.fromModel(this,t),this.atomicity=ve.COMPOSITE}setSteps(t){return this.steps=t,this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new Vr({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([X(()=>Vr),n("design:type",Array)],Xr.prototype,"steps",void 0);class Zr extends Pt{get type(){if(!this._type){const t=ot.get(this.constructor,xe);"string"==typeof t?this._type=t:t&&"string"==typeof t.type&&(this._type=t.type)}if(!this._type)throw new u("No type annotation for this handler found. did you use @task()?");return this._type}constructor(){super(),h(this,this.runPrefix.bind(this),this.run.bind(this),this.runSuffix.bind(this),this.run.name)}async runPrefix(t,...e){const{log:r,ctx:s,ctxArgs:i}=this.logCtx(e,this.runPrefix);return r.info(`Running task ${s.taskId} attempt ${s.attempt}`),[t,...i]}runSuffix(t,e){const{log:r}=this.logCtx([e],this.runPrefix);return r.info(`Concluded task ${e.taskId} attempt ${e.attempt}`),t}}function Kr(t){return ct.for(xe).define({decorator:t=>e=>{const r={type:t};return ot.set(xe,t,e),gt(xe,r)(e)},args:[t]}).apply()}let ts=class extends Zr{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof Wt)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=Wt.attr("status").eq(ye.SUCCEEDED).and(Wt.attr("updatedAt").lte(t.successfulExpiry)),i=Wt.attr("status").eq(ye.FAILED).and(Wt.attr("updatedAt").lte(t.failedExpiry)),n=Wt.attr("status").eq(ye.CANCELED).and(Wt.attr("updatedAt").lte(t.cancelledExpiry));s=e.or(i).or(n)}r.info("Querying tasks for cleanup");const i=await this.tasks.select(["id"]).where(s).execute(e);if(0===i.length)return r.info("No tasks found for cleanup"),[];r.info(`Found ${i.length} tasks to delete`);const n=await this.tasks.deleteAll(i.map(t=>t.id),e);return r.info(`Successfully deleted ${n.length} tasks`),r.debug("deleted tasks:",n),n}catch(t){throw r.error("Error during task cleanup",t),t}}};i([br(qr),n("design:type",Object)],ts.prototype,"tasks",void 0),ts=i([Kr("cleanup-task"),n("design:paramtypes",[])],ts);class es{constructor(t,e=150,r=300,s){this.logger=t,this.bufferSize=e,this.maxBufferSize=r,this.pipe=s,this.history=[],this.root=this.logger.root,Object.values(M).forEach(t=>{this[t]=new Proxy(this[t],{apply:(e,r,s)=>{e.apply(r,s),r.push(t,...s)}})})}push(t,e,r){this.history.length<this.maxBufferSize||this.history.splice(0,this.history.length-this.bufferSize),this.history.push([t,e,r])}flush(t){const e=this.history;return this.history=[],t&&e.length?t(e).catch(t=>this.logger.error("Failed to pipe logs",t)).finally(()=>this.history=[]):(this.history=[],e)}benchmark(t){return this.logger.benchmark(t)}clear(){return this.logger=this.logger.clear(),this}debug(t,e){this.logger.debug(t,e)}error(t,e,r){this.logger.error(t,e,r)}for(t,...e){return new Proxy(this,{get:(r,s)=>"logger"===s?Reflect.get(r,s).for(t,...e):Reflect.get(r,s)})}info(t,e){this.logger.info(t,e)}setConfig(t){this.logger.setConfig(t)}silly(t,e){this.logger.silly(t,e)}trace(t,e){this.logger.trace(t,e)}verbose(t,e,r){this.logger.verbose(t,e,r)}warn(t,e){this.logger.warn(t,e)}}function rs(t,e={logProgress:!0,logStatus:!0,style:!0}){return async r=>{switch(t=t.for(r.taskId,{style:!1,timestamp:!1,logLevel:!1}),r.classification){case be.LOG:{const s=r.payload;for(let[r,i,n]of s){e.style||(i=Y(i),i=i.clear().toString());const s=[i];r===M.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case be.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case be.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=Y(e);switch(e){case ye.SUCCEEDED:s=s.green.bold;break;case ye.RUNNING:s=s.blue.bold;break;case ye.PENDING:s=s.yellow;break;case ye.WAITING_RETRY:s=s.yellow.bold;break;case ye.FAILED:s=s.red.bold;break;case ye.CANCELED:s=s.red;break;default:throw new u("Received unknown task status: "+r.payload)}t.info("### STATUS "+s)}break;default:throw new u("Unknown task event classification: "+r.classification)}}}class ss extends _t{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(t,e){const r=this.cache.has("resultCache")&&this.cache.get("resultCache")||{};r[t]=e,this.cache.put("resultCache",r)}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class is{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=ot.tasks();t&&Object.entries(t).forEach(([t,e])=>{let r;try{r=new e}catch(e){throw new u(`Failed to initialize handler with key ${t}: ${e}`)}this.register(r)})}register(t){if(this.handlers.has(t.type))throw new u("Duplicate task handler: "+t.type);this.handlers.set(t.type,t)}get(t){return this.handlers.get(t)}}class ns extends Bt{constructor(){super(...arguments),this.listeners=new Set}observe(t,e){return super.observe(t,e)}unObserve(t){super.unObserve(t)}emit(t,e){this.updateObservers(Gr,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:a}=qt.logCtx(this.updateObservers,void 0,!1,...i);(await Promise.allSettled(this.observers.filter(s=>{const{filter:i}=s;if(!i)return!0;try{return i(t,e,r,...a)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(t=>{t.observer.refresh(s,...a)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}function as(t,e){const r=e.strategy===me.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===we.FULL?Math.floor(Math.random()*s):s}function os(t){return new Yr({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function cs(t){return new Promise(e=>setTimeout(e,t))}class ls{constructor(t,e){this.bus=t,this.task=e,this.resolved=!1,this.unregistration=t.observe(this,(t,e,r,...s)=>r.startsWith(this.task.id)&&(t===Gr||t===G.tableName(Gr))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([ye.SUCCEEDED,ye.FAILED,ye.CANCELED,ye.WAITING_RETRY])}wait(){return this.awaitStatusTerminal([ye.SUCCEEDED,ye.FAILED,ye.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(rs(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==be.LOG)return;const r=e.payload;await t(r)},be.LOG)}pipe(t,e=be.ALL){this.pipes=this.pipes||{},this.pipes[e]=this.pipes[e]||new Set,this.pipes[e].add(t)}succeed(t){this.complete(t)}fail(t){this.complete(t)}cancel(t){t.payload?.error&&this.fail(t.payload.error)}retry(t){t.payload&&t.payload.error&&(this.task.error=t.payload.error)}onSucceed(t){return this.registerStatusHandler(ye.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(ye.FAILED,t)}onCancel(t){return this.registerStatusHandler(ye.CANCELED,t)}awaitStatusTerminal(t){return new Promise((e,r)=>{const s=[];let i=!1;const n=async t=>{if(!i){(()=>{if(!i){i=!0;for(const t of s)t()}})();try{t.payload?.status===ye.SUCCEEDED?e(this.extractOutput(t)):r(this.extractError(t))}catch(t){r(t)}}};t.forEach(t=>{const e=this.registerStatusHandler(t,n);s.push(e)})})}extractOutput(t){return void 0!==t.payload?.output?t.payload.output:this.task.output}extractError(t){if(t.payload?.error)return t.payload.error;if(this.task.error)return this.task.error;if(this.lastTerminalPayload instanceof Yr)return this.lastTerminalPayload;const e=t.payload?.status??this.task.status,r=e===ye.WAITING_RETRY?`Task ${this.task.id} scheduled for retry`:`Task ${this.task.id} ${e}`;return new Yr({message:r})}complete(t){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0,this.lastTerminalPayload=t)}isTerminalStatus(t){return[ye.SUCCEEDED,ye.CANCELED,ye.FAILED].includes(t)}async track(t,e){t.payload&&(this.task.status=t.payload.status,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),t.payload.status===ye.SUCCEEDED&&this.succeed(t.payload.output),t.payload.status===ye.FAILED&&this.fail(t.payload.error),t.payload.status===ye.CANCELED&&this.cancel(t),t.payload.status===ye.WAITING_RETRY&&this.retry(t))}registerStatusHandler(t,e){const r=async(r,s)=>{r.payload?.status===t&&await e(r,s)};if(this.pipe(r,be.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[be.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new _t),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===ye.SUCCEEDED&&(e.output=this.task.output),t!==ye.FAILED&&t!==ye.CANCELED||!this.task.error||(e.error=this.task.error),new Gr({classification:be.STATUS,taskId:this.task.id,payload:e})}resolveTerminalState(){this.isTerminalStatus(this.task.status)&&(this.task.status!==ye.SUCCEEDED?this.task.error&&this.fail(this.task.error):this.succeed(this.task.output))}async refresh(t,e){if(!this.pipes)return;const r=this.pipes[be.ALL]?[...this.pipes[be.ALL].values()]:[];r.push(...this.pipes[t.classification]?.values()||[]);for(const s of r)try{await s(t,e)}catch(r){e.logger.error(`Failed to trigger pipe ${s.name} for event ${t.classification}. discarding event`,r)}}}class us extends Pt{get Context(){return ss}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=he.forModel(qr,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=he.forModel(Gr,this.config.adapter.alias)),this._events}constructor(t){super(),this.config=t,this.lock=new nt,this.running=!1,this.config=Object.assign({},Ae,t,{bus:t.bus||new ns,registry:t.registry||new is})}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,o.CREATE,!0)).for(this.push);i.verbose("pushing task "+t.classification);const n=await this.tasks.create(t,s);return i.info(`${t.classification} task registered under ${n.id}`),e?{task:n,tracker:new ls(this.bus,n)}:n}async track(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,o.READ,!0)).for(this.track);s.verbose("tracking task "+t);let i=await this.tasks.read(t,r);return i=await this.ensureTaskError(i,r),s.info(`${i.classification} task found with id ${t}`),{task:i,tracker:new ls(this.bus,i)}}async ensureTaskError(t,e){if(![ye.FAILED,ye.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await cs(20);try{const t=await this.tasks.read(r.id,e);if(t.error)return t;r=t}catch{break}}return r}async cancel(t,...e){const{ctx:r}=(await this.logCtx(e,"cancel",!0)).for(this.cancel),s=await this.tasks.read(t,r);if(s.status===ye.SUCCEEDED||s.status===ye.FAILED)return s;s.status=ye.CANCELED;const i=new Yr({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0;const n=await this.tasks.update(s,r);return await this.emitStatus(r,n,ye.CANCELED,i),n}async isRunning(){await this.lock.acquire();const t=this.running;return this.lock.release(),t}async start(...t){const{ctx:e}=(await this.logCtx(t,"run",!0)).for(this.start);await this.lock.acquire(),this.running||(this.running=!0,this.lock.release(),this.loop(e))}async stop(...t){const{ctx:e,log:r}=(await this.logCtx(t,At.SHUTDOWN,!0)).for(this.stop);await this.lock.acquire(),this.running||r.warn("stop method called when task engine was not running"),this.running=!1,this.lock.release();const s=await this.tasks.select(["id"]).where(Wt.attr("status").eq(ye.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((t,n)=>{const a=setTimeout(()=>{r.error(`Graceful shutdown interrupted after ${i} ms...`),t()},i);Promise.allSettled(s.map(({id:t})=>new Promise((r,s)=>{this.track(t,e).then(({tracker:t})=>{t.resolve().then(r)}).catch(s)}))).then(e=>{clearTimeout(a),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()}).catch(t=>{clearTimeout(a),n(t)})})}async loop(...t){const{ctx:e}=this.logCtx(t,this.loop);for(;await this.isRunning();){const t=await this.claimBatch(e);await Promise.allSettled(t.map(t=>this.executeClaimed(t))),await cs(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=t.timestamp,s=Wt.attribute("status").eq(ye.PENDING),i=Wt.attribute("status").eq(ye.WAITING_RETRY).and(Wt.attribute("nextRunAt").lte(r)),n=Wt.attribute("status").eq(ye.RUNNING).and(Wt.attribute("leaseExpiry").lte(r)),a=s.or(i).or(n),o=await this.tasks.select().where(a).limit(Math.max(4*this.config.concurrency,20)).execute();e.verbose("claimBatch candidates:"+o.length);const c=[];for(const e of o){const r=await this.tryClaim(e,t);if(r&&c.push(r),c.length>=this.config.concurrency)break}return e.verbose("claimBatch claimed:"+c.length),c}async tryClaim(t,e){const r=e.logger.for(this.claimBatch),s=(new Date).getTime();let i=t;try{i=await this.tasks.read(t.id,e)}catch{}const n=new qr({...i,status:ye.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4))});r.info(`running handler for ${t.id} (${t.classification}) atomicity ${t.atomicity}`);try{return await this.tasks.update(n,e)}catch{return null}}async executeClaimed(t){const{ctx:e,log:r}=(await this.logCtx([],t.classification,!0)).for(this.executeClaimed),s=new ss(e).accumulate({taskId:t.id,logger:new es(r,this.config.streamBufferSize,this.config.maxLoggingBuffer),attempt:t.attempt,resultCache:{},pipe:async e=>{const[,r]=await this.appendLog(s,t,e);await this.emitLog(s,t.id,r)},flush:async()=>s.logger.flush(s.pipe),progress:async e=>{await this.emitProgress(s,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(s,t,ye.RUNNING);try{let e;if(t.atomicity===ve.COMPOSITE){e=await this.runComposite(t,s);try{t=await this.tasks.read(t.id,s)}catch{}e?.stepResults&&(t.stepResults=e.stepResults,t.currentStep=e.stepResults.length)}else{const i=this.registry.get(t.classification);if(r.debug(`handler type for ${t.id} is ${i?.constructor?.name??"none"}`),!i)throw new u("No task handler registered for type: "+t.classification);e=await i.run(t.input,s),r.verbose("handler finished for "+t.id)}t.status=ye.SUCCEEDED,t.output=e,t.error=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),s.logger.info(`task ${t.id} success state ${t.status}`),r.info(`task ${t.id} success state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,ye.SUCCEEDED,e)}catch(e){r.error("task execution error",e);try{t=await this.tasks.read(t.id,s)}catch{}if(t.atomicity===ve.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===ye.FAILED);0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=os(e);if(i<t.maxAttempts){const e=as(i,this.normalizeBackoff(t.backoff)),a=new Date(Date.now()+e);t.attempt=i,t.status=ye.WAITING_RETRY,t.nextRunAt=a,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.warn(`task ${t.id} waiting retry state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,ye.WAITING_RETRY),await s.pipe(M.warn,"Retry scheduled",{nextRunAt:a,delayMs:e,attempt:i})}else t.attempt=i,t.status=ye.FAILED,t.error=n,t.leaseOwner=void 0,t.leaseExpiry=void 0,t=await this.tasks.update(t,s),r.error(`task ${t.id} failed state ${t.status} attempt ${t.attempt}`),await this.emitStatus(s,t,ye.FAILED,n),await s.pipe(M.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts})}}async runComposite(t,e){const{ctx:r}=(await this.logCtx([e],t.classification,!0)).for(this.runComposite),s=this.normalizeSteps(t.steps);let i=t.currentStep??0;const n=this.normalizeStepResults(t.stepResults),a=(t,s)=>{e.cacheResult(t,s),r instanceof ss&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===ye.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;a(i.classification,r.output),a(n,r.output)}}for(;i<s.length;){const r=s[i],o=this.registry.get(r.classification);if(!o)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([M.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await o.run(r.input,e),l=i,u=new Date;n[l]=new Qr({status:ye.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const p=`${t.id}:step:${l}`;a(r.classification,c),a(p,c),i=l+1,t.stepResults=n,t.currentStep=i,t=await this.tasks.update(t),await this.emitProgress(e,t.id,{currentStep:i,totalSteps:s.length,output:c})}catch(e){const r=new Date;throw n[i]=new Qr({status:ye.FAILED,error:os(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=os(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Mr)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Mr(e)}normalizeSteps(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map(t=>{if(t instanceof Vr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Vr(e)}):[]}normalizeStepResults(t){if(!t)return[];let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return[]}return e instanceof Set&&(e=Array.from(e)),Array.isArray(e)?e.map(t=>{if(t instanceof Qr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Qr(e)}):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map(([t,e,r])=>new Hr({level:t,msg:e,meta:r})),i=[...e.logTail??[],...s].slice(-this.config.logTailMax);e.logTail=i;try{return[await this.tasks.update(e,t),s]}catch{return[e,[]]}}async emitStatus(t,e,r,s){t instanceof ss&&await t.flush();const i={status:r};s&&s instanceof Yr?i.error=s:s&&(i.output=s);const n=await this.persistEvent(t,e.id,be.STATUS,i);this.bus.emit(n,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,be.LOG,r.map(t=>({ts:t.ts,level:t.level,msg:t.msg,meta:t.meta})));this.bus.emit(s,t)}async emitProgress(t,e,r){const s=await this.persistEvent(t,e,be.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Gr({taskId:e,classification:r,payload:s});return await this.events.create(i,t)}toString(){return`TaskEngine<${this.config.adapter.alias}>`}async context(t,e,...r){return this.adapter.context(t,e,qr,...r)}}class ps extends Nr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof _t)throw new u("No/invalid config provided");const{log:r}=(await this.logCtx(t,At.INITIALIZATION,!0)).for(this.initialize);if(!e.adapter)throw new u("No adapter provided");r.info("Initializing Task Engine...");const s=new us(e);return r.verbose(s+" initialized"),{client:s,config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,o.CREATE,!0)).for(this.push),i=await this.client.push(t,e,...s);return await this.client.isRunning()||this.client.start(),i}async track(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.push);return this.client.track(t,...r)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.CREATE,!0)).for(this.create),s=await this.repo.create(t,...r);return await this.client.isRunning()||this.client.start(),s}async createAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.CREATE_ALL,!0)).for(this.createAll),s=await this.repo.createAll(t,...r);return await this.client.isRunning()||this.client.start(),s}async delete(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.DELETE,!0)).for(this.delete);return this.repo.delete(t,...r)}async deleteAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.DELETE_ALL,!0)).for(this.deleteAll);return this.repo.deleteAll(t,...r)}async read(t,...e){const{ctxArgs:r}=(await this.logCtx(e,o.READ,!0)).for(this.read);return this.repo.read(t,...r)}async readAll(t,...e){const{ctxArgs:r}=(await this.logCtx(e,c.READ_ALL,!0)).for(this.readAll);return this.repo.readAll(t,...r)}async query(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.QUERY,!0)).for(this.query),s=this.repo?.[t];if("function"!=typeof s)throw new u(`Method "${t}" is not implemented`);return s.apply(this.repo,r)}async update(t,...e){throw new Rt("Updates to tasks are not available")}async updateAll(t,...e){throw new Rt("Updates to tasks are not available")}async listBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.LIST_BY,!0)).for(this.listBy);return this.repo.listBy(t,e,...s)}async paginateBy(t,e,r,...s){const{ctxArgs:i}=(await this.logCtx(s,xt.PAGE_BY,!0)).for(this.paginateBy);return this.repo.paginateBy(t,e,r,...i)}async findOneBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_ONE_BY,!0)).for(this.findOneBy);return this.repo.findOneBy(t,e,...s)}async findBy(t,e,...r){const{ctxArgs:s}=(await this.logCtx(r,xt.FIND_BY,!0)).for(this.findBy);return this.repo.findBy(t,e,...s)}async statement(t,...e){const{ctxArgs:r}=(await this.logCtx(e,At.STATEMENT,!0)).for(this.statement);return this.repo.statement(t,...r)}refresh(t,e,r,...s){return this.repo.refresh(t,e,r,...s)}observe(t,e){return this.repo.observe(t,e)}unObserve(t){return this.repo.unObserve(t)}updateObservers(t,e,r,...s){return this.repo.updateObservers(t,e,r,...s)}logCtx(t,e,r=!1){const s=this.repo.adapter.logCtx([this.repo.class,...t],e,r,this.repo._overrides||{});function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}async shutdown(...t){const{ctxArgs:e,ctx:r,log:s}=(await this.logCtx(t,At.SHUTDOWN,!0)).for(this.shutdown);await super.shutdown(...e),s.info("attempting to gracefully shutdown task runner"),await this.client.stop(r),s.verbose("gracefully shutdown task runner")}}i([br(qr),n("design:type",Object)],ps.prototype,"repo",void 0),i([Dr(),n("design:type",Function),n("design:paramtypes",[qr,void 0]),n("design:returntype",Promise)],ps.prototype,"create",null),i([Dr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"createAll",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ps.prototype,"delete",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"deleteAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],ps.prototype,"read",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"readAll",null),i([_r(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],ps.prototype,"query",null),i([$r(),n("design:type",Function),n("design:paramtypes",[qr,void 0]),n("design:returntype",Promise)],ps.prototype,"update",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],ps.prototype,"updateAll",null),e.setRegistry(new fe);const ds="##VERSION##",hs="##PACKAGE##";ot.registerLibrary(hs,ds);export{Pt as AbsContextual,qt as Adapter,Ue as AuthorizationError,me as BackoffStrategy,lr as BaseModel,hr as BigIntSequence,Xt as Cascade,ts as CleanUpTask,Nr as ClientBasedService,Xr as CompositeTaskBuilder,Wt as Condition,Ye as ConnectionError,_t as Context,Dt as ContextLock,$t as ContextualLoggedClass,Ot as DefaultAdapterFlags,Zt as DefaultCascade,Et as DefaultContextFlags,pe as DefaultRepositoryFilters,pr as DefaultSequenceOptions,Ae as DefaultTaskEngineConfig,Ee as Dispatch,Me as ForbiddenError,vt as GroupOperator,fe as InjectablesRegistry,we as JitterStrategy,ee as MethodQueryBuilder,It as MigrationError,Lt as MigrationRuleError,jr as ModelService,Nt as MultipleSelectOperationKeys,Ct as NonTransactionOperationKeys,ur as NoneSequenceOptions,dr as NumericSequence,vr as ObserverError,Bt as ObserverHandler,bt as Operator,Kt as OperatorsMap,Jt as OrderDirection,hs as PACKAGE_NAME,kt as PaginationOperationKeys,xr as Paginator,Vt as PagingError,At as PersistenceKeys,Ur as PersistenceService,xt as PreparedStatementKeys,wt as QueryClause,Qt as QueryError,he as Repository,Tt as SelectOperationKeys,wr as Sequence,mr as SequenceModel,zt as Serial,Tr as Service,Cr as Statement,Wr as TaskBackoffBuilder,Mr as TaskBackoffModel,Jr as TaskBuilder,ss as TaskContext,us as TaskEngine,Yr as TaskErrorModel,ns as TaskEventBus,Gr as TaskEventModel,be as TaskEventType,Zr as TaskHandler,is as TaskHandlerRegistry,zr as TaskIOSerializer,Hr as TaskLogEntryModel,es as TaskLogger,qr as TaskModel,ps as TaskService,ye as TaskStatus,Qr as TaskStepResultModel,Vr as TaskStepSpecModel,ls as TaskTracker,ve as TaskType,xe as TasksKey,St as TransactionOperationKeys,Gt as UUID,Rt as UnsupportedError,ds as VERSION,Rr as auth,Re as cacheModelForPopulate,Le as cascadeDelete,ze as column,as as computeBackoffMs,Dr as create,Ce as createOrUpdate,Xe as createdAt,We as createdBy,Ve as createdByOnCreateUpdate,Pr as del,ge as generateInjectableNameForRepository,de as getFilters,rs as getLogPipe,Ke as getPkTypes,Pe as getPopulateKey,Be as getTagForDeleteKey,He as index,Ft as injectableServiceKey,Ut as isOperationBlocked,sr as manyToMany,rr as manyToOne,ir as noValidateOn,nr as noValidateOnCreate,or as noValidateOnCreateUpdate,ar as noValidateOnUpdate,Mt as normalizeImport,er as oneToMany,De as oneToManyOnCreate,$e as oneToManyOnDelete,_e as oneToManyOnUpdate,tr as oneToOne,Te as oneToOneOnCreate,ke as oneToOneOnDelete,Ne as oneToOneOnUpdate,le as onlyOnBulk,ie as onlyOnCreate,ae as onlyOnDelete,ue as onlyOnFilter,ce as onlyOnSingle,oe as onlyOnTransactional,ne as onlyOnUpdate,yr as pk,fr as pkDec,gr as pkOnCreate,Ie as populate,Yt as prefixMethod,re as prepared,jt as promiseSequence,se as query,_r as read,cr as relation,br as repository,je as repositoryFromTypeMetadata,Ir as roles,Lr as route,os as serializeError,Br as service,cs as sleep,Ge as table,Kr as task,Qe as unique,qe as uniqueOnCreateUpdate,$r as update,Ze as updatedAt,Je as updatedBy,Se as uuid,Oe as uuidCreateUpdateHandler};
2
2
  //# sourceMappingURL=core.js.map