@decaf-ts/core 0.8.24 → 0.8.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +1 -1
  2. package/dist/core.cjs +1 -1
  3. package/dist/core.cjs.map +1 -1
  4. package/dist/core.js +1 -1
  5. package/dist/core.js.map +1 -1
  6. package/lib/esm/identity/index.d.ts +5 -0
  7. package/lib/esm/identity/index.js +5 -0
  8. package/lib/esm/identity/index.js.map +1 -1
  9. package/lib/esm/index.d.ts +1 -1
  10. package/lib/esm/index.js +1 -1
  11. package/lib/esm/interfaces/index.d.ts +5 -0
  12. package/lib/esm/interfaces/index.js +5 -0
  13. package/lib/esm/interfaces/index.js.map +1 -1
  14. package/lib/esm/migrations/index.d.ts +5 -0
  15. package/lib/esm/migrations/index.js +5 -0
  16. package/lib/esm/migrations/index.js.map +1 -1
  17. package/lib/esm/model/decorators.d.ts +3 -0
  18. package/lib/esm/model/decorators.js.map +1 -1
  19. package/lib/esm/model/index.d.ts +5 -0
  20. package/lib/esm/model/index.js +5 -0
  21. package/lib/esm/model/index.js.map +1 -1
  22. package/lib/esm/overrides/index.d.ts +5 -0
  23. package/lib/esm/overrides/index.js +5 -0
  24. package/lib/esm/overrides/index.js.map +1 -1
  25. package/lib/esm/persistence/index.d.ts +5 -0
  26. package/lib/esm/persistence/index.js +5 -0
  27. package/lib/esm/persistence/index.js.map +1 -1
  28. package/lib/esm/query/Condition.js +21 -0
  29. package/lib/esm/query/Condition.js.map +1 -1
  30. package/lib/esm/query/Statement.d.ts +14 -5
  31. package/lib/esm/query/Statement.js +92 -8
  32. package/lib/esm/query/Statement.js.map +1 -1
  33. package/lib/esm/query/constants.d.ts +2 -0
  34. package/lib/esm/query/constants.js +2 -1
  35. package/lib/esm/query/constants.js.map +1 -1
  36. package/lib/esm/query/index.d.ts +5 -0
  37. package/lib/esm/query/index.js +5 -0
  38. package/lib/esm/query/index.js.map +1 -1
  39. package/lib/esm/query/options.d.ts +101 -7
  40. package/lib/esm/ram/RamAdapter.d.ts +13 -5
  41. package/lib/esm/ram/RamAdapter.js +213 -26
  42. package/lib/esm/ram/RamAdapter.js.map +1 -1
  43. package/lib/esm/ram/RamStatement.d.ts +7 -0
  44. package/lib/esm/ram/RamStatement.js +117 -3
  45. package/lib/esm/ram/RamStatement.js.map +1 -1
  46. package/lib/esm/ram/index.js +5 -0
  47. package/lib/esm/ram/index.js.map +1 -1
  48. package/lib/esm/ram/types.d.ts +7 -16
  49. package/lib/esm/repository/Repository.d.ts +49 -1
  50. package/lib/esm/repository/Repository.js +78 -0
  51. package/lib/esm/repository/Repository.js.map +1 -1
  52. package/lib/esm/repository/index.d.ts +5 -0
  53. package/lib/esm/repository/index.js +5 -0
  54. package/lib/esm/repository/index.js.map +1 -1
  55. package/lib/esm/services/index.d.ts +5 -0
  56. package/lib/esm/services/index.js +5 -0
  57. package/lib/esm/services/index.js.map +1 -1
  58. package/lib/esm/tasks/TaskContext.d.ts +9 -0
  59. package/lib/esm/tasks/TaskContext.js +39 -0
  60. package/lib/esm/tasks/TaskContext.js.map +1 -1
  61. package/lib/esm/tasks/TaskEngine.d.ts +14 -0
  62. package/lib/esm/tasks/TaskEngine.js +99 -2
  63. package/lib/esm/tasks/TaskEngine.js.map +1 -1
  64. package/lib/esm/tasks/TaskErrors.d.ts +20 -0
  65. package/lib/esm/tasks/TaskErrors.js +42 -0
  66. package/lib/esm/tasks/TaskErrors.js.map +1 -0
  67. package/lib/esm/tasks/TaskStateChangeError.d.ts +11 -0
  68. package/lib/esm/tasks/TaskStateChangeError.js +9 -0
  69. package/lib/esm/tasks/TaskStateChangeError.js.map +1 -0
  70. package/lib/esm/tasks/TaskTracker.d.ts +7 -5
  71. package/lib/esm/tasks/TaskTracker.js +72 -36
  72. package/lib/esm/tasks/TaskTracker.js.map +1 -1
  73. package/lib/esm/tasks/constants.d.ts +1 -0
  74. package/lib/esm/tasks/constants.js +1 -0
  75. package/lib/esm/tasks/constants.js.map +1 -1
  76. package/lib/esm/tasks/index.d.ts +6 -0
  77. package/lib/esm/tasks/index.js +6 -0
  78. package/lib/esm/tasks/index.js.map +1 -1
  79. package/lib/esm/tasks/logging.js +4 -1
  80. package/lib/esm/tasks/logging.js.map +1 -1
  81. package/lib/esm/tasks/models/TaskModel.d.ts +1 -0
  82. package/lib/esm/tasks/models/TaskModel.js +5 -0
  83. package/lib/esm/tasks/models/TaskModel.js.map +1 -1
  84. package/lib/esm/tasks/types.d.ts +2 -0
  85. package/lib/esm/utils/index.d.ts +5 -0
  86. package/lib/esm/utils/index.js +5 -0
  87. package/lib/esm/utils/index.js.map +1 -1
  88. package/lib/identity/index.cjs +5 -0
  89. package/lib/identity/index.d.ts +5 -0
  90. package/lib/identity/index.js.map +1 -1
  91. package/lib/index.cjs +1 -1
  92. package/lib/index.d.ts +1 -1
  93. package/lib/interfaces/index.cjs +5 -0
  94. package/lib/interfaces/index.d.ts +5 -0
  95. package/lib/interfaces/index.js.map +1 -1
  96. package/lib/migrations/index.cjs +5 -0
  97. package/lib/migrations/index.d.ts +5 -0
  98. package/lib/migrations/index.js.map +1 -1
  99. package/lib/model/decorators.d.ts +3 -0
  100. package/lib/model/decorators.js.map +1 -1
  101. package/lib/model/index.cjs +5 -0
  102. package/lib/model/index.d.ts +5 -0
  103. package/lib/model/index.js.map +1 -1
  104. package/lib/overrides/index.cjs +5 -0
  105. package/lib/overrides/index.d.ts +5 -0
  106. package/lib/overrides/index.js.map +1 -1
  107. package/lib/persistence/index.cjs +5 -0
  108. package/lib/persistence/index.d.ts +5 -0
  109. package/lib/persistence/index.js.map +1 -1
  110. package/lib/query/Condition.cjs +21 -0
  111. package/lib/query/Condition.js.map +1 -1
  112. package/lib/query/Statement.cjs +92 -8
  113. package/lib/query/Statement.d.ts +14 -5
  114. package/lib/query/Statement.js.map +1 -1
  115. package/lib/query/constants.cjs +2 -1
  116. package/lib/query/constants.d.ts +2 -0
  117. package/lib/query/constants.js.map +1 -1
  118. package/lib/query/index.cjs +5 -0
  119. package/lib/query/index.d.ts +5 -0
  120. package/lib/query/index.js.map +1 -1
  121. package/lib/query/options.d.ts +101 -7
  122. package/lib/ram/RamAdapter.cjs +213 -26
  123. package/lib/ram/RamAdapter.d.ts +13 -5
  124. package/lib/ram/RamAdapter.js.map +1 -1
  125. package/lib/ram/RamStatement.cjs +116 -2
  126. package/lib/ram/RamStatement.d.ts +7 -0
  127. package/lib/ram/RamStatement.js.map +1 -1
  128. package/lib/ram/index.cjs +5 -0
  129. package/lib/ram/index.js.map +1 -1
  130. package/lib/ram/types.d.ts +7 -16
  131. package/lib/repository/Repository.cjs +78 -0
  132. package/lib/repository/Repository.d.ts +49 -1
  133. package/lib/repository/Repository.js.map +1 -1
  134. package/lib/repository/index.cjs +5 -0
  135. package/lib/repository/index.d.ts +5 -0
  136. package/lib/repository/index.js.map +1 -1
  137. package/lib/services/index.cjs +5 -0
  138. package/lib/services/index.d.ts +5 -0
  139. package/lib/services/index.js.map +1 -1
  140. package/lib/tasks/TaskContext.cjs +39 -0
  141. package/lib/tasks/TaskContext.d.ts +9 -0
  142. package/lib/tasks/TaskContext.js.map +1 -1
  143. package/lib/tasks/TaskEngine.cjs +99 -2
  144. package/lib/tasks/TaskEngine.d.ts +14 -0
  145. package/lib/tasks/TaskEngine.js.map +1 -1
  146. package/lib/tasks/TaskErrors.cjs +50 -0
  147. package/lib/tasks/TaskErrors.d.ts +20 -0
  148. package/lib/tasks/TaskErrors.js.map +1 -0
  149. package/lib/tasks/TaskStateChangeError.cjs +13 -0
  150. package/lib/tasks/TaskStateChangeError.d.ts +11 -0
  151. package/lib/tasks/TaskStateChangeError.js.map +1 -0
  152. package/lib/tasks/TaskTracker.cjs +72 -36
  153. package/lib/tasks/TaskTracker.d.ts +7 -5
  154. package/lib/tasks/TaskTracker.js.map +1 -1
  155. package/lib/tasks/constants.cjs +1 -0
  156. package/lib/tasks/constants.d.ts +1 -0
  157. package/lib/tasks/constants.js.map +1 -1
  158. package/lib/tasks/index.cjs +6 -0
  159. package/lib/tasks/index.d.ts +6 -0
  160. package/lib/tasks/index.js.map +1 -1
  161. package/lib/tasks/logging.cjs +4 -1
  162. package/lib/tasks/logging.js.map +1 -1
  163. package/lib/tasks/models/TaskModel.cjs +5 -0
  164. package/lib/tasks/models/TaskModel.d.ts +1 -0
  165. package/lib/tasks/models/TaskModel.js.map +1 -1
  166. package/lib/tasks/types.d.ts +2 -0
  167. package/lib/utils/index.cjs +5 -0
  168. package/lib/utils/index.d.ts +5 -0
  169. package/lib/utils/index.js.map +1 -1
  170. package/package.json +1 -1
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- import{InjectableRegistryImp as t,Injectables as e,inject as r,injectable as s}from"@decaf-ts/injectable-decorators";import{__decorate as i,__metadata as n}from"tslib";import{DefaultRepositoryFlags as o,OperationKeys as a,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as d,Repository as p,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 B,SerializationError as _,prefixMethod as $,composed as P,transient as I,serialize as R}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 ot}from"@decaf-ts/transactional-decorators";import{Metadata as at,Decoration as ct,DefaultFlavour as lt,propMetadata as ut,apply as dt,methodMetadata as pt,DecorationKeys as ht,uses as gt,metadata 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",t.VIEW="view"})(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({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),St=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Ct=[a.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 Bt 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 o=n instanceof Bt;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new u("No context provided");if(o&&!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 $t extends _t{constructor(){super(),this._Context=Bt}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 Bt||(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 Pt{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:o}=s;if(!o)return!0;try{return o(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 It extends u{constructor(t){super(t,It.name,500)}}class Rt extends u{constructor(t,e=Rt.name){super(t,e,500)}}class Lt extends Rt{constructor(t){super(t,Lt.name)}}function Ft(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):at.Symbol(at.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}=at.get(t,a.REFLECT+a.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 at.registeredFlavour?at.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 $t{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 Pt}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 o=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?at.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:o})}get Context(){return Bt}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 Bt||(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:o}=this.logCtx(i,this.revert),a=G.pk(e),c=new e;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[At.METADATA],d=Object.keys(c).filter(t=>t!==a).reduce((r,s)=>(r[s]=t[G.columnName(e,s)],r),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in d&&void 0!==d[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(d,At.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),d}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new d("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new d("Ids and models must have the same length");const o=G.tableName(t);return i.debug(`Creating ${e.length} entries ${o} 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 o=G.tableName(t);return i.debug(`Updating ${e.length} entries ${o} 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),o=!i.get("noEmitSingle"),a=!i.get("noEmitBulk");(s&&a||!s&&o)&&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 at.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 at.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 at.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,Bt]),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:o,limit:a,offset:c}=this.extractOrderLimitOffset(t,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,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:o}=this.parseFieldAndOperator(t),a=o?Kt[o]:Kt.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(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,o;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]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function re(){return ct.for(At.STATEMENT).define({decorator:()=>(t,e,r)=>dt(pt(at.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 dt(pt(at.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:o,orderBy:a,limit:c,offset:l}=ee.build(e.name,...s);let u=r.select(i);n&&(u=u.where(n));const{allowLimit:d,allowOffset:p,allowOrderBy:h,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(a||[])[0],allowed:h},{key:"limit",value:c,allowed:d},{key:"offset",value:l,allowed:p}];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,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(at.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),o=at.key(t,i,n),a={...r||{},kind:e,attribute:i};return ut(o,a)(s,i)}}function ne(t){return ct.for(bt.VIEW).define({decorator:t=>ie(bt.VIEW,"view",t),args:[t]}).apply()}function oe(t){return pe(t,[a.CREATE,c.CREATE_ALL])}function ae(t){return pe(t,[a.UPDATE,c.UPDATE_ALL])}function ce(t){return pe(t,[a.DELETE,c.DELETE_ALL])}function le(t){return pe(t,St)}function ue(t){return pe(t,Object.values(a))}function de(t){return pe(t,Object.values(c))}function pe(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:o}=_t.prototype.logCtx(n,pe);return o.silly(`filtering ${s} event for${r?" "+(G.tableName(r)||r):""} ${i}`),("string"==typeof r?r===G.tableName(t)||r===t.constructor.name:at.constr(t)===at.constr(r))&&e.includes(s)}}const he={onlyOnCreate:oe,onlyOnUpdate:ae,onlyOnDelete:ce,onlyOnTransactional:le,onlyOnSingle:ue,onlyOnBulk:de};function ge(t){const e=Object.assign({},he);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}class fe extends p{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new 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 ge(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&&(fe.register(e,this,this.adapter.alias),t)&&at.get(e,ht.FLAVOUR)===lt&&gt(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 Pt}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),t=new this.class(t),n||await f(this,r,t,a.CREATE,a.ON),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new d(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:o,transient:a}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,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)),o=n.map(t=>t.id);let a=n.map(t=>t.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((t,e)=>this.adapter.revert(t,this.class,o[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"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!t.length)return[t,...s];const l=G.sequenceFor(t[0]);let p=[];if(G.generatedBySequence(this.class)?(l.name||(l.name=G.sequenceName(t[0],"pk")),p=await(await this.adapter.Sequence(l)).range(t.length,...s)):G.generated(this.class,this.pk)||(p=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?p[e]:""+t[this.pk]),n||await f(this,r,t,a.CREATE,a.ON),t))),!o){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 d(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=t,n||await f(this,r,o,a.READ,a.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,a.READ,a.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:o,transient:a}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${G.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);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,a.UPDATE,a.ON,l),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new d(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"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const l=t.map(t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e});let p;if(r.get("applyUpdateValidation")&&(p=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>G.merge(p[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>f(this,r,t,a.UPDATE,a.ON,p?p[e]:void 0))),!o){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(p[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=y(s);if(n)throw new d(n)}return[t,...s,p]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.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,a.DELETE,a.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,a.DELETE,a.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:o}=(await this.logCtx(n,At.QUERY,!0)).for(this.query),a=[e,r],c=this.select().where(t).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}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:o,limit:a}=r;if(!n&&!o)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 d;if(c.verbose(`paginating ${G.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===Jt.ASC?this.attr(G.pk(this.class)).gt(o):this.attr(G.pk(this.class)).lt(o))()).orderBy([t,e]).paginate(a,...u);else{if(!n)throw new Qt("PaginateBy needs a page or a bookmark");d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...u)}const p=await d.page(i,o,...u);return d.serialize(p)}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(!fe.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:at.constr(t)===at.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||at.flavourOf(t)||qt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof fe)return s;const n=e||at.flavourOf(t)||s&&at.get(s,At.ADAPTER)||qt.currentFlavour,o=n?qt.get(n):void 0;if(!o)throw new u("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,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 fe)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof fe?t.constructor:t,s=at.get(r,e?at.key(At.STATEMENT,e):At.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof fe?t.constructor:t;return at.get(r,e?at.key(At.QUERY,e):At.QUERY)}}function ye(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)],fe.prototype,"listBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],fe.prototype,"paginateBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],fe.prototype,"findOneBy",null),i([re(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],fe.prototype,"findBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],fe.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],fe.prototype,"unObserve",null),qt&&(qt._baseRepository=fe);class me 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 o=At.ADAPTER,a=r||at.get(n,o);try{let t=a;try{a&&qt.get(a)}catch{const e=qt.current;e&&e.flavour===a&&(t=e.alias)}if(i=fe.forModel(n,t),i instanceof fe)return i;const r=a||at.get(i.constructor,o)||at.get(n,o);e.register(i,ye(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=fe.get(n,a);if("function"==typeof e){const t=a?qt.get(a):qt.current;if(!t)return;return new e(t,n)}}}return i}}var we,be,ve,xe,Ae;(t=>{t.PENDING="pending",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(we||(we={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(be||(be={})),(t=>{t.NONE="none",t.FULL="full"})(ve||(ve={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(xe||(xe={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Ae||(Ae={}));const Ee="tasks",Oe={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};at.tasks=(()=>at.innerGet(Symbol.for(Ee))).bind(at),at.taskFor=(t=>{const e=at.tasks();return e?e[t]:void 0}).bind(at),at.validationExceptions=((t,e)=>{const r=at.get(t,At.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t);let i=[];return e!==a.CREATE&&e!==a.UPDATE||(i=G.nestedRelations(t)),[...new Set([...s,...i])]}).bind(at),at.migrationsFor=(t=>{if(!(t=t??qt.current))throw new u("Could not get adapter for migrations");return at.innerGet(Symbol.for(At.MIGRATION),t.alias).map(t=>t.class)}).bind(at),at.migrations=(()=>{const t=at.innerGet(Symbol.for([At.MIGRATION,At.BY_KEY].join("-")));return Object.values(t).flat().map(t=>[t.class.name,t.class])}).bind(at),at.relations=((t,e)=>{const r=at.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(at),G.relations=(t,e)=>at.relations(t instanceof G?t.constructor:t,e)||[],G.nestedRelations=((t,e=[])=>{let r=[];const s=at.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=at.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),at.createdBy=(t=>{const e=at.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(at),at.updatedBy=(t=>{const e=at.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(at),G.tableName=t=>{if(!(t instanceof G?G.get(t.constructor.name):t))throw new u("Unable to find model "+t);return at.get(t instanceof G?t.constructor:t,At.TABLE)||(t instanceof G?t.constructor.name:t.name)},G.columnName=(t,e)=>at.get(t instanceof G?t.constructor:t,at.key(At.COLUMN,e))||e,G.sequenceName=(t,...e)=>[G.tableName(t),...e].join("_"),G.sequenceFor=(t,e)=>{if(e)throw new It("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=at.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=()=>at.innerGet(Symbol.for(At.SERVICE)),e.repositories=()=>at.innerGet(Symbol.for(b.REPOSITORY));class Se 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;[a.CREATE,a.UPDATE,a.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 a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,d=await e.call(r,c,l,u,...o),p=[c,i(t),l];return a.get("observeFullResult")&&p.push(d),this.updateObservers(...p,...o).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`)),d}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof qt))throw new It("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 It("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:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...o)}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 Ce(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 Te(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(Ce,s,{priority:54})];return t&&i.push(A(Ce,s,{priority:54})),t||i.push(E()),dt(...i)},args:[t,e,...r]}).apply()}async function Ne(t,e,r,s,i){const n=e.logger.for(Ne);if(!s){const e=G.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=fe.forModel(e,r),n.info("Retrieved "+s.toString())}let o;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`),o=await s.create(t,e);else{n.info(`pk found in ${G.tableName(s.class)} - attempting update`);try{o=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)),o=await s.create(t,e)}n.info("After create update: "+o)}return o}async function ke(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=Me(s,r,this.adapter.alias),n=await e.read(i,t);return await Le(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 o=fe.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=G.pk(a);await Le(t,s,r,a[c],a),s[r]=a[c]}async function De(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Xt.CASCADE)return;if("object"!=typeof i){const e=Me(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Le(t,s,r,i,n),void(s[r]=i)}const n=await Ne(s[r],t,this.adapter.alias,void 0,this._overrides),o=G.pk(n);await Le(t,s,r,n[o],n),s[r]=n[o]}async function Be(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Xt.CASCADE)return;const n=Me(s,r,this.adapter.alias);let o;o=i instanceof G?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Le(t,s,r,o[n.pk],o)}async function _e(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 o=t.logger.for(_e),a=new Set([...i]);if("object"!==n){const e=Me(s,r,this.adapter.alias),i=await e.readAll([...a.values()],t);for(let e=0;e<i.length;e++){const s=i[e];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await Le(t,s,r,[...a.values()][e],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=G.pk(i[0].constructor),l=new Set;for(const e of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(e));const i=await Ne(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Le(t,s,r,i[c],i),o.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 _e.call(this,t,e,r,s)}async function Pe(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 o="function"!=typeof e.class||e.class.name?e.class:e.class(),a="object"===n,c=a?fe.forModel(o,this.adapter.alias):Me(s,r,this.adapter.alias),l=[...new Set([...a?i.map(t=>t[c.pk]):i]).values()];let d,p;try{d=await c.deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){p=d[e];try{await Le(t,s,r,l[e],p)}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 Ie(t,e,r){return[At.POPULATE,t,e,r].join(".")}function Re(t,e,r){return[At.TAG_FOR_DELETION,t,r].join(".")}async function Le(t,e,r,s,i){const n=Ie(e.constructor.name,r,s),o=t.get("cacheForPopulate")||{};return o[n]=i,t.accumulate({cacheForPopulate:o})}async function Fe(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(e,r,s,i)=>{let n,o;const a=[],c=e.get("cacheForPopulate")||{};for(const e of i){n=Ie(r.constructor.name,s,e);try{if(o=c[n],!o)throw Error("Not found in cache")}catch(i){const n=Me(r,s);if(!n)throw new u("Could not find repo");o=await n.read(e,t)}a.push(o)}return a})(t,s,r,n?i:[i]);s[r]=n?o:o[0]}async function je(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 o(t){return Array.isArray(t)?t.map(o):"object"!=typeof t?t:t[G.pk(t)]}const a=o(s[r]),c=o(i[r]);if(void 0===c||Q(a,c))return;if(Array.isArray(a)!==Array.isArray(c))throw new u("Cannot cascade update for different array types");const l=(Array.isArray(a)?a:[a]).filter(Boolean),d=(Array.isArray(c)?c:[c]).filter(Boolean).filter(t=>!l.includes(t)),p=Me(s,r);if(!p)throw new u("Could not find repo");try{const e=await p.deleteAll(d,t);t.logger.debug(`Deleted ${e.length} entries from table ${G.tableName(p.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}qt&&(qt._baseDispatch=Se);const Ue=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Me(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=at.get(t instanceof G?t.constructor:t,at.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=at.getPropDesignTypes(t instanceof G?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Ue.includes((""+t.name).toLowerCase()));return fe.forModel(i,r)}class Ye extends O{constructor(t,e=Ye.name,r=401){super(t,e,r)}}class Ge extends Ye{constructor(t,e=Ge.name){super(t,e,403)}}class ze extends u{constructor(t){super(t,ze.name,503)}}function He(t){return ct.for(At.TABLE).define({decorator:t=>e=>(at.set(At.TABLE,t||e.name.toLowerCase(),e),ft(At.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function qe(t){return ct.for(At.COLUMN).define({decorator:t=>(e,r)=>ut(at.key(At.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function Qe(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),ut(at.key(`${At.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Ve(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 We(){const t=At.UNIQUE;return ct.for(t).define(W(),T(Ve),ut(t,{})).apply()}async function Je(t,e,r,s){throw new Ye("This adapter does not support user identification")}function Xe(){return ct.for(At.CREATED_BY).define({decorator:()=>(t,e)=>dt(x(Je),ut(At.CREATED_BY,e),v(At.CREATED_BY))(t,e),args:[]}).apply()}function Ze(){return ct.for(At.UPDATED_BY).define({decorator:()=>(t,e)=>dt(A(Je),ut(At.UPDATED_BY,e),v(At.UPDATED_BY))(t,e),args:[]}).apply()}function Ke(){return N([a.CREATE])}function tr(){return N()}function er(t){const e="function"==typeof t&&t.name?t:t(),r=G.pk(e);return at.allowedTypes(e,r)||[]}function rr(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 o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=er(t),c=[yt(),ur(n,o),J([t,...a]),x(ke,o,{priority:70}),A(De,o,{priority:70}),k(Be,o,{priority:70}),D(je,o,{priority:70}),B(Fe,o,{priority:70})];return dt(...c)},args:[t,e,r,s,i]}).apply()}function sr(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 o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=er(t),c=[yt(),ur(n,o),X([t,...a]),x(_e,o,{priority:70}),A($e,o,{priority:70}),k(Pe,o,{priority:70}),D(je,o,{priority:70}),B(Fe,o,{priority:70})];return dt(...c)},args:[t,e,r,s,i]}).apply()}function ir(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 o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=er(t),c=[yt(),ur(n,o),J([t,...a])];return dt(...c)},args:[t,e,r,s,i]}).apply()}function nr(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 o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=er(t),c=[yt(),ur(n,o),X([t,...a])];return dt(...c)},args:[t,e,r,s,i]}).apply()}function or(...t){return(e,r)=>{const s=at.get(e,at.key(At.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return dt(ft(at.key(At.NO_VALIDATE,r),i))(e,r)}}function ar(){return or(a.CREATE)}function cr(){return or(a.UPDATE)}function lr(){return or(a.UPDATE,a.CREATE)}function ur(t,e){return ct.for(At.RELATIONS).define({decorator:(t,e)=>(r,s)=>(ut(t,e)(r,s),ut(at.key(At.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class dr extends G{constructor(t){super(t)}}i([Ke(),n("design:type",Date)],dr.prototype,"createdAt",void 0),i([tr(),n("design:type",Date)],dr.prototype,"updatedAt",void 0);const pr={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},hr=pr,gr={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},fr=Object.assign({},gr,{type:"BigInt"});async function yr(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,o,a;n=s,o=r,a=await i.next(t),Reflect.set(n,o,a)}function mr(t,e){return(r,s)=>{if(yt()(r,s),!t.type){const e=at.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(),Qe([Jt.ASC,Jt.DSC]),H(),E(),ut(at.key(b.ID,s),t),x(yr,t,e)];return t.generated&&i.push(v()),dt(...i)(r,s)}}function wr(t){const e=Object.assign({},hr);return delete e.generated,t=Object.assign({},e,t),ct.for(b.ID).define({decorator:mr,args:[t,{priority:60}]}).apply()}let br=class extends dr{constructor(t){super(t)}};i([wr({type:String,generated:!1}),n("design:type",String)],br.prototype,"id",void 0),i([H(),Qe(),n("design:type",Object)],br.prototype,"current",void 0),br=i([He("??sequence"),Z(),n("design:paramtypes",[Object])],br);class vr extends _t{static{this.lock=new ot}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=fe.forModel(br,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,a.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:o}=this.options;if(!o)throw new u("Sequence name is required");return vr.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 a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new br({id:o,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${t}`),this.repo.create(new br({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(Gt.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${o} current=${c} next=${t}`),e.current}catch(t){if(t instanceof C)continue;throw t}}const d=await(async t=>{switch(a){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),p=await l(d);return r.debug(`Sequence.increment ${o} current=${c} next=${d}`),p.current},o)}async next(...t){const{ctx:e}=(await this.logCtx(t,a.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new It(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(o-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return vr.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([br,...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 It(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function xr(t,e){return(i,n)=>n?r(at.constr(t))(i,n):(at.set(b.REPOSITORY,at.key(e||qt.currentFlavour,G.tableName(t)),i),ft(b.REPOSITORY,i.name)(t),e=e||at.get(i.constructor,At.ADAPTER),fe.register(t,i,e),s(at.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}qt._baseSequence=vr;class Ar extends u{constructor(t){super(t,Ar.name,500)}}class Er 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 Bt?[e,...r]:[...r],this.pagePrepared);s.debug(`Running paged prepared statement ${t} page${e?" - bookmark "+e:""}`),!e||e instanceof Bt||(this._bookmark=e);const n=fe.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,u=RegExp(`^${xt.FIND_BY}|${xt.LIST_BY}`,"gi");if(!a.match(u))throw new It(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,xt.PAGE_BY),p=[d,...c];let h={limit:this.size,offset:t,bookmark:this._bookmark};d!==xt.PAGE_BY||p.length>2?h={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:p.push(l.direction),p.push(h);const g=await n.statement(...p,...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 It("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?Er.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 Or,Sr,Cr,Tr;class Nr extends _t{constructor(t,e){super(),this.adapter=t,this.overrides=e,[this.execute,this.paginate].forEach(t=>{$(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"),o=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${o}`),(n&&this.isSimpleQuery()||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(Nr)}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,e){return this.orderBySelectors=[this.normalizeOrderCriterion(t,e)],this}thenBy(t,e){if(Array.isArray(t)||void 0!==e){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new Qt("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new Qt("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(t),this}normalizeOrderCriterion(t,e){if(Array.isArray(t)){const[e,r]=t;return[e,this.normalizeOrderDirection(r)]}return[t,this.normalizeOrderDirection(e)]}normalizeOrderDirection(t){if(!t)throw new Qt("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===Jt.ASC)return Jt.ASC;if(e===Jt.DSC)return Jt.DSC;throw new Qt(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Jt).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new Qt("groupBy must be called before orderBy.");return this.groupBySelectors=[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=fe.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 It("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),o=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(o):o(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,o=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);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;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.groupBySelectors&&this.groupBySelectors.length)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.orderBySelectors?.[0]?this.orderBySelectors[0]: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 o={class:this.fromSelector,method:xt.LIST_BY,args:[s],params:n};return e&&(o.method=xt.FIND_BY,o.args=[e,this.whereCondition.comparison],o.params=n),o}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)}if(this.selectSelector&&i.push(wt.SELECT,this.selectSelector.join(` ${wt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;i.push(wt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map(([t,e])=>[t,e]),e.forEach(([t])=>{i.push(wt.THEN_BY,t)}))}if(this.groupBySelectors?.length){const[t,...e]=this.groupBySelectors;i.push(wt.GROUP_BY,t),e.forEach(t=>i.push(wt.THEN_BY,t))}return 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.groupBySelectors&&this.groupBySelectors.length||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)],Nr.prototype,"select",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Or="undefined"!=typeof S&&S)?Or:Object]),n("design:returntype",Object)],Nr.prototype,"distinct",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Sr="undefined"!=typeof S&&S)?Sr:Object]),n("design:returntype",Object)],Nr.prototype,"max",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Cr="undefined"!=typeof S&&S)?Cr:Object]),n("design:returntype",Object)],Nr.prototype,"min",null),i([j(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Tr="undefined"!=typeof S&&S)?Tr:Object]),n("design:returntype",Object)],Nr.prototype,"count",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Nr.prototype,"from",null),i([j(),n("design:type",Function),n("design:paramtypes",[Wt]),n("design:returntype",Object)],Nr.prototype,"where",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],Nr.prototype,"orderBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],Nr.prototype,"thenBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],Nr.prototype,"groupBy",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Nr.prototype,"limit",null),i([j(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],Nr.prototype,"offset",null),i([j(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],Nr.prototype,"execute",null);class kr extends _t{constructor(t){super(),this.name=t,this.observers=[],this.Context=Bt}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new Pt,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 Bt||(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 Bt||(t.push(r),r=void 0);const s=await kr.prototype.flags(At.INITIALIZATION,{},...t);r=r?new Bt(r).accumulate({...s,parentContext:r}):(new Bt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=kr.prototype.logCtx(t,this.boot),o=e.services();for(const[t,r]of Object.entries(o))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 Dr&&(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 Bt||(t.push(r),r=void 0);const s=await kr.prototype.flags(At.SHUTDOWN,{},...t);r=r?new Bt(r).accumulate({...s,parentContext:r}):(new Bt).accumulate(s),t=[...t,r];const{log:i,ctxArgs:n}=kr.prototype.logCtx(t,this.shutdown),o=e.services();for(const[t,r]of Object.entries(o).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 Dr){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)],kr.prototype,"observe",null),i([j(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],kr.prototype,"unObserve",null);class Dr extends kr{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 Br(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)],Dr.prototype,"boot",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],Dr.prototype,"config",null),i([j(),n("design:type",Object),n("design:paramtypes",[])],Dr.prototype,"client",null);const _r=()=>Br(a.CREATE),$r=()=>Br(a.READ),Pr=()=>Br(a.UPDATE),Ir=()=>Br(a.DELETE);function Rr(t){return(e,i,n)=>{n||i?(yt()(e,i),t=t||at.type(e.constructor,i)):t=t||e,t=Ft(t);const o=[];if(n&&"number"==typeof n.value)o.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(t))}else at.set(At.SERVICE,t,e),o.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return dt(...o)(e,i,n)}}function Lr(t){const e=At.AUTH;return ct.for(e).define({decorator:t=>ft(e,t),args:[t]}).apply()}const Fr=t=>ft(At.AUTH_ROLE,t);function jr(t,e){const r=At.DECAF_ROUTE;return ct.for(r).define({decorator:()=>(s,i,n)=>{const o={path:e,httpMethod:t,handler:n};return dt(pt(at.key(r,i),o))(s,i,n)},args:[]}).apply()}const Ur=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class Mr extends kr{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=fe.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=Ur(t);try{const t=kr.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,a.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,a.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,a.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,a.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=Ur(e||t);try{r=Mr.get(e)}catch(t){r=void 0}if(r instanceof Mr)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([Rr(e),n("design:paramtypes",[])],o),new o}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([_r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Mr.prototype,"create",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Mr.prototype,"createAll",null),i([Ir(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Mr.prototype,"delete",null),i([Ir(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Mr.prototype,"deleteAll",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Mr.prototype,"read",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],Mr.prototype,"readAll",null),i([$r(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],Mr.prototype,"query",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],Mr.prototype,"update",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],Mr.prototype,"updateAll",null);class Yr extends Dr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||!Array.isArray(e)||e instanceof Bt||!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 Gr=class extends G{constructor(t){super(t),this.strategy=be.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=ve.FULL}};i([H(),J(String),K(be),mt("the backoff strategy"),n("design:type",String)],Gr.prototype,"strategy",void 0),i([H(),mt("base interval between attempts"),n("design:type",Number)],Gr.prototype,"baseMs",void 0),i([H(),mt("max interval"),n("design:type",Number)],Gr.prototype,"maxMs",void 0),i([J(String),K(ve),mt("optional jitter strategy"),n("design:type",String)],Gr.prototype,"jitter",void 0),Gr=i([Z(),n("design:paramtypes",[Object])],Gr);let zr=class extends G{constructor(t){super(t)}};i([H(),mt("The error message"),n("design:type",String)],zr.prototype,"message",void 0),i([yt(),mt("The error stack"),n("design:type",String)],zr.prototype,"stack",void 0),i([yt(),mt("The error code"),n("design:type",String)],zr.prototype,"code",void 0),i([yt(),mt("The error details"),n("design:type",Object)],zr.prototype,"details",void 0),zr=i([Z(),n("design:paramtypes",[Object])],zr);let Hr=class extends G{constructor(t){super(t),this.ts=new Date}};i([P(["taskId","classification","uuid"],":"),wr(),n("design:type",String)],Hr.prototype,"id",void 0),i([E(),H(),I(),Te(!1),n("design:type",String)],Hr.prototype,"uuid",void 0),i([E(),H(),n("design:type",String)],Hr.prototype,"taskId",void 0),i([tt(),H(),n("design:type",Date)],Hr.prototype,"ts",void 0),i([E(),H(),K(xe),n("design:type",String)],Hr.prototype,"classification",void 0),i([yt(),E(),n("design:type",Object)],Hr.prototype,"payload",void 0),Hr=i([He("task_event"),Z(),n("design:paramtypes",[Object])],Hr);class qr 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=at.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 Qr=class extends G{constructor(t){super(t),this.ts=new Date}};i([tt(),H(),n("design:type",Date)],Qr.prototype,"ts",void 0),i([H(),K(M),n("design:type",String)],Qr.prototype,"level",void 0),i([H(),yt(),n("design:type",String)],Qr.prototype,"msg",void 0),i([yt(),n("design:type",Object)],Qr.prototype,"meta",void 0),Qr=i([Z(),n("design:paramtypes",[Object])],Qr);let Vr=class extends G{constructor(t){super(t),this.atomicity=Ae.ATOMIC,this.status=we.PENDING,this.attempt=0,this.logTail=[]}};i([wr({type:"uuid"}),mt("the task id"),n("design:type",String)],Vr.prototype,"id",void 0),i([H(),J(String),K(Ae),mt("defines a single or composite task"),n("design:type",String)],Vr.prototype,"atomicity",void 0),i([H(),mt("Holds task classification - must match @task()"),n("design:type",String)],Vr.prototype,"classification",void 0),i([H(),J(String),K(we),mt("Holds the task current status"),n("design:type",String)],Vr.prototype,"status",void 0),i([yt(),R(qr),mt("Holds task input"),n("design:type",Object)],Vr.prototype,"input",void 0),i([yt(),R(qr),mt("Holds the task output when successfully completed"),n("design:type",Object)],Vr.prototype,"output",void 0),i([yt(),R(),mt("Holds the error for failed tasks"),n("design:type",zr)],Vr.prototype,"error",void 0),i([H(),st(0),mt("Holds the current attempt"),n("design:type",Number)],Vr.prototype,"attempt",void 0),i([st(1),H(),mt("max attempts for the task"),n("design:type",Number)],Vr.prototype,"maxAttempts",void 0),i([H(),R(),mt("backoff configuration"),n("design:type",Gr)],Vr.prototype,"backoff",void 0),i([tt(),mt("Next execution timestamp"),n("design:type",Date)],Vr.prototype,"nextRunAt",void 0),i([yt(),mt("Task lease owner identifier"),n("design:type",String)],Vr.prototype,"leaseOwner",void 0),i([tt(),mt("Task lease expiration timestamp"),n("design:type",Date)],Vr.prototype,"leaseExpiry",void 0),i([yt(),R(),mt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],Vr.prototype,"steps",void 0),i([st(0),yt(),mt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],Vr.prototype,"currentStep",void 0),i([yt(),R(),mt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],Vr.prototype,"stepResults",void 0),i([yt(),R(),mt("Holds the task log entries"),n("design:type",Array)],Vr.prototype,"logTail",void 0),i([qe(),Ke(),mt("timestamp of creation"),n("design:type",Date)],Vr.prototype,"createdAt",void 0),i([qe(),tr(),mt("timestamp of last update"),n("design:type",Date)],Vr.prototype,"updatedAt",void 0),i([qe(),Xe(),mt("Holds the creator of the task"),n("design:type",String)],Vr.prototype,"createdBy",void 0),i([qe(),Ze(),mt("Holds the creator of the task"),n("design:type",String)],Vr.prototype,"updatedBy",void 0),Vr=i([mt("Holds the current step when applicable"),He("tasks"),Z(),n("design:paramtypes",[Object])],Vr);let Wr=class extends G{constructor(t){super(t)}};i([H(),mt("The status of a step"),n("design:type",String)],Wr.prototype,"status",void 0),i([yt(),mt("The result of a successful step"),n("design:type",Object)],Wr.prototype,"output",void 0),i([yt(),mt("the error of a failed step"),n("design:type",zr)],Wr.prototype,"error",void 0),Wr=i([Z(),n("design:paramtypes",[Object])],Wr);let Jr=class extends G{constructor(t){super(t)}};i([H(),yt(),mt("task handler type"),n("design:type",String)],Jr.prototype,"classification",void 0),i([mt("optional task step input"),yt(),n("design:type",Object)],Jr.prototype,"input",void 0),Jr=i([Z(),n("design:paramtypes",[Object])],Jr);class Xr extends G{constructor(t){super(t),this.baseMs=1e3,this.jitter=ve.FULL,this.maxMs=6e4,this.strategy=be.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 d(t);return new Gr(this)}}i([H(),st(1e3),n("design:type",Number)],Xr.prototype,"baseMs",void 0),i([H(),K(ve),n("design:type",String)],Xr.prototype,"jitter",void 0),i([it("baseMs"),st(1e3),H(),n("design:type",Number)],Xr.prototype,"maxMs",void 0),i([H(),K(be),n("design:type",String)],Xr.prototype,"strategy",void 0);class Zr 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 Xr,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=we.PENDING,this.atomicity=Ae.ATOMIC,this.backoff=new Gr,this.maxAttempts=1,G.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new Vr(this)}}i([H(),n("design:type",String)],Zr.prototype,"classification",void 0),i([H(),n("design:type",String)],Zr.prototype,"status",void 0),i([H(),n("design:type",String)],Zr.prototype,"atomicity",void 0),i([H(),n("design:type",Gr)],Zr.prototype,"backoff",void 0),i([yt(),n("design:type",Object)],Zr.prototype,"input",void 0),i([st(1),H(),n("design:type",Number)],Zr.prototype,"maxAttempts",void 0);class Kr extends Zr{constructor(t){super(t),this.stepResults=[],G.fromModel(this,t),this.atomicity=Ae.COMPOSITE}setSteps(t){return this.steps=t,this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new Jr({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([X(()=>Jr),n("design:type",Array)],Kr.prototype,"steps",void 0);class ts extends $t{get type(){if(!this._type){const t=at.get(this.constructor,Ee);"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 es(t){return ct.for(Ee).define({decorator:t=>e=>{const r={type:t};return at.set(Ee,t,e),ft(Ee,r)(e)},args:[t]}).apply()}let rs=class extends ts{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(we.SUCCEEDED).and(Wt.attr("updatedAt").lte(t.successfulExpiry)),i=Wt.attr("status").eq(we.FAILED).and(Wt.attr("updatedAt").lte(t.failedExpiry)),n=Wt.attr("status").eq(we.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([xr(Vr),n("design:type",Object)],rs.prototype,"tasks",void 0),rs=i([es("cleanup-task"),n("design:paramtypes",[])],rs);class ss{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 is(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 xe.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 xe.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case xe.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=Y(e);switch(e){case we.SUCCEEDED:s=s.green.bold;break;case we.RUNNING:s=s.blue.bold;break;case we.PENDING:s=s.yellow;break;case we.WAITING_RETRY:s=s.yellow.bold;break;case we.FAILED:s=s.red.bold;break;case we.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 ns extends Bt{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 os{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=at.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 as extends Pt{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(Hr,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=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,...o)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(t=>{t.observer.refresh(s,...o)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}function cs(t,e){const r=e.strategy===be.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===ve.FULL?Math.floor(Math.random()*s):s}function ls(t){return new zr({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function us(t){return new Promise(e=>setTimeout(e,t))}class ds{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===Hr||t===G.tableName(Hr))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([we.SUCCEEDED,we.FAILED,we.CANCELED,we.WAITING_RETRY])}wait(){return this.awaitStatusTerminal([we.SUCCEEDED,we.FAILED,we.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(is(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==xe.LOG)return;const r=e.payload;await t(r)},xe.LOG)}pipe(t,e=xe.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(we.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(we.FAILED,t)}onCancel(t){return this.registerStatusHandler(we.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===we.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 zr)return this.lastTerminalPayload;const e=t.payload?.status??this.task.status,r=e===we.WAITING_RETRY?`Task ${this.task.id} scheduled for retry`:`Task ${this.task.id} ${e}`;return new zr({message:r})}complete(t){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0,this.lastTerminalPayload=t)}isTerminalStatus(t){return[we.SUCCEEDED,we.CANCELED,we.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===we.SUCCEEDED&&this.succeed(t.payload.output),t.payload.status===we.FAILED&&this.fail(t.payload.error),t.payload.status===we.CANCELED&&this.cancel(t),t.payload.status===we.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,xe.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[xe.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new Bt),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===we.SUCCEEDED&&(e.output=this.task.output),t!==we.FAILED&&t!==we.CANCELED||!this.task.error||(e.error=this.task.error),new Hr({classification:xe.STATUS,taskId:this.task.id,payload:e})}resolveTerminalState(){this.isTerminalStatus(this.task.status)&&(this.task.status!==we.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[xe.ALL]?[...this.pipes[xe.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 ps extends $t{get Context(){return ns}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=fe.forModel(Vr,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=fe.forModel(Hr,this.config.adapter.alias)),this._events}constructor(t){super(),this.config=t,this.lock=new nt,this.running=!1,this.config=Object.assign({},Oe,t,{bus:t.bus||new as,registry:t.registry||new os})}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.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 ds(this.bus,n)}:n}async track(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.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 ds(this.bus,i)}}async ensureTaskError(t,e){if(![we.FAILED,we.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await us(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===we.SUCCEEDED||s.status===we.FAILED)return s;s.status=we.CANCELED;const i=new zr({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,we.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(we.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((t,n)=>{const o=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(o),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()}).catch(t=>{clearTimeout(o),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 us(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(we.PENDING),i=Wt.attribute("status").eq(we.WAITING_RETRY).and(Wt.attribute("nextRunAt").lte(r)),n=Wt.attribute("status").eq(we.RUNNING).and(Wt.attribute("leaseExpiry").lte(r)),o=s.or(i).or(n),a=await this.tasks.select().where(o).limit(Math.max(4*this.config.concurrency,20)).execute();e.verbose("claimBatch candidates:"+a.length);const c=[];for(const e of a){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 Vr({...i,status:we.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 ns(e).accumulate({taskId:t.id,logger:new ss(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,we.RUNNING);try{let e;if(t.atomicity===Ae.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=we.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,we.SUCCEEDED,e)}catch(e){r.error("task execution error",e);try{t=await this.tasks.read(t.id,s)}catch{}if(t.atomicity===Ae.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===we.FAILED);0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=ls(e);if(i<t.maxAttempts){const e=cs(i,this.normalizeBackoff(t.backoff)),o=new Date(Date.now()+e);t.attempt=i,t.status=we.WAITING_RETRY,t.nextRunAt=o,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,we.WAITING_RETRY),await s.pipe(M.warn,"Retry scheduled",{nextRunAt:o,delayMs:e,attempt:i})}else t.attempt=i,t.status=we.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,we.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),o=(t,s)=>{e.cacheResult(t,s),r instanceof ns&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===we.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;o(i.classification,r.output),o(n,r.output)}}for(;i<s.length;){const r=s[i],a=this.registry.get(r.classification);if(!a)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 a.run(r.input,e),l=i,u=new Date;n[l]=new Wr({status:we.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const d=`${t.id}:step:${l}`;o(r.classification,c),o(d,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 Wr({status:we.FAILED,error:ls(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=ls(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(t){if(t instanceof Gr)return t;let e=t??{};if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Gr(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 Jr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Jr(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 Wr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Wr(e)}):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map(([t,e,r])=>new Qr({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 ns&&await t.flush();const i={status:r};s&&s instanceof zr?i.error=s:s&&(i.output=s);const n=await this.persistEvent(t,e.id,xe.STATUS,i);this.bus.emit(n,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,xe.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,xe.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Hr({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,Vr,...r)}}class hs extends Dr{constructor(){super()}async initialize(...t){const e=t.shift();if(!e||e instanceof Bt)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 ps(e);return r.verbose(s+" initialized"),{client:s,config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.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,a.CREATE,!0)).for(this.push);return this.client.track(t,...r)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.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,a.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,a.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 It("Updates to tasks are not available")}async updateAll(t,...e){throw new It("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([xr(Vr),n("design:type",Object)],hs.prototype,"repo",void 0),i([_r(),n("design:type",Function),n("design:paramtypes",[Vr,void 0]),n("design:returntype",Promise)],hs.prototype,"create",null),i([_r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"createAll",null),i([Ir(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"delete",null),i([Ir(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"deleteAll",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],hs.prototype,"read",null),i([$r(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"readAll",null),i([$r(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],hs.prototype,"query",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Vr,void 0]),n("design:returntype",Promise)],hs.prototype,"update",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],hs.prototype,"updateAll",null),e.setRegistry(new me);const gs="##VERSION##",fs="##PACKAGE##";at.registerLibrary(fs,gs);export{$t as AbsContextual,qt as Adapter,Ye as AuthorizationError,be as BackoffStrategy,dr as BaseModel,fr as BigIntSequence,Xt as Cascade,rs as CleanUpTask,Dr as ClientBasedService,Kr as CompositeTaskBuilder,Wt as Condition,ze as ConnectionError,Bt as Context,Dt as ContextLock,_t as ContextualLoggedClass,Ot as DefaultAdapterFlags,Zt as DefaultCascade,Et as DefaultContextFlags,he as DefaultRepositoryFilters,hr as DefaultSequenceOptions,Oe as DefaultTaskEngineConfig,Se as Dispatch,Ge as ForbiddenError,vt as GroupOperator,me as InjectablesRegistry,ve as JitterStrategy,ee as MethodQueryBuilder,Rt as MigrationError,Lt as MigrationRuleError,Mr as ModelService,Nt as MultipleSelectOperationKeys,Ct as NonTransactionOperationKeys,pr as NoneSequenceOptions,gr as NumericSequence,Ar as ObserverError,Pt as ObserverHandler,bt as Operator,Kt as OperatorsMap,Jt as OrderDirection,fs as PACKAGE_NAME,kt as PaginationOperationKeys,Er as Paginator,Vt as PagingError,At as PersistenceKeys,Yr as PersistenceService,xt as PreparedStatementKeys,wt as QueryClause,Qt as QueryError,fe as Repository,Tt as SelectOperationKeys,vr as Sequence,br as SequenceModel,zt as Serial,kr as Service,Nr as Statement,Xr as TaskBackoffBuilder,Gr as TaskBackoffModel,Zr as TaskBuilder,ns as TaskContext,ps as TaskEngine,zr as TaskErrorModel,as as TaskEventBus,Hr as TaskEventModel,xe as TaskEventType,ts as TaskHandler,os as TaskHandlerRegistry,qr as TaskIOSerializer,Qr as TaskLogEntryModel,ss as TaskLogger,Vr as TaskModel,hs as TaskService,we as TaskStatus,Wr as TaskStepResultModel,Jr as TaskStepSpecModel,ds as TaskTracker,Ae as TaskType,Ee as TasksKey,St as TransactionOperationKeys,Gt as UUID,It as UnsupportedError,gs as VERSION,ie as applyViewDecorator,Lr as auth,Le as cacheModelForPopulate,je as cascadeDelete,qe as column,cs as computeBackoffMs,_r as create,Ne as createOrUpdate,Ke as createdAt,Xe as createdBy,Je as createdByOnCreateUpdate,Ir as del,ye as generateInjectableNameForRepository,ge as getFilters,is as getLogPipe,er as getPkTypes,Ie as getPopulateKey,Re as getTagForDeleteKey,Qe as index,Ft as injectableServiceKey,Ut as isOperationBlocked,nr as manyToMany,ir as manyToOne,or as noValidateOn,ar as noValidateOnCreate,lr as noValidateOnCreateUpdate,cr as noValidateOnUpdate,Mt as normalizeImport,sr as oneToMany,_e as oneToManyOnCreate,Pe as oneToManyOnDelete,$e as oneToManyOnUpdate,rr as oneToOne,ke as oneToOneOnCreate,Be as oneToOneOnDelete,De as oneToOneOnUpdate,de as onlyOnBulk,oe as onlyOnCreate,ce as onlyOnDelete,pe as onlyOnFilter,ue as onlyOnSingle,le as onlyOnTransactional,ae as onlyOnUpdate,wr as pk,mr as pkDec,yr as pkOnCreate,Fe as populate,Yt as prefixMethod,re as prepared,jt as promiseSequence,se as query,$r as read,ur as relation,xr as repository,Me as repositoryFromTypeMetadata,Fr as roles,jr as route,ls as serializeError,Rr as service,us as sleep,He as table,es as task,We as unique,Ve as uniqueOnCreateUpdate,Pr as update,tr as updatedAt,Ze as updatedBy,Te as uuid,Ce as uuidCreateUpdateHandler,ne as view};
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 o,OperationKeys as a,BulkCrudOperationKeys as c,Context as l,InternalError as u,ValidationError as d,Repository as h,wrapMethodWithContext as p,wrapMethodWithContextForUpdate as g,enforceDBDecorators as f,reduceErrorsToPrint as y,NotFoundError as m,DefaultSeparator as w,DBKeys as b,generated as v,onCreate as E,onUpdate as x,readonly as A,BadRequestError as O,ConflictError as C,onCreateUpdate as T,timestamp as k,onDelete as N,afterUpdate as D,afterAny as R,SerializationError as _,prefixMethod as B,composed as $,transient as I,serialize as P,BaseError as L}from"@decaf-ts/db-decorators";import{LoggedClass as F,Logging as j,final as U,toCamelCase as M,LogLevel as G,style as Y}from"@decaf-ts/logging";import{Model as H,hashObj as q,required as z,sf as Q,isEqual as W,ValidationKeys as V,async as J,type as X,list as Z,model as K,option as tt,date as et,JSONSerializer as rt,ModelKeys as st,min as it,gt as nt}from"@decaf-ts/decorator-validation";import{Lock as ot,MultiLock as at}from"@decaf-ts/transactional-decorators";import{Metadata as ct,Decoration as lt,DefaultFlavour as ut,propMetadata as dt,apply as ht,methodMetadata as pt,DecorationKeys as gt,uses as ft,metadata as yt,prop as mt,description as wt}from"@decaf-ts/decoration";var bt,vt,Et,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"})(bt||(bt={})),(t=>{t.EQUAL="EQUAL",t.DIFFERENT="DIFFERENT",t.BIGGER="BIGGER",t.BIGGER_EQ="BIGGER_EQ",t.SMALLER="SMALLER",t.SMALLER_EQ="SMALLER_EQ",t.BETWEEN="BETWEEN",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",t.VIEW="view"})(vt||(vt={})),(t=>{t.AND="AND",t.OR="OR"})(Et||(Et={})),(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 St=Object.assign({},{ignoreDevSafeGuards:!1}),Ot=Object.assign({},o,{enforceUpdateValidation:!0,allowRawStatements:!0,forcePrepareSimpleQueries:!1,forcePrepareComplexQueries:!1,cacheForPopulate:{},noEmit:!1,noEmitSingle:!1,noEmitBulk:!1,observeFullResult:!0,paginateByBookmark:!1,dryRun:!1}),Ct=[a.CREATE,a.UPDATE,a.DELETE,c.CREATE_ALL,c.UPDATE_ALL,c.DELETE_ALL],Tt=[a.READ,c.READ_ALL],kt=[At.STATEMENT,xt.FIND_ONE_BY],Nt=[At.QUERY,xt.PAGE_BY,xt.LIST_BY,xt.FIND_BY],Dt=[xt.PAGE_BY];class Rt extends ot{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 Bt extends F{logCtx(t,e,r=!1,s){return Bt.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||j.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 o=n instanceof _t;if(n&&!o&&(s.push(n),n=void 0),!r&&!o)throw new u("No context provided");if(o&&!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 $t extends Bt{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 It{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}=Bt.logCtx(this.updateObservers,void 0,!1,...s);(await Promise.allSettled(this.observers.filter(s=>{const{filter:o}=s;if(!o)return!0;try{return o(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 Pt extends u{constructor(t){super(t,Pt.name,500)}}class Lt extends u{constructor(t,e=Lt.name){super(t,e,500)}}class Ft extends Lt{constructor(t){super(t,Ft.name)}}function jt(t){if(!t)throw new u("No name provided");return"string"==typeof t?t.replaceAll(".","-"):ct.Symbol(ct.constr(t)).toString().replaceAll(".","-")}function Ut(t){return t.reduce((t,e)=>t.then(async t=>[...t,await e()]),Promise.resolve([]))}function Mt(t,e){const{handler:r,args:s}=ct.get(t,a.REFLECT+a.BLOCK)||{};return!!r&&(r(...s,e)??!1)}async function Gt(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 Ft)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 Ht{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 Ht._instance||(Ht._instance=new Ht),Ht._instance}}class qt{constructor(){this.count=14}generate(t){return(""+((t=(t?parseInt(t):0)||0)+1)).padStart(this.count,"0")}static get instance(){return qt._instance||(qt._instance=new qt),qt._instance}}const zt=lt.flavourResolver.bind(lt);lt.flavourResolver=t=>{try{const e=zt(t);if(e&&e!==ut)return e;const r="function"==typeof t?t:t?.constructor,s=r&&"function"==typeof ct.registeredFlavour?ct.registeredFlavour(r):void 0;if(s&&s!==ut)return s;const i=Qt._currentFlavour;if(i){const t=Qt._cache?.[i];return t?.flavour?t.flavour:i}}catch(t){return ut}};class Qt extends $t{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 It}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?H.tableName(i)+" - ":"";r.correlationId=r.correlationId||`${n}${t}-${Ht.instance.generate()}`;const o=r.logger||j.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:Ct.includes(t),timestamp:new Date,operation:t,ignoredValidationProperties:e?ct.validationExceptions(Array.isArray(e)&&e[0]?e[0]:e,t):[],logger:o})}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=>H.tableName(t)):H.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=H.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[H.pk(t.constructor)],transient:s.transient}}revert(t,e,r,s,...i){const{log:n,ctx:o}=this.logCtx(i,this.revert),a=H.pk(e),c=new e;c[a]=r,n.silly(`Rebuilding model ${c.constructor.name} id ${r}`);const l=t[At.METADATA],d=Object.keys(c).filter(t=>t!==a).reduce((r,s)=>(r[s]=t[H.columnName(e,s)],r),c);return o.get("rebuildWithTransient")&&s&&(n.verbose("re-adding transient properties: "+Object.keys(s).join(", ")),Object.entries(s).forEach(([t,e])=>{if(t in d&&void 0!==d[t])throw new u(`Transient property ${t} already exists on model ${c.constructor.name}. should be impossible`);d[t]=e})),l&&(n.silly(`Passing along ${this.flavour} persistence metadata for ${c.constructor.name} id ${r}: ${l}`),Object.defineProperty(d,At.METADATA,{enumerable:!1,configurable:!0,writable:!0,value:l})),d}async createAll(t,e,r,...s){const{log:i,ctx:n}=this.logCtx(s,this.createAll);if(!e||!r)throw new d("Ids and models cannot be null or undefined");if(e.length!==r.length)throw new d("Ids and models must have the same length");const o=H.tableName(t);return i.debug(`Creating ${e.length} entries ${o} table`),Ut(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=H.tableName(t);return s.debug(`Reading ${e.length} entries ${n} table`),Ut(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 o=H.tableName(t);return i.debug(`Updating ${e.length} entries ${o} table`),Ut(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`),Ut(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),o=!i.get("noEmitSingle"),a=!i.get("noEmitBulk");(s&&a||!s&&o)&&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 ct.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 ct.flavouredAs(t).filter(H.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} - ${q(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 ct.migrationsFor(this)}async getQueryRunner(){return this}logCtx(t,e,r=!1,s){return super.logCtx(t,e,r,s)}}i([U(),n("design:type",Function),n("design:paramtypes",[String]),n("design:returntype",Promise)],Qt.prototype,"shutdownProxies",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Object,Object,_t]),n("design:returntype",Promise)],Qt.prototype,"context",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Qt.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Qt.prototype,"unObserve",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],Qt.prototype,"client",null);class Wt extends u{constructor(t){super(t,Wt.name,500)}}class Vt extends u{constructor(t){super(t,Vt.name,500)}}class Jt extends H{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):H.fromModel(this,t)}and(t){return Jt.and(this,t)}or(t){return Jt.or(this,t)}not(t){return new Jt(this,vt.NOT,t)}hasErrors(...t){const e=()=>{const t=`Invalid operator ${this.operator}}`;if("string"==typeof this.attr1){if(this.comparison instanceof Jt)return{comparison:{condition:"Both sides of the comparison must be of the same type"}};if(-1===Object.values(vt).indexOf(this.operator))return{operator:{condition:t}};if(this.operator===vt.BETWEEN&&(!Array.isArray(this.comparison)||2!==this.comparison.length))return{comparison:{condition:"BETWEEN operator requires an array with exactly 2 values [min, max]"}}}if(this.attr1 instanceof Jt){if(!(this.comparison instanceof Jt)&&this.operator!==vt.NOT)return{comparison:{condition:t}};if(-1===Object.values(Et).indexOf(this.operator)&&this.operator!==vt.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 Jt.group(t,Et.AND,e)}static or(t,e){return Jt.group(t,Et.OR,e)}static group(t,e,r){return new Jt(t,e,r)}static attribute(t){return(new Jt.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(vt.EQUAL,t)}dif(t){return this.setOp(vt.DIFFERENT,t)}gt(t){return this.setOp(vt.BIGGER,t)}lt(t){return this.setOp(vt.SMALLER,t)}gte(t){return this.setOp(vt.BIGGER_EQ,t)}lte(t){return this.setOp(vt.SMALLER_EQ,t)}in(t){return this.setOp(vt.IN,t)}regexp(t){return this.setOp(vt.REGEXP,RegExp(t).source)}between(t,e){return this.setOp(vt.BETWEEN,[t,e])}setOp(t,e){return this.operator=t,this.comparison=e,this.build()}build(){try{return new Jt(this.attr1,this.operator,this.comparison)}catch(t){throw new Wt(t)}}}}static builder(){return new Jt.Builder}static from(t){return new Jt(t)}}var Xt,Zt;i([z(),n("design:type",Object)],Jt.prototype,"attr1",void 0),i([z(),n("design:type",String)],Jt.prototype,"operator",void 0),i([z(),n("design:type",Object)],Jt.prototype,"comparison",void 0),(t=>{t.ASC="asc",t.DSC="desc"})(Xt||(Xt={})),(t=>{t.CASCADE="cascade",t.NONE="none"})(Zt||(Zt={}));const Kt={update:Zt.CASCADE,delete:Zt.NONE},te={Equals:(t,e)=>Jt.attribute(t).eq(e),Diff:(t,e)=>Jt.attribute(t).dif(e),LessThan:(t,e)=>Jt.attribute(t).lt(e),LessThanEqual:(t,e)=>Jt.attribute(t).lte(e),GreaterThan:(t,e)=>Jt.attribute(t).gt(e),GreaterThanEqual:(t,e)=>Jt.attribute(t).gte(e),In:(t,e)=>Jt.attribute(t).in(e),Matches:(t,e)=>Jt.attribute(t).regexp(e)},ee=t=>t.charAt(0).toLowerCase()+t.slice(1);class re extends F{static get log(){return this._logger||(this._logger=j.for(re.name)),this._logger}static build(t,...e){if(!t.startsWith(bt.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:o,limit:a,offset:c}=this.extractOrderLimitOffset(t,e);return{action:"find",select:s,where:n,groupBy:i,orderBy:o,limit:a,offset:c}}static extractCore(t){const e=t.substring(bt.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(bt.SELECT);if(-1===e)return;const r=t.substring(e+bt.SELECT.length),s=r.match(/(Then[A-Z]|OrderBy|GroupBy|Limit|Offset)/);return(s?r.substring(0,s.index):r).split(bt.AND).map(ee).filter(Boolean)}static extractGroupBy(t){const e=t.indexOf(bt.GROUP_BY);if(-1!==e)return t.substring(e+bt.GROUP_BY.length).split(bt.ORDER_BY)[0].split(bt.THEN_BY).map(ee).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:o}=this.parseFieldAndOperator(t),a=o?te[o]:te.Equals;if(!a)throw Error("Unsupported operator "+o);const c=e[r];if(void 0===c)throw Error("Invalid value for field "+n);const l=a(n,c);i=0===r?l:s[r-1]===bt.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(te))if(t.endsWith(e)){const r=t.slice(0,-e.length);return{field:ee(r),operator:e}}return{field:ee(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=re.log.for(this.getProperlyOrderByOrThrow);if(e||t){if(e&&!t)throw new Wt("Expected OrderBy clause, but no sortable field was found in method name.");if(e||!t){if(!Object.values(Xt).includes(e))throw new Wt(`Invalid OrderBy direction ${e}. Expected one of: ${Object.values(Xt).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,o;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]||(o=s[2]),{orderBy:i,limit:n,offset:o}}}function se(){return lt.for(At.STATEMENT).define({decorator:()=>(t,e,r)=>ht(pt(ct.key(At.STATEMENT,e),!0))(t,e,r),args:[]}).apply()}function ie(t={}){return lt.for(At.QUERY).define({decorator:t=>(e,r,s)=>{const i=re.getFieldsFromMethodName(r);return ht(pt(ct.key(At.QUERY,r),{...t,fields:i}),se(),(t=>(e,r,s)=>{s.value=new Proxy(s.value,{apply(e,r,s){const{select:i,where:n,groupBy:o,orderBy:a,limit:c,offset:l}=re.build(e.name,...s);let u=r.select(i);n&&(u=u.where(n));const{allowLimit:d,allowOffset:h,allowOrderBy:p,throws:g}={allowLimit:!0,allowOrderBy:!0,allowOffset:!0,throws:!0,...t},f=[{key:"orderBy",value:(a||[])[0],allowed:p},{key:"limit",value:c,allowed:d},{key:"offset",value:l,allowed:h}];for(const t of f)if(void 0!==t.value){if(!t.allowed&&g)throw new Wt(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 ne(t,e,r){return(s,i)=>{const n=r?.name||((t,e,r)=>{const s=(ct.get(t.constructor,e)||{})[r]||{};return Object.keys(s).length+1+""})(s,t,i),o=ct.key(t,i,n),a={...r||{},kind:e,attribute:i};return dt(o,a)(s,i)}}function oe(t){return lt.for(vt.VIEW).define({decorator:t=>ne(vt.VIEW,"view",t),args:[t]}).apply()}function ae(t){return pe(t,[a.CREATE,c.CREATE_ALL])}function ce(t){return pe(t,[a.UPDATE,c.UPDATE_ALL])}function le(t){return pe(t,[a.DELETE,c.DELETE_ALL])}function ue(t){return pe(t,Ct)}function de(t){return pe(t,Object.values(a))}function he(t){return pe(t,Object.values(c))}function pe(t,e){return(r,s,i,...n)=>{if("string"==typeof t)throw new u("clazz cannot be string. This should be impossible");const{log:o}=Bt.prototype.logCtx(n,pe);return o.silly(`filtering ${s} event for${r?" "+(H.tableName(r)||r):""} ${i}`),("string"==typeof r?r===H.tableName(t)||r===t.constructor.name:ct.constr(t)===ct.constr(r))&&e.includes(s)}}const ge={onlyOnCreate:ae,onlyOnUpdate:ce,onlyOnDelete:le,onlyOnTransactional:ue,onlyOnSingle:de,onlyOnBulk:he};function fe(t){const e=Object.assign({},ge);return Object.entries(e).forEach(([r,s])=>{e[r]=s(t.class)}),e}class ye extends h{static{this._cache={}}get log(){return this.logger||(this.logger=this.adapter.log.for(this.toString())),this.logger}get adapter(){if(!this._adapter)throw new 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=H.tableName(this.class)),this._tableName}get pkProps(){return super.pkProps}get filters(){return fe(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&&(ye.register(e,this,this.adapter.alias),t)&&ct.get(e,gt.FLAVOUR)===ut&&ft(t.flavour)(e);const s=this;[this.createAll,this.readAll,this.deleteAll].forEach(t=>{const e=t.name;p(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 It}async createPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.CREATE,!0)).for(this.createPrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),t=new this.class(t),n||await f(this,r,t,a.CREATE,a.ON),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(...e));if(s)throw new d(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 ${H.tableName(this.class)}`);let{record:n,id:o,transient:a}=this.adapter.prepare(t,r);return n=await this.adapter.create(this.class,o,n,...i),this.adapter.revert(n,this.class,o,a,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 ${H.tableName(this.class)}`);const n=t.map(t=>this.adapter.prepare(t,r)),o=n.map(t=>t.id);let a=n.map(t=>t.record);return a=await this.adapter.createAll(this.class,o,a,...i),a.map((t,e)=>this.adapter.revert(t,this.class,o[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"),o=r.get("ignoreValidation");if(i.silly(`handlerSetting: ${n}, validationSetting: ${o}`),!t.length)return[t,...s];const l=H.sequenceFor(t[0]);let h=[];if(H.generatedBySequence(this.class)?(l.name||(l.name=H.sequenceName(t[0],"pk")),h=await(await this.adapter.Sequence(l)).range(t.length,...s)):H.generated(this.class,this.pk)||(h=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?h[e]:""+t[this.pk]),n||await f(this,r,t,a.CREATE,a.ON),t))),!o){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 d(n)}return[t,...s]}async readPrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.READ,!0)).for(this.readPrefix),n=r.get("ignoreHandlers");i.silly("handlerSetting: "+n);const o=new this.class;return o[this.pk]=t,n||await f(this,r,o,a.READ,a.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 ${H.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,a.READ,a.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 ${H.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:o,transient:a}=this.adapter.prepare(t,i);return s.debug(`updating ${this.class.name} in table ${H.tableName(this.class)} with id ${o}`),n=await this.adapter.update(this.class,o,n,...r),this.adapter.revert(n,this.class,o,a,i)}async updatePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.UPDATE,!0)).for(this.updatePrefix),n=r.get("ignoreHandlers"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, validationSetting: ${o}`);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=H.merge(l,t,this.class))),n||await f(this,r,t,a.UPDATE,a.ON,l),!o){const e=r.get("ignoredValidationProperties")||[];i.silly("ignored validation properties: "+e);const s=await Promise.resolve(t.hasErrors(l,...e));if(s)throw new d(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 ${H.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"),o=r.get("ignoreValidation");i.silly(`handlerSetting: ${n}, ignoredValidation: ${o}`);const l=t.map(t=>{const e=t[this.pk];if(!e)throw new u("missing id on update operation");return e});let h;if(r.get("applyUpdateValidation")&&(h=await this.readAll(l,r),r.get("mergeForUpdate")&&(t=t.map((t,e)=>H.merge(h[e],t,this.class)))),n||await Promise.all(t.map((t,e)=>f(this,r,t,a.UPDATE,a.ON,h?h[e]:void 0))),!o){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(h[r],...e)))):await Promise.resolve(t.map(t=>t.hasErrors(...e)));const n=y(s);if(n)throw new d(n)}return[t,...s,h]}async deletePrefix(t,...e){const{ctx:r,ctxArgs:s,log:i}=(await this.logCtx(e,a.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,a.DELETE,a.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 ${H.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,a.DELETE,a.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 ${H.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)}count(t){return this.adapter.Statement(this._overrides).count(t).from(this.class)}min(t){return this.adapter.Statement(this._overrides).min(t).from(this.class)}max(t){return this.adapter.Statement(this._overrides).max(t).from(this.class)}sum(t){return this.adapter.Statement(this._overrides).sum(t).from(this.class)}avg(t){return this.adapter.Statement(this._overrides).avg(t).from(this.class)}distinct(t){return this.adapter.Statement(this._overrides).distinct(t).from(this.class)}async query(t,e,r=Xt.ASC,s,i,...n){const{ctxArgs:o}=(await this.logCtx(n,At.QUERY,!0)).for(this.query),a=[e,r],c=this.select().where(t).orderBy(a);return s&&c.limit(s),i&&c.offset(i),c.execute(...o)}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 ${H.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:o,limit:a}=r;if(!n&&!o)throw new Wt("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 d;if(c.verbose(`paginating ${H.tableName(this.class)} with page size ${a}`),o&&l.get("paginateByBookmark"))d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().where((()=>e===Xt.ASC?this.attr(H.pk(this.class)).gt(o):this.attr(H.pk(this.class)).lt(o))()).orderBy([t,e]).paginate(a,...u);else{if(!n)throw new Wt("PaginateBy needs a page or a bookmark");d=await this.override({forcePrepareComplexQueries:!1,forcePrepareSimpleQueries:!1}).select().orderBy([t,e]).paginate(a,...u)}const h=await d.page(i,o,...u);return d.serialize(h)}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 ${H.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 ${H.tableName(this.class)} with ${t} ${e}`),this.select().where(this.attr(t).eq(e)).execute(...i)}async statement(t,...e){if(!ye.statements(this,t))throw new Wt("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 Jt.attr(t)}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:this.ObserverHandler(),writable:!1});const r=this.log.for(this.observe),s=H.tableName(this.class);return this.adapter.observe(this,(t,e,r,...i)=>"string"==typeof t?t===s:ct.constr(t)===ct.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(H.sequenceFor(this.class).type,t)):Qt._baseSequence.parseValue(H.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||ct.flavourOf(t)||Qt.currentFlavour;try{s=this.get(t,i)}catch(t){s=void 0}if(s instanceof ye)return s;const n=e||ct.flavourOf(t)||s&&ct.get(s,At.ADAPTER)||Qt.currentFlavour,o=n?Qt.get(n):void 0;if(!o)throw new u("No registered persistence adapter found flavour "+n);return s=s||o.repository(),new s(o,t,...r)}static get(t,e){const r=H.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=H.tableName(t);if(r&&(s=[s,r].join(w)),s in this._cache&&this._cache[s]instanceof ye)throw new u(s+" already has a registered instance");this._cache[s]=e}static statements(t,e){const r=t instanceof ye?t.constructor:t,s=ct.get(r,e?ct.key(At.STATEMENT,e):At.STATEMENT);return(e?s:Object.keys(s))||!1}static queries(t,e){const r=t instanceof ye?t.constructor:t;return ct.get(r,e?ct.key(At.QUERY,e):At.QUERY)}}function me(t,e){if(!(e||(e=lt.flavourResolver(t instanceof H?t.constructor:t))&&e!==ut))throw new u("Could not retrieve flavour from model "+(t instanceof H?t.constructor.name:t.name));return Q(At.INJECTABLE,e,H.tableName(t))}i([se(),n("design:type",Function),n("design:paramtypes",[Object,String,void 0]),n("design:returntype",Promise)],ye.prototype,"listBy",null),i([se(),n("design:type",Function),n("design:paramtypes",[Object,String,Object,void 0]),n("design:returntype",Promise)],ye.prototype,"paginateBy",null),i([se(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],ye.prototype,"findOneBy",null),i([se(),n("design:type",Function),n("design:paramtypes",[Object,Object,void 0]),n("design:returntype",Promise)],ye.prototype,"findBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],ye.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],ye.prototype,"unObserve",null),Qt&&(Qt._baseRepository=ye);class we extends t{get log(){return this.logger||(this.logger=j.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=H.get(t.name)||t:"symbol"!=typeof t&&"string"!=typeof t||(n=H.get(t.toString())),!n)return;const o=At.ADAPTER,a=r||ct.get(n,o);try{let t=a;try{a&&Qt.get(a)}catch{const e=Qt.current;e&&e.flavour===a&&(t=e.alias)}if(i=ye.forModel(n,t),i instanceof ye)return i;const r=a||ct.get(i.constructor,o)||ct.get(n,o);e.register(i,me(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=ye.get(n,a);if("function"==typeof e){const t=a?Qt.get(a):Qt.current;if(!t)return;return new e(t,n)}}}return i}}var be,ve,Ee,xe,Ae;(t=>{t.PENDING="pending",t.SCHEDULED="scheduled",t.RUNNING="running",t.FAILED="failed",t.SUCCEEDED="succeeded",t.CANCELED="canceled",t.WAITING_RETRY="waiting_retry"})(be||(be={})),(t=>{t.EXPONENTIAL="exponential",t.FIXED="fixed"})(ve||(ve={})),(t=>{t.NONE="none",t.FULL="full"})(Ee||(Ee={})),(t=>{t.STATUS="status",t.LOG="log",t.PROGRESS="progress",t.ALL="all"})(xe||(xe={})),(t=>{t.ATOMIC="atomic",t.COMPOSITE="composite"})(Ae||(Ae={}));const Se="tasks",Oe={workerId:"default-worker",concurrency:10,leaseMs:6e4,pollMsIdle:1e3,pollMsBusy:500,logTailMax:100,streamBufferSize:5,maxLoggingBuffer:300,loggingBufferTruncation:20,gracefulShutdownMsTimeout:12e4};ct.tasks=(()=>ct.innerGet(Symbol.for(Se))).bind(ct),ct.taskFor=(t=>{const e=ct.tasks();return e?e[t]:void 0}).bind(ct),ct.validationExceptions=((t,e)=>{const r=ct.get(t,At.NO_VALIDATE)||[],s=Object.entries(r).filter(([,t])=>t.includes(e)).map(([t])=>t);let i=[];return e!==a.CREATE&&e!==a.UPDATE||(i=H.nestedRelations(t)),[...new Set([...s,...i])]}).bind(ct),ct.migrationsFor=(t=>{if(!(t=t??Qt.current))throw new u("Could not get adapter for migrations");return ct.innerGet(Symbol.for(At.MIGRATION),t.alias).map(t=>t.class)}).bind(ct),ct.migrations=(()=>{const t=ct.innerGet(Symbol.for([At.MIGRATION,At.BY_KEY].join("-")));return Object.values(t).flat().map(t=>[t.class.name,t.class])}).bind(ct),ct.relations=((t,e)=>{const r=ct.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(ct),H.relations=(t,e)=>ct.relations(t instanceof H?t.constructor:t,e)||[],H.nestedRelations=((t,e=[])=>{let r=[];const s=ct.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&&H.relations(i.class)){const s=H.relations(i.class).map(e=>`${t}.${e}`);e=[...e,...s],r=H.nestedRelations(i.class,e)}}return[...new Set([...e,...r])]}).bind(H),H.generatedBySequence=((t,e)=>{const r="function"!=typeof t?t.constructor:t;return!!H.sequenceFor(r).generated}).bind(H),H.fromTable=(t=>{const e=ct.innerGet(Symbol.for(At.TABLE));if(!e||!e[t]||!H.get(e[t].name))throw new u("No table metadata found for model. did you use @table()?");return H.get(e[t].name)}).bind(H),ct.createdBy=(t=>{const e=ct.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(ct),ct.updatedBy=(t=>{const e=ct.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(ct),H.tableName=t=>{if(!(t instanceof H?H.get(t.constructor.name):t))throw new u("Unable to find model "+t);return ct.get(t instanceof H?t.constructor:t,At.TABLE)||(t instanceof H?t.constructor.name:t.name)},H.columnName=(t,e)=>ct.get(t instanceof H?t.constructor:t,ct.key(At.COLUMN,e))||e,H.sequenceName=(t,...e)=>[H.tableName(t),...e].join("_"),H.sequenceFor=(t,e)=>{if(e)throw new Pt("not currently supported");const r=H.pkProps(t instanceof H?t.constructor:t);if(!r)throw new u("No sequence options defined for model. did you use the @pk decorator?");return r},H.indexes=t=>{const e=ct.get(t instanceof H?t.constructor:t,At.INDEX);return Object.keys(e||{}).reduce((t,r)=>(t[r]={[At.INDEX]:e[r]},t),{})},e.services=()=>ct.innerGet(Symbol.for(At.SERVICE)),e.repositories=()=>ct.innerGet(Symbol.for(b.REPOSITORY));class Ce extends Bt{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;[a.CREATE,a.UPDATE,a.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 a.CREATE;case c.UPDATE_ALL:return a.UPDATE;case c.DELETE_ALL:return a.DELETE;default:return t}}e&&e.writable?r[t]=new Proxy(r[t],{apply:async(e,r,s)=>{const{log:n,ctxArgs:o,ctx:a}=r.logCtx(s.slice(3-(4-s.length),s.length),e),[c,l,u]=s,d=await e.call(r,c,l,u,...o),h=[c,i(t),l];return a.get("observeFullResult")&&h.push(d),this.updateObservers(...h,...o).catch(e=>n.error(`Failed to dispatch observer refresh for ${t} on ${c.name||c} for ${l}: ${e}`)),d}}):this.log.error(`Could not find method ${t} to bind Observables Dispatch`)})}async close(){}observe(t){if(!(t instanceof Qt))throw new Pt("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 Pt("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:H.tableName(t),{log:n,ctxArgs:o,ctx:a}=this.logCtx(s,this.updateObservers);if(this.adapter)try{n.debug(`dispatching observer refresh for ${e}:${i}: ${r}${a.get("observeFullResult")?" - including result":""}`),await this.adapter.refresh(t,e,r,...o)}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 Te(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 Ht.instance.generate(i)}function ke(t=!1,e,...r){"function"==typeof t&&(e=t,t=!1);const s=At.UUID;return lt.for(s).define({decorator:(t,e,...r)=>{const s={update:t,seed:e,args:r},i=[z(),v(At.UUID),E(Te,s,{priority:54})];return t&&i.push(x(Te,s,{priority:54})),t||i.push(A()),ht(...i)},args:[t,e,...r]}).apply()}async function Ne(t,e,r,s,i){const n=e.logger.for(Ne);if(!s){const e=H.get(t.constructor.name);if(!e)throw new u("Could not find model "+t.constructor.name);s=ye.forModel(e,r),n.info("Retrieved "+s.toString())}let o;if(s=i?s.override(i):s,void 0===t[H.pk(s.class)])n.info(`No pk found in ${H.tableName(s.class)} - creating`),o=await s.create(t,e);else{n.info(`pk found in ${H.tableName(s.class)} - attempting update`);try{o=await s.update(t,e),n.info("Updated "+H.tableName(s.class))}catch(r){if(!(r instanceof m))throw r;n.info("update Failed - creating new "+H.tableName(s.class)),o=await s.create(t,e)}n.info("After create update: "+o)}return o}async function De(t,e,r,s){const i=s[r];if(!i)return;if("object"!=typeof i){const e=Ge(s,r,this.adapter.alias),n=await e.read(i,t);return await Fe(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 o=ye.forModel(n,this.adapter.alias),a=await o.override(this._overrides).create(i,t),c=H.pk(a);await Fe(t,s,r,a[c],a),s[r]=a[c]}async function Re(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Zt.CASCADE)return;if("object"!=typeof i){const e=Ge(s,r,this.adapter.alias),n=await e.override(this._overrides).read(i,t);return await Fe(t,s,r,i,n),void(s[r]=i)}const n=await Ne(s[r],t,this.adapter.alias,void 0,this._overrides),o=H.pk(n);await Fe(t,s,r,n[o],n),s[r]=n[o]}async function _e(t,e,r,s){const i=s[r];if(!i)return;if(e.cascade.update!==Zt.CASCADE)return;const n=Ge(s,r,this.adapter.alias);let o;o=i instanceof H?await n.delete(s[r][n.pk],t):await n.delete(s[r],t),await Fe(t,s,r,o[n.pk],o)}async function Be(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 o=t.logger.for(Be),a=new Set([...i]);if("object"!==n){const e=Ge(s,r,this.adapter.alias),i=await e.readAll([...a.values()],t);for(let e=0;e<i.length;e++){const s=i[e];o.info("FOUND ONE TO MANY VALUE: "+JSON.stringify(s)),await Fe(t,s,r,[...a.values()][e],i)}return s[r]=[...a],void o.info("SET ONE TO MANY IDS: "+s[r])}const c=H.pk(i[0].constructor),l=new Set;for(const e of i){o.info("Creating or updating one-to-many model: "+JSON.stringify(e));const i=await Ne(e,t,this.adapter.alias,void 0,this._overrides);o.info(`caching: ${JSON.stringify(i)} under ${i[c]}`),await Fe(t,s,r,i[c],i),o.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===Zt.CASCADE)return Be.call(this,t,e,r,s)}async function Ie(t,e,r,s){if(e.cascade.delete!==Zt.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 o="function"!=typeof e.class||e.class.name?e.class:e.class(),a="object"===n,c=a?ye.forModel(o,this.adapter.alias):Ge(s,r,this.adapter.alias),l=[...new Set([...a?i.map(t=>t[c.pk]):i]).values()];let d,h;try{d=await c.deleteAll(l,t)}catch(e){throw t.logger.error("Failed to delete all records",e),e}for(let e=0;e<d.length;e++){h=d[e];try{await Fe(t,s,r,l[e],h)}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 Le(t,e,r){return[At.TAG_FOR_DELETION,t,r].join(".")}async function Fe(t,e,r,s,i){const n=Pe(e.constructor.name,r,s),o=t.get("cacheForPopulate")||{};return o[n]=i,t.accumulate({cacheForPopulate:o})}async function je(t,e,r,s){if(!e.populate)return;const i=s[r],n=Array.isArray(i);if(void 0===i||n&&0===i.length)return;const o=await(async(e,r,s,i)=>{let n,o;const a=[],c=e.get("cacheForPopulate")||{};for(const e of i){n=Pe(r.constructor.name,s,e);try{if(o=c[n],!o)throw Error("Not found in cache")}catch(i){const n=Ge(r,s);if(!n)throw new u("Could not find repo");o=await n.read(e,t)}a.push(o)}return a})(t,s,r,n?i:[i]);s[r]=n?o:o[0]}async function Ue(t,e,r,s,i){if(e.cascade.update!==Zt.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 o(t){return Array.isArray(t)?t.map(o):"object"!=typeof t?t:t[H.pk(t)]}const a=o(s[r]),c=o(i[r]);if(void 0===c||W(a,c))return;if(Array.isArray(a)!==Array.isArray(c))throw new u("Cannot cascade update for different array types");const l=(Array.isArray(a)?a:[a]).filter(Boolean),d=(Array.isArray(c)?c:[c]).filter(Boolean).filter(t=>!l.includes(t)),h=Ge(s,r);if(!h)throw new u("Could not find repo");try{const e=await h.deleteAll(d,t);t.logger.debug(`Deleted ${e.length} entries from table ${H.tableName(h.class)} due to cascade rules with `)}catch(t){throw new u("Error deleting cascade entries: "+t)}}Qt&&(Qt._baseDispatch=Ce);const Me=["array","string","number","boolean","symbol","function","object","undefined","null","bigint"];function Ge(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=ct.get(t instanceof H?t.constructor:t,ct.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=ct.getPropDesignTypes(t instanceof H?t.constructor:t,e)?.designTypes;const i=s?.find(t=>!Me.includes((""+t.name).toLowerCase()));return ye.forModel(i,r)}class Ye extends O{constructor(t,e=Ye.name,r=401){super(t,e,r)}}class He extends Ye{constructor(t,e=He.name){super(t,e,403)}}class qe extends u{constructor(t){super(t,qe.name,503)}}function ze(t){return lt.for(At.TABLE).define({decorator:t=>e=>(ct.set(At.TABLE,t||e.name.toLowerCase(),e),yt(At.TABLE,t||e.name.toLowerCase())(e)),args:[t]}).apply()}function Qe(t){return lt.for(At.COLUMN).define({decorator:t=>(e,r)=>dt(ct.key(At.COLUMN,r),t||r)(e,r),args:[t]}).apply()}function We(t,e,r){return lt.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=>![Xt.ASC,Xt.DSC].includes(t))&&(e=t,t=void 0),dt(ct.key(`${At.INDEX}${e&&e?.length?"."+e.join("."):""}`,i),{directions:t,compositions:e,name:r})(s,i)),args:[t,e,r]}).apply()}async function Ve(t,e,r,s){if(s[r]&&(await this.select().where(Jt.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 Je(){const t=At.UNIQUE;return lt.for(t).define(J(),T(Ve),dt(t,{})).apply()}async function Xe(t,e,r,s){throw new Ye("This adapter does not support user identification")}function Ze(){return lt.for(At.CREATED_BY).define({decorator:()=>(t,e)=>ht(E(Xe),dt(At.CREATED_BY,e),v(At.CREATED_BY))(t,e),args:[]}).apply()}function Ke(){return lt.for(At.UPDATED_BY).define({decorator:()=>(t,e)=>ht(x(Xe),dt(At.UPDATED_BY,e),v(At.UPDATED_BY))(t,e),args:[]}).apply()}function tr(){return k([a.CREATE])}function er(){return k()}function rr(t){const e="function"==typeof t&&t.name?t:t(),r=H.pk(e);return ct.allowedTypes(e,r)||[]}function sr(t,e=Kt,r=!0,s,i){const n=At.ONE_TO_ONE;return lt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=rr(t),c=[mt(),dr(n,o),X([t,...a]),E(De,o,{priority:70}),x(Re,o,{priority:70}),N(_e,o,{priority:70}),D(Ue,o,{priority:70}),R(je,o,{priority:70})];return ht(...c)},args:[t,e,r,s,i]}).apply()}function ir(t,e=Kt,r=!0,s,i){const n=At.ONE_TO_MANY;return lt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=rr(t),c=[mt(),dr(n,o),Z([t,...a]),E(Be,o,{priority:70}),x($e,o,{priority:70}),N(Ie,o,{priority:70}),D(Ue,o,{priority:70}),R(je,o,{priority:70})];return ht(...c)},args:[t,e,r,s,i]}).apply()}function nr(t,e=Kt,r=!0,s,i){const n=At.MANY_TO_ONE;return lt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=rr(t),c=[mt(),dr(n,o),X([t,...a])];return ht(...c)},args:[t,e,r,s,i]}).apply()}function or(t,e=Kt,r=!0,s,i){const n=At.MANY_TO_MANY;return lt.for(n).define({decorator:(t,e,r,s,i)=>{const o={class:t,cascade:e,populate:r};s&&(o.joinTable=s),i&&(o.name=i);const a=rr(t),c=[mt(),dr(n,o),Z([t,...a])];return ht(...c)},args:[t,e,r,s,i]}).apply()}function ar(...t){return(e,r)=>{const s=ct.get(e,ct.key(At.NO_VALIDATE,r))||[],i=[...new Set([...s,...t])];return ht(yt(ct.key(At.NO_VALIDATE,r),i))(e,r)}}function cr(){return ar(a.CREATE)}function lr(){return ar(a.UPDATE)}function ur(){return ar(a.UPDATE,a.CREATE)}function dr(t,e){return lt.for(At.RELATIONS).define({decorator:(t,e)=>(r,s)=>(dt(t,e)(r,s),dt(ct.key(At.RELATIONS,s),Object.assign({},e,{key:t}))(r,s)),args:[t,e]}).apply()}class hr extends H{constructor(t){super(t)}}i([tr(),n("design:type",Date)],hr.prototype,"createdAt",void 0),i([er(),n("design:type",Date)],hr.prototype,"updatedAt",void 0);const pr={type:void 0,generated:!1,startWith:0,incrementBy:1,cycle:!1},gr=pr,fr={type:Number,generated:!0,startWith:0,incrementBy:1,cycle:!1},yr=Object.assign({},fr,{type:"BigInt"});async function mr(t,e,r,s){if(!e.type||!e.generated||s[r])return;let i;e.name||(e.name=H.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,o,a;n=s,o=r,a=await i.next(t),Reflect.set(n,o,a)}function wr(t,e){return(r,s)=>{if(mt()(r,s),!t.type){const e=ct.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=[mt(),We([Xt.ASC,Xt.DSC]),z(),A(),dt(ct.key(b.ID,s),t),E(mr,t,e)];return t.generated&&i.push(v()),ht(...i)(r,s)}}function br(t){const e=Object.assign({},gr);return delete e.generated,t=Object.assign({},e,t),lt.for(b.ID).define({decorator:wr,args:[t,{priority:60}]}).apply()}let vr=class extends hr{constructor(t){super(t)}};i([br({type:String,generated:!1}),n("design:type",String)],vr.prototype,"id",void 0),i([z(),We(),n("design:type",Object)],vr.prototype,"current",void 0),vr=i([ze("??sequence"),K(),n("design:paramtypes",[Object])],vr);class Er extends Bt{static{this.lock=new at}constructor(t,e,r={}){super(),this.options=t,this.adapter=e,this.repo=ye.forModel(vr,e.alias).override(r)}async current(...t){const{log:e,ctx:r}=await this.logCtx(t,a.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:o}=this.options;if(!o)throw new u("Sequence name is required");return Er.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 a="function"==typeof i&&i?.name?i.name:i,c=await this.current(s),l=async t=>{try{return await this.repo.update(new vr({id:o,current:t}),s)}catch(e){if(e instanceof m)return r.debug(`Sequence create ${o} current=${c} next=${t}`),this.repo.create(new vr({id:o,current:t}),s);throw e}};if("uuid"===a)for(;;){const t=await Promise.resolve(Ht.instance.generate(c));try{const e=await l(t);return r.debug(`Sequence uuid increment ${o} current=${c} next=${t}`),e.current}catch(t){if(t instanceof C)continue;throw t}}const d=await(async t=>{switch(a){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(qt.instance.generate(t));default:throw new u("Should never happen")}})(c),h=await l(d);return r.debug(`Sequence.increment ${o} current=${c} next=${d}`),h.current},o)}async next(...t){const{ctx:e}=(await this.logCtx(t,a.UPDATE,!0)).for(this.next);return this.increment(void 0,e)}async range(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.UPDATE,!0)).for(this.range);if("uuid"===this.options.type||"serial"===this.options.type)throw new Pt(`type ${this.options.type} is currently not suppported for this adapter`);const i="function"==typeof this.options.type&&this.options.type?.name?this.options.type.name:this.options.type,n=this.parse(this.options.incrementBy),o=await this.increment(this.parse(t)*n,r);let c=[];for(let e=0;t-1>=e;e++)c.push(o-n*this.parse(e));if(c=c.reverse(),c[c.length-1]!==o&&"String"!==i)throw new u("Miscalculation of range");return s.debug("Calculated range: "+c.join(", ")),c}parse(t){return Er.parseValue(this.options.type,t)}logCtx(t,e,r=!1){const s=this.adapter.logCtx([vr,...t],e,r);function i(t){return t.ctxArgs.shift(),t}return s instanceof Promise?s.then(i):i(s)}static pk(t){return H.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 Pt(`Unsupported sequence type: ${t} for adapter ${this}`)}}}function xr(t,e){return(i,n)=>n?r(ct.constr(t))(i,n):(ct.set(b.REPOSITORY,ct.key(e||Qt.currentFlavour,H.tableName(t)),i),yt(b.REPOSITORY,i.name)(t),e=e||ct.get(i.constructor,At.ADAPTER),ye.register(t,i,e),s(ct.constr(t),{callback:e=>(Object.defineProperty(e,b.CLASS,{enumerable:!1,configurable:!1,writable:!1,value:t}),e)})(i))}Qt._baseSequence=Er;class Ar extends u{constructor(t){super(t,Ar.name,500)}}class Sr extends F{get current(){return this._currentPage}get total(){return this._totalPages}get count(){return this._recordCount}get statement(){return this._statement||(this._statement=this.prepare(this.query)),this._statement}constructor(t,e,r,s){super(),this.adapter=t,this.query=e,this.size=r,this.clazz=s,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=ye.forModel(this.clazz,this.adapter.alias),o=this.query,{method:a,args:c,params:l}=o,u=RegExp(`^${xt.FIND_BY}|${xt.LIST_BY}`,"gi");if(!a.match(u))throw new Pt(`Method ${a} is not supported for pagination`);u.lastIndex=0;const d=a.replace(u,xt.PAGE_BY),h=[d,...c];let p={limit:this.size,offset:t,bookmark:this._bookmark};d!==xt.PAGE_BY||h.length>2?p={direction:l.direction,limit:this.size,offset:t,bookmark:this._bookmark}:h.push(l.direction),h.push(p);const g=await n.statement(...h,...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 Pt("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?Sr.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 Or,Cr,Tr,kr,Nr,Dr,Rr;class _r extends Bt{constructor(t,e){super(),this.adapter=t,this.overrides=e,this._inCountMode=!1,[this.execute,this.paginate].forEach(t=>{B(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"),o=r.get("forcePrepareComplexQueries");return i.silly(`statement force simple ${n}, forceComplex: ${o}`),(n&&this.isSimpleQuery()||o)&&(i.silly(`squashing ${o?"complex":"simple"} query to prepared statement`),await this.prepare(r),i.silly(`squashed ${o?"complex":"simple"} query to ${JSON.stringify(this.prepared,null,2)}`)),s}get log(){return this.adapter.log.for(_r)}select(t){return Object.defineProperty(this,"selectSelector",{value:t,writable:!1}),this}distinct(t){if(this._inCountMode)return this.countDistinctSelector=this.countSelector,this.countSelector=void 0,this._inCountMode=!1,this;if(!t)throw new Wt("distinct() requires a selector when not chained after count()");return this.distinctSelector=t,this}max(t){return this.maxSelector=t,this}min(t){return this.minSelector=t,this}sum(t){return this.sumSelector=t,this}avg(t){return this.avgSelector=t,this}count(t){return this.countSelector=t??null,this._inCountMode=!0,this}from(t){if(this.fromSelector="string"==typeof t?H.get(t):t,!this.fromSelector)throw new Wt("Could not find selector model: "+t);return this}where(t){return this.whereCondition=t,this}orderBy(t,e){return this.orderBySelectors=[this.normalizeOrderCriterion(t,e)],this}thenBy(t,e){if(Array.isArray(t)||void 0!==e){if(!this.orderBySelectors||!this.orderBySelectors.length)throw new Wt("thenBy requires orderBy to be called first");return this.orderBySelectors.push(this.normalizeOrderCriterion(t,e)),this}if(!this.groupBySelectors||!this.groupBySelectors.length)throw new Wt("groupBy must be called before chaining group selectors");return this.groupBySelectors.push(t),this}normalizeOrderCriterion(t,e){if(Array.isArray(t)){const[e,r]=t;return[e,this.normalizeOrderDirection(r)]}return[t,this.normalizeOrderDirection(e)]}normalizeOrderDirection(t){if(!t)throw new Wt("orderBy direction is required when specifying the attribute separately.");const e=(t+"").toLowerCase();if(e===Xt.ASC)return Xt.ASC;if(e===Xt.DSC)return Xt.DSC;throw new Wt(`Invalid OrderBy direction ${t}. Expected one of: ${Object.values(Xt).join(", ")}.`)}groupBy(t){if(this.orderBySelectors&&this.orderBySelectors.length)throw new Wt("groupBy must be called before orderBy.");return this.groupBySelectors=[t],this}limit(t){return this.limitSelector=t,this}offset(t){return this.offsetSelector=t,this}async execute(...t){const{log:e,ctx:r,ctxArgs:s}=this.logCtx(t,this.execute);try{if(this.prepared)return this.executePrepared(...t);e.silly("Building raw statement...");const i=this.build();e.silly("executing raw statement");const n=await this.raw(i,...s);if(this.hasAggregation())return n;if(!this.selectSelector){const t=H.pk(this.fromSelector),e=function(e){const s=e[t];return this.adapter.revert(e,this.fromSelector,s,void 0,r)}.bind(this);return this.groupBySelectors?.length?this.revertGroupedResults(n,e):Array.isArray(n)?n.map(e):e(n)}return n}catch(t){throw new Wt(t)}}revertGroupedResults(t,e){return Array.isArray(t)?t.map(e):t&&"object"==typeof t?Object.entries(t).reduce((t,[r,s])=>(t[r]=this.revertGroupedResults(s,e),t),{}):t}async executePrepared(...t){const e=ye.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 Pt("Raw statements are not allowed in the current configuration");const i=await this.adapter.raw(t,!0,...s);if(this.hasAggregation())return i;if(!this.selectSelector)return i;const n=H.pk(this.fromSelector),o=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(o):o(i)}prepareCondition(t,e){let{attr1:r,operator:s,comparison:i}=t;const n={};switch(s){case Et.AND:case Et.OR:{let t=r,o=i;if("string"!=typeof r){const s=this.prepareCondition(r,e);t=s.method,n.args=[...n.args||[],...s.args||[]]}if(i instanceof Jt){const t=this.prepareCondition(i,e);o=t.method,n.args=[...n.args||[],...t.args||[]]}n.method=`${t} ${s.toLowerCase()} ${o}`;break}case vt.EQUAL:n.method=r,n.args=[...n.args||[],i];break;case vt.DIFFERENT:n.method=r+" diff",n.args=[...n.args||[],i];break;case vt.REGEXP:n.method=r+" matches",n.args=[...n.args||[],i];break;case vt.BIGGER:n.method=r+" bigger",n.args=[...n.args||[],i];break;case vt.BIGGER_EQ:n.method=r+" bigger than equal";break;case vt.SMALLER:n.method=r+" less",n.args=[...n.args||[],i];break;case vt.SMALLER_EQ:n.method=r+" less than equal",n.args=[...n.args||[],i];break;case vt.IN:n.method=r+" in",n.args=[...n.args||[],i];break;default:throw new Wt("Unsupported operator "+s)}return n}squash(t){if(this.selectSelector&&this.selectSelector.length)return;if(this.groupBySelectors&&this.groupBySelectors.length)return;if(void 0!==this.countSelector)return;if(this.countDistinctSelector)return;if(this.maxSelector)return;if(this.minSelector)return;if(this.sumSelector)return;if(this.avgSelector)return;let e;if(this.whereCondition){if(this.whereCondition.comparison instanceof Jt)return;e=this.whereCondition.attr1}const r=this.orderBySelectors?.[0]?this.orderBySelectors[0]:e?[e,Xt.DSC]:[H.pk(this.fromSelector),Xt.DSC],[s,i]=r,n={direction:i};this.limitSelector&&(n.limit=this.limitSelector),this.offsetSelector&&(n.offset=this.offsetSelector);const o={class:this.fromSelector,method:xt.LIST_BY,args:[s],params:n};return e&&(o.method=xt.FIND_BY,o.args=[e,this.whereCondition.comparison],o.params=n),o}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=[bt.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)}if(this.selectSelector&&i.push(bt.SELECT,this.selectSelector.join(` ${bt.AND.toLowerCase()} `)),this.orderBySelectors?.length){const[t,...e]=this.orderBySelectors;i.push(bt.ORDER_BY,t[0]),r.direction=t[1],e.length&&(r.order=this.orderBySelectors.map(([t,e])=>[t,e]),e.forEach(([t])=>{i.push(bt.THEN_BY,t)}))}if(this.groupBySelectors?.length){const[t,...e]=this.groupBySelectors;i.push(bt.GROUP_BY,t),e.forEach(t=>i.push(bt.THEN_BY,t))}return this.limitSelector&&(r.limit=this.limitSelector),this.offsetSelector&&(r.skip=this.offsetSelector),s.method=M(i.join(" ")),s.params=r,this.prepared=s,this}isSimpleQuery(){return!(this.selectSelector&&this.selectSelector.length||this.groupBySelectors&&this.groupBySelectors.length||void 0!==this.countSelector||this.countDistinctSelector||this.maxSelector||this.minSelector||this.sumSelector||this.avgSelector)}hasAggregation(){return void 0!==this.countSelector||void 0!==this.countDistinctSelector||void 0!==this.maxSelector||void 0!==this.minSelector||void 0!==this.sumSelector||void 0!==this.avgSelector||void 0!==this.distinctSelector||(this.groupBySelectors?.length||0)>0}async paginate(t,...e){e.pop();try{return this.adapter.Paginator(this.prepared||this.build(),t,this.fromSelector)}catch(t){throw new Wt(t)}}toString(){return this.adapter.flavour+" statement"}}i([U(),n("design:type",Function),n("design:paramtypes",[Array]),n("design:returntype",Object)],_r.prototype,"select",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Or="undefined"!=typeof S&&S)?Or:Object]),n("design:returntype",Object)],_r.prototype,"distinct",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Cr="undefined"!=typeof S&&S)?Cr:Object]),n("design:returntype",Object)],_r.prototype,"max",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Tr="undefined"!=typeof S&&S)?Tr:Object]),n("design:returntype",Object)],_r.prototype,"min",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(kr="undefined"!=typeof S&&S)?kr:Object]),n("design:returntype",Object)],_r.prototype,"sum",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Nr="undefined"!=typeof S&&S)?Nr:Object]),n("design:returntype",Object)],_r.prototype,"avg",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Dr="undefined"!=typeof S&&S)?Dr:Object]),n("design:returntype",Object)],_r.prototype,"count",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Object)],_r.prototype,"from",null),i([U(),n("design:type",Function),n("design:paramtypes",[Jt]),n("design:returntype",Object)],_r.prototype,"where",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],_r.prototype,"orderBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object,String]),n("design:returntype",Object)],_r.prototype,"thenBy",null),i([U(),n("design:type",Function),n("design:paramtypes",["function"==typeof(Rr="undefined"!=typeof Key&&Key)?Rr:Object]),n("design:returntype",Object)],_r.prototype,"groupBy",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],_r.prototype,"limit",null),i([U(),n("design:type",Function),n("design:paramtypes",[Number]),n("design:returntype",Object)],_r.prototype,"offset",null),i([U(),n("design:type",Function),n("design:paramtypes",[void 0]),n("design:returntype",Promise)],_r.prototype,"execute",null);class Br extends Bt{constructor(t){super(),this.name=t,this.observers=[],this.Context=_t}observe(t,e){this.observerHandler||Object.defineProperty(this,"observerHandler",{value:new It,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}-${Ht.instance.generate()}`;const s=e.logger||j.for(this);return s.setConfig({correlationId:e.correlationId}),Object.assign({},St,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 Bt.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=jt(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 Br.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}=Br.prototype.logCtx(t,this.boot),o=e.services();for(const[t,r]of Object.entries(o))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 $r&&(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 Br.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}=Br.prototype.logCtx(t,this.shutdown),o=e.services();for(const[t,r]of Object.entries(o).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 $r){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([U(),n("design:type",Function),n("design:paramtypes",[Object,Function]),n("design:returntype",Function)],Br.prototype,"observe",null),i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",void 0)],Br.prototype,"unObserve",null);class $r extends Br{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 Ir(t){return function(e,r,s){const i=s.value;return s.value=function(...e){const r=this.class;if(r&&Mt(r,t))throw Error(`Operation "${t}" is blocked by @BlockOperations for ${r?.name??"Model"}.`);return i.apply(this,e)},s}}i([U(),n("design:type",Function),n("design:paramtypes",[Object]),n("design:returntype",Promise)],$r.prototype,"boot",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],$r.prototype,"config",null),i([U(),n("design:type",Object),n("design:paramtypes",[])],$r.prototype,"client",null);const Pr=()=>Ir(a.CREATE),Lr=()=>Ir(a.READ),Fr=()=>Ir(a.UPDATE),jr=()=>Ir(a.DELETE);function Ur(t){return(e,i,n)=>{n||i?(mt()(e,i),t=t||ct.type(e.constructor,i)):t=t||e,t=jt(t);const o=[];if(n&&"number"==typeof n.value)o.push(r(t));else if(n||i){if(n)throw Error("Invalid decorator usage. Should be impossible");o.push(r(t))}else ct.set(At.SERVICE,t,e),o.push(s(t,{singleton:!0,callback:e=>Object.defineProperty(e,"name",{enumerable:!0,configurable:!1,writable:!1,value:t})}));return ht(...o)(e,i,n)}}function Mr(t){const e=At.AUTH;return lt.for(e).define({decorator:t=>yt(e,t),args:[t]}).apply()}const Gr=t=>yt(At.AUTH_ROLE,t);function Yr(t,e){const r=At.DECAF_ROUTE;return lt.for(r).define({decorator:()=>(s,i,n)=>{const o={path:e,httpMethod:t,handler:n};return ht(pt(ct.key(r,i),o))(s,i,n)},args:[]}).apply()}const Hr=t=>"string"==typeof t?t.endsWith("Service")?t:t+"Service":"symbol"==typeof t?t.toString():t.name+"Service";class qr extends Br{get class(){if(!this.clazz)throw new u("Class not initialized");return this.clazz}get repo(){return this._repository||(this._repository=ye.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=Hr(t);try{const t=Br.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,a.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,a.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,a.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,a.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=Hr(e||t);try{r=qr.get(e)}catch(t){r=void 0}if(r instanceof qr)return r;const s=this;let o=class extends s{constructor(){super(t)}};return o=i([Ur(e),n("design:paramtypes",[])],o),new o}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([Pr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],qr.prototype,"create",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],qr.prototype,"createAll",null),i([jr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],qr.prototype,"delete",null),i([jr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],qr.prototype,"deleteAll",null),i([Lr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],qr.prototype,"read",null),i([Lr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],qr.prototype,"readAll",null),i([Lr(),n("design:type",Function),n("design:paramtypes",[String,Object]),n("design:returntype",Promise)],qr.prototype,"query",null),i([Fr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],qr.prototype,"update",null),i([Fr(),n("design:type",Function),n("design:paramtypes",[Array,Object]),n("design:returntype",Promise)],qr.prototype,"updateAll",null);class zr extends $r{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 Qr=class extends H{constructor(t){super(t),this.strategy=ve.EXPONENTIAL,this.baseMs=1e3,this.maxMs=6e4,this.jitter=Ee.FULL}};i([z(),X(String),tt(ve),wt("the backoff strategy"),n("design:type",String)],Qr.prototype,"strategy",void 0),i([z(),wt("base interval between attempts"),n("design:type",Number)],Qr.prototype,"baseMs",void 0),i([z(),wt("max interval"),n("design:type",Number)],Qr.prototype,"maxMs",void 0),i([X(String),tt(Ee),wt("optional jitter strategy"),n("design:type",String)],Qr.prototype,"jitter",void 0),Qr=i([K(),n("design:paramtypes",[Object])],Qr);let Wr=class extends H{constructor(t){super(t)}};i([z(),wt("The error message"),n("design:type",String)],Wr.prototype,"message",void 0),i([mt(),wt("The error stack"),n("design:type",String)],Wr.prototype,"stack",void 0),i([mt(),wt("The error code"),n("design:type",String)],Wr.prototype,"code",void 0),i([mt(),wt("The error details"),n("design:type",Object)],Wr.prototype,"details",void 0),Wr=i([K(),n("design:paramtypes",[Object])],Wr);let Vr=class extends H{constructor(t){super(t),this.ts=new Date}};i([$(["taskId","classification","uuid"],":"),br(),n("design:type",String)],Vr.prototype,"id",void 0),i([A(),z(),I(),ke(!1),n("design:type",String)],Vr.prototype,"uuid",void 0),i([A(),z(),n("design:type",String)],Vr.prototype,"taskId",void 0),i([et(),z(),n("design:type",Date)],Vr.prototype,"ts",void 0),i([A(),z(),tt(xe),n("design:type",String)],Vr.prototype,"classification",void 0),i([mt(),A(),n("design:type",Object)],Vr.prototype,"payload",void 0),Vr=i([ze("task_event"),K(),n("design:paramtypes",[Object])],Vr);class Jr extends rt{constructor(){super()}preSerialize(t,...e){if(null===t||"object"!=typeof t)return t;const r=Object.assign({},t);if(t instanceof Jt)return r[st.ANCHOR]="??condition",r;if(H.isModel(t)){let e;try{e=ct.modelName(t.constructor)}catch(t){e=void 0}e&&(r[st.ANCHOR]=e)}return r}deserialize(t,...e){const r=JSON.parse(t),s=r[st.ANCHOR];return s?"??condition"===s?Jt.from(r):H.build(r,s):r}serialize(t,...e){return JSON.stringify(this.preSerialize(t))}}let Xr=class extends H{constructor(t){super(t),this.ts=new Date}};i([et(),z(),n("design:type",Date)],Xr.prototype,"ts",void 0),i([z(),tt(G),n("design:type",String)],Xr.prototype,"level",void 0),i([z(),mt(),n("design:type",String)],Xr.prototype,"msg",void 0),i([mt(),n("design:type",Object)],Xr.prototype,"meta",void 0),Xr=i([K(),n("design:paramtypes",[Object])],Xr);let Zr=class extends H{constructor(t){super(t),this.atomicity=Ae.ATOMIC,this.status=be.PENDING,this.attempt=0,this.logTail=[]}};i([br({type:"uuid"}),wt("the task id"),n("design:type",String)],Zr.prototype,"id",void 0),i([z(),X(String),tt(Ae),wt("defines a single or composite task"),n("design:type",String)],Zr.prototype,"atomicity",void 0),i([z(),wt("Holds task classification - must match @task()"),n("design:type",String)],Zr.prototype,"classification",void 0),i([z(),X(String),tt(be),wt("Holds the task current status"),n("design:type",String)],Zr.prototype,"status",void 0),i([mt(),P(Jr),wt("Holds task input"),n("design:type",Object)],Zr.prototype,"input",void 0),i([mt(),P(Jr),wt("Holds the task output when successfully completed"),n("design:type",Object)],Zr.prototype,"output",void 0),i([mt(),P(),wt("Holds the error for failed tasks"),n("design:type",Wr)],Zr.prototype,"error",void 0),i([z(),it(0),wt("Holds the current attempt"),n("design:type",Number)],Zr.prototype,"attempt",void 0),i([it(1),z(),wt("max attempts for the task"),n("design:type",Number)],Zr.prototype,"maxAttempts",void 0),i([z(),P(),wt("backoff configuration"),n("design:type",Qr)],Zr.prototype,"backoff",void 0),i([et(),wt("Next execution timestamp"),n("design:type",Date)],Zr.prototype,"nextRunAt",void 0),i([et(),wt("Task scheduled timestamp"),n("design:type",Date)],Zr.prototype,"scheduledTo",void 0),i([mt(),wt("Task lease owner identifier"),n("design:type",String)],Zr.prototype,"leaseOwner",void 0),i([et(),wt("Task lease expiration timestamp"),n("design:type",Date)],Zr.prototype,"leaseExpiry",void 0),i([mt(),P(),wt("Holds the various steps definition and inputs - only for type === 'composite'"),n("design:type",Array)],Zr.prototype,"steps",void 0),i([it(0),mt(),wt("Holds the current step - only for type === 'composite'"),n("design:type",Number)],Zr.prototype,"currentStep",void 0),i([mt(),P(),wt("Holds the step results - only for type === 'composite'"),n("design:type",Array)],Zr.prototype,"stepResults",void 0),i([mt(),P(),wt("Holds the task log entries"),n("design:type",Array)],Zr.prototype,"logTail",void 0),i([Qe(),tr(),wt("timestamp of creation"),n("design:type",Date)],Zr.prototype,"createdAt",void 0),i([Qe(),er(),wt("timestamp of last update"),n("design:type",Date)],Zr.prototype,"updatedAt",void 0),i([Qe(),Ze(),wt("Holds the creator of the task"),n("design:type",String)],Zr.prototype,"createdBy",void 0),i([Qe(),Ke(),wt("Holds the creator of the task"),n("design:type",String)],Zr.prototype,"updatedBy",void 0),Zr=i([wt("Holds the current step when applicable"),ze("tasks"),K(),n("design:paramtypes",[Object])],Zr);let Kr=class extends H{constructor(t){super(t)}};i([z(),wt("The status of a step"),n("design:type",String)],Kr.prototype,"status",void 0),i([mt(),wt("The result of a successful step"),n("design:type",Object)],Kr.prototype,"output",void 0),i([mt(),wt("the error of a failed step"),n("design:type",Wr)],Kr.prototype,"error",void 0),Kr=i([K(),n("design:paramtypes",[Object])],Kr);let ts=class extends H{constructor(t){super(t)}};i([z(),mt(),wt("task handler type"),n("design:type",String)],ts.prototype,"classification",void 0),i([wt("optional task step input"),mt(),n("design:type",Object)],ts.prototype,"input",void 0),ts=i([K(),n("design:paramtypes",[Object])],ts);class es extends H{constructor(t){super(t),this.baseMs=1e3,this.jitter=Ee.FULL,this.maxMs=6e4,this.strategy=ve.EXPONENTIAL,H.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 d(t);return new Qr(this)}}i([z(),it(1e3),n("design:type",Number)],es.prototype,"baseMs",void 0),i([z(),tt(Ee),n("design:type",String)],es.prototype,"jitter",void 0),i([nt("baseMs"),it(1e3),z(),n("design:type",Number)],es.prototype,"maxMs",void 0),i([z(),tt(ve),n("design:type",String)],es.prototype,"strategy",void 0);class rs extends H{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 es,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=be.PENDING,this.atomicity=Ae.ATOMIC,this.backoff=new Qr,this.maxAttempts=1,H.fromModel(this,t)}build(){const t=this.hasErrors();if(t)throw new d(t);return new Zr(this)}}i([z(),n("design:type",String)],rs.prototype,"classification",void 0),i([z(),n("design:type",String)],rs.prototype,"status",void 0),i([z(),n("design:type",String)],rs.prototype,"atomicity",void 0),i([z(),n("design:type",Qr)],rs.prototype,"backoff",void 0),i([mt(),n("design:type",Object)],rs.prototype,"input",void 0),i([it(1),z(),n("design:type",Number)],rs.prototype,"maxAttempts",void 0);class ss extends rs{constructor(t){super(t),this.stepResults=[],H.fromModel(this,t),this.atomicity=Ae.COMPOSITE}setSteps(t){return this.steps=t,this}addStep(t,e){this.steps=this.steps||[];const r=new Date;return this.steps.push(new ts({classification:t,input:e,createdAt:r,updatedAt:r})),this}}i([Z(()=>ts),n("design:type",Array)],ss.prototype,"steps",void 0);class is extends $t{get type(){if(!this._type){const t=ct.get(this.constructor,Se);"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(),p(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 ns(t){return lt.for(Se).define({decorator:t=>e=>{const r={type:t};return ct.set(Se,t,e),yt(Se,r)(e)},args:[t]}).apply()}let os=class extends is{constructor(){super()}async run(t,e){const r=e.logger;try{let s;if(t instanceof Jt)s=t,r.info("Starting task cleanup with custom condition");else{r.info("Starting task cleanup with expiry dates");const e=Jt.attr("status").eq(be.SUCCEEDED).and(Jt.attr("updatedAt").lte(t.successfulExpiry)),i=Jt.attr("status").eq(be.FAILED).and(Jt.attr("updatedAt").lte(t.failedExpiry)),n=Jt.attr("status").eq(be.CANCELED).and(Jt.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([xr(Zr),n("design:type",Object)],os.prototype,"tasks",void 0),os=i([ns("cleanup-task"),n("design:paramtypes",[])],os);class as{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(G).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 cs(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 xe.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===G.verbose&&s.push(1),s.push(n);try{t[r](...s)}catch(e){t.error("Failed to pipe task logs",e)}}break}case xe.PROGRESS:if(e.logProgress){const{currentStep:e,totalSteps:s}=r.payload;t.info(`### STEP ${e}/${s}`)}break;case xe.STATUS:if(e.logStatus){const e=r.payload?.status??r.payload;let s=Y(e);switch(e){case be.SUCCEEDED:s=s.green.bold;break;case be.RUNNING:s=s.blue.bold;break;case be.PENDING:s=s.yellow;break;case be.WAITING_RETRY:s=s.yellow.bold;break;case be.FAILED:s=s.red.bold;break;case be.CANCELED:s=s.magenta.bold;break;case be.SCHEDULED:s=s.cyan;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)}}}function ls(t,e){const r=e.strategy===ve.FIXED?e.baseMs:e.baseMs*Math.pow(2,Math.max(0,t-1)),s=Math.min(r,e.maxMs);return e.jitter===Ee.FULL?Math.floor(Math.random()*s):s}function us(t){return new Wr({message:t?.message??t+"",stack:t?.stack,code:t?.code,details:t?.details})}function ds(t){return new Promise(e=>setTimeout(e,t))}class hs extends Error{constructor(t){super("Task requested state change: "+t.status),this.request=t,this.name=hs.name,Object.setPrototypeOf(this,hs.prototype)}}class ps 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)}changeState(t,e){throw new hs({status:t,...e})}cancel(t,e){this.changeState(be.CANCELED,{error:this.toTaskError(t,e)})}retry(t){this.changeState(be.WAITING_RETRY,{error:this.toTaskError(t)})}reschedule(t,e){const r=t instanceof Date?t:t.build();this.changeState(be.SCHEDULED,{error:this.toTaskError(e),scheduledTo:r})}toTaskError(t,e){if(t||e)return t instanceof Wr?t:t instanceof Error?us(t):new Wr({message:(t??"Task requested state change")+"",details:e})}get resultCache(){return this.get("resultCache")}constructor(t){super(t)}}class gs{constructor(){this.handlers=new Map,this.initialize()}initialize(){const t=ct.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 fs extends It{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(Vr,t.classification,t.id,t,e)}async updateObservers(t,e,r,s,...i){const{log:n,ctxArgs:o}=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,...o)}catch(t){return n.error(`Failed to filter observer ${s.observer.toString()}: ${t}`),!1}}).map(t=>{t.observer.refresh(s,...o)}))).forEach((t,e)=>{"rejected"===t.status&&n.error(`Failed to update observable ${this.observers[e].toString()}: ${t.reason}`)})}}class ys extends L{constructor(t,e,r,s,i,n=500){super(t,r,n),this.taskId=e,this.details=s,this.meta=i}}class ms extends ys{constructor(t,e,r){super(ms.name,t,e?.message??`Task ${t} failed`,e,r,500)}}class ws extends ys{constructor(t,e,r){const s=r?.nextRunAt instanceof Date?r.nextRunAt.toISOString():r?.nextRunAt;super(ws.name,t,e?.message??`Task ${t} scheduled for retry${s?" at "+s:""}`,e,r,409)}}class bs extends ys{constructor(t,e,r){super(bs.name,t,e?.message??`Task ${t} canceled`,e,r,400)}}class vs extends ys{constructor(t,e,r){const s=r?.scheduledTo instanceof Date?r.scheduledTo.toISOString():r?.scheduledTo;super(vs.name,t,e?.message??`Task ${t} rescheduled${s?" to "+s:""}`,e,r,202)}}class Es{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===Vr||t===H.tableName(Vr))),this.pipe(this.track.bind(this)),this.resolveTerminalState()}resolve(){return this.awaitStatusTerminal([be.SUCCEEDED,be.FAILED,be.CANCELED,be.WAITING_RETRY,be.SCHEDULED])}wait(){return this.awaitStatusTerminal([be.SUCCEEDED,be.FAILED,be.CANCELED])}attach(t,e={logProgress:!0,logStatus:!0,style:!0}){this.pipe(cs(t,e))}logs(t){this.pipe(async e=>{if(e.classification!==xe.LOG)return;const r=e.payload;await t(r)},xe.LOG)}pipe(t,e=xe.ALL){this.pipes=this.pipes||{},this.pipes[e]=this.pipes[e]||new Set,this.pipes[e].add(t)}succeed(t){this.complete()}fail(t){this.complete()}cancel(t){t.payload&&this.fail()}retry(){}reschedule(){}onSucceed(t){return this.registerStatusHandler(be.SUCCEEDED,t)}onFailure(t){return this.registerStatusHandler(be.FAILED,t)}onCancel(t){return this.registerStatusHandler(be.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===be.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){const e=t.payload?.status??this.task.status,r=this.buildMeta(e,t.payload);return this.createTaskControlError(e,t.payload?.error??this.task.error,r)}complete(){this.resolved||(this.resolved=!0,this.unregistration(),this.pipes=void 0)}isTerminalStatus(t){return[be.SUCCEEDED,be.CANCELED,be.FAILED].includes(t)}async track(t,e){if(!t.payload)return;const r=t.payload.status;this.task.status=r,void 0!==t.payload.output&&(this.task.output=t.payload.output),t.payload.error&&(this.task.error=t.payload.error),void 0!==t.payload.nextRunAt&&(this.task.nextRunAt=t.payload.nextRunAt),void 0!==t.payload.scheduledTo&&(this.task.scheduledTo=t.payload.scheduledTo),r!==be.SUCCEEDED?(r===be.FAILED&&this.fail(),r===be.CANCELED&&this.cancel(t),r===be.WAITING_RETRY&&this.retry(),r===be.SCHEDULED&&this.reschedule()):this.succeed()}registerStatusHandler(t,e){const r=async(r,s)=>{r.payload?.status===t&&await e(r,s)};if(this.pipe(r,xe.STATUS),this.task.status===t){const e=this.buildTerminalEvent(t);r(e,this.getTerminalContext())}return()=>{this.pipes?.[xe.STATUS]?.delete(r)}}getTerminalContext(){return this.terminalContext||(this.terminalContext=new _t),this.terminalContext}buildTerminalEvent(t){const e={status:t};return t===be.SUCCEEDED&&(e.output=this.task.output),t!==be.FAILED&&t!==be.CANCELED||!this.task.error||(e.error=this.task.error),this.task.nextRunAt&&(e.nextRunAt=this.task.nextRunAt),this.task.scheduledTo&&(e.scheduledTo=this.task.scheduledTo),new Vr({classification:xe.STATUS,taskId:this.task.id,payload:e})}createTaskControlError(t,e,r){switch(t){case be.FAILED:return new ms(this.task.id,e,r);case be.CANCELED:return new bs(this.task.id,e,r);case be.WAITING_RETRY:return new ws(this.task.id,e,r);case be.SCHEDULED:return new vs(this.task.id,e,r);default:return new ms(this.task.id,e,r)}}buildMeta(t,e){const r={};if(e?.nextRunAt&&(r.nextRunAt=e.nextRunAt),e?.scheduledTo&&(r.scheduledTo=e.scheduledTo),Object.keys(r).length)return r}resolveTerminalState(){if(!this.isTerminalStatus(this.task.status))return;if(this.task.status===be.SUCCEEDED)return void this.succeed(this.task.output);const t={status:this.task.status,nextRunAt:this.task.nextRunAt,scheduledTo:this.task.scheduledTo};this.fail(this.createTaskControlError(this.task.status,this.task.error,this.buildMeta(this.task.status,t)))}async refresh(t,e){if(!this.pipes)return;const r=this.pipes[xe.ALL]?[...this.pipes[xe.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 xs extends $t{get Context(){return ps}get adapter(){return this.config.adapter}get registry(){return this.config.registry}get bus(){return this.config.bus}get tasks(){return this._tasks||(this._tasks=ye.forModel(Zr,this.adapter.alias)),this._tasks}get events(){return this._events||(this._events=ye.forModel(Vr,this.config.adapter.alias)),this._events}constructor(t){super(),this.config=t,this.lock=new ot,this.running=!1,this.config=Object.assign({},Oe,t,{bus:t.bus||new fs,registry:t.registry||new gs})}async push(t,e=!1,...r){const{ctx:s,log:i}=(await this.logCtx(r,a.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 Es(this.bus,n)}:n}schedule(t,e=!1,...r){return{for:async s=>{const i=s instanceof Date?s:s.build();return t.status=be.SCHEDULED,t.scheduledTo=i,t.nextRunAt=void 0,t.leaseOwner=void 0,t.leaseExpiry=void 0,await this.push(t,e,...r)}}}async track(t,...e){const{ctx:r,log:s}=(await this.logCtx(e,a.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 Es(this.bus,i)}}async ensureTaskError(t,e){if(![be.FAILED,be.CANCELED].includes(t.status)||t.error)return t;let r=t;for(let t=0;6>t;t+=1){await ds(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===be.SUCCEEDED||s.status===be.FAILED)return s;s.status=be.CANCELED;const i=new Wr({message:`Task ${s.id} canceled`,code:400});s.error=i,s.leaseOwner=void 0,s.leaseExpiry=void 0,s.nextRunAt=void 0,s.scheduledTo=void 0;const n=await this.tasks.update(s,r);return await this.emitStatus(r,n,be.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(Jt.attr("status").eq(be.RUNNING)).execute(e),i=e.getOrUndefined?.("gracefulShutdownMsTimeout")??this.config.gracefulShutdownMsTimeout;return new Promise((t,n)=>{const o=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(o),r.info(`Graceful shutdown completed before expiry. concluded ${e.length} tasks`),t()}).catch(t=>{clearTimeout(o),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 ds(t.length?this.config.pollMsBusy:this.config.pollMsIdle)}}async claimBatch(t){const e=t.logger.for(this.claimBatch),r=t.timestamp,s=Jt.attribute("status").eq(be.PENDING),i=Jt.attribute("status").eq(be.WAITING_RETRY).and(Jt.attribute("nextRunAt").lte(r)),n=Jt.attribute("status").eq(be.RUNNING).and(Jt.attribute("leaseExpiry").lte(r)),o=Jt.attribute("status").eq(be.SCHEDULED).and(Jt.attribute("scheduledTo").lte(r)),a=s.or(i).or(n).or(o),c=await this.tasks.select().where(a).limit(Math.max(4*this.config.concurrency,20)).execute();e.verbose("claimBatch candidates:"+c.length);const l=[];for(const e of c){const r=await this.tryClaim(e,t);if(r&&l.push(r),l.length>=this.config.concurrency)break}return e.verbose("claimBatch claimed:"+l.length),l}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 Zr({...i,status:be.RUNNING,leaseOwner:this.config.workerId.toString(),leaseExpiry:new Date(s+(parseInt(this.config.leaseMs.toString())||6e4)),scheduledTo:void 0,nextRunAt:void 0});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 ps(e).accumulate({taskId:t.id,logger:new as(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,be.RUNNING);try{let e;if(t.atomicity===Ae.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=be.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,be.SUCCEEDED,e)}catch(e){try{t=await this.tasks.read(t.id,s)}catch{}if(e instanceof hs)return void await this.handleTaskStateChange(e.request,t,s);if(r.error("task execution error",e),t.atomicity===Ae.COMPOSITE){const e=this.normalizeStepResults(t.stepResults);if(t.stepResults=e,null==t.currentStep){const r=e.findIndex(t=>t.status===be.FAILED);0>r||(t.currentStep=r)}}const i=(t.attempt??0)+1,n=us(e);if(i<t.maxAttempts){const e=ls(i,this.normalizeBackoff(t.backoff)),o=new Date(Date.now()+e);t.attempt=i,t.status=be.WAITING_RETRY,t.nextRunAt=o,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,be.WAITING_RETRY),await s.pipe(G.warn,"Retry scheduled",{nextRunAt:o,delayMs:e,attempt:i})}else t.attempt=i,t.status=be.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,be.FAILED,n),await s.pipe(G.error,"Task failed (max attempts reached)",{maxAttempts:t.maxAttempts})}}async handleTaskStateChange(t,e,r){switch(e.leaseOwner=void 0,e.leaseExpiry=void 0,t.status){case be.CANCELED:{const s=t.error??new Wr({message:`Task ${e.id} canceled`});return e.status=be.CANCELED,e.error=s,e.nextRunAt=void 0,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,be.CANCELED,s),void await r.pipe(G.warn,"Task canceled via context")}case be.WAITING_RETRY:{const s=(e.attempt??0)+1,i=ls(s,this.normalizeBackoff(e.backoff)),n=t.scheduledTo instanceof Date?t.scheduledTo:new Date(Date.now()+i),o=t.error??new Wr({message:`Task ${e.id} requested retry`});return e.status=be.WAITING_RETRY,e.attempt=s,e.error=o,e.nextRunAt=n,e.scheduledTo=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,be.WAITING_RETRY,o),void await r.pipe(G.warn,"Retry requested",{nextRunAt:n,delayMs:i,attempt:s})}case be.SCHEDULED:{if(!t.scheduledTo)throw new u("Scheduled state requires a target date");const s=t.error??new Wr({message:`Task ${e.id} rescheduled`});return e.status=be.SCHEDULED,e.scheduledTo=t.scheduledTo,e.error=s,e.nextRunAt=void 0,e=await this.tasks.update(e,r),await this.emitStatus(r,e,be.SCHEDULED,s),void await r.pipe(G.info,"Task rescheduled",{scheduledTo:t.scheduledTo.toISOString()})}default:throw new u("Unsupported task state change requested: "+t.status)}}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),o=(t,s)=>{e.cacheResult(t,s),r instanceof ps&&r!==e&&r.cacheResult(t,s)};for(let e=0;e<n.length;e+=1){const r=n[e];if(r?.status===be.SUCCEEDED){const i=s[e];if(!i)continue;const n=`${t.id}:step:${e}`;o(i.classification,r.output),o(n,r.output)}}for(;i<s.length;){const r=s[i],a=this.registry.get(r.classification);if(!a)throw Error("No task handler registered for composite step: "+r.classification);await e.pipe([G.info,`Composite step ${i+1}/${s.length}: ${r.classification}`]);try{const c=await a.run(r.input,e),l=i,u=new Date;n[l]=new Kr({status:be.SUCCEEDED,output:c,createdAt:u,updatedAt:u});const d=`${t.id}:step:${l}`;o(r.classification,c),o(d,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 Kr({status:be.FAILED,error:us(e),createdAt:r,updatedAt:r}),t.stepResults=n,t.currentStep=i,t.error=us(e),t=await this.tasks.update(t),e}}return{stepResults:n}}normalizeBackoff(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)}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 ts)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new ts(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 Kr)return t;let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{e={}}return new Kr(e)}):[]}async appendLog(t,e,r){const s=(Array.isArray(r)&&Array.isArray(r[0])?r:[r]).map(([t,e,r])=>new Xr({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 ps&&await t.flush();const i={status:r};s&&s instanceof Wr?i.error=s:s&&(i.output=s),e.nextRunAt&&(i.nextRunAt=e.nextRunAt),e.scheduledTo&&(i.scheduledTo=e.scheduledTo);const n=await this.persistEvent(t,e.id,xe.STATUS,i);this.bus.emit(n,t)}async emitLog(t,e,r){const s=await this.persistEvent(t,e,xe.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,xe.PROGRESS,r);this.bus.emit(s,t)}async persistEvent(t,e,r,s){const i=new Vr({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,Zr,...r)}}class As extends $r{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 xs(e);return r.verbose(s+" initialized"),{client:s,config:e}}async push(t,e=!1,...r){const{ctxArgs:s}=(await this.logCtx(r,a.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,a.CREATE,!0)).for(this.push);return this.client.track(t,...r)}async create(t,...e){const{ctxArgs:r}=(await this.logCtx(e,a.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,a.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,a.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 Pt("Updates to tasks are not available")}async updateAll(t,...e){throw new Pt("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([xr(Zr),n("design:type",Object)],As.prototype,"repo",void 0),i([Pr(),n("design:type",Function),n("design:paramtypes",[Zr,void 0]),n("design:returntype",Promise)],As.prototype,"create",null),i([Pr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],As.prototype,"createAll",null),i([jr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],As.prototype,"delete",null),i([jr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],As.prototype,"deleteAll",null),i([Lr(),n("design:type",Function),n("design:paramtypes",[Object,void 0]),n("design:returntype",Promise)],As.prototype,"read",null),i([Lr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],As.prototype,"readAll",null),i([Lr(),n("design:type",Function),n("design:paramtypes",[String,void 0]),n("design:returntype",Promise)],As.prototype,"query",null),i([Fr(),n("design:type",Function),n("design:paramtypes",[Zr,void 0]),n("design:returntype",Promise)],As.prototype,"update",null),i([Fr(),n("design:type",Function),n("design:paramtypes",[Array,void 0]),n("design:returntype",Promise)],As.prototype,"updateAll",null),e.setRegistry(new we);const Ss="##VERSION##",Os="##PACKAGE##";ct.registerLibrary(Os,Ss);export{$t as AbsContextual,Qt as Adapter,Ye as AuthorizationError,ve as BackoffStrategy,hr as BaseModel,yr as BigIntSequence,Zt as Cascade,os as CleanUpTask,$r as ClientBasedService,ss as CompositeTaskBuilder,Jt as Condition,qe as ConnectionError,_t as Context,Rt as ContextLock,Bt as ContextualLoggedClass,Ot as DefaultAdapterFlags,Kt as DefaultCascade,St as DefaultContextFlags,ge as DefaultRepositoryFilters,gr as DefaultSequenceOptions,Oe as DefaultTaskEngineConfig,Ce as Dispatch,He as ForbiddenError,Et as GroupOperator,we as InjectablesRegistry,Ee as JitterStrategy,re as MethodQueryBuilder,Lt as MigrationError,Ft as MigrationRuleError,qr as ModelService,Nt as MultipleSelectOperationKeys,Tt as NonTransactionOperationKeys,pr as NoneSequenceOptions,fr as NumericSequence,Ar as ObserverError,It as ObserverHandler,vt as Operator,te as OperatorsMap,Xt as OrderDirection,Os as PACKAGE_NAME,Dt as PaginationOperationKeys,Sr as Paginator,Vt as PagingError,At as PersistenceKeys,zr as PersistenceService,xt as PreparedStatementKeys,bt as QueryClause,Wt as QueryError,ye as Repository,kt as SelectOperationKeys,Er as Sequence,vr as SequenceModel,qt as Serial,Br as Service,_r as Statement,es as TaskBackoffBuilder,Qr as TaskBackoffModel,rs as TaskBuilder,bs as TaskCancelError,ps as TaskContext,ys as TaskControlError,xs as TaskEngine,Wr as TaskErrorModel,fs as TaskEventBus,Vr as TaskEventModel,xe as TaskEventType,ms as TaskFailError,is as TaskHandler,gs as TaskHandlerRegistry,Jr as TaskIOSerializer,Xr as TaskLogEntryModel,as as TaskLogger,Zr as TaskModel,vs as TaskRescheduleError,ws as TaskRetryError,As as TaskService,be as TaskStatus,Kr as TaskStepResultModel,ts as TaskStepSpecModel,Es as TaskTracker,Ae as TaskType,Se as TasksKey,Ct as TransactionOperationKeys,Ht as UUID,Pt as UnsupportedError,Ss as VERSION,ne as applyViewDecorator,Mr as auth,Fe as cacheModelForPopulate,Ue as cascadeDelete,Qe as column,ls as computeBackoffMs,Pr as create,Ne as createOrUpdate,tr as createdAt,Ze as createdBy,Xe as createdByOnCreateUpdate,jr as del,me as generateInjectableNameForRepository,fe as getFilters,cs as getLogPipe,rr as getPkTypes,Pe as getPopulateKey,Le as getTagForDeleteKey,We as index,jt as injectableServiceKey,Mt as isOperationBlocked,or as manyToMany,nr as manyToOne,ar as noValidateOn,cr as noValidateOnCreate,ur as noValidateOnCreateUpdate,lr as noValidateOnUpdate,Gt as normalizeImport,ir as oneToMany,Be as oneToManyOnCreate,Ie as oneToManyOnDelete,$e as oneToManyOnUpdate,sr as oneToOne,De as oneToOneOnCreate,_e as oneToOneOnDelete,Re as oneToOneOnUpdate,he as onlyOnBulk,ae as onlyOnCreate,le as onlyOnDelete,pe as onlyOnFilter,de as onlyOnSingle,ue as onlyOnTransactional,ce as onlyOnUpdate,br as pk,wr as pkDec,mr as pkOnCreate,je as populate,Yt as prefixMethod,se as prepared,Ut as promiseSequence,ie as query,Lr as read,dr as relation,xr as repository,Ge as repositoryFromTypeMetadata,Gr as roles,Yr as route,us as serializeError,Ur as service,ds as sleep,ze as table,ns as task,Je as unique,Ve as uniqueOnCreateUpdate,Fr as update,er as updatedAt,Ke as updatedBy,ke as uuid,Te as uuidCreateUpdateHandler,oe as view};
2
2
  //# sourceMappingURL=core.js.map